CombinedText
stringlengths
4
3.42M
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cequel-migrations-rails/version' Gem::Specification.new do |gem| gem.name = "cequel-migrations-rails" gem.version = Cequel::Migrations::Rails::VERSION gem.authors = ["Andrew De Ponte"] gem.email = ["cyphactor@gmail.com"] gem.description = %q{TODO: Write a gem description} gem.summary = %q{TODO: Write a gem summary} gem.homepage = "" 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.require_paths = ["lib"] end Added some necessary deps and cleaned up gemspec. # -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'cequel-migrations-rails/version' Gem::Specification.new do |gem| gem.name = "cequel-migrations-rails" gem.version = Cequel::Migrations::Rails::VERSION gem.authors = ["Andrew De Ponte"] gem.email = ["cyphactor@gmail.com"] gem.description = %q{Cequel migration support for Rails.} gem.summary = %q{A Rails plugin that provides migration support for Cequel.} gem.homepage = "http://github.com/cyphactor/cequel-migrations-rails" 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.require_paths = ["lib"] gem.add_dependency('shearwater') gem.add_development_dependency('rspec') end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "rails_api_validation_errors/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "rails_api_validation_errors" s.version = RailsApiValidationErrors::VERSION s.authors = ["Moritz Lawitschka"] s.email = ["me@moritzlawitschka.de"] s.homepage = "https://github.com/lawitschka/rails-api-validation-errors" s.summary = "Untranslated validation errors with all meta data for APIs behind Javascript frontends" s.description = "Instead of Rails translating validation errors automatically to current locale, validation errors are returned as error meta hashes easily embedded in API error responses and translated in the frontend." s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", "~> 4.0.3" s.add_development_dependency "sqlite3" s.add_development_dependency "rspec-rails", "~> 2.14.0" s.add_development_dependency "rr", "~> 1.1.2" s.add_development_dependency "simplecov" s.add_development_dependency "coveralls" end Fix warnings in Gemspec $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "rails_api_validation_errors/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "rails_api_validation_errors" s.version = RailsApiValidationErrors::VERSION s.licenses = ['MIT'] s.authors = ["Moritz Lawitschka"] s.email = ["me@moritzlawitschka.de"] s.homepage = "https://github.com/lawitschka/rails-api-validation-errors" s.summary = "Untranslated validation errors with all meta data for APIs behind Javascript frontends" s.description = "Instead of Rails translating validation errors automatically to current locale, validation errors are returned as error meta hashes easily embedded in API error responses and translated in the frontend." s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", "~> 4.0", ">= 4.0.0" s.add_development_dependency "sqlite3", "~> 0" s.add_development_dependency "rspec-rails", "~> 2.14", ">= 2.14.0" s.add_development_dependency "rr", "~> 1.1", ">= 1.1.2" s.add_development_dependency "simplecov", "~> 0" s.add_development_dependency "coveralls", "~> 0" end
module Infrarecord class Parser attr_accessor :parser, :ruby2ruby def initialize @parser = Ruby19Parser.new @ruby2ruby = Ruby2Ruby.new end def parse(a_string) sexp = @parser.parse(a_string) AstNode.new(sexp, nil) end def first_possible_orm_call(a_string) possible_calls = find_possible_orm_calls(a_string) if possible_calls.count == 0 nil else possible_calls.first end end def find_possible_orm_calls(a_string) node = self.parse(a_string) #FIXME check if parent is call node, then figure out the chain etc. find_const_nodes_receiving_calls(node).collect {|each| ruby2ruby.process(each.parent_node.sexp) } end def find_const_nodes_receiving_calls(a_node) a_node.find_const_nodes.select { |node| node.is_const_node? and node.parent_node != nil and node.parent_node.is_call_node? } end end class AstNode attr_accessor :sexp, :parent_node def initialize(sexp, parent) @sexp = sexp @parent_node = parent end def is_const_node? node_type == :const end def is_call_node? node_type == :call end def is_fcall_node? node_type == :call #and receiver is nil? end #FIXME #def is_call_node? # node_type == :call #and receiver is not nil #end #here be more stuff def child_nodes @sexp.entries.select{ |e| e.class == Sexp }.map{ |e| AstNode.new(e, self) } end def all_child_nodes res = [self] self.child_nodes.each { |e| res = res.concat(e.all_child_nodes) } res end def find_const_nodes all_child_nodes.select { |e| e.is_const_node? } end def method_missing(name, *args, &block) @sexp.send(name, *args, &block) end end end refactor server-side parser class Sexp #extensions to Sexp def is_call? count > 2 and self[0] == :call end def has_receiver? is_call? and self[1] != nil end def has_const_receiver? has_receiver? and self[1][0] == :const end def recursive_replace(old, new) if self == old return new end res = Sexp.new self.each do |exp| if exp.class == Sexp res << exp.recursive_replace(old, new) else res << exp end end res end def args return nil if not is_call? return [] if self.count < 4 self[3..self.count] end def replace_arg_in_const_call(idx, new_exp) res = self.clone return res if not has_const_receiver? return res if args.count < 1 res[3 + idx] = Sexp.from_array(new_exp) res end def all_const_calls res = [] res << self.clone if has_const_receiver? self.each do |e| if e.class == Sexp res.concat(e.all_const_calls) end end res end def first_const_call calls = all_const_calls return nil if calls.count == 0 calls.first end end module Infrarecord class Parser attr_accessor :parser, :ruby2ruby def initialize @parser = Ruby19Parser.new @ruby2ruby = Ruby2Ruby.new end def parse(a_string) @parser.parse(a_string) end def first_possible_orm_call(a_string) possible_call = parse(a_string).first_const_call return nil if possible_call.nil? @ruby2ruby.process(possible_call) end end end
require 'abstract_unit' require 'rails/initializable' module InitializableTests class Foo include Rails::Initializable attr_accessor :foo, :bar initializer :start do @foo ||= 0 @foo += 1 end end class Bar < Foo initializer :bar do @bar ||= 0 @bar += 1 end end module Word include Rails::Initializable initializer :word do $word = "bird" end end class Parent include Rails::Initializable initializer :one do $arr << 1 end initializer :two do $arr << 2 end end class Child < Parent include Rails::Initializable initializer :three, before: :one do $arr << 3 end initializer :four, after: :one, before: :two do $arr << 4 end end class Parent initializer :five, before: :one do $arr << 5 end end class Instance include Rails::Initializable initializer :one, group: :assets do $arr << 1 end initializer :two do $arr << 2 end initializer :three, group: :all do $arr << 3 end initializer :four do $arr << 4 end end class WithArgs include Rails::Initializable initializer :foo do |arg| $with_arg = arg end end class OverriddenInitializer class MoreInitializers include Rails::Initializable initializer :startup, before: :last do $arr << 3 end initializer :terminate, after: :first, before: :startup do $arr << two end def two 2 end end include Rails::Initializable initializer :first do $arr << 1 end initializer :last do $arr << 4 end def self.initializers super + MoreInitializers.new.initializers end end module Interdependent class PluginA include Rails::Initializable initializer "plugin_a.startup" do $arr << 1 end initializer "plugin_a.terminate" do $arr << 4 end end class PluginB include Rails::Initializable initializer "plugin_b.startup", after: "plugin_a.startup" do $arr << 2 end initializer "plugin_b.terminate", before: "plugin_a.terminate" do $arr << 3 end end class Application include Rails::Initializable def self.initializers PluginB.initializers + PluginA.initializers end end end class Basic < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation test "initializers run" do foo = Foo.new foo.run_initializers assert_equal 1, foo.foo end test "initializers are inherited" do bar = Bar.new bar.run_initializers assert_equal [1, 1], [bar.foo, bar.bar] end test "initializers only get run once" do foo = Foo.new foo.run_initializers foo.run_initializers assert_equal 1, foo.foo end test "creating initializer without a block raises an error" do assert_raise(ArgumentError) do Class.new do include Rails::Initializable initializer :foo end end end end class BeforeAfter < ActiveSupport::TestCase test "running on parent" do $arr = [] Parent.new.run_initializers assert_equal [5, 1, 2], $arr end test "running on child" do $arr = [] Child.new.run_initializers assert_equal [5, 3, 1, 4, 2], $arr end test "handles dependencies introduced before all initializers are loaded" do $arr = [] Interdependent::Application.new.run_initializers assert_equal [1, 2, 3, 4], $arr end end class InstanceTest < ActiveSupport::TestCase test "running locals" do $arr = [] instance = Instance.new instance.run_initializers assert_equal [2, 3, 4], $arr end test "running locals with groups" do $arr = [] instance = Instance.new instance.run_initializers(:assets) assert_equal [1, 3], $arr end end class WithArgsTest < ActiveSupport::TestCase test "running initializers with args" do $with_arg = nil WithArgs.new.run_initializers(:default, 'foo') assert_equal 'foo', $with_arg end end class OverriddenInitializerTest < ActiveSupport::TestCase test "merges in the initializers from the parent in the right order" do $arr = [] OverriddenInitializer.new.run_initializers assert_equal [1, 2, 3, 4], $arr end end end Remove not used module from initializable test require 'abstract_unit' require 'rails/initializable' module InitializableTests class Foo include Rails::Initializable attr_accessor :foo, :bar initializer :start do @foo ||= 0 @foo += 1 end end class Bar < Foo initializer :bar do @bar ||= 0 @bar += 1 end end class Parent include Rails::Initializable initializer :one do $arr << 1 end initializer :two do $arr << 2 end end class Child < Parent include Rails::Initializable initializer :three, before: :one do $arr << 3 end initializer :four, after: :one, before: :two do $arr << 4 end end class Parent initializer :five, before: :one do $arr << 5 end end class Instance include Rails::Initializable initializer :one, group: :assets do $arr << 1 end initializer :two do $arr << 2 end initializer :three, group: :all do $arr << 3 end initializer :four do $arr << 4 end end class WithArgs include Rails::Initializable initializer :foo do |arg| $with_arg = arg end end class OverriddenInitializer class MoreInitializers include Rails::Initializable initializer :startup, before: :last do $arr << 3 end initializer :terminate, after: :first, before: :startup do $arr << two end def two 2 end end include Rails::Initializable initializer :first do $arr << 1 end initializer :last do $arr << 4 end def self.initializers super + MoreInitializers.new.initializers end end module Interdependent class PluginA include Rails::Initializable initializer "plugin_a.startup" do $arr << 1 end initializer "plugin_a.terminate" do $arr << 4 end end class PluginB include Rails::Initializable initializer "plugin_b.startup", after: "plugin_a.startup" do $arr << 2 end initializer "plugin_b.terminate", before: "plugin_a.terminate" do $arr << 3 end end class Application include Rails::Initializable def self.initializers PluginB.initializers + PluginA.initializers end end end class Basic < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation test "initializers run" do foo = Foo.new foo.run_initializers assert_equal 1, foo.foo end test "initializers are inherited" do bar = Bar.new bar.run_initializers assert_equal [1, 1], [bar.foo, bar.bar] end test "initializers only get run once" do foo = Foo.new foo.run_initializers foo.run_initializers assert_equal 1, foo.foo end test "creating initializer without a block raises an error" do assert_raise(ArgumentError) do Class.new do include Rails::Initializable initializer :foo end end end end class BeforeAfter < ActiveSupport::TestCase test "running on parent" do $arr = [] Parent.new.run_initializers assert_equal [5, 1, 2], $arr end test "running on child" do $arr = [] Child.new.run_initializers assert_equal [5, 3, 1, 4, 2], $arr end test "handles dependencies introduced before all initializers are loaded" do $arr = [] Interdependent::Application.new.run_initializers assert_equal [1, 2, 3, 4], $arr end end class InstanceTest < ActiveSupport::TestCase test "running locals" do $arr = [] instance = Instance.new instance.run_initializers assert_equal [2, 3, 4], $arr end test "running locals with groups" do $arr = [] instance = Instance.new instance.run_initializers(:assets) assert_equal [1, 3], $arr end end class WithArgsTest < ActiveSupport::TestCase test "running initializers with args" do $with_arg = nil WithArgs.new.run_initializers(:default, 'foo') assert_equal 'foo', $with_arg end end class OverriddenInitializerTest < ActiveSupport::TestCase test "merges in the initializers from the parent in the right order" do $arr = [] OverriddenInitializer.new.run_initializers assert_equal [1, 2, 3, 4], $arr end end end
module CukeModeler # NOT A PART OF THE PUBLIC API # A module providing source text parsing functionality. module Parsing # Have to at least load some version of the gem before which version of the gem has been loaded can # be determined and the rest of the needed files can be loaded. Try the old one first and then the # new one. begin require 'gherkin' rescue LoadError begin require 'gherkin/parser' rescue LoadError # Gherkin 6.x require 'gherkin/gherkin' end end # The *gherkin* gem loads differently and has different grammar rules across major versions. Parsing # will be done with an 'adapter' appropriate to the version of the *gherkin* gem that has been activated. gherkin_version = Gem.loaded_specs['gherkin'].version.version case gherkin_version when /^6\./ require 'gherkin/gherkin' require 'cuke_modeler/adapters/gherkin_6_adapter' # The method to use for parsing Gherkin text def self.parsing_method(source_text, filename) messages = Gherkin::Gherkin.from_source(filename, source_text, {:default_dialect => CukeModeler::Parsing.dialect}).to_a messages.map(&:to_hash).find { |message| message[:gherkinDocument] }[:gherkinDocument] end # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin6Adapter end when /^[54]\./ require 'gherkin/parser' require 'cuke_modeler/adapters/gherkin_4_adapter' # todo - make these methods private? # The method to use for parsing Gherkin text # Filename isn't used by this version of Gherkin but keeping the parameter so that the calling method only has to know one method signature def self.parsing_method(source_text, _filename) Gherkin::Parser.new.parse(source_text) end # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin4Adapter end when /^3\./ require 'gherkin/parser' require 'cuke_modeler/adapters/gherkin_3_adapter' # The method to use for parsing Gherkin text # Filename isn't used by this version of Gherkin but keeping the parameter so that the calling method only has to know one method signature def self.parsing_method(source_text, _filename) Gherkin::Parser.new.parse(source_text) end # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin3Adapter end when /^2\./ require 'stringio' require 'gherkin/formatter/json_formatter' require 'gherkin' require 'json' require 'multi_json' require 'cuke_modeler/adapters/gherkin_2_adapter' # The method to use for parsing Gherkin text def self.parsing_method(source_text, filename) io = StringIO.new formatter = Gherkin::Formatter::JSONFormatter.new(io) parser = Gherkin::Parser::Parser.new(formatter) parser.parse(source_text, filename, 0) formatter.done MultiJson.load(io.string) end # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin2Adapter end else raise("Unknown Gherkin version: '#{gherkin_version}'") end class << self # The dialect that will be used to parse snippets of Gherkin text attr_writer :dialect # The dialect that will be used to parse snippets of Gherkin text def dialect @dialect || 'en' end # The dialects currently known by the gherkin gem def dialects unless @dialects @dialects = Gem.loaded_specs['gherkin'].version.version[/^2\./] ? Gherkin::I18n::LANGUAGES : Gherkin::DIALECTS end @dialects end # Parses the Cucumber feature given in *source_text* and returns an array # containing the hash representation of its logical structure. def parse_text(source_text, filename = 'cuke_modeler_fake_file.feature') raise(ArgumentError, "Text to parse must be a String but got #{source_text.class}") unless source_text.is_a?(String) begin parsed_result = parsing_method(source_text, filename) rescue => e raise(ArgumentError, "Error encountered while parsing '#{filename}'\n#{e.class} - #{e.message}") end adapted_result = adapter_class.new.adapt(parsed_result) adapted_result end end private def dialect_feature_keyword get_word(Parsing.dialects[Parsing.dialect]['feature']) end def dialect_scenario_keyword get_word(Parsing.dialects[Parsing.dialect]['scenario']) end def dialect_outline_keyword get_word(Parsing.dialects[Parsing.dialect]['scenarioOutline'] || Parsing.dialects[Parsing.dialect]['scenario_outline']) end def dialect_step_keyword get_word(Parsing.dialects[Parsing.dialect]['given']) end def get_word(word_set) word_set = word_set.is_a?(Array) ? word_set : word_set.split('|') word_set.first end end end Marking non-API code Documenting some code as not a part of the public API and un-marking some parts that should be public. . module CukeModeler # A module providing source text parsing functionality. module Parsing # Have to at least load some version of the gem before which version of the gem has been loaded can # be determined and the rest of the needed files can be loaded. Try the old one first and then the # new one. begin require 'gherkin' rescue LoadError begin require 'gherkin/parser' rescue LoadError # Gherkin 6.x require 'gherkin/gherkin' end end # The *gherkin* gem loads differently and has different grammar rules across major versions. Parsing # will be done with an 'adapter' appropriate to the version of the *gherkin* gem that has been activated. gherkin_version = Gem.loaded_specs['gherkin'].version.version case gherkin_version when /^6\./ require 'gherkin/gherkin' require 'cuke_modeler/adapters/gherkin_6_adapter' # NOT A PART OF THE PUBLIC API # The method to use for parsing Gherkin text def self.parsing_method(source_text, filename) messages = Gherkin::Gherkin.from_source(filename, source_text, {:default_dialect => CukeModeler::Parsing.dialect}).to_a messages.map(&:to_hash).find { |message| message[:gherkinDocument] }[:gherkinDocument] end # NOT A PART OF THE PUBLIC API # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin6Adapter end when /^[54]\./ require 'gherkin/parser' require 'cuke_modeler/adapters/gherkin_4_adapter' # todo - make these methods private? # NOT A PART OF THE PUBLIC API # The method to use for parsing Gherkin text # Filename isn't used by this version of Gherkin but keeping the parameter so that the calling method only has to know one method signature def self.parsing_method(source_text, _filename) Gherkin::Parser.new.parse(source_text) end # NOT A PART OF THE PUBLIC API # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin4Adapter end when /^3\./ require 'gherkin/parser' require 'cuke_modeler/adapters/gherkin_3_adapter' # NOT A PART OF THE PUBLIC API # The method to use for parsing Gherkin text # Filename isn't used by this version of Gherkin but keeping the parameter so that the calling method only has to know one method signature def self.parsing_method(source_text, _filename) Gherkin::Parser.new.parse(source_text) end # NOT A PART OF THE PUBLIC API # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin3Adapter end when /^2\./ require 'stringio' require 'gherkin/formatter/json_formatter' require 'gherkin' require 'json' require 'multi_json' require 'cuke_modeler/adapters/gherkin_2_adapter' # NOT A PART OF THE PUBLIC API # The method to use for parsing Gherkin text def self.parsing_method(source_text, filename) io = StringIO.new formatter = Gherkin::Formatter::JSONFormatter.new(io) parser = Gherkin::Parser::Parser.new(formatter) parser.parse(source_text, filename, 0) formatter.done MultiJson.load(io.string) end # NOT A PART OF THE PUBLIC API # The adapter to use when converting an AST to a standard internal shape def self.adapter_class CukeModeler::Gherkin2Adapter end else raise("Unknown Gherkin version: '#{gherkin_version}'") end class << self # The dialect that will be used to parse snippets of Gherkin text attr_writer :dialect # The dialect that will be used to parse snippets of Gherkin text def dialect @dialect || 'en' end # The dialects currently known by the gherkin gem def dialects unless @dialects @dialects = Gem.loaded_specs['gherkin'].version.version[/^2\./] ? Gherkin::I18n::LANGUAGES : Gherkin::DIALECTS end @dialects end # Parses the Cucumber feature given in *source_text* and returns an array # containing the hash representation of its logical structure. def parse_text(source_text, filename = 'cuke_modeler_fake_file.feature') raise(ArgumentError, "Text to parse must be a String but got #{source_text.class}") unless source_text.is_a?(String) begin parsed_result = parsing_method(source_text, filename) rescue => e raise(ArgumentError, "Error encountered while parsing '#{filename}'\n#{e.class} - #{e.message}") end adapted_result = adapter_class.new.adapt(parsed_result) adapted_result end end private def dialect_feature_keyword get_word(Parsing.dialects[Parsing.dialect]['feature']) end def dialect_scenario_keyword get_word(Parsing.dialects[Parsing.dialect]['scenario']) end def dialect_outline_keyword get_word(Parsing.dialects[Parsing.dialect]['scenarioOutline'] || Parsing.dialects[Parsing.dialect]['scenario_outline']) end def dialect_step_keyword get_word(Parsing.dialects[Parsing.dialect]['given']) end def get_word(word_set) word_set = word_set.is_a?(Array) ? word_set : word_set.split('|') word_set.first end end end
require_relative '../../../data/vulndb' module Dap module Filter module BaseVulnMatch def search(hash, service) SEARCHES[service].each do | entry | entry[:regex].each do | regex, value | if regex =~ hash[entry[:hash_key]].force_encoding('BINARY') # Handle cases that could be multiple hits, not for upnp but could be others. hash[entry[:output_key]] = ( hash[entry[:output_key]] ? hash[entry[:output_key]] + value : value ) end end if hash[entry[:hash_key]] end hash end def lookup(hash, service) SEARCHES[service].each do | entry | if hash[entry[:hash_key]] res = entry[:cvemap][hash[entry[:hash_key]]] if res hash[entry[:output_key]] = res end end end hash end end class FilterVulnMatchUPNP include Base include BaseVulnMatch def process(doc) doc = search(doc, :upnp) [ doc ] end end class FilterVulnMatchIPMI include Base include BaseVulnMatch def process(doc) doc = search(doc, :ipmi) if (doc['data.ipmi_user_non_null'] == "0") && (doc['data.ipmi_user_null'] == "0") doc["vulnerability"] = ( doc["vulnerability"] ? doc["vulnerability"] + ["IPMI-ANON"] : ["IPMI-ANON"] ) end [ doc ] end end class FilterVulnMatchMSSQL include Base include BaseVulnMatch def process(doc) doc = lookup(doc, :mssql) [ doc ] end end class FilterVulnMatchHTTP include Base include BaseVulnMatch def check_shellshock(doc) if not doc["http.headers"] return [] end h = doc["http.headers"] sspattern = /\(\)\s*{\s*:;\s*};/ if h["user-agent"] and h["user-agent"] =~ sspattern return ['VULN-SHELLSHOCK', 'CVE-2014-6271'] end if h["referrer"] and h["referrer"] =~ sspattern return ['VULN-SHELLSHOCK', 'CVE-2014-6271'] end return [] end def check_elastic(doc) if not doc['http.path'] return [] end if not doc['http.path'] == '/_search' return [] end input = doc['http.query'] if doc['http.method'] == "POST" input = doc['http.body'] end if not input.match("script_fields") return [] end out = ['VULN-ELASTICSEARCH-RCE'] if (input.match("Runtime") and input.match("getRuntime()")) or (input.match("FileOutputStream") and input.match("URLClassLoader")) out += ['CVE-2014-3120'] end if input.match("getDeclaredConstructor") out += ['CVE-2015-1427'] end if input.match("metasploit.Payload") out += ['METASPLOIT'] end return out end def process(doc) if not doc['vulnerability'] doc['vulnerability'] = [] end doc['vulnerability'] |= check_elastic(doc) doc['vulnerability'] |= check_shellshock(doc) # see vulndb.rb, allows for simple matches to be added quickly SEARCHES[:http].each do | entry | success = true # all matches must go through entry[:match].each do | k, v | if not doc[k] success = false else m = doc[k].match(v) if not m success = false end end if not success break end end if success doc['vulnerability'] |= entry[:cve] end end [ doc ] end end end end slight logic update for the http vuln matcher require_relative '../../../data/vulndb' module Dap module Filter module BaseVulnMatch def search(hash, service) SEARCHES[service].each do | entry | entry[:regex].each do | regex, value | if regex =~ hash[entry[:hash_key]].force_encoding('BINARY') # Handle cases that could be multiple hits, not for upnp but could be others. hash[entry[:output_key]] = ( hash[entry[:output_key]] ? hash[entry[:output_key]] + value : value ) end end if hash[entry[:hash_key]] end hash end def lookup(hash, service) SEARCHES[service].each do | entry | if hash[entry[:hash_key]] res = entry[:cvemap][hash[entry[:hash_key]]] if res hash[entry[:output_key]] = res end end end hash end end class FilterVulnMatchUPNP include Base include BaseVulnMatch def process(doc) doc = search(doc, :upnp) [ doc ] end end class FilterVulnMatchIPMI include Base include BaseVulnMatch def process(doc) doc = search(doc, :ipmi) if (doc['data.ipmi_user_non_null'] == "0") && (doc['data.ipmi_user_null'] == "0") doc["vulnerability"] = ( doc["vulnerability"] ? doc["vulnerability"] + ["IPMI-ANON"] : ["IPMI-ANON"] ) end [ doc ] end end class FilterVulnMatchMSSQL include Base include BaseVulnMatch def process(doc) doc = lookup(doc, :mssql) [ doc ] end end class FilterVulnMatchHTTP include Base include BaseVulnMatch def check_shellshock(doc) if not doc["http.headers"] return [] end h = doc["http.headers"] sspattern = /\(\)\s*{\s*:;\s*};/ if h["user-agent"] and h["user-agent"] =~ sspattern return ['VULN-SHELLSHOCK', 'CVE-2014-6271'] end if h["referrer"] and h["referrer"] =~ sspattern return ['VULN-SHELLSHOCK', 'CVE-2014-6271'] end return [] end def check_elastic(doc) if not doc['http.path'] return [] end if not doc['http.path'] == '/_search' return [] end input = doc['http.query'] if doc['http.method'] == "POST" input = doc['http.body'] end if not input.match("script_fields") return [] end out = ['VULN-ELASTICSEARCH-RCE'] if (input.match("Runtime") and input.match("getRuntime()")) or (input.match("FileOutputStream") and input.match("URLClassLoader")) out += ['CVE-2014-3120'] end if input.match("getDeclaredConstructor") out += ['CVE-2015-1427'] end if input.match("metasploit.Payload") out += ['METASPLOIT'] end return out end def process(doc) vulns = [] if doc['vulnerability'] vulns |= doc['vulnerability'] end vulns |= check_elastic(doc) vulns |= check_shellshock(doc) # see vulndb.rb, allows for simple matches to be added quickly SEARCHES[:http].each do | entry | success = true # all matches must go through entry[:match].each do | k, v | if not doc[k] success = false else m = doc[k].match(v) if not m success = false end end if not success break end end if success vulns |= entry[:cve] end end if vulns doc['vulnerability'] = vulns end [ doc ] end end end end
def print_error(errmsg, opts = {}) errmsg = errmsg.join("\n") if errmsg.kind_of?(Array) errmsg = errmsg.strip.split("\n").map {|i| "// #{i.strip}" }.join("\n") errmsg += "\n\n" unless opts[:strip] $stderr.puts errmsg end def print_rownum(data, opts = {}) rownum = data.to_i msg = "// #{rownum} #{rownum > 1 ? 'rows' : 'row'} changed" msg << " (%.2f sec)" % opts[:time] if opts[:time] msg << "\n" msg << "\n" unless opts[:strip] puts msg end def print_version puts "#{File.basename($0)} #{Version}" end def print_json(data, out, opts = {}) str = nil last_evaluated_key = nil if data.kind_of?(DynamoDB::Iteratorable) last_evaluated_key = data.last_evaluated_key data = data.data end if data.kind_of?(Array) and opts[:inline] str = "[\n" data.each_with_index do |item, i| str << " #{item.to_json}" str << ',' if i < (data.length - 1) str << "\n" end str << "]" else if data.kind_of?(Array) or data.kind_of?(Hash) str = JSON.pretty_generate(data) else str = data.to_json end end str.sub!(/(?:\r\n|\r|\n)*\Z/, "\n") if opts[:show_rows] if [Array, Hash].any? {|i| data.kind_of?(i) } str << "// #{data.length} #{data.length > 1 ? 'rows' : 'row'} in set" else str << '// 1 row in set' end str << " (%.2f sec)" % opts[:time] if opts[:time] str << "\n" end if last_evaluated_key str << "// has more\n" end str << "\n" unless opts[:strip] out.puts(str) end def evaluate_command(driver, cmd_arg) cmd, arg = cmd_arg.split(/\s+/, 2).map {|i| i.strip } arg = nil if (arg || '').strip.empty? r = /\A#{Regexp.compile(cmd)}/i commands = { 'help' => lambda { print_help }, ['exit', 'quit'] => lambda { exit 0 }, 'timeout' => lambda { case arg when nil puts driver.timeout when /\d+/ driver.timeout = arg.to_i else print_error('Invalid argument') end }, 'consistent' => lambda { if arg r_arg = /\A#{Regexp.compile(arg)}/i if r_arg =~ 'true' driver.consistent = true elsif r_arg =~ 'false' driver.consistent = false else print_error('Invalid argument') end else puts driver.consistent end }, 'iteratable' => lambda { if arg r_arg = /\A#{Regexp.compile(arg)}/i if r_arg =~ 'true' driver.iteratable = true elsif r_arg =~ 'false' driver.iteratable = false else print_error('Invalid argument') end else puts driver.iteratable end }, 'retry' => lambda { case arg when nil puts driver.retry_num when /\d+/ driver.retry_num = arg.to_i else print_error('Invalid argument') end }, 'retry_interval' => lambda { case arg when nil puts driver.retry_intvl when /\d+/ driver.retry_intvl = arg.to_i else print_error('Invalid argument') end }, 'debug' => lambda { if arg r_arg = /\A#{Regexp.compile(arg)}/i if r_arg =~ 'true' driver.debug = true elsif r_arg =~ 'false' driver.debug = false else print_error('Invalid argument') end else puts driver.debug end }, 'version' => lambda { print_version } } cmd_name, cmd_proc = commands.find do |name, proc| if name.kind_of?(Array) name.any? {|i| r =~ i } else r =~ name end end if cmd_proc cmd_proc.call else print_error('Unknown command') end end fix help def print_error(errmsg, opts = {}) errmsg = errmsg.join("\n") if errmsg.kind_of?(Array) errmsg = errmsg.strip.split("\n").map {|i| "// #{i.strip}" }.join("\n") errmsg += "\n\n" unless opts[:strip] $stderr.puts errmsg end def print_rownum(data, opts = {}) rownum = data.to_i msg = "// #{rownum} #{rownum > 1 ? 'rows' : 'row'} changed" msg << " (%.2f sec)" % opts[:time] if opts[:time] msg << "\n" msg << "\n" unless opts[:strip] puts msg end def print_version puts "#{File.basename($0)} #{Version}" end def print_json(data, out, opts = {}) str = nil last_evaluated_key = nil if data.kind_of?(DynamoDB::Iteratorable) last_evaluated_key = data.last_evaluated_key data = data.data end if data.kind_of?(Array) and opts[:inline] str = "[\n" data.each_with_index do |item, i| str << " #{item.to_json}" str << ',' if i < (data.length - 1) str << "\n" end str << "]" else if data.kind_of?(Array) or data.kind_of?(Hash) str = JSON.pretty_generate(data) else str = data.to_json end end str.sub!(/(?:\r\n|\r|\n)*\Z/, "\n") if opts[:show_rows] if [Array, Hash].any? {|i| data.kind_of?(i) } str << "// #{data.length} #{data.length > 1 ? 'rows' : 'row'} in set" else str << '// 1 row in set' end str << " (%.2f sec)" % opts[:time] if opts[:time] str << "\n" end if last_evaluated_key str << "// has more\n" end str << "\n" unless opts[:strip] out.puts(str) end def evaluate_command(driver, cmd_arg) cmd, arg = cmd_arg.split(/\s+/, 2).map {|i| i.strip } arg = nil if (arg || '').strip.empty? r = /\A#{Regexp.compile(cmd)}/i commands = { 'help' => lambda { print_help(:pagerize => true) }, ['exit', 'quit'] => lambda { exit 0 }, 'timeout' => lambda { case arg when nil puts driver.timeout when /\d+/ driver.timeout = arg.to_i else print_error('Invalid argument') end }, 'consistent' => lambda { if arg r_arg = /\A#{Regexp.compile(arg)}/i if r_arg =~ 'true' driver.consistent = true elsif r_arg =~ 'false' driver.consistent = false else print_error('Invalid argument') end else puts driver.consistent end }, 'iteratable' => lambda { if arg r_arg = /\A#{Regexp.compile(arg)}/i if r_arg =~ 'true' driver.iteratable = true elsif r_arg =~ 'false' driver.iteratable = false else print_error('Invalid argument') end else puts driver.iteratable end }, 'retry' => lambda { case arg when nil puts driver.retry_num when /\d+/ driver.retry_num = arg.to_i else print_error('Invalid argument') end }, 'retry_interval' => lambda { case arg when nil puts driver.retry_intvl when /\d+/ driver.retry_intvl = arg.to_i else print_error('Invalid argument') end }, 'debug' => lambda { if arg r_arg = /\A#{Regexp.compile(arg)}/i if r_arg =~ 'true' driver.debug = true elsif r_arg =~ 'false' driver.debug = false else print_error('Invalid argument') end else puts driver.debug end }, 'version' => lambda { print_version } } cmd_name, cmd_proc = commands.find do |name, proc| if name.kind_of?(Array) name.any? {|i| r =~ i } else r =~ name end end if cmd_proc cmd_proc.call else print_error('Unknown command') end end
module Deployinator VERSION = "1.0.2" end Bumping minor version for release module Deployinator VERSION = "1.1.0" end
module DeviseRoles VERSION = "0.2.1" end Bump to 0.2.2 module DeviseRoles VERSION = "0.2.2" end
#!/usr/bin/env ruby # encoding: UTF-8 # Item class for the SuccessWhale API. Represents a feed item, such as # a status update or a reply. class Item def initialize () @service = :twitter @content = {} @actions = {} end # Fills in the contents of the item based on a tweet. def populateFromTweet (tweet) @content.merge!(:text => tweet.full_text) @content.merge!(:id => tweet.id) @content.merge!(:time => tweet.created_at) @content.merge!(:fromuser => tweet.from_user) @content.merge!(:fromusername => tweet.user.name) @content.merge!(:fromuseravatar => tweet.user.profile_image_url) @content.merge!(:isreply => tweet.reply?) @content.merge!(:isretweet => tweet.retweet?) @content.merge!(:numfavourited => tweet.favoriters_count) @content.merge!(:numretweeted => tweet.retweeters_count) @content.merge!(:numreplied => tweet.repliers_count) @content.merge!(:numfavourited => tweet.favoriters_count) @content.merge!(:inreplytostatusid => tweet.in_reply_to_status_id) @content.merge!(:inreplytouserid => tweet.in_reply_to_user_id) @content.merge!(:urls => tweet.urls) if tweet.retweet? @content.merge!(:retweet => {}) @content[:retweet].merge!(:text => tweet.retweeted_status.full_text) @content[:retweet].merge!(:id => tweet.retweeted_status.id) @content[:retweet].merge!(:time => tweet.retweeted_status.created_at) @content[:retweet].merge!(:fromuser => tweet.retweeted_status.from_user) @content[:retweet].merge!(:fromusername => tweet.retweeted_status.user.name) @content[:retweet].merge!(:fromuseravatar => tweet.retweeted_status.user.profile_image_url) @content[:retweet].merge!(:isreply => tweet.retweeted_status.reply?) @content[:retweet].merge!(:isretweet => tweet.retweeted_status.retweet?) @content[:retweet].merge!(:numfavourited => tweet.retweeted_status.favoriters_count) @content[:retweet].merge!(:numretweeted => tweet.retweeted_status.retweeters_count) @content[:retweet].merge!(:numreplied => tweet.retweeted_status.repliers_count) @content[:retweet].merge!(:numfavourited => tweet.retweeted_status.favoriters_count) @content[:retweet].merge!(:inreplytostatusid => tweet.retweeted_status.in_reply_to_status_id) @content[:retweet].merge!(:inreplytouserid => tweet.retweeted_status.in_reply_to_user_id) @content[:retweet].merge!(:urls => tweet.retweeted_status.urls) end # TODO: fill in actions # TODO: Pick out URLs like Twitter end # Returns the item as a hash. def asHash return {:service => @service, :content => @content, :actions => @actions} end # Gets the time that the item was originally posted. Used to sort # feeds by time. def getTime return @content[:time] end # Gets the text of the post. Used to determine whether the text includes # a phrase in the user's blocklist. def getText if @content.has_key?('isretweet') && @content['isretweet'] == true return @content['retweet']['text'] else return @content['text'] end end # Check if the text in the item contains any of the phrases in the list # provided. Used in the feed API for removing items that match phrases in # a user's banned phrases list. def matchesPhrase(phrases) for phrase in phrases if @content[:text].include? phrase return false end end return false end end Changed the way the feeds API displays retweets. Hopefully for the better! #!/usr/bin/env ruby # encoding: UTF-8 # Item class for the SuccessWhale API. Represents a feed item, such as # a status update or a reply. class Item def initialize () @service = :twitter @content = {} @actions = {} end # Fills in the contents of the item based on a tweet. def populateFromTweet (tweet) if tweet.retweet? # Keep the retweet's ID for replies and the time for sorting @content.merge!(:id => tweet.id) @content.merge!(:time => tweet.created_at) # Add extra tags to show who retweeted it and when @content.merge!(:retweetedbyuser => tweet.from_user) @content.merge!(:retweetedat => tweet.created_at) @content.merge!(:isretweet => tweet.retweet?) # Copy the retweeted status's data into the main body @content.merge!(:text => tweet.retweeted_status.full_text) @content.merge!(:fromuser => tweet.retweeted_status.from_user) @content.merge!(:fromusername => tweet.retweeted_status.user.name) @content.merge!(:fromuseravatar => tweet.retweeted_status.user.profile_image_url) @content.merge!(:isreply => tweet.retweeted_status.reply?) @content.merge!(:numfavourited => tweet.retweeted_status.favoriters_count) @content.merge!(:numretweeted => tweet.retweeted_status.retweeters_count) @content.merge!(:numreplied => tweet.retweeted_status.repliers_count) @content.merge!(:numfavourited => tweet.retweeted_status.favoriters_count) @content.merge!(:inreplytostatusid => tweet.retweeted_status.in_reply_to_status_id) @content.merge!(:inreplytouserid => tweet.retweeted_status.in_reply_to_user_id) @content.merge!(:urls => tweet.retweeted_status.urls) else # Not a retweet, so populate the content of the item normally. @content.merge!(:text => tweet.full_text) @content.merge!(:id => tweet.id) @content.merge!(:time => tweet.created_at) @content.merge!(:fromuser => tweet.from_user) @content.merge!(:fromusername => tweet.user.name) @content.merge!(:fromuseravatar => tweet.user.profile_image_url) @content.merge!(:isreply => tweet.reply?) @content.merge!(:isretweet => tweet.retweet?) @content.merge!(:numfavourited => tweet.favoriters_count) @content.merge!(:numretweeted => tweet.retweeters_count) @content.merge!(:numreplied => tweet.repliers_count) @content.merge!(:numfavourited => tweet.favoriters_count) @content.merge!(:inreplytostatusid => tweet.in_reply_to_status_id) @content.merge!(:inreplytouserid => tweet.in_reply_to_user_id) @content.merge!(:urls => tweet.urls) end # TODO: fill in actions end # TODO: Populate from Facebook # TODO: Populate from LinkedIn # Returns the item as a hash. def asHash return {:service => @service, :content => @content, :actions => @actions} end # Gets the time that the item was originally posted. Used to sort # feeds by time. def getTime return @content[:time] end # Gets the text of the post. Used to determine whether the text includes # a phrase in the user's blocklist. def getText if @content.has_key?('isretweet') && @content['isretweet'] == true return @content['retweet']['text'] else return @content['text'] end end # Check if the text in the item contains any of the phrases in the list # provided. Used in the feed API for removing items that match phrases in # a user's banned phrases list. def matchesPhrase(phrases) for phrase in phrases if @content[:text].include? phrase return false end end return false end end
# -*- encoding: utf-8 -*- $:.unshift File.expand_path("../lib", __FILE__) require "pathological/version" Gem::Specification.new do |s| s.name = "pathological" s.version = Pathological::VERSION s.platform = Gem::Platform::RUBY s.required_rubygems_version = Gem::Requirement.new(">=2.3.0") if s.respond_to? :required_rubygems_version= s.specification_version = 2 if s.respond_to? :specification_version= s.authors = "Daniel MacDougall", "Caleb Spare", "Evan Chan" s.email = "dmac@ooyala.com", "caleb@ooyala.com", "ev@ooyala.com" s.homepage = "http://www.ooyala.com" s.rubyforge_project = "pathological" s.summary = "A nice way to manage your project's require paths." s.description = <<-DESCRIPTION Pathological provides a way to manage a project's require paths by using a small config file that indicates all directories to include in the load path. DESCRIPTION s.files = `git ls-files`.split("\n").reject { |f| f == ".gitignore" } s.require_paths = ["lib"] # Require rr >= 1.0.3 and scope >= 0.2.3 for mutual compatibility. s.add_development_dependency "rr", "~> 1.0.4" s.add_development_dependency "scope", "~> 0.2.3" s.add_development_dependency "fakefs", "~> 0.4.0" s.add_development_dependency "rake", "~>0.9.2.2" s.add_development_dependency "minitest" "~>4.3.3" s.add_development_dependency "dedent" end Updted gem # -*- encoding: utf-8 -*- $:.unshift File.expand_path("../lib", __FILE__) require "pathological/version" Gem::Specification.new do |s| s.name = "pathological" s.version = Pathological::VERSION s.platform = Gem::Platform::RUBY s.required_rubygems_version = Gem::Requirement.new(">=2.3.0") if s.respond_to? :required_rubygems_version= s.specification_version = 2 if s.respond_to? :specification_version= s.authors = "Daniel MacDougall", "Caleb Spare", "Evan Chan" s.email = "dmac@ooyala.com", "caleb@ooyala.com", "ev@ooyala.com" s.homepage = "http://www.ooyala.com" s.rubyforge_project = "pathological" s.summary = "A nice way to manage your project's require paths." s.description = <<-DESCRIPTION Pathological provides a way to manage a project's require paths by using a small config file that indicates all directories to include in the load path. DESCRIPTION s.files = `git ls-files`.split("\n").reject { |f| f == ".gitignore" } s.require_paths = ["lib"] # Require rr >= 1.0.3 and scope >= 0.2.3 for mutual compatibility. s.add_development_dependency "rr", "=1.0.4" s.add_development_dependency "scope", "~> 0.2.3" s.add_development_dependency "fakefs", "~> 0.4.0" s.add_development_dependency "rake", "~>0.9.2.2" s.add_development_dependency "minitest" "=4.3.3" s.add_development_dependency "dedent" end
[Update] RongCloudIMManager (0.1.6) # # Be sure to run `pod spec lint RxWebClient.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| # ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # s.name = "RongCloudIMManager" s.version = "0.1.6" s.summary = "RongCloudIM‘s upper pack of RongCloudIMManager." # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC 兔博士团队融云消息中心封装,基于Object-C,链式调用方式、对外接口 http://www.rongcloud.cn DESC s.homepage = "https://github.com/jingtao910429/RongCloudIMManager.git" # s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Licensing your code is important. See http://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # s.license = "MIT" # s.license = { :type => "MIT", :file => "FILE_LICENSE" } # ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # s.author = "http://gw.2boss.cn" # Or just: s.author = "2Boss" # s.authors = { "2Boss" => "" } # s.social_media_url = "http://twitter.com/2Boss" # ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # # s.platform = :ios s.platform = :ios, "8.0" # When using multiple platforms # s.ios.deployment_target = "5.0" # s.osx.deployment_target = "10.7" # s.watchos.deployment_target = "2.0" # s.tvos.deployment_target = "9.0" # ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # , :tag => "#{s.version}" s.source = { :git => "https://github.com/jingtao910429/RongCloudIMManager.git"} # ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any swift, h, m, mm, c & cpp files. # For header files it will include any header in the folder. # Not including the public_header_files will make all headers public. # # , "RongCloudIM/RongIMLib/*.{h}", "RongCloudIM/RongIMKit/*.{h}" s.source_files = "Source/*.{h,m}" # s.source_files = "Classes", "Classes/**/*.{h,m}" # s.exclude_files = "Classes/Exclude" # s.prefix_header_contents = "#import <RongIMLib/RongIMLib>" # s.public_header_files = "Source/RongCloudIM/RongIMLib/headers/*.{h}", "Source/RongCloudIM/RongIMKit/headers/*.{h}" # ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # s.resource = "icon.png" # s.resources = "Resources/*.png" # s.preserve_paths = "FilesToSave", "MoreFilesToSave" # ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # s.framework = "SomeFramework" s.frameworks = 'Foundation' s.vendored_frameworks = ['RongCloudIM/RongIMLib.framework', 'RongCloudIM/RongIMKit.framework'] s.resource_bundles = {'Resources' => 'RongCloudIM/RongCloud.bundle'} s.resources = "RongCloudIM/*.plist", "RongCloudIM/*.lproj" s.vendored_libraries = 'RongCloudIM/libopencore-amrnb.a' #表示依赖第三方/自己的静态库(比如libWeChatSDK.a) # # s.library = "iconv" s.libraries = "sqlite3.0", "c++", "xml2", "stdc++", "z" # ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. s.requires_arc = true # s.xcconfig = { 'HEADER_SEARCH_PATHS' => "${PODS_ROOT}/Headers/Public/RongCloudIMManager" } # s.xcconfig = { 'OTHER_LDFLAGS' => '-all_load'} # s.xcconfig = { 'SWIFT_OBJC_BRIDGING_HEADER' => 'RongCloudIMManager-umbrella.h' } # s.dependency 'RongCloudIMLibrary', '~>0.0.1' # s.dependency 'Moya' # s.dependency 'RxSwift' # s.dependency 'ObjectMapper' end
module Docs class Lodash < UrlScraper self.name = 'lodash' self.slug = 'lodash' self.type = 'lodash' self.links = { home: 'https://lodash.com/', code: 'https://github.com/lodash/lodash/' } html_filters.push 'lodash/entries', 'lodash/clean_html', 'title' options[:title] = 'lodash' options[:skip_links] = true options[:attribution] = <<-HTML &copy; 2012&ndash;2016 The Dojo Foundation<br> Licensed under the MIT License. HTML version '4' do self.release = '4.12.0' self.base_url = 'https://lodash.com/docs' end version '3' do self.release = '3.10.0' self.base_url = 'https://lodash.com/docs' # OUT-OF-DATE end end end Update lodash documentation (4.13.1, 3.10.0) module Docs class Lodash < UrlScraper self.name = 'lodash' self.slug = 'lodash' self.type = 'lodash' self.links = { home: 'https://lodash.com/', code: 'https://github.com/lodash/lodash/' } html_filters.push 'lodash/entries', 'lodash/clean_html', 'title' options[:title] = 'lodash' options[:skip_links] = true options[:attribution] = <<-HTML &copy; 2012&ndash;2016 The Dojo Foundation<br> Licensed under the MIT License. HTML version '4' do self.release = '4.13.1' self.base_url = 'https://lodash.com/docs' end version '3' do self.release = '3.10.0' self.base_url = 'https://lodash.com/docs' # OUT-OF-DATE end end end
require 'openssl' module DocusignRest class Client # Define the same set of accessors as the DocusignRest module attr_accessor *Configuration::VALID_CONFIG_KEYS attr_accessor :docusign_authentication_headers, :acct_id def initialize(options={}) # Merge the config values from the module and those passed to the client. merged_options = DocusignRest.options.merge(options) # Copy the merged values to this client and ignore those not part # of our configuration Configuration::VALID_CONFIG_KEYS.each do |key| send("#{key}=", merged_options[key]) end # Set up the DocuSign Authentication headers with the values passed from # our config block if access_token.nil? @docusign_authentication_headers = { 'X-DocuSign-Authentication' => { 'Username' => username, 'Password' => password, 'IntegratorKey' => integrator_key }.to_json } else @docusign_authentication_headers = { 'Authorization' => "Bearer #{access_token}" } end # Set the account_id from the configure block if present, but can't call # the instance var @account_id because that'll override the attr_accessor # that is automatically configured for the configure block @acct_id = account_id end # Internal: sets the default request headers allowing for user overrides # via options[:headers] from within other requests. Additionally injects # the X-DocuSign-Authentication header to authorize the request. # # Client can pass in header options to any given request: # headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'} # # Then we pass them on to this method to merge them with the other # required headers # # Example: # # headers(options[:headers]) # # Returns a merged hash of headers overriding the default Accept header if # the user passes in a new 'Accept' header key and adds any other # user-defined headers along with the X-DocuSign-Authentication headers def headers(user_defined_headers={}) default = { 'Accept' => 'json' #this seems to get added automatically, so I can probably remove this } default.merge!(user_defined_headers) if user_defined_headers @docusign_authentication_headers.merge(default) end # Internal: builds a URI based on the configurable endpoint, api_version, # and the passed in relative url # # url - a relative url requiring a leading forward slash # # Example: # # build_uri('/login_information') # # Returns a parsed URI object def build_uri(url) URI.parse("#{endpoint}/#{api_version}#{url}") end # Internal: configures Net:HTTP with some default values that are required # for every request to the DocuSign API # # Returns a configured Net::HTTP object into which a request can be passed def initialize_net_http_ssl(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') if http.use_ssl? if ca_file if (File.exists?(DocusignRest.ca_file)) http.ca_file = DocusignRest.ca_file # Explicitly verifies that the certificate matches the domain. Requires # that we use www when calling the production DocuSign API http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.verify_depth = 5 else raise 'Certificate path not found.' end else http.verify_mode = OpenSSL::SSL::VERIFY_PEER end else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.ca_file = ca_file if ca_file http end def get_token(account_id, email, password) content_type = {'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'} uri = build_uri('/oauth2/token') request = Net::HTTP::Post.new(uri.request_uri, content_type) request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api" http = initialize_net_http_ssl(uri) response = http.request(request) JSON.parse(response.body) end # Public: gets info necessary to make additional requests to the DocuSign API # # options - hash of headers if the client wants to override something # # Examples: # # client = DocusignRest::Client.new # response = client.login_information # puts response.body # # Returns: # accountId - For the username, password, and integrator_key specified # baseUrl - The base URL for all future DocuSign requests # email - The email used when signing up for DocuSign # isDefault - # TODO identify what this is # name - The account name provided when signing up for DocuSign # userId - # TODO determine what this is used for, if anything # userName - Full name provided when signing up for DocuSign def get_login_information(options={}) uri = build_uri('/login_information') request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers])) http = initialize_net_http_ssl(uri) http.request(request) end # Internal: uses the get_login_information method to determine the client's # accountId and then caches that value into an instance variable so we # don't end up hitting the API for login_information more than once per # request. # # This is used by the rake task in lib/tasks/docusign_task.rake to add # the config/initialzers/docusign_rest.rb file with the proper config block # which includes the account_id in it. That way we don't require hitting # the /login_information URI in normal requests # # Returns the accountId string def get_account_id unless acct_id response = get_login_information.body hashed_response = JSON.parse(response) login_accounts = hashed_response['loginAccounts'] acct_id ||= login_accounts.first['accountId'] end acct_id end # Internal: takes in an array of hashes of signers and concatenates all the # hashes with commas # # embedded - Tells DocuSign if this is an embedded signer which determines # weather or not to deliver emails. Also lets us authenticate # them when they go to do embedded signing. Behind the scenes # this is setting the clientUserId value to the signer's email. # name - The name of the signer # email - The email of the signer # role_name - The role name of the signer ('Attorney', 'Client', etc.). # # Returns a hash of users that need to be embedded in the template to # create an envelope def get_template_roles(signers) template_roles = [] signers.each_with_index do |signer, index| template_role = { :name => signer[:name], :email => signer[:email], :roleName => signer[:role_name], :tabs => { :textTabs => get_signer_tabs(signer[:text_tabs]), :checkboxTabs => get_signer_tabs(signer[:checkbox_tabs]) } } if signer[:email_notification] template_role[:emailNotification] = signer[:email_notification] end template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true template_roles << template_role end template_roles end def get_signer_tabs(tabs) Array(tabs).map do |tab| { 'tabLabel' => tab[:label], 'name' => tab[:name], 'value' => tab[:value], 'documentId' => tab[:document_id], 'selected' => tab[:selected] } end end def get_event_notification(event_notification) return {} unless event_notification { useSoapInterface: event_notification[:use_soap_interface] || false, includeCertificatWithSoap: event_notification[:include_certificate_with_soap] || false, url: event_notification[:url], loggingEnabled: event_notification[:logging], 'EnvelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event| { includeDocuments: envelope_event[:include_documents] || false, envelopeEventStatusCode: envelope_event[:envelope_event_status_code] } end } end # Internal: takes an array of hashes of signers required to complete a # document and allows for setting several options. Not all options are # currently dynamic but that's easy to change/add which I (and I'm # sure others) will be doing in the future. # # template - Includes other optional fields only used when # being called from a template # email - The signer's email # name - The signer's name # embedded - Tells DocuSign if this is an embedded signer which # determines weather or not to deliver emails. Also # lets us authenticate them when they go to do # embedded signing. Behind the scenes this is setting # the clientUserId value to the signer's email. # email_notification - Send an email or not # role_name - The signer's role, like 'Attorney' or 'Client', etc. # template_locked - Doesn't seem to work/do anything # template_required - Doesn't seem to work/do anything # anchor_string - The string of text to anchor the 'sign here' tab to # document_id - If the doc you want signed isn't the first doc in # the files options hash # page_number - Page number of the sign here tab # x_position - Distance horizontally from the anchor string for the # 'sign here' tab to appear. Note: doesn't seem to # currently work. # y_position - Distance vertically from the anchor string for the # 'sign here' tab to appear. Note: doesn't seem to # currently work. # sign_here_tab_text - Instead of 'sign here'. Note: doesn't work # tab_label - TODO: figure out what this is def get_signers(signers, options={}) doc_signers = [] signers.each_with_index do |signer, index| doc_signer = { :email => signer[:email], :name => signer[:name], :accessCode => '', :addAccessCodeToEmail => false, :customFields => nil, :iDCheckConfigurationName => nil, :iDCheckInformationInput => nil, :inheritEmailNotificationConfiguration => false, :note => '', :phoneAuthentication => nil, :recipientAttachment => nil, :recipientId => index+1, :requireIdLookup => false, :roleName => signer[:role_name], :routingOrder => index+1, :socialAuthentications => nil } if signer[:email_notification] doc_signer[:emailNotification] = signer[:email_notification] end if signer[:embedded] doc_signer[:clientUserId] = signer[:client_id] || signer[:email] end if options[:template] == true doc_signer[:templateAccessCodeRequired] = false doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked] doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required] end doc_signer[:autoNavigation] = false doc_signer[:defaultRecipient] = false doc_signer[:signatureInfo] = nil doc_signer[:tabs] = {} doc_signer[:tabs][:approveTabs] = nil doc_signer[:tabs][:checkboxTabs] = nil doc_signer[:tabs][:companyTabs] = nil doc_signer[:tabs][:dateSignedTabs] = get_tabs(signer[:date_signed_tabs], options, index) doc_signer[:tabs][:dateTabs] = nil doc_signer[:tabs][:declineTabs] = nil doc_signer[:tabs][:emailTabs] = get_tabs(signer[:email_tabs], options, index) doc_signer[:tabs][:envelopeIdTabs] = nil doc_signer[:tabs][:fullNameTabs] = get_tabs(signer[:full_name_tabs], options, index) doc_signer[:tabs][:listTabs] = nil doc_signer[:tabs][:noteTabs] = nil doc_signer[:tabs][:numberTabs] = nil doc_signer[:tabs][:radioGroupTabs] = nil doc_signer[:tabs][:initialHereTabs] = get_tabs(signer[:initial_here_tabs], options, index) doc_signer[:tabs][:signHereTabs] = get_tabs(signer[:sign_here_tabs], options, index) doc_signer[:tabs][:signerAttachmentTabs] = nil doc_signer[:tabs][:ssnTabs] = nil doc_signer[:tabs][:textTabs] = get_tabs(signer[:text_tabs], options, index) doc_signer[:tabs][:titleTabs] = nil doc_signer[:tabs][:zipTabs] = nil # append the fully build string to the array doc_signers << doc_signer end doc_signers.to_json end def get_tabs(tabs, options, index) tab_array = [] Array(tabs).map do |tab| tab_hash = {} tab_hash[:anchorString] = tab[:anchor_string] tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0' tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0' tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false tab_hash[:anchorUnits] = 'pixels' tab_hash[:conditionalParentLabel] = nil tab_hash[:conditionalParentValue] = nil tab_hash[:documentId] = tab[:document_id] || '1' tab_hash[:pageNumber] = tab[:page_number] || '1' tab_hash[:recipientId] = index+1 tab_hash[:required] = tab[:required] || false if options[:template] == true tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked] tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required] end tab_hash[:xPosition] = tab[:x_position] || '0' tab_hash[:yPosition] = tab[:y_position] || '0' tab_hash[:name] = tab[:name] || 'Sign Here' tab_hash[:optional] = false tab_hash[:scaleValue] = 1 tab_hash[:tabLabel] = tab[:label] || 'Signature 1' tab_array << tab_hash end tab_array end # Internal: sets up the file ios array # # files - a hash of file params # # Returns the properly formatted ios used to build the file_params hash def create_file_ios(files) # UploadIO is from the multipart-post gem's lib/composite_io.rb:57 # where it has this documentation: # # ******************************************************************** # Create an upload IO suitable for including in the params hash of a # Net::HTTP::Post::Multipart. # # Can take two forms. The first accepts a filename and content type, and # opens the file for reading (to be closed by finalizer). # # The second accepts an already-open IO, but also requires a third argument, # the filename from which it was opened (particularly useful/recommended if # uploading directly from a form in a framework, which often save the file to # an arbitrarily named RackMultipart file in /tmp). # # Usage: # # UploadIO.new('file.txt', 'text/plain') # UploadIO.new(file_io, 'text/plain', 'file.txt') # ******************************************************************** # # There is also a 4th undocumented argument, opts={}, which allows us # to send in not only the Content-Disposition of 'file' as required by # DocuSign, but also the documentId parameter which is required as well # ios = [] files.each_with_index do |file, index| ios << UploadIO.new( file[:io] || file[:path], file[:content_type] || 'application/pdf', file[:name], 'Content-Disposition' => "file; documentid=#{index+1}" ) end ios end # Internal: sets up the file_params for inclusion in a multipart post request # # ios - An array of UploadIO formatted file objects # # Returns a hash of files params suitable for inclusion in a multipart # post request def create_file_params(ios) # multi-doc uploading capabilities, each doc needs to be it's own param file_params = {} ios.each_with_index do |io,index| file_params.merge!("file#{index+1}" => io) end file_params end # Internal: takes in an array of hashes of documents and calculates the # documentId then concatenates all the hashes with commas # # Returns a hash of documents that are to be uploaded def get_documents(ios) documents = [] ios.each_with_index do |io, index| documents << "{ \"documentId\" : \"#{index+1}\", \"name\" : \"#{io.original_filename}\" }" end documents.join(',') end # Internal sets up the Net::HTTP request # # uri - The fully qualified final URI # post_body - The custom post body including the signers, etc # file_params - Formatted hash of ios to merge into the post body # headers - Allows for passing in custom headers # # Returns a request object suitable for embedding in a request def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers) # Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb # # path - The fully qualified URI for the request # params - A hash of params (including files for uploading and a # customized request body) # headers={} - The fully merged, final request headers # boundary - Optional: you can give the request a custom boundary # request = Net::HTTP::Post::Multipart.new( uri.request_uri, {post_body: post_body}.merge(file_params), headers ) # DocuSign requires that we embed the document data in the body of the # JSON request directly so we need to call '.read' on the multipart-post # provided body_stream in order to serialize all the files into a # compatible JSON string. request.body = request.body_stream.read request end # Public: creates an envelope from a document directly without a template # # file_io - Optional: an opened file stream of data (if you don't # want to save the file to the file system as an incremental # step) # file_path - Required if you don't provide a file_io stream, this is # the local path of the file you wish to upload. Absolute # paths recommended. # file_name - The name you want to give to the file you are uploading # content_type - (for the request body) application/json is what DocuSign # is expecting # email_subject - (Optional) short subject line for the email # email_body - (Optional) custom text that will be injected into the # DocuSign generated email # signers - A hash of users who should receive the document and need # to sign it. More info about the options available for # this method are documented above it's method definition. # status - Options include: 'sent', 'created', 'voided' and determine # if the envelope is sent out immediately or stored for # sending at a later time # headers - Allows a client to pass in some # # Returns a JSON parsed response object containing: # envelopeId - The envelope's ID # status - Sent, created, or voided # statusDateTime - The date/time the envelope was created # uri - The relative envelope uri def create_envelope_from_document(options={}) ios = create_file_ios(options[:files]) file_params = create_file_params(ios) post_body = "{ \"emailBlurb\" : \"#{options[:email][:body] if options[:email]}\", \"emailSubject\" : \"#{options[:email][:subject] if options[:email]}\", \"documents\" : [#{get_documents(ios)}], \"recipients\" : { \"signers\" : #{get_signers(options[:signers])} }, \"status\" : \"#{options[:status]}\" } " uri = build_uri("/accounts/#{acct_id}/envelopes") http = initialize_net_http_ssl(uri) request = initialize_net_http_multipart_post_request( uri, post_body, file_params, headers(options[:headers]) ) # Finally do the Net::HTTP request! response = http.request(request) parsed_response = JSON.parse(response.body) end # Public: allows a template to be dynamically created with several options. # # files - An array of hashes of file parameters which will be used # to create actual files suitable for upload in a multipart # request. # # Options: io, path, name. The io is optional and would # require creating a file_io object to embed as the first # argument of any given file hash. See the create_file_ios # method definition above for more details. # # email/body - (Optional) sets the text in the email. Note: the envelope # seems to override this, not sure why it needs to be # configured here as well. I usually leave it blank. # email/subject - (Optional) sets the text in the email. Note: the envelope # seems to override this, not sure why it needs to be # configured here as well. I usually leave it blank. # signers - An array of hashes of signers. See the # get_signers method definition for options. # description - The template description # name - The template name # headers - Optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns a JSON parsed response body containing the template's: # name - Name given above # templateId - The auto-generated ID provided by DocuSign # Uri - the URI where the template is located on the DocuSign servers def create_template(options={}) ios = create_file_ios(options[:files]) file_params = create_file_params(ios) post_body = "{ \"emailBlurb\" : \"#{options[:email][:body] if options[:email]}\", \"emailSubject\" : \"#{options[:email][:subject] if options[:email]}\", \"documents\" : [#{get_documents(ios)}], \"recipients\" : { \"signers\" : #{get_signers(options[:signers], template: true)} }, \"envelopeTemplateDefinition\" : { \"description\" : \"#{options[:description]}\", \"name\" : \"#{options[:name]}\", \"pageCount\" : 1, \"password\" : \"\", \"shared\" : false } } " uri = build_uri("/accounts/#{acct_id}/templates") http = initialize_net_http_ssl(uri) request = initialize_net_http_multipart_post_request( uri, post_body, file_params, headers(options[:headers]) ) # Finally do the Net::HTTP request! response = http.request(request) JSON.parse(response.body) end def get_template(template_id, options = {}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) JSON.parse(response.body) end # Public: create an envelope for delivery from a template # # headers - Optional hash of headers to merge into the existing # required headers for a POST request. # status - Options include: 'sent', 'created', 'voided' and # determine if the envelope is sent out immediately or # stored for sending at a later time # email/body - Sets the text in the email body # email/subject - Sets the text in the email subject line # template_id - The id of the template upon which we want to base this # envelope # template_roles - See the get_template_roles method definition for a list # of options to pass. Note: for consistency sake we call # this 'signers' and not 'templateRoles' when we build up # the request in client code. # headers - Optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns a JSON parsed response body containing the envelope's: # name - Name given above # templateId - The auto-generated ID provided by DocuSign # Uri - the URI where the template is located on the DocuSign servers def create_envelope_from_template(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] post_body = { :status => options[:status], :emailBlurb => options[:email][:body], :emailSubject => options[:email][:subject], :templateId => options[:template_id], :eventNotification => get_event_notification(options[:event_notification]), :templateRoles => get_template_roles(options[:signers]) }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) parsed_response = JSON.parse(response.body) end # Public returns the URL for embedded signing # # envelope_id - the ID of the envelope you wish to use for embedded signing # name - the name of the signer # email - the email of the recipient # return_url - the URL you want the user to be directed to after he or she # completes the document signing # headers - optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns the URL string for embedded signing (can be put in an iFrame) def get_recipient_view(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] post_body = { :authenticationMethod => 'email', :clientUserId => options[:client_id] || options[:email], :email => options[:email], :returnUrl => options[:return_url], :userName => options[:name] }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end # Public returns the URL for embedded console # # envelope_id - the ID of the envelope you wish to use for embedded signing # headers - optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns the URL string for embedded console (can be put in an iFrame) def get_console_view(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] post_body = "{ \"envelopeId\" : \"#{options[:envelope_id]}\" }" uri = build_uri("/accounts/#{acct_id}/views/console") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) parsed_response = JSON.parse(response.body) parsed_response['url'] end # Public returns the envelope recipients for a given envelope # # include_tabs - boolean, determines if the tabs for each signer will be # returned in the response, defaults to false. # envelope_id - ID of the envelope for which you want to retrive the # signer info # headers - optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns a hash of detailed info about the envelope including the signer # hash and status of each signer def get_envelope_recipients(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] include_tabs = options[:include_tabs] || false include_extended = options[:include_extended] || false uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) parsed_response = JSON.parse(response.body) end # Public retrieves the attached file from a given envelope # # envelope_id - ID of the envelope from which the doc will be retrieved # document_id - ID of the document to retrieve # local_save_path - Local absolute path to save the doc to including the # filename itself # headers - Optional hash of headers to merge into the existing # required headers for a multipart request. # # Example # # client.get_document_from_envelope( # envelope_id: @envelope_response['envelopeId'], # document_id: 1, # local_save_path: 'docusign_docs/file_name.pdf' # ) # # Returns the PDF document as a byte stream. def get_document_from_envelope(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) http.request(request) end def create_account(options) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri('/accounts') post_body = convert_hash_keys(options).to_json http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end def delete_account(account_id, options = {}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{account_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type)) response = http.request(request) json = response.body json = '{}' if json.nil? || json == '' JSON.parse(json) end def convert_hash_keys(value) case value when Array value.map { |v| convert_hash_keys(v) } when Hash Hash[value.map { |k, v| [k.to_s.camelize(:lower), convert_hash_keys(v)] }] else value end end # Public: Retrieves a list of available templates # # Example # # client.get_templates() # # Returns a list of the available templates. def get_templates uri = build_uri("/accounts/#{acct_id}/templates") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers({'Content-Type' => 'application/json'})) JSON.parse(http.request(request).body) end # Grabs envelope data. # Equivalent to the following call in the API explorer: # Get Envelopev2/accounts/:accountId/envelopes/:envelopeId # # envelope_id- DS id of envelope to be retrieved. def get_envelope(envelope_id) content_type = {'Content-Type' => 'application/json'} uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) parsed_response = JSON.parse(response.body) end end end Remove unnecessary local vars for parsed_response require 'openssl' module DocusignRest class Client # Define the same set of accessors as the DocusignRest module attr_accessor *Configuration::VALID_CONFIG_KEYS attr_accessor :docusign_authentication_headers, :acct_id def initialize(options={}) # Merge the config values from the module and those passed to the client. merged_options = DocusignRest.options.merge(options) # Copy the merged values to this client and ignore those not part # of our configuration Configuration::VALID_CONFIG_KEYS.each do |key| send("#{key}=", merged_options[key]) end # Set up the DocuSign Authentication headers with the values passed from # our config block if access_token.nil? @docusign_authentication_headers = { 'X-DocuSign-Authentication' => { 'Username' => username, 'Password' => password, 'IntegratorKey' => integrator_key }.to_json } else @docusign_authentication_headers = { 'Authorization' => "Bearer #{access_token}" } end # Set the account_id from the configure block if present, but can't call # the instance var @account_id because that'll override the attr_accessor # that is automatically configured for the configure block @acct_id = account_id end # Internal: sets the default request headers allowing for user overrides # via options[:headers] from within other requests. Additionally injects # the X-DocuSign-Authentication header to authorize the request. # # Client can pass in header options to any given request: # headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'} # # Then we pass them on to this method to merge them with the other # required headers # # Example: # # headers(options[:headers]) # # Returns a merged hash of headers overriding the default Accept header if # the user passes in a new 'Accept' header key and adds any other # user-defined headers along with the X-DocuSign-Authentication headers def headers(user_defined_headers={}) default = { 'Accept' => 'json' #this seems to get added automatically, so I can probably remove this } default.merge!(user_defined_headers) if user_defined_headers @docusign_authentication_headers.merge(default) end # Internal: builds a URI based on the configurable endpoint, api_version, # and the passed in relative url # # url - a relative url requiring a leading forward slash # # Example: # # build_uri('/login_information') # # Returns a parsed URI object def build_uri(url) URI.parse("#{endpoint}/#{api_version}#{url}") end # Internal: configures Net:HTTP with some default values that are required # for every request to the DocuSign API # # Returns a configured Net::HTTP object into which a request can be passed def initialize_net_http_ssl(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') if http.use_ssl? if ca_file if (File.exists?(DocusignRest.ca_file)) http.ca_file = DocusignRest.ca_file # Explicitly verifies that the certificate matches the domain. Requires # that we use www when calling the production DocuSign API http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.verify_depth = 5 else raise 'Certificate path not found.' end else http.verify_mode = OpenSSL::SSL::VERIFY_PEER end else http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.ca_file = ca_file if ca_file http end def get_token(account_id, email, password) content_type = {'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json'} uri = build_uri('/oauth2/token') request = Net::HTTP::Post.new(uri.request_uri, content_type) request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api" http = initialize_net_http_ssl(uri) response = http.request(request) JSON.parse(response.body) end # Public: gets info necessary to make additional requests to the DocuSign API # # options - hash of headers if the client wants to override something # # Examples: # # client = DocusignRest::Client.new # response = client.login_information # puts response.body # # Returns: # accountId - For the username, password, and integrator_key specified # baseUrl - The base URL for all future DocuSign requests # email - The email used when signing up for DocuSign # isDefault - # TODO identify what this is # name - The account name provided when signing up for DocuSign # userId - # TODO determine what this is used for, if anything # userName - Full name provided when signing up for DocuSign def get_login_information(options={}) uri = build_uri('/login_information') request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers])) http = initialize_net_http_ssl(uri) http.request(request) end # Internal: uses the get_login_information method to determine the client's # accountId and then caches that value into an instance variable so we # don't end up hitting the API for login_information more than once per # request. # # This is used by the rake task in lib/tasks/docusign_task.rake to add # the config/initialzers/docusign_rest.rb file with the proper config block # which includes the account_id in it. That way we don't require hitting # the /login_information URI in normal requests # # Returns the accountId string def get_account_id unless acct_id response = get_login_information.body hashed_response = JSON.parse(response) login_accounts = hashed_response['loginAccounts'] acct_id ||= login_accounts.first['accountId'] end acct_id end # Internal: takes in an array of hashes of signers and concatenates all the # hashes with commas # # embedded - Tells DocuSign if this is an embedded signer which determines # weather or not to deliver emails. Also lets us authenticate # them when they go to do embedded signing. Behind the scenes # this is setting the clientUserId value to the signer's email. # name - The name of the signer # email - The email of the signer # role_name - The role name of the signer ('Attorney', 'Client', etc.). # # Returns a hash of users that need to be embedded in the template to # create an envelope def get_template_roles(signers) template_roles = [] signers.each_with_index do |signer, index| template_role = { :name => signer[:name], :email => signer[:email], :roleName => signer[:role_name], :tabs => { :textTabs => get_signer_tabs(signer[:text_tabs]), :checkboxTabs => get_signer_tabs(signer[:checkbox_tabs]) } } if signer[:email_notification] template_role[:emailNotification] = signer[:email_notification] end template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true template_roles << template_role end template_roles end def get_signer_tabs(tabs) Array(tabs).map do |tab| { 'tabLabel' => tab[:label], 'name' => tab[:name], 'value' => tab[:value], 'documentId' => tab[:document_id], 'selected' => tab[:selected] } end end def get_event_notification(event_notification) return {} unless event_notification { useSoapInterface: event_notification[:use_soap_interface] || false, includeCertificatWithSoap: event_notification[:include_certificate_with_soap] || false, url: event_notification[:url], loggingEnabled: event_notification[:logging], 'EnvelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event| { includeDocuments: envelope_event[:include_documents] || false, envelopeEventStatusCode: envelope_event[:envelope_event_status_code] } end } end # Internal: takes an array of hashes of signers required to complete a # document and allows for setting several options. Not all options are # currently dynamic but that's easy to change/add which I (and I'm # sure others) will be doing in the future. # # template - Includes other optional fields only used when # being called from a template # email - The signer's email # name - The signer's name # embedded - Tells DocuSign if this is an embedded signer which # determines weather or not to deliver emails. Also # lets us authenticate them when they go to do # embedded signing. Behind the scenes this is setting # the clientUserId value to the signer's email. # email_notification - Send an email or not # role_name - The signer's role, like 'Attorney' or 'Client', etc. # template_locked - Doesn't seem to work/do anything # template_required - Doesn't seem to work/do anything # anchor_string - The string of text to anchor the 'sign here' tab to # document_id - If the doc you want signed isn't the first doc in # the files options hash # page_number - Page number of the sign here tab # x_position - Distance horizontally from the anchor string for the # 'sign here' tab to appear. Note: doesn't seem to # currently work. # y_position - Distance vertically from the anchor string for the # 'sign here' tab to appear. Note: doesn't seem to # currently work. # sign_here_tab_text - Instead of 'sign here'. Note: doesn't work # tab_label - TODO: figure out what this is def get_signers(signers, options={}) doc_signers = [] signers.each_with_index do |signer, index| doc_signer = { :email => signer[:email], :name => signer[:name], :accessCode => '', :addAccessCodeToEmail => false, :customFields => nil, :iDCheckConfigurationName => nil, :iDCheckInformationInput => nil, :inheritEmailNotificationConfiguration => false, :note => '', :phoneAuthentication => nil, :recipientAttachment => nil, :recipientId => index+1, :requireIdLookup => false, :roleName => signer[:role_name], :routingOrder => index+1, :socialAuthentications => nil } if signer[:email_notification] doc_signer[:emailNotification] = signer[:email_notification] end if signer[:embedded] doc_signer[:clientUserId] = signer[:client_id] || signer[:email] end if options[:template] == true doc_signer[:templateAccessCodeRequired] = false doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked] doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required] end doc_signer[:autoNavigation] = false doc_signer[:defaultRecipient] = false doc_signer[:signatureInfo] = nil doc_signer[:tabs] = {} doc_signer[:tabs][:approveTabs] = nil doc_signer[:tabs][:checkboxTabs] = nil doc_signer[:tabs][:companyTabs] = nil doc_signer[:tabs][:dateSignedTabs] = get_tabs(signer[:date_signed_tabs], options, index) doc_signer[:tabs][:dateTabs] = nil doc_signer[:tabs][:declineTabs] = nil doc_signer[:tabs][:emailTabs] = get_tabs(signer[:email_tabs], options, index) doc_signer[:tabs][:envelopeIdTabs] = nil doc_signer[:tabs][:fullNameTabs] = get_tabs(signer[:full_name_tabs], options, index) doc_signer[:tabs][:listTabs] = nil doc_signer[:tabs][:noteTabs] = nil doc_signer[:tabs][:numberTabs] = nil doc_signer[:tabs][:radioGroupTabs] = nil doc_signer[:tabs][:initialHereTabs] = get_tabs(signer[:initial_here_tabs], options, index) doc_signer[:tabs][:signHereTabs] = get_tabs(signer[:sign_here_tabs], options, index) doc_signer[:tabs][:signerAttachmentTabs] = nil doc_signer[:tabs][:ssnTabs] = nil doc_signer[:tabs][:textTabs] = get_tabs(signer[:text_tabs], options, index) doc_signer[:tabs][:titleTabs] = nil doc_signer[:tabs][:zipTabs] = nil # append the fully build string to the array doc_signers << doc_signer end doc_signers.to_json end def get_tabs(tabs, options, index) tab_array = [] Array(tabs).map do |tab| tab_hash = {} tab_hash[:anchorString] = tab[:anchor_string] tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0' tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0' tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false tab_hash[:anchorUnits] = 'pixels' tab_hash[:conditionalParentLabel] = nil tab_hash[:conditionalParentValue] = nil tab_hash[:documentId] = tab[:document_id] || '1' tab_hash[:pageNumber] = tab[:page_number] || '1' tab_hash[:recipientId] = index+1 tab_hash[:required] = tab[:required] || false if options[:template] == true tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked] tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required] end tab_hash[:xPosition] = tab[:x_position] || '0' tab_hash[:yPosition] = tab[:y_position] || '0' tab_hash[:name] = tab[:name] || 'Sign Here' tab_hash[:optional] = false tab_hash[:scaleValue] = 1 tab_hash[:tabLabel] = tab[:label] || 'Signature 1' tab_array << tab_hash end tab_array end # Internal: sets up the file ios array # # files - a hash of file params # # Returns the properly formatted ios used to build the file_params hash def create_file_ios(files) # UploadIO is from the multipart-post gem's lib/composite_io.rb:57 # where it has this documentation: # # ******************************************************************** # Create an upload IO suitable for including in the params hash of a # Net::HTTP::Post::Multipart. # # Can take two forms. The first accepts a filename and content type, and # opens the file for reading (to be closed by finalizer). # # The second accepts an already-open IO, but also requires a third argument, # the filename from which it was opened (particularly useful/recommended if # uploading directly from a form in a framework, which often save the file to # an arbitrarily named RackMultipart file in /tmp). # # Usage: # # UploadIO.new('file.txt', 'text/plain') # UploadIO.new(file_io, 'text/plain', 'file.txt') # ******************************************************************** # # There is also a 4th undocumented argument, opts={}, which allows us # to send in not only the Content-Disposition of 'file' as required by # DocuSign, but also the documentId parameter which is required as well # ios = [] files.each_with_index do |file, index| ios << UploadIO.new( file[:io] || file[:path], file[:content_type] || 'application/pdf', file[:name], 'Content-Disposition' => "file; documentid=#{index+1}" ) end ios end # Internal: sets up the file_params for inclusion in a multipart post request # # ios - An array of UploadIO formatted file objects # # Returns a hash of files params suitable for inclusion in a multipart # post request def create_file_params(ios) # multi-doc uploading capabilities, each doc needs to be it's own param file_params = {} ios.each_with_index do |io,index| file_params.merge!("file#{index+1}" => io) end file_params end # Internal: takes in an array of hashes of documents and calculates the # documentId then concatenates all the hashes with commas # # Returns a hash of documents that are to be uploaded def get_documents(ios) documents = [] ios.each_with_index do |io, index| documents << "{ \"documentId\" : \"#{index+1}\", \"name\" : \"#{io.original_filename}\" }" end documents.join(',') end # Internal sets up the Net::HTTP request # # uri - The fully qualified final URI # post_body - The custom post body including the signers, etc # file_params - Formatted hash of ios to merge into the post body # headers - Allows for passing in custom headers # # Returns a request object suitable for embedding in a request def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers) # Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb # # path - The fully qualified URI for the request # params - A hash of params (including files for uploading and a # customized request body) # headers={} - The fully merged, final request headers # boundary - Optional: you can give the request a custom boundary # request = Net::HTTP::Post::Multipart.new( uri.request_uri, {post_body: post_body}.merge(file_params), headers ) # DocuSign requires that we embed the document data in the body of the # JSON request directly so we need to call '.read' on the multipart-post # provided body_stream in order to serialize all the files into a # compatible JSON string. request.body = request.body_stream.read request end # Public: creates an envelope from a document directly without a template # # file_io - Optional: an opened file stream of data (if you don't # want to save the file to the file system as an incremental # step) # file_path - Required if you don't provide a file_io stream, this is # the local path of the file you wish to upload. Absolute # paths recommended. # file_name - The name you want to give to the file you are uploading # content_type - (for the request body) application/json is what DocuSign # is expecting # email_subject - (Optional) short subject line for the email # email_body - (Optional) custom text that will be injected into the # DocuSign generated email # signers - A hash of users who should receive the document and need # to sign it. More info about the options available for # this method are documented above it's method definition. # status - Options include: 'sent', 'created', 'voided' and determine # if the envelope is sent out immediately or stored for # sending at a later time # headers - Allows a client to pass in some # # Returns a JSON parsed response object containing: # envelopeId - The envelope's ID # status - Sent, created, or voided # statusDateTime - The date/time the envelope was created # uri - The relative envelope uri def create_envelope_from_document(options={}) ios = create_file_ios(options[:files]) file_params = create_file_params(ios) post_body = "{ \"emailBlurb\" : \"#{options[:email][:body] if options[:email]}\", \"emailSubject\" : \"#{options[:email][:subject] if options[:email]}\", \"documents\" : [#{get_documents(ios)}], \"recipients\" : { \"signers\" : #{get_signers(options[:signers])} }, \"status\" : \"#{options[:status]}\" } " uri = build_uri("/accounts/#{acct_id}/envelopes") http = initialize_net_http_ssl(uri) request = initialize_net_http_multipart_post_request( uri, post_body, file_params, headers(options[:headers]) ) # Finally do the Net::HTTP request! response = http.request(request) JSON.parse(response.body) end # Public: allows a template to be dynamically created with several options. # # files - An array of hashes of file parameters which will be used # to create actual files suitable for upload in a multipart # request. # # Options: io, path, name. The io is optional and would # require creating a file_io object to embed as the first # argument of any given file hash. See the create_file_ios # method definition above for more details. # # email/body - (Optional) sets the text in the email. Note: the envelope # seems to override this, not sure why it needs to be # configured here as well. I usually leave it blank. # email/subject - (Optional) sets the text in the email. Note: the envelope # seems to override this, not sure why it needs to be # configured here as well. I usually leave it blank. # signers - An array of hashes of signers. See the # get_signers method definition for options. # description - The template description # name - The template name # headers - Optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns a JSON parsed response body containing the template's: # name - Name given above # templateId - The auto-generated ID provided by DocuSign # Uri - the URI where the template is located on the DocuSign servers def create_template(options={}) ios = create_file_ios(options[:files]) file_params = create_file_params(ios) post_body = "{ \"emailBlurb\" : \"#{options[:email][:body] if options[:email]}\", \"emailSubject\" : \"#{options[:email][:subject] if options[:email]}\", \"documents\" : [#{get_documents(ios)}], \"recipients\" : { \"signers\" : #{get_signers(options[:signers], template: true)} }, \"envelopeTemplateDefinition\" : { \"description\" : \"#{options[:description]}\", \"name\" : \"#{options[:name]}\", \"pageCount\" : 1, \"password\" : \"\", \"shared\" : false } } " uri = build_uri("/accounts/#{acct_id}/templates") http = initialize_net_http_ssl(uri) request = initialize_net_http_multipart_post_request( uri, post_body, file_params, headers(options[:headers]) ) # Finally do the Net::HTTP request! response = http.request(request) JSON.parse(response.body) end def get_template(template_id, options = {}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) JSON.parse(response.body) end # Public: create an envelope for delivery from a template # # headers - Optional hash of headers to merge into the existing # required headers for a POST request. # status - Options include: 'sent', 'created', 'voided' and # determine if the envelope is sent out immediately or # stored for sending at a later time # email/body - Sets the text in the email body # email/subject - Sets the text in the email subject line # template_id - The id of the template upon which we want to base this # envelope # template_roles - See the get_template_roles method definition for a list # of options to pass. Note: for consistency sake we call # this 'signers' and not 'templateRoles' when we build up # the request in client code. # headers - Optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns a JSON parsed response body containing the envelope's: # name - Name given above # templateId - The auto-generated ID provided by DocuSign # Uri - the URI where the template is located on the DocuSign servers def create_envelope_from_template(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] post_body = { :status => options[:status], :emailBlurb => options[:email][:body], :emailSubject => options[:email][:subject], :templateId => options[:template_id], :eventNotification => get_event_notification(options[:event_notification]), :templateRoles => get_template_roles(options[:signers]) }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end # Public returns the URL for embedded signing # # envelope_id - the ID of the envelope you wish to use for embedded signing # name - the name of the signer # email - the email of the recipient # return_url - the URL you want the user to be directed to after he or she # completes the document signing # headers - optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns the URL string for embedded signing (can be put in an iFrame) def get_recipient_view(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] post_body = { :authenticationMethod => 'email', :clientUserId => options[:client_id] || options[:email], :email => options[:email], :returnUrl => options[:return_url], :userName => options[:name] }.to_json uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end # Public returns the URL for embedded console # # envelope_id - the ID of the envelope you wish to use for embedded signing # headers - optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns the URL string for embedded console (can be put in an iFrame) def get_console_view(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] post_body = "{ \"envelopeId\" : \"#{options[:envelope_id]}\" }" uri = build_uri("/accounts/#{acct_id}/views/console") http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) parsed_response = JSON.parse(response.body) parsed_response['url'] end # Public returns the envelope recipients for a given envelope # # include_tabs - boolean, determines if the tabs for each signer will be # returned in the response, defaults to false. # envelope_id - ID of the envelope for which you want to retrive the # signer info # headers - optional hash of headers to merge into the existing # required headers for a multipart request. # # Returns a hash of detailed info about the envelope including the signer # hash and status of each signer def get_envelope_recipients(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] include_tabs = options[:include_tabs] || false include_extended = options[:include_extended] || false uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) JSON.parse(response.body) end # Public retrieves the attached file from a given envelope # # envelope_id - ID of the envelope from which the doc will be retrieved # document_id - ID of the document to retrieve # local_save_path - Local absolute path to save the doc to including the # filename itself # headers - Optional hash of headers to merge into the existing # required headers for a multipart request. # # Example # # client.get_document_from_envelope( # envelope_id: @envelope_response['envelopeId'], # document_id: 1, # local_save_path: 'docusign_docs/file_name.pdf' # ) # # Returns the PDF document as a byte stream. def get_document_from_envelope(options={}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) http.request(request) end def create_account(options) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri('/accounts') post_body = convert_hash_keys(options).to_json http = initialize_net_http_ssl(uri) request = Net::HTTP::Post.new(uri.request_uri, headers(content_type)) request.body = post_body response = http.request(request) JSON.parse(response.body) end def delete_account(account_id, options = {}) content_type = {'Content-Type' => 'application/json'} content_type.merge(options[:headers]) if options[:headers] uri = build_uri("/accounts/#{account_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type)) response = http.request(request) json = response.body json = '{}' if json.nil? || json == '' JSON.parse(json) end def convert_hash_keys(value) case value when Array value.map { |v| convert_hash_keys(v) } when Hash Hash[value.map { |k, v| [k.to_s.camelize(:lower), convert_hash_keys(v)] }] else value end end # Public: Retrieves a list of available templates # # Example # # client.get_templates() # # Returns a list of the available templates. def get_templates uri = build_uri("/accounts/#{acct_id}/templates") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers({'Content-Type' => 'application/json'})) JSON.parse(http.request(request).body) end # Grabs envelope data. # Equivalent to the following call in the API explorer: # Get Envelopev2/accounts/:accountId/envelopes/:envelopeId # # envelope_id- DS id of envelope to be retrieved. def get_envelope(envelope_id) content_type = {'Content-Type' => 'application/json'} uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}") http = initialize_net_http_ssl(uri) request = Net::HTTP::Get.new(uri.request_uri, headers(content_type)) response = http.request(request) JSON.parse(response.body) end end end
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Domgen::TypeDB.config_element('graphql') do attr_writer :scalar_type def scalar_type @scalar_type || (Domgen.error('scalar type not defined')) end end Domgen::TypeDB.enhance(:text, 'graphql.scalar_type' => 'String') Domgen::TypeDB.enhance(:integer, 'graphql.scalar_type' => 'Int') Domgen::TypeDB.enhance(:long, 'graphql.scalar_type' => 'Long') Domgen::TypeDB.enhance(:real, 'graphql.scalar_type' => 'Float') Domgen::TypeDB.enhance(:date, 'graphql.scalar_type' => 'Date') Domgen::TypeDB.enhance(:datetime, 'graphql.scalar_type' => 'DateTime') Domgen::TypeDB.enhance(:boolean, 'graphql.scalar_type' => 'Boolean') Domgen::TypeDB.enhance(:point, 'graphql.scalar_type' => 'Point') Domgen::TypeDB.enhance(:multipoint, 'graphql.scalar_type' => 'MultiPoint') Domgen::TypeDB.enhance(:linestring, 'graphql.scalar_type' => 'LineString') Domgen::TypeDB.enhance(:multilinestring, 'graphql.scalar_type' => 'MultiLineString') Domgen::TypeDB.enhance(:polygon, 'graphql.scalar_type' => 'Polygon') Domgen::TypeDB.enhance(:multipolygon, 'graphql.scalar_type' => 'MultiPolygon') Domgen::TypeDB.enhance(:geometry, 'graphql.scalar_type' => 'Geometry') Domgen::TypeDB.enhance(:pointm, 'graphql.scalar_type' => 'PointM') Domgen::TypeDB.enhance(:multipointm, 'graphql.scalar_type' => 'MultiPointM') Domgen::TypeDB.enhance(:linestringm, 'graphql.scalar_type' => 'LineStringM') Domgen::TypeDB.enhance(:multilinestringm, 'graphql.scalar_type' => 'MultiLineStringM') Domgen::TypeDB.enhance(:polygonm, 'graphql.scalar_type' => 'PolygonM') Domgen::TypeDB.enhance(:multipolygonm, 'graphql.scalar_type' => 'MultiPolygonM') module Domgen module Graphql module GraphqlCharacteristic def type Domgen.error("Invoked graphql.type on #{characteristic.qualified_name} when characteristic is a remote_reference") if characteristic.remote_reference? if characteristic.reference? return characteristic.referenced_entity.graphql.name elsif characteristic.enumeration? return characteristic.enumeration.graphql.name else return scalar_type end end attr_writer :scalar_type def scalar_type return @scalar_type if @scalar_type Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic is a non_standard_type") if characteristic.non_standard_type? return 'ID' if characteristic.respond_to?(:primary_key?) && characteristic.primary_key? Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic is a reference") if characteristic.reference? Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic is a remote_reference") if characteristic.remote_reference? Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic has no characteristic_type") unless characteristic.characteristic_type characteristic.characteristic_type.graphql.scalar_type end def save_scalar_type if @scalar_type data_module.repository.graphql.scalar(@scalar_type) elsif characteristic.characteristic_type data_module.repository.graphql.scalar(characteristic.characteristic_type.graphql.scalar_type) end end end end FacetManager.facet(:graphql) do |facet| facet.enhance(Repository) do include Domgen::Java::JavaClientServerApplication include Domgen::Java::BaseJavaGenerator java_artifact :endpoint, :servlet, :server, :graphql, '#{repository.name}GraphQLEndpoint' java_artifact :graphqls_servlet, :servlet, :server, :graphql, '#{repository.name}GraphQLSchemaServlet' java_artifact :abstract_endpoint, :servlet, :server, :graphql, 'Abstract#{repository.name}GraphQLEndpoint' java_artifact :abstract_schema_builder, :servlet, :server, :graphql, 'Abstract#{repository.name}GraphQLSchemaProvider' java_artifact :schema_builder, :servlet, :server, :graphql, '#{repository.name}GraphQLSchemaProvider' attr_accessor :query_description attr_accessor :mutation_description attr_accessor :subscription_description attr_writer :graphqls_schema_url def graphqls_schema_url @graphqls_schema_url || "/graphiql/#{Reality::Naming.underscore(repository.name)}.graphqls" end attr_writer :custom_endpoint def custom_endpoint? @custom_endpoint.nil? ? false : !!@custom_endpoint end attr_writer :custom_schema_builder def custom_schema_builder? @custom_schema_builder.nil? ? false : !!@custom_schema_builder end attr_writer :api_endpoint def api_endpoint @api_endpoint || (repository.jaxrs? ? "/#{repository.jaxrs.path}/graphql" : '/api/graphql') end attr_writer :graphql_keycloak_client def graphql_keycloak_client @graphql_keycloak_client || (repository.application? && !repository.application.user_experience? ? repository.keycloak.default_client.key : :api) end attr_writer :graphiql def graphiql? @graphiql_api_endpoint.nil? ? true : !!@graphiql_api_endpoint end attr_writer :graphiql_api_endpoint def graphiql_api_endpoint @graphiql_api_endpoint || '/graphql' end attr_writer :graphiql_endpoint def graphiql_endpoint @graphiql_endpoint || '/graphiql' end attr_writer :graphiql_keycloak_client def graphiql_keycloak_client @graphiql_keycloak_client || :graphiql end attr_writer :context_service_jndi_name def context_service_jndi_name @context_service_jndi_name || "#{Reality::Naming.camelize(repository.name)}/concurrent/GraphQLContextService" end def scalars @scalars ||= [] end def scalar(scalar) s = self.scalars s << scalar unless s.include?(scalar) s end def non_standard_scalars self.scalars.select {|s| !%w(Byte Short Int Long BigInteger Float BigDecimal String Boolean ID Char).include?(s)} end def pre_complete if self.repository.keycloak? if self.graphiql? client = repository.keycloak.client_by_key?(self.graphiql_keycloak_client) ? repository.keycloak.client_by_key(self.graphiql_keycloak_client) : repository.keycloak.client(self.graphiql_keycloak_client) # This client and endpoint assumes a human is using graphiql to explore the API client.protected_url_patterns << "#{self.graphiql_endpoint}/*" client.protected_url_patterns << "#{self.graphiql_api_endpoint}/*" end client = repository.keycloak.client_by_key?(self.graphql_keycloak_client) ? repository.keycloak.client_by_key(self.graphql_keycloak_client) : repository.keycloak.client(self.graphql_keycloak_client) client.protected_url_patterns << "#{api_endpoint}/*" end end end facet.enhance(DataModule) do include Domgen::Java::ImitJavaPackage attr_writer :prefix def prefix @prefix ||= data_module.name.to_s == data_module.repository.name.to_s ? '' : data_module.name.to_s end end facet.enhance(EnumerationSet) do attr_writer :name def name @name || "#{enumeration.data_module.graphql.prefix}#{enumeration.name}" end attr_writer :description def description @description || enumeration.description end end facet.enhance(EnumerationValue) do attr_writer :name def name @name || "#{value.enumeration.data_module.graphql.prefix}#{value.name}" end attr_writer :description def description @description || value.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end end facet.enhance(Query) do include Domgen::Java::BaseJavaGenerator attr_writer :name def name return @name unless @name.nil? type_inset = query.result_entity? ? query.entity.graphql.name : query.struct.graphql.name type_inset = Reality::Naming.pluralize(type_inset) if query.multiplicity == :many @name || Reality::Naming.camelize("#{query.name_prefix}#{type_inset}#{query.base_name}") end attr_writer :description def description @description || query.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end def pre_complete if !query.result_entity? && !query.result_struct? # For the time being only queries that return entities or structs are valid query.disable_facet(:graphql) elsif !query.jpa? # queries that have no jpa counterpart can not be automatically loaded so ignore them query.disable_facet(:graphql) elsif query.query_type != :select && query.dao.jpa? && :requires_new == query.dao.jpa.transaction_type && query.dao.data_module.repository.imit? # If we have replicant enabled for project and we have requires_new transaction that modifies data then # the current infrastructure will not route it through replicant so we just disable this capability query.disable_facet(:graphql) elsif query.query_type != :select # For now disable all non select querys on DAOs. # Eventually we may get around to creating a way to automatically returning values to clients # but this will need to wait until it is needed. end end end facet.enhance(QueryParameter) do include Domgen::Graphql::GraphqlCharacteristic attr_writer :name def name @name || (parameter.reference? ? Reality::Naming.camelize(parameter.referencing_link_name) : Reality::Naming.camelize(parameter.name)) end attr_writer :description def description @description || parameter.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end def pre_complete save_scalar_type end protected def data_module parameter.query.dao.data_module end def characteristic parameter end end facet.enhance(Entity) do include Domgen::Java::BaseJavaGenerator attr_writer :name def name @name || "#{entity.data_module.graphql.prefix}#{entity.name}" end attr_writer :description def description @description || entity.description end end facet.enhance(Attribute) do include Domgen::Java::ImitJavaCharacteristic include Domgen::Graphql::GraphqlCharacteristic attr_writer :name def name @name || (attribute.name.to_s.upcase == attribute.name.to_s ? attribute.name.to_s : Reality::Naming.camelize(attribute.name)) end attr_writer :description def description @description || attribute.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end def pre_complete save_scalar_type end protected def data_module attribute.entity.data_module end def characteristic attribute end end facet.enhance(InverseElement) do attr_writer :name def name @name || (inverse.name.to_s.upcase == inverse.name.to_s ? inverse.name.to_s : Reality::Naming.camelize(inverse.name)) end def traversable=(traversable) Domgen.error("traversable #{traversable} is invalid") unless inverse.class.inverse_traversable_types.include?(traversable) @traversable = traversable end def traversable? @traversable.nil? ? (self.inverse.traversable? && self.inverse.attribute.referenced_entity.graphql?) : @traversable end end facet.enhance(Struct) do include Domgen::Java::BaseJavaGenerator java_artifact :struct_resolver, :data_type, :server, :graphql, '#{struct.name}Resolver', :sub_package => 'internal' attr_writer :name def name @name || "#{struct.data_module.graphql.prefix}#{struct.name}" end end facet.enhance(StructField) do include Domgen::Java::ImitJavaCharacteristic def type if field.struct? return field.referenced_struct.graphql.name elsif field.enumeration? return field.enumeration.graphql.name else return scalar_type end end attr_writer :scalar_type def scalar_type return @scalar_type if @scalar_type Domgen.error("Invoked graphql.scalar_type on #{field.qualified_name} when field is a non_standard_type") if field.non_standard_type? Domgen.error("Invoked graphql.scalar_type on #{field.qualified_name} when field has no characteristic_type") unless field.characteristic_type field.characteristic_type.graphql.scalar_type end protected def characteristic field end end end end Add missing statement that disables facet # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Domgen::TypeDB.config_element('graphql') do attr_writer :scalar_type def scalar_type @scalar_type || (Domgen.error('scalar type not defined')) end end Domgen::TypeDB.enhance(:text, 'graphql.scalar_type' => 'String') Domgen::TypeDB.enhance(:integer, 'graphql.scalar_type' => 'Int') Domgen::TypeDB.enhance(:long, 'graphql.scalar_type' => 'Long') Domgen::TypeDB.enhance(:real, 'graphql.scalar_type' => 'Float') Domgen::TypeDB.enhance(:date, 'graphql.scalar_type' => 'Date') Domgen::TypeDB.enhance(:datetime, 'graphql.scalar_type' => 'DateTime') Domgen::TypeDB.enhance(:boolean, 'graphql.scalar_type' => 'Boolean') Domgen::TypeDB.enhance(:point, 'graphql.scalar_type' => 'Point') Domgen::TypeDB.enhance(:multipoint, 'graphql.scalar_type' => 'MultiPoint') Domgen::TypeDB.enhance(:linestring, 'graphql.scalar_type' => 'LineString') Domgen::TypeDB.enhance(:multilinestring, 'graphql.scalar_type' => 'MultiLineString') Domgen::TypeDB.enhance(:polygon, 'graphql.scalar_type' => 'Polygon') Domgen::TypeDB.enhance(:multipolygon, 'graphql.scalar_type' => 'MultiPolygon') Domgen::TypeDB.enhance(:geometry, 'graphql.scalar_type' => 'Geometry') Domgen::TypeDB.enhance(:pointm, 'graphql.scalar_type' => 'PointM') Domgen::TypeDB.enhance(:multipointm, 'graphql.scalar_type' => 'MultiPointM') Domgen::TypeDB.enhance(:linestringm, 'graphql.scalar_type' => 'LineStringM') Domgen::TypeDB.enhance(:multilinestringm, 'graphql.scalar_type' => 'MultiLineStringM') Domgen::TypeDB.enhance(:polygonm, 'graphql.scalar_type' => 'PolygonM') Domgen::TypeDB.enhance(:multipolygonm, 'graphql.scalar_type' => 'MultiPolygonM') module Domgen module Graphql module GraphqlCharacteristic def type Domgen.error("Invoked graphql.type on #{characteristic.qualified_name} when characteristic is a remote_reference") if characteristic.remote_reference? if characteristic.reference? return characteristic.referenced_entity.graphql.name elsif characteristic.enumeration? return characteristic.enumeration.graphql.name else return scalar_type end end attr_writer :scalar_type def scalar_type return @scalar_type if @scalar_type Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic is a non_standard_type") if characteristic.non_standard_type? return 'ID' if characteristic.respond_to?(:primary_key?) && characteristic.primary_key? Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic is a reference") if characteristic.reference? Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic is a remote_reference") if characteristic.remote_reference? Domgen.error("Invoked graphql.scalar_type on #{characteristic.qualified_name} when characteristic has no characteristic_type") unless characteristic.characteristic_type characteristic.characteristic_type.graphql.scalar_type end def save_scalar_type if @scalar_type data_module.repository.graphql.scalar(@scalar_type) elsif characteristic.characteristic_type data_module.repository.graphql.scalar(characteristic.characteristic_type.graphql.scalar_type) end end end end FacetManager.facet(:graphql) do |facet| facet.enhance(Repository) do include Domgen::Java::JavaClientServerApplication include Domgen::Java::BaseJavaGenerator java_artifact :endpoint, :servlet, :server, :graphql, '#{repository.name}GraphQLEndpoint' java_artifact :graphqls_servlet, :servlet, :server, :graphql, '#{repository.name}GraphQLSchemaServlet' java_artifact :abstract_endpoint, :servlet, :server, :graphql, 'Abstract#{repository.name}GraphQLEndpoint' java_artifact :abstract_schema_builder, :servlet, :server, :graphql, 'Abstract#{repository.name}GraphQLSchemaProvider' java_artifact :schema_builder, :servlet, :server, :graphql, '#{repository.name}GraphQLSchemaProvider' attr_accessor :query_description attr_accessor :mutation_description attr_accessor :subscription_description attr_writer :graphqls_schema_url def graphqls_schema_url @graphqls_schema_url || "/graphiql/#{Reality::Naming.underscore(repository.name)}.graphqls" end attr_writer :custom_endpoint def custom_endpoint? @custom_endpoint.nil? ? false : !!@custom_endpoint end attr_writer :custom_schema_builder def custom_schema_builder? @custom_schema_builder.nil? ? false : !!@custom_schema_builder end attr_writer :api_endpoint def api_endpoint @api_endpoint || (repository.jaxrs? ? "/#{repository.jaxrs.path}/graphql" : '/api/graphql') end attr_writer :graphql_keycloak_client def graphql_keycloak_client @graphql_keycloak_client || (repository.application? && !repository.application.user_experience? ? repository.keycloak.default_client.key : :api) end attr_writer :graphiql def graphiql? @graphiql_api_endpoint.nil? ? true : !!@graphiql_api_endpoint end attr_writer :graphiql_api_endpoint def graphiql_api_endpoint @graphiql_api_endpoint || '/graphql' end attr_writer :graphiql_endpoint def graphiql_endpoint @graphiql_endpoint || '/graphiql' end attr_writer :graphiql_keycloak_client def graphiql_keycloak_client @graphiql_keycloak_client || :graphiql end attr_writer :context_service_jndi_name def context_service_jndi_name @context_service_jndi_name || "#{Reality::Naming.camelize(repository.name)}/concurrent/GraphQLContextService" end def scalars @scalars ||= [] end def scalar(scalar) s = self.scalars s << scalar unless s.include?(scalar) s end def non_standard_scalars self.scalars.select {|s| !%w(Byte Short Int Long BigInteger Float BigDecimal String Boolean ID Char).include?(s)} end def pre_complete if self.repository.keycloak? if self.graphiql? client = repository.keycloak.client_by_key?(self.graphiql_keycloak_client) ? repository.keycloak.client_by_key(self.graphiql_keycloak_client) : repository.keycloak.client(self.graphiql_keycloak_client) # This client and endpoint assumes a human is using graphiql to explore the API client.protected_url_patterns << "#{self.graphiql_endpoint}/*" client.protected_url_patterns << "#{self.graphiql_api_endpoint}/*" end client = repository.keycloak.client_by_key?(self.graphql_keycloak_client) ? repository.keycloak.client_by_key(self.graphql_keycloak_client) : repository.keycloak.client(self.graphql_keycloak_client) client.protected_url_patterns << "#{api_endpoint}/*" end end end facet.enhance(DataModule) do include Domgen::Java::ImitJavaPackage attr_writer :prefix def prefix @prefix ||= data_module.name.to_s == data_module.repository.name.to_s ? '' : data_module.name.to_s end end facet.enhance(EnumerationSet) do attr_writer :name def name @name || "#{enumeration.data_module.graphql.prefix}#{enumeration.name}" end attr_writer :description def description @description || enumeration.description end end facet.enhance(EnumerationValue) do attr_writer :name def name @name || "#{value.enumeration.data_module.graphql.prefix}#{value.name}" end attr_writer :description def description @description || value.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end end facet.enhance(Query) do include Domgen::Java::BaseJavaGenerator attr_writer :name def name return @name unless @name.nil? type_inset = query.result_entity? ? query.entity.graphql.name : query.struct.graphql.name type_inset = Reality::Naming.pluralize(type_inset) if query.multiplicity == :many @name || Reality::Naming.camelize("#{query.name_prefix}#{type_inset}#{query.base_name}") end attr_writer :description def description @description || query.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end def pre_complete if !query.result_entity? && !query.result_struct? # For the time being only queries that return entities or structs are valid query.disable_facet(:graphql) elsif !query.jpa? # queries that have no jpa counterpart can not be automatically loaded so ignore them query.disable_facet(:graphql) elsif query.query_type != :select && query.dao.jpa? && :requires_new == query.dao.jpa.transaction_type && query.dao.data_module.repository.imit? # If we have replicant enabled for project and we have requires_new transaction that modifies data then # the current infrastructure will not route it through replicant so we just disable this capability query.disable_facet(:graphql) elsif query.query_type != :select # For now disable all non select querys on DAOs. # Eventually we may get around to creating a way to automatically returning values to clients # but this will need to wait until it is needed. query.disable_facet(:graphql) end end end facet.enhance(QueryParameter) do include Domgen::Graphql::GraphqlCharacteristic attr_writer :name def name @name || (parameter.reference? ? Reality::Naming.camelize(parameter.referencing_link_name) : Reality::Naming.camelize(parameter.name)) end attr_writer :description def description @description || parameter.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end def pre_complete save_scalar_type end protected def data_module parameter.query.dao.data_module end def characteristic parameter end end facet.enhance(Entity) do include Domgen::Java::BaseJavaGenerator attr_writer :name def name @name || "#{entity.data_module.graphql.prefix}#{entity.name}" end attr_writer :description def description @description || entity.description end end facet.enhance(Attribute) do include Domgen::Java::ImitJavaCharacteristic include Domgen::Graphql::GraphqlCharacteristic attr_writer :name def name @name || (attribute.name.to_s.upcase == attribute.name.to_s ? attribute.name.to_s : Reality::Naming.camelize(attribute.name)) end attr_writer :description def description @description || attribute.description end attr_accessor :deprecation_reason def deprecated? !@deprecation_reason.nil? end def pre_complete save_scalar_type end protected def data_module attribute.entity.data_module end def characteristic attribute end end facet.enhance(InverseElement) do attr_writer :name def name @name || (inverse.name.to_s.upcase == inverse.name.to_s ? inverse.name.to_s : Reality::Naming.camelize(inverse.name)) end def traversable=(traversable) Domgen.error("traversable #{traversable} is invalid") unless inverse.class.inverse_traversable_types.include?(traversable) @traversable = traversable end def traversable? @traversable.nil? ? (self.inverse.traversable? && self.inverse.attribute.referenced_entity.graphql?) : @traversable end end facet.enhance(Struct) do include Domgen::Java::BaseJavaGenerator java_artifact :struct_resolver, :data_type, :server, :graphql, '#{struct.name}Resolver', :sub_package => 'internal' attr_writer :name def name @name || "#{struct.data_module.graphql.prefix}#{struct.name}" end end facet.enhance(StructField) do include Domgen::Java::ImitJavaCharacteristic def type if field.struct? return field.referenced_struct.graphql.name elsif field.enumeration? return field.enumeration.graphql.name else return scalar_type end end attr_writer :scalar_type def scalar_type return @scalar_type if @scalar_type Domgen.error("Invoked graphql.scalar_type on #{field.qualified_name} when field is a non_standard_type") if field.non_standard_type? Domgen.error("Invoked graphql.scalar_type on #{field.qualified_name} when field has no characteristic_type") unless field.characteristic_type field.characteristic_type.graphql.scalar_type end protected def characteristic field end end end end
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module Domgen module GwtRpc class GwtService < Domgen.ParentedElement(:service) def use_autobean_structs? service.data_module.facet_enabled?(:auto_bean) end attr_writer :xsrf_protected def xsrf_protected? @xsrf_protected.nil? ? false : @xsrf_protected end attr_writer :facade_service_name def facade_service_name @facade_service_name || service.name end def qualified_facade_service_name "#{service.data_module.gwt_rpc.client_service_package}.#{facade_service_name}" end def proxy_name "#{facade_service_name}Proxy" end def qualified_proxy_name "#{qualified_facade_service_name}Proxy" end attr_writer :rpc_service_name def rpc_service_name @rpc_service_name || "Gwt#{service.name}" end def qualified_service_name "#{service.data_module.gwt_rpc.shared_service_package}.#{rpc_service_name}" end def async_rpc_service_name "#{rpc_service_name}Async" end def qualified_async_rpc_service_name "#{service.data_module.gwt_rpc.shared_service_package}.#{async_rpc_service_name}" end def servlet_name @servlet_name || "#{rpc_service_name}Servlet" end def qualified_servlet_name "#{service.data_module.gwt_rpc.server_servlet_package}.#{servlet_name}" end end class GwtMethod < Domgen.ParentedElement(:method) def name Domgen::Naming.camelize(method.name) end attr_writer :cancelable def cancelable? @cancelable.nil? ? false : @cancelable end end class GwtModule < Domgen.ParentedElement(:data_module) include Domgen::Java::ClientServerJavaPackage attr_writer :server_servlet_package def server_servlet_package @server_servlet_package || "#{data_module.repository.gwt_rpc.server_servlet_package}.#{package_key}" end protected def facet_key :gwt end end class GwtReturn < Domgen.ParentedElement(:result) include Domgen::Java::ImitJavaCharacteristic protected def characteristic result end end class GwtParameter < Domgen.ParentedElement(:parameter) include Domgen::Java::ImitJavaCharacteristic # Does the parameter come from the environment? def environmental? !!@environment_key end attr_reader :environment_key def environment_key=(environment_key) raise "Unknown environment_key #{environment_key}" unless self.class.environment_key_set.include?(environment_key) @environment_key = environment_key end def environment_value raise "environment_value invoked for non-environmental value" unless environmental? self.class.environment_key_set[environment_key] end def self.environment_key_set { "request:session:id" => 'getThreadLocalRequest().getSession(true).getId()', "request:permutation-strong-name" => 'getPermutationStrongName()', "request:locale" => 'getThreadLocalRequest().getLocale().toString()', "request:remote-host" => 'getThreadLocalRequest().getRemoteHost()', "request:remote-address" => 'getThreadLocalRequest().getRemoteAddr()', "request:remote-port" => 'getThreadLocalRequest().getRemotePort()', "request:remote-user" => 'getThreadLocalRequest().getRemoteUser()', } end protected def characteristic parameter end end class GwtException < Domgen.ParentedElement(:exception) def name exception.name.to_s =~ /Exception$/ ? exception.name.to_s : "#{exception.name}Exception" end def qualified_name "#{exception.data_module.gwt_rpc.shared_data_type_package}.#{name}" end end class GwtApplication < Domgen.ParentedElement(:repository) include Domgen::Java::JavaClientServerApplication attr_writer :module_name def module_name @module_name || Domgen::Naming.underscore(repository.name) end attr_writer :rpc_services_module_name def rpc_services_module_name @rpc_services_module_name || "#{repository.name}GwtRpcServicesModule" end def qualified_rpc_services_module_name "#{client_ioc_package}.#{rpc_services_module_name}" end attr_writer :mock_services_module_name def mock_services_module_name @mock_services_module_name || "#{repository.name}MockGwtServicesModule" end def qualified_mock_services_module_name "#{client_ioc_package}.#{mock_services_module_name}" end attr_writer :client_ioc_package def client_ioc_package @client_ioc_package || "#{client_package}.ioc" end attr_writer :server_servlet_package def server_servlet_package @server_servlet_package || "#{server_package}.servlet" end attr_writer :services_module_name def services_module_name @services_module_name || "#{repository.name}GwtServicesModule" end def qualified_services_module_name "#{client_ioc_package}.#{services_module_name}" end protected def facet_key :gwt end end end FacetManager.define_facet(:gwt_rpc, { Service => Domgen::GwtRpc::GwtService, Method => Domgen::GwtRpc::GwtMethod, Parameter => Domgen::GwtRpc::GwtParameter, Result => Domgen::GwtRpc::GwtReturn, Exception => Domgen::GwtRpc::GwtException, DataModule => Domgen::GwtRpc::GwtModule, Repository => Domgen::GwtRpc::GwtApplication }, [:gwt]) end Prefix the name of the gwt-rpc proxy services with GwtRpc if the imit facet is enabled to avoid collisions # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module Domgen module GwtRpc class GwtService < Domgen.ParentedElement(:service) def use_autobean_structs? service.data_module.facet_enabled?(:auto_bean) end attr_writer :xsrf_protected def xsrf_protected? @xsrf_protected.nil? ? false : @xsrf_protected end attr_writer :facade_service_name def facade_service_name @facade_service_name || service.imit? ? "GwtRpc#{service.name}" : service.name end def qualified_facade_service_name "#{service.data_module.gwt_rpc.client_service_package}.#{facade_service_name}" end def proxy_name "#{facade_service_name}Proxy" end def qualified_proxy_name "#{qualified_facade_service_name}Proxy" end attr_writer :rpc_service_name def rpc_service_name @rpc_service_name || "Gwt#{service.name}" end def qualified_service_name "#{service.data_module.gwt_rpc.shared_service_package}.#{rpc_service_name}" end def async_rpc_service_name "#{rpc_service_name}Async" end def qualified_async_rpc_service_name "#{service.data_module.gwt_rpc.shared_service_package}.#{async_rpc_service_name}" end def servlet_name @servlet_name || "#{rpc_service_name}Servlet" end def qualified_servlet_name "#{service.data_module.gwt_rpc.server_servlet_package}.#{servlet_name}" end end class GwtMethod < Domgen.ParentedElement(:method) def name Domgen::Naming.camelize(method.name) end attr_writer :cancelable def cancelable? @cancelable.nil? ? false : @cancelable end end class GwtModule < Domgen.ParentedElement(:data_module) include Domgen::Java::ClientServerJavaPackage attr_writer :server_servlet_package def server_servlet_package @server_servlet_package || "#{data_module.repository.gwt_rpc.server_servlet_package}.#{package_key}" end protected def facet_key :gwt end end class GwtReturn < Domgen.ParentedElement(:result) include Domgen::Java::ImitJavaCharacteristic protected def characteristic result end end class GwtParameter < Domgen.ParentedElement(:parameter) include Domgen::Java::ImitJavaCharacteristic # Does the parameter come from the environment? def environmental? !!@environment_key end attr_reader :environment_key def environment_key=(environment_key) raise "Unknown environment_key #{environment_key}" unless self.class.environment_key_set.include?(environment_key) @environment_key = environment_key end def environment_value raise "environment_value invoked for non-environmental value" unless environmental? self.class.environment_key_set[environment_key] end def self.environment_key_set { "request:session:id" => 'getThreadLocalRequest().getSession(true).getId()', "request:permutation-strong-name" => 'getPermutationStrongName()', "request:locale" => 'getThreadLocalRequest().getLocale().toString()', "request:remote-host" => 'getThreadLocalRequest().getRemoteHost()', "request:remote-address" => 'getThreadLocalRequest().getRemoteAddr()', "request:remote-port" => 'getThreadLocalRequest().getRemotePort()', "request:remote-user" => 'getThreadLocalRequest().getRemoteUser()', } end protected def characteristic parameter end end class GwtException < Domgen.ParentedElement(:exception) def name exception.name.to_s =~ /Exception$/ ? exception.name.to_s : "#{exception.name}Exception" end def qualified_name "#{exception.data_module.gwt_rpc.shared_data_type_package}.#{name}" end end class GwtApplication < Domgen.ParentedElement(:repository) include Domgen::Java::JavaClientServerApplication attr_writer :module_name def module_name @module_name || Domgen::Naming.underscore(repository.name) end attr_writer :rpc_services_module_name def rpc_services_module_name @rpc_services_module_name || "#{repository.name}GwtRpcServicesModule" end def qualified_rpc_services_module_name "#{client_ioc_package}.#{rpc_services_module_name}" end attr_writer :mock_services_module_name def mock_services_module_name @mock_services_module_name || "#{repository.name}MockGwtServicesModule" end def qualified_mock_services_module_name "#{client_ioc_package}.#{mock_services_module_name}" end attr_writer :client_ioc_package def client_ioc_package @client_ioc_package || "#{client_package}.ioc" end attr_writer :server_servlet_package def server_servlet_package @server_servlet_package || "#{server_package}.servlet" end attr_writer :services_module_name def services_module_name @services_module_name || "#{repository.name}GwtServicesModule" end def qualified_services_module_name "#{client_ioc_package}.#{services_module_name}" end protected def facet_key :gwt end end end FacetManager.define_facet(:gwt_rpc, { Service => Domgen::GwtRpc::GwtService, Method => Domgen::GwtRpc::GwtMethod, Parameter => Domgen::GwtRpc::GwtParameter, Result => Domgen::GwtRpc::GwtReturn, Exception => Domgen::GwtRpc::GwtException, DataModule => Domgen::GwtRpc::GwtModule, Repository => Domgen::GwtRpc::GwtApplication }, [:gwt]) end
require "ejabberd_rest/errors" require "securerandom" module EjabberdRest class Client attr_accessor :debug, :http_adapter, :mod_rest_url DEFAULT_MOD_REST_URL = "http://localhost:5285" def initialize(attributes={}) @mod_rest_url = attributes[:url] || DEFAULT_MOD_REST_URL @http_adapter = attributes[:http_adapter] || :net_http @debug = attributes[:debug] || false end def add_user(username, domain, password) rbody = post("/rest", body: "register #{username} #{domain} #{password}") if rbody.include?("successfully registered") true else if rbody.include?("already registered") raise Error::UserAlreadyRegistered else false end end end def delete_user(username, domain) post("/rest", body: "unregister #{username} #{domain}") end def post_stanza(stanza) post("/rest", body: stanza) end def pubsub_subscribe(jid, host, node) stanza = "<iq type='set' from='#{jid}' to='#{host}' id='#{SecureRandom.uuid}'>" stanza << "<pubsub xmlns='http://jabber.org/protocol/pubsub'>" stanza << "<subscribe node='#{node}' jid='#{jid}' />" stanza << "</pubsub>" stanza << "</iq>" post_stanza(stanza) end private def connection connection = Faraday.new(@mod_rest_url) do |builder| builder.request :url_encoded builder.response :logger if @debug builder.adapter @http_adapter end end def post(path, options) response = connection.send(:post, path) do |request| request.body = options[:body] if options[:body] end response.body end end end Add PubSub publish item require "ejabberd_rest/errors" require "securerandom" module EjabberdRest class Client attr_accessor :debug, :http_adapter, :mod_rest_url DEFAULT_MOD_REST_URL = "http://localhost:5285" def initialize(attributes={}) @mod_rest_url = attributes[:url] || DEFAULT_MOD_REST_URL @http_adapter = attributes[:http_adapter] || :net_http @debug = attributes[:debug] || false end def add_user(username, domain, password) rbody = post("/rest", body: "register #{username} #{domain} #{password}") if rbody.include?("successfully registered") true else if rbody.include?("already registered") raise Error::UserAlreadyRegistered else false end end end def delete_user(username, domain) post("/rest", body: "unregister #{username} #{domain}") end def post_stanza(stanza) post("/rest", body: stanza) end def pubsub_publish(from_jid, host, node, message) stanza = "<iq type='set' from='#{from_jid}' to='#{host}' id='#{SecureRandom.uuid}'>" stanza << " <pubsub xmlns='http://jabber.org/protocol/pubsub'>" stanza << " <publish node='#{node}'>" stanza << " <item id='#{SecureRandom.uuid}'>" stanza << " #{message}" stanza << " </item>" stanza << " </publish>" stanza << " </pubsub>" stanza << "</iq>" post_stanza(stanza) end def pubsub_subscribe(jid, host, node) stanza = "<iq type='set' from='#{jid}' to='#{host}' id='#{SecureRandom.uuid}'>" stanza << "<pubsub xmlns='http://jabber.org/protocol/pubsub'>" stanza << "<subscribe node='#{node}' jid='#{jid}' />" stanza << "</pubsub>" stanza << "</iq>" post_stanza(stanza) end private def connection connection = Faraday.new(@mod_rest_url) do |builder| builder.request :url_encoded builder.response :logger if @debug builder.adapter @http_adapter end end def post(path, options) response = connection.send(:post, path) do |request| request.body = options[:body] if options[:body] end response.body end end end
Capistrano::Configuration.instance.load do _cset(:eye_default_hooks) { true } _cset(:eye_config) { "config/eye.yml" } _cset(:eye_bin) { "bundle exec eye-patch" } _cset(:eye_roles) { :app } if fetch(:eye_default_hooks) after "deploy:stop", "eye:stop" after "deploy:start", "eye:load_config" before "deploy:restart", "eye:restart" end namespace :eye do desc "Start eye with the desired configuration file" task :load_config, roles: -> { fetch(:eye_roles) } do run "cd #{current_path} && #{fetch(:eye_bin)} quit && #{fetch(:eye_bin)} load #{fetch(:eye_config)}" end desc "Stop eye and all of its monitored tasks" task :stop, roles: -> { fetch(:eye_roles) } do run "cd #{current_path} && #{fetch(:eye_bin)} stop all && #{fetch(:eye_bin)} quit" end desc "Restart all tasks monitored by eye" task :restart, roles: -> { fetch(:eye_roles) } do run "cd #{current_path} && #{fetch(:eye_bin)} restart all" end end before "eye:restart", "eye:load_config" end fix 'Line is too long.' error Capistrano::Configuration.instance.load do _cset(:eye_default_hooks) { true } _cset(:eye_config) { "config/eye.yml" } _cset(:eye_bin) { "bundle exec eye-patch" } _cset(:eye_roles) { :app } if fetch(:eye_default_hooks) after "deploy:stop", "eye:stop" after "deploy:start", "eye:load_config" before "deploy:restart", "eye:restart" end namespace :eye do desc "Start eye with the desired configuration file" task :load_config, roles: -> { fetch(:eye_roles) } do run "cd #{current_path} && #{fetch(:eye_bin)} quit" run "cd #{current_path} && #{fetch(:eye_bin)} load #{fetch(:eye_config)}" end desc "Stop eye and all of its monitored tasks" task :stop, roles: -> { fetch(:eye_roles) } do run "cd #{current_path} && #{fetch(:eye_bin)} stop all" run "cd #{current_path} && #{fetch(:eye_bin)} quit" end desc "Restart all tasks monitored by eye" task :restart, roles: -> { fetch(:eye_roles) } do run "cd #{current_path} && #{fetch(:eye_bin)} restart all" end end before "eye:restart", "eye:load_config" end
# frozen_string_literal: true require 'fastly_nsq/http' class FastlyNsq::Http::Nsqd extend Forwardable def_delegator :client, :get def_delegator :client, :post BASE_NSQD_URL = ENV.fetch 'NSQD_URL', "https://#{ENV.fetch('NSQD_HTTPS_ADDRESS', '')}" def self.ping new(request_uri: '/ping').get end def self.info new(request_uri: '/info').get end def self.stats(topic: nil, format: 'json', channel: nil) # format can be 'text' or 'json' # topic and channel are for filtering params = { format: 'json' } params[:topic] = topic if topic params[:channel] = channel if channel new(request_uri: '/stats').get(params) end def self.pub(topic:, defer: nil, message:) # defer is ms delay to apply to message delivery params = { topic: topic } params[:defer] = defer if defer new(request_uri: '/pub').post(params, message) end def self.mpub(topic:, binary: 'false', message:) # \n seperate messages in message params = { topic: topic, binary: binary} new(request_uri: '/mpub').post({format: 'json'}, message) end def self.config # TODO end def self.topic_create(topic:) new(request_uri: '/topic/create').post(topic: topic) end def self.topic_delete(topic:) new(request_uri: '/topic/delete').post(topic: topic) end def self.topic_empty(topic:) new(request_uri: '/topic/empty').post(topic: topic) end def self.topic_pause(topic:) new(request_uri: '/topic/pause').post(topic: topic) end def self.topic_unpause(topic:) new(request_uri: '/topic/unpause').post(topic: topic) end def self.channel_create(topic:, channel:) new(request_uri: '/channel/create').post(topic: topic, channel: channel) end def self.channel_delete(topic:, channel:) new(request_uri: '/channel/delete').post(topic: topic, channel: channel) end def self.channel_empty(topic:, channel:) new(request_uri: '/channel/empty').post(topic: topic, channel: channel) end def self.channel_pause(topic:, channel:) new(request_uri: '/channel/pause').post(topic: topic, channel: channel) end def self.channel_unpause(topic:, channel:) new(request_uri: '/channel/unpause').post(topic: topic, channel: channel) end def initialize(request_uri:, base_uri: nil, requester: nil) @base_uri = base_uri || BASE_NSQD_URL @requester = requester || FastlyNsq::Http uri = URI.join(@base_uri, request_uri) @client = @requester.new(uri: uri) @client.use_ssl end private attr_accessor :client end add get of config/nsqlookupd_tcp_addresses # frozen_string_literal: true require 'fastly_nsq/http' class FastlyNsq::Http::Nsqd extend Forwardable def_delegator :client, :get def_delegator :client, :post BASE_NSQD_URL = ENV.fetch 'NSQD_URL', "https://#{ENV.fetch('NSQD_HTTPS_ADDRESS', '')}" def self.ping new(request_uri: '/ping').get end def self.info new(request_uri: '/info').get end def self.stats(topic: nil, format: 'json', channel: nil) # format can be 'text' or 'json' # topic and channel are for filtering params = { format: 'json' } params[:topic] = topic if topic params[:channel] = channel if channel new(request_uri: '/stats').get(params) end def self.pub(topic:, defer: nil, message:) # defer is ms delay to apply to message delivery params = { topic: topic } params[:defer] = defer if defer new(request_uri: '/pub').post(params, message) end def self.mpub(topic:, binary: 'false', message:) # \n seperate messages in message params = { topic: topic, binary: binary} new(request_uri: '/mpub').post({format: 'json'}, message) end def self.config_nsqlookupd_tcp_addresses new(request_uri: '/config/nsqlookupd_tcp_addresses').get end def self.topic_create(topic:) new(request_uri: '/topic/create').post(topic: topic) end def self.topic_delete(topic:) new(request_uri: '/topic/delete').post(topic: topic) end def self.topic_empty(topic:) new(request_uri: '/topic/empty').post(topic: topic) end def self.topic_pause(topic:) new(request_uri: '/topic/pause').post(topic: topic) end def self.topic_unpause(topic:) new(request_uri: '/topic/unpause').post(topic: topic) end def self.channel_create(topic:, channel:) new(request_uri: '/channel/create').post(topic: topic, channel: channel) end def self.channel_delete(topic:, channel:) new(request_uri: '/channel/delete').post(topic: topic, channel: channel) end def self.channel_empty(topic:, channel:) new(request_uri: '/channel/empty').post(topic: topic, channel: channel) end def self.channel_pause(topic:, channel:) new(request_uri: '/channel/pause').post(topic: topic, channel: channel) end def self.channel_unpause(topic:, channel:) new(request_uri: '/channel/unpause').post(topic: topic, channel: channel) end def initialize(request_uri:, base_uri: nil, requester: nil) @base_uri = base_uri || BASE_NSQD_URL @requester = requester || FastlyNsq::Http uri = URI.join(@base_uri, request_uri) @client = @requester.new(uri: uri) @client.use_ssl end private attr_accessor :client end
# Fat Free CRM # Copyright (C) 2008-2011 by Michael Dvorkin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http:#www.gnu.org/licenses/>. #------------------------------------------------------------------------------ require "net/imap" require "mail" include Rails.application.routes.url_helpers module FatFreeCRM class Dropbox ASSETS = [ Account, Contact, Lead ].freeze KEYWORDS = %w(account campaign contact lead opportunity).freeze #-------------------------------------------------------------------------------------- def initialize @settings = Setting.email_dropbox @archived, @discarded = 0, 0 end #-------------------------------------------------------------------------------------- def run log "connecting to #{@settings[:server]}..." connect! or return nil log "logged in to #{@settings[:server]}..." with_new_emails do |uid, email| process(uid, email) archive(uid) end ensure log "messages processed: #{@archived + @discarded}, archived: #{@archived}, discarded: #{@discarded}." disconnect! end # Setup imap folders in settings. #-------------------------------------------------------------------------------------- def setup log "connecting to #{@settings[:server]}..." connect!(:setup => true) or return nil log "logged in to #{@settings[:server]}, checking folders..." folders = [ @settings[:scan_folder] ] folders << @settings[:move_to_folder] unless @settings[:move_to_folder].blank? folders << @settings[:move_invalid_to_folder] unless @settings[:move_invalid_to_folder].blank? # Open (or create) destination folder in read-write mode. folders.each do |folder| if @imap.list("", folder) log "folder #{folder} OK" else log "folder #{folder} missing, creating..." @imap.create(folder) end end rescue => e $stderr.puts "setup error #{e.inspect}" ensure disconnect! end private #-------------------------------------------------------------------------------------- def with_new_emails @imap.uid_search(['NOT', 'SEEN']).each do |uid| begin email = Mail.new(@imap.uid_fetch(uid, 'RFC822').first.attr['RFC822']) log "fetched new message...", email if is_valid?(email) && sent_from_known_user?(email) yield(uid, email) else discard(uid) end rescue Exception => e if ["test", "development"].include?(Rails.env) $stderr.puts e $stderr.puts e.backtrace end log "error processing email: #{e.inspect}", email discard(uid) end end end # Email processing pipeline: each steps gets executed if previous one returns false. #-------------------------------------------------------------------------------------- def process(uid, email) with_explicit_keyword(email) do |keyword, name| data = {"Type" => keyword, "Name" => name} find_or_create_and_attach(email, data) end and return with_recipients(email) do |recipient| find_and_attach(email, recipient) end and return with_forwarded_recipient(email) do |recipient| find_and_attach(email, recipient) end and return with_recipients(email) do |recipient| create_and_attach(email, recipient) end and return with_forwarded_recipient(email) do |recipient| create_and_attach(email, recipient) end end # Connects to the imap server with the loaded settings from settings.yml #------------------------------------------------------------------------------ def connect!(options = {}) @imap = Net::IMAP.new(@settings[:server], @settings[:port], @settings[:ssl]) @imap.login(@settings[:user], @settings[:password]) @imap.select(@settings[:scan_folder]) unless options[:setup] @imap rescue Exception => e $stderr.puts "Dropbox: could not login to the IMAP server: #{e.inspect}" unless Rails.env == "test" nil end #------------------------------------------------------------------------------ def disconnect! if @imap @imap.logout unless @imap.disconnected? @imap.disconnect rescue nil end end end # Discard message (not valid) action based on settings from settings.yml #------------------------------------------------------------------------------ def discard(uid) if @settings[:move_invalid_to_folder] @imap.uid_copy(uid, @settings[:move_invalid_to_folder]) end @imap.uid_store(uid, "+FLAGS", [:Deleted]) @discarded += 1 end # Archive message (valid) action based on settings from settings.yml #------------------------------------------------------------------------------ def archive(uid) if @settings[:move_to_folder] @imap.uid_copy(uid, @settings[:move_to_folder]) end @imap.uid_store(uid, "+FLAGS", [:Seen]) @archived += 1 end #------------------------------------------------------------------------------ def is_valid?(email) valid = email.content_type != "text/html" log("not a text message, discarding") unless valid valid end #------------------------------------------------------------------------------ def sent_from_known_user?(email) email_address = email.from.first known = !find_sender(email_address).nil? log("sent by unknown user #{email_address}, discarding") unless known known end #------------------------------------------------------------------------------ def find_sender(email_address) @sender = User.where('lower(email) = ? AND suspended_at IS NULL', email_address.downcase).first end # Checks the email to detect keyword on the first line. #-------------------------------------------------------------------------------------- def with_explicit_keyword(email) first_line = plain_text_body(email).split("\n").first if first_line =~ %r|^[\./]?(#{KEYWORDS.join('|')})\s(.+)$|i yield $1.capitalize, $2.strip end end # Checks the email to detect assets on to/bcc addresses #-------------------------------------------------------------------------------------- def with_recipients(email, options = {}) recipients = [] recipients += email.to_addrs unless email.to.blank? recipients += email.cc_addrs unless email.cc.blank? recipients -= [ @settings[:address] ] recipients.inject(false) { |attached, recipient| attached ||= yield recipient } end # Checks the email to detect valid email address in body (first email), detect forwarded emails #---------------------------------------------------------------------------------------- def with_forwarded_recipient(email, options = {}) if plain_text_body(email) =~ /\b([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})\b/ yield $1 end end # Process pipe_separated_data or explicit keyword. #-------------------------------------------------------------------------------------- def find_or_create_and_attach(email, data) klass = data["Type"].constantize if data["Email"] && klass.new.respond_to?(:email) conditions = ['email = ?', data["Email"]] elsif klass.new.respond_to?(:first_name) first_name, *last_name = data["Name"].split conditions = if last_name.empty? # Treat single name as last name. [ 'last_name LIKE ?', "%#{first_name}" ] else [ 'first_name LIKE ? AND last_name LIKE ?', "%#{first_name}", "%#{last_name.join(' ')}" ] end else conditions = ['name LIKE ?', "%#{data["Name"]}%"] end # Find the asset from deduced conditions if asset = klass.where(conditions).first if sender_has_permissions_for?(asset) attach(email, asset, :strip_first_line) else log "Sender does not have permissions to attach email to #{data["Type"]} #{data["Email"]} <#{data["Name"]}>" end else log "#{data["Type"]} #{data["Email"]} <#{data["Name"]}> not found, creating new one..." asset = klass.create!(default_values(klass, data)) attach(email, asset, :strip_first_line) end true end #---------------------------------------------------------------------------------------- def find_and_attach(email, recipient) attached = false ASSETS.each do |klass| asset = klass.find_by_email(recipient) # Leads and Contacts have an alt_email: try it if lookup by primary email has failed. if !asset && klass.column_names.include?("alt_email") asset = klass.find_by_alt_email(recipient) end if asset && sender_has_permissions_for?(asset) attach(email, asset) attached = true end end attached end #---------------------------------------------------------------------------------------- def create_and_attach(email, recipient) contact = Contact.create!(default_values_for_contact(email, recipient)) attach(email, contact) end #---------------------------------------------------------------------------------------- def attach(email, asset, strip_first_line=false) to = email.to.blank? ? nil : email.to.join(", ") cc = email.cc.blank? ? nil : email.cc.join(", ") email_body = if strip_first_line plain_text_body(email).split("\n")[1..-1].join("\n").strip else plain_text_body(email) end Email.create( :imap_message_id => email.message_id, :user => @sender, :mediator => asset, :sent_from => email.from.first, :sent_to => to, :cc => cc, :subject => email.subject, :body => email_body, :received_at => email.date, :sent_at => email.date ) asset.touch if asset.is_a?(Lead) && asset.status == "new" asset.update_attribute(:status, "contacted") end if @settings[:attach_to_account] && asset.respond_to?(:account) && asset.account Email.create( :imap_message_id => email.message_id, :user => @sender, :mediator => asset.account, :sent_from => email.from.first, :sent_to => to, :cc => cc, :subject => email.subject, :body => email_body, :received_at => email.date, :sent_at => email.date ) asset.account.touch end end #---------------------------------------------------------------------------------------- def default_values(klass, data) data = data.dup keyword = data.delete("Type").capitalize defaults = { :user => @sender, :access => default_access } case keyword when "Account", "Campaign", "Opportunity" defaults[:status] = "planned" if keyword == "Campaign" # TODO: I18n defaults[:stage] = "prospecting" if keyword == "Opportunity" # TODO: I18n when "Contact", "Lead" first_name, *last_name = data.delete("Name").split(' ') defaults[:first_name] = first_name defaults[:last_name] = (last_name.any? ? last_name.join(" ") : "(unknown)") defaults[:status] = "contacted" if keyword == "Lead" # TODO: I18n end data.each do |key, value| key = key.downcase defaults[key.to_sym] = value if klass.new.respond_to?(key + '=') end defaults end #---------------------------------------------------------------------------------------- def default_values_for_contact(email, recipient) recipient_local, recipient_domain = recipient.split('@') defaults = { :user => @sender, :first_name => recipient_local.capitalize, :last_name => "(unknown)", :email => recipient, :access => default_access } # Search for domain name in Accounts. account = Account.where('email like ?', "%#{recipient_domain}").first if account log "asociating new contact #{recipient} with the account #{account.name}" defaults[:account] = account else log "creating new account #{recipient_domain.capitalize} for the contact #{recipient}" defaults[:account] = Account.create!( :user => @sender, :email => recipient, :name => recipient_domain.capitalize, :access => default_access ) end defaults end # If default access is 'Shared' then change it to 'Private' because we don't know how # to choose anyone to share it with here. #-------------------------------------------------------------------------------------- def default_access Setting.default_access == "Shared" ? 'Private' : Setting.default_access end #-------------------------------------------------------------------------------------- def sender_has_permissions_for?(asset) return true if asset.access == "Public" return true if asset.user_id == @sender.id || asset.assigned_to == @sender.id return true if asset.access == "Shared" && Permission.where('user_id = ? AND asset_id = ? AND asset_type = ?', @sender.id, asset.id, asset.class.to_s).count > 0 false end # Notify users with the results of the operations (feedback from dropbox) #-------------------------------------------------------------------------------------- def notify(email, mediator_links) ack_email = Notifier.create_dropbox_ack_notification(@sender, @settings[:address], email, mediator_links) Notifier.deliver(ack_email) end # Centralized logging. #-------------------------------------------------------------------------------------- def log(message, email = nil) return if Rails.env == "test" puts "Dropbox: #{message}" puts " From: #{email.from}, Subject: #{email.subject} (#{email.message_id})" if email end # Returns the plain-text version of an email, or strips html tags # if only html is present. #-------------------------------------------------------------------------------------- def plain_text_body(email) parts = email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten if parts.empty? parts << email end plain_text_part = parts.detect {|p| p.content_type.include?('text/plain')} if plain_text_part.nil? # no text/plain part found, assuming html-only email # strip html tags and remove doctype directive plain_text_body = email.body.to_s.gsub(/<\/?[^>]*>/, "") plain_text_body.gsub! %r{^<!DOCTYPE .*$}, '' else plain_text_body = plain_text_part.body.to_s end plain_text_body.strip.gsub("\r\n", "\n") end end # class Dropbox end # module FatFreeCRM Dropbox should also the alt_email for the originating user # Fat Free CRM # Copyright (C) 2008-2011 by Michael Dvorkin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http:#www.gnu.org/licenses/>. #------------------------------------------------------------------------------ require "net/imap" require "mail" include Rails.application.routes.url_helpers module FatFreeCRM class Dropbox ASSETS = [ Account, Contact, Lead ].freeze KEYWORDS = %w(account campaign contact lead opportunity).freeze #-------------------------------------------------------------------------------------- def initialize @settings = Setting.email_dropbox @archived, @discarded = 0, 0 end #-------------------------------------------------------------------------------------- def run log "connecting to #{@settings[:server]}..." connect! or return nil log "logged in to #{@settings[:server]}..." with_new_emails do |uid, email| process(uid, email) archive(uid) end ensure log "messages processed: #{@archived + @discarded}, archived: #{@archived}, discarded: #{@discarded}." disconnect! end # Setup imap folders in settings. #-------------------------------------------------------------------------------------- def setup log "connecting to #{@settings[:server]}..." connect!(:setup => true) or return nil log "logged in to #{@settings[:server]}, checking folders..." folders = [ @settings[:scan_folder] ] folders << @settings[:move_to_folder] unless @settings[:move_to_folder].blank? folders << @settings[:move_invalid_to_folder] unless @settings[:move_invalid_to_folder].blank? # Open (or create) destination folder in read-write mode. folders.each do |folder| if @imap.list("", folder) log "folder #{folder} OK" else log "folder #{folder} missing, creating..." @imap.create(folder) end end rescue => e $stderr.puts "setup error #{e.inspect}" ensure disconnect! end private #-------------------------------------------------------------------------------------- def with_new_emails @imap.uid_search(['NOT', 'SEEN']).each do |uid| begin email = Mail.new(@imap.uid_fetch(uid, 'RFC822').first.attr['RFC822']) log "fetched new message...", email if is_valid?(email) && sent_from_known_user?(email) yield(uid, email) else discard(uid) end rescue Exception => e if ["test", "development"].include?(Rails.env) $stderr.puts e $stderr.puts e.backtrace end log "error processing email: #{e.inspect}", email discard(uid) end end end # Email processing pipeline: each steps gets executed if previous one returns false. #-------------------------------------------------------------------------------------- def process(uid, email) with_explicit_keyword(email) do |keyword, name| data = {"Type" => keyword, "Name" => name} find_or_create_and_attach(email, data) end and return with_recipients(email) do |recipient| find_and_attach(email, recipient) end and return with_forwarded_recipient(email) do |recipient| find_and_attach(email, recipient) end and return with_recipients(email) do |recipient| create_and_attach(email, recipient) end and return with_forwarded_recipient(email) do |recipient| create_and_attach(email, recipient) end end # Connects to the imap server with the loaded settings from settings.yml #------------------------------------------------------------------------------ def connect!(options = {}) @imap = Net::IMAP.new(@settings[:server], @settings[:port], @settings[:ssl]) @imap.login(@settings[:user], @settings[:password]) @imap.select(@settings[:scan_folder]) unless options[:setup] @imap rescue Exception => e $stderr.puts "Dropbox: could not login to the IMAP server: #{e.inspect}" unless Rails.env == "test" nil end #------------------------------------------------------------------------------ def disconnect! if @imap @imap.logout unless @imap.disconnected? @imap.disconnect rescue nil end end end # Discard message (not valid) action based on settings from settings.yml #------------------------------------------------------------------------------ def discard(uid) if @settings[:move_invalid_to_folder] @imap.uid_copy(uid, @settings[:move_invalid_to_folder]) end @imap.uid_store(uid, "+FLAGS", [:Deleted]) @discarded += 1 end # Archive message (valid) action based on settings from settings.yml #------------------------------------------------------------------------------ def archive(uid) if @settings[:move_to_folder] @imap.uid_copy(uid, @settings[:move_to_folder]) end @imap.uid_store(uid, "+FLAGS", [:Seen]) @archived += 1 end #------------------------------------------------------------------------------ def is_valid?(email) valid = email.content_type != "text/html" log("not a text message, discarding") unless valid valid end #------------------------------------------------------------------------------ def sent_from_known_user?(email) email_address = email.from.first known = !find_sender(email_address).nil? log("sent by unknown user #{email_address}, discarding") unless known known end #------------------------------------------------------------------------------ def find_sender(email_address) @sender = User.first(:conditions => [ "(lower(email) = ? OR lower(alt_email) = ?) AND suspended_at IS NULL", email_address.downcase, email_address.downcase ]) end # Checks the email to detect keyword on the first line. #-------------------------------------------------------------------------------------- def with_explicit_keyword(email) first_line = plain_text_body(email).split("\n").first if first_line =~ %r|^[\./]?(#{KEYWORDS.join('|')})\s(.+)$|i yield $1.capitalize, $2.strip end end # Checks the email to detect assets on to/bcc addresses #-------------------------------------------------------------------------------------- def with_recipients(email, options = {}) recipients = [] recipients += email.to_addrs unless email.to.blank? recipients += email.cc_addrs unless email.cc.blank? recipients -= [ @settings[:address] ] recipients.inject(false) { |attached, recipient| attached ||= yield recipient } end # Checks the email to detect valid email address in body (first email), detect forwarded emails #---------------------------------------------------------------------------------------- def with_forwarded_recipient(email, options = {}) if plain_text_body(email) =~ /\b([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})\b/ yield $1 end end # Process pipe_separated_data or explicit keyword. #-------------------------------------------------------------------------------------- def find_or_create_and_attach(email, data) klass = data["Type"].constantize if data["Email"] && klass.new.respond_to?(:email) conditions = ['email = ?', data["Email"]] elsif klass.new.respond_to?(:first_name) first_name, *last_name = data["Name"].split conditions = if last_name.empty? # Treat single name as last name. [ 'last_name LIKE ?', "%#{first_name}" ] else [ 'first_name LIKE ? AND last_name LIKE ?', "%#{first_name}", "%#{last_name.join(' ')}" ] end else conditions = ['name LIKE ?', "%#{data["Name"]}%"] end # Find the asset from deduced conditions if asset = klass.where(conditions).first if sender_has_permissions_for?(asset) attach(email, asset, :strip_first_line) else log "Sender does not have permissions to attach email to #{data["Type"]} #{data["Email"]} <#{data["Name"]}>" end else log "#{data["Type"]} #{data["Email"]} <#{data["Name"]}> not found, creating new one..." asset = klass.create!(default_values(klass, data)) attach(email, asset, :strip_first_line) end true end #---------------------------------------------------------------------------------------- def find_and_attach(email, recipient) attached = false ASSETS.each do |klass| asset = klass.find_by_email(recipient) # Leads and Contacts have an alt_email: try it if lookup by primary email has failed. if !asset && klass.column_names.include?("alt_email") asset = klass.find_by_alt_email(recipient) end if asset && sender_has_permissions_for?(asset) attach(email, asset) attached = true end end attached end #---------------------------------------------------------------------------------------- def create_and_attach(email, recipient) contact = Contact.create!(default_values_for_contact(email, recipient)) attach(email, contact) end #---------------------------------------------------------------------------------------- def attach(email, asset, strip_first_line=false) to = email.to.blank? ? nil : email.to.join(", ") cc = email.cc.blank? ? nil : email.cc.join(", ") email_body = if strip_first_line plain_text_body(email).split("\n")[1..-1].join("\n").strip else plain_text_body(email) end Email.create( :imap_message_id => email.message_id, :user => @sender, :mediator => asset, :sent_from => email.from.first, :sent_to => to, :cc => cc, :subject => email.subject, :body => email_body, :received_at => email.date, :sent_at => email.date ) asset.touch if asset.is_a?(Lead) && asset.status == "new" asset.update_attribute(:status, "contacted") end if @settings[:attach_to_account] && asset.respond_to?(:account) && asset.account Email.create( :imap_message_id => email.message_id, :user => @sender, :mediator => asset.account, :sent_from => email.from.first, :sent_to => to, :cc => cc, :subject => email.subject, :body => email_body, :received_at => email.date, :sent_at => email.date ) asset.account.touch end end #---------------------------------------------------------------------------------------- def default_values(klass, data) data = data.dup keyword = data.delete("Type").capitalize defaults = { :user => @sender, :access => default_access } case keyword when "Account", "Campaign", "Opportunity" defaults[:status] = "planned" if keyword == "Campaign" # TODO: I18n defaults[:stage] = "prospecting" if keyword == "Opportunity" # TODO: I18n when "Contact", "Lead" first_name, *last_name = data.delete("Name").split(' ') defaults[:first_name] = first_name defaults[:last_name] = (last_name.any? ? last_name.join(" ") : "(unknown)") defaults[:status] = "contacted" if keyword == "Lead" # TODO: I18n end data.each do |key, value| key = key.downcase defaults[key.to_sym] = value if klass.new.respond_to?(key + '=') end defaults end #---------------------------------------------------------------------------------------- def default_values_for_contact(email, recipient) recipient_local, recipient_domain = recipient.split('@') defaults = { :user => @sender, :first_name => recipient_local.capitalize, :last_name => "(unknown)", :email => recipient, :access => default_access } # Search for domain name in Accounts. account = Account.where('email like ?', "%#{recipient_domain}").first if account log "asociating new contact #{recipient} with the account #{account.name}" defaults[:account] = account else log "creating new account #{recipient_domain.capitalize} for the contact #{recipient}" defaults[:account] = Account.create!( :user => @sender, :email => recipient, :name => recipient_domain.capitalize, :access => default_access ) end defaults end # If default access is 'Shared' then change it to 'Private' because we don't know how # to choose anyone to share it with here. #-------------------------------------------------------------------------------------- def default_access Setting.default_access == "Shared" ? 'Private' : Setting.default_access end #-------------------------------------------------------------------------------------- def sender_has_permissions_for?(asset) return true if asset.access == "Public" return true if asset.user_id == @sender.id || asset.assigned_to == @sender.id return true if asset.access == "Shared" && Permission.where('user_id = ? AND asset_id = ? AND asset_type = ?', @sender.id, asset.id, asset.class.to_s).count > 0 false end # Notify users with the results of the operations (feedback from dropbox) #-------------------------------------------------------------------------------------- def notify(email, mediator_links) ack_email = Notifier.create_dropbox_ack_notification(@sender, @settings[:address], email, mediator_links) Notifier.deliver(ack_email) end # Centralized logging. #-------------------------------------------------------------------------------------- def log(message, email = nil) return if Rails.env == "test" puts "Dropbox: #{message}" puts " From: #{email.from}, Subject: #{email.subject} (#{email.message_id})" if email end # Returns the plain-text version of an email, or strips html tags # if only html is present. #-------------------------------------------------------------------------------------- def plain_text_body(email) parts = email.parts.collect {|c| (c.respond_to?(:parts) && !c.parts.empty?) ? c.parts : c}.flatten if parts.empty? parts << email end plain_text_part = parts.detect {|p| p.content_type.include?('text/plain')} if plain_text_part.nil? # no text/plain part found, assuming html-only email # strip html tags and remove doctype directive plain_text_body = email.body.to_s.gsub(/<\/?[^>]*>/, "") plain_text_body.gsub! %r{^<!DOCTYPE .*$}, '' else plain_text_body = plain_text_part.body.to_s end plain_text_body.strip.gsub("\r\n", "\n") end end # class Dropbox end # module FatFreeCRM
module FFI module Hunspell # ffi-hunspell versiont # @since 0.5.0 VERSION = '0.5.0' end end Version bump to 0.6.0. module FFI module Hunspell # ffi-hunspell versiont # @since 0.5.0 VERSION = '0.6.0' end end
require('sequel/extensions/inflector') unless [:singularize, :camelize, :underscore, :constantize].all?{|meth| "".respond_to?(meth)} require 'erb' class FixtureDependencies @fixtures = {} @loaded = {} @verbose = 0 # Load all record arguments into the database. If a single argument is # given and it corresponds to a single fixture, return the the model # instance corresponding to that fixture. If a single argument if given # and it corresponds to a model, return all model instances corresponding # to that model. If multiple arguments are given, return a list of # model instances (for single fixture arguments) or list of model instances # (for model fixture arguments). If no arguments, return the empty list. # If any of the arguments is a hash, assume the key specifies the model # and the values specify the fixture, and treat it as though individual # symbols specifying both model and fixture were given. # # Examples: # * load(:posts) # All post fixtures, not recommended # * load(:posts, :comments) # All post and comment fixtures, again not recommended # * load(:post__post1) # Just the post fixture named post1 # * load(:post__post1, :post__post2) # Post fixtures named post1 and post2 # * load(:posts=>[:post1, :post2]) # Post fixtures named post1 and post2 # * load(:post__post1, :comment__comment2) # Post fixture named post1 and comment fixture named comment2 # * load({:posts=>[:post1, :post2]}, :comment__comment2) # Post fixtures named post1 and post2 and comment fixture named comment2 # # This will load the data from the yaml files for each argument whose model # is not already in the fixture hash. def self.load(*records) ret = records.map do |record| if record.is_a?(Hash) record.map do |k, vals| model = k.to_s.singularize vals.map{|v| :"#{model}__#{v}"} end else record end end.flatten.compact.map do |record| model_name, name = split_name(record) if name use(record.to_sym) else model_name = model_name.singularize unless loaded[model_name.to_sym] puts "loading #{model_name}.yml" if verbose > 0 load_yaml(model_name) end fixtures[model_name.to_sym].keys.map{|name| use(:"#{model_name}__#{name}")} end end ret.length == 1 ? ret[0] : ret end end require 'fixture_dependencies/active_record' if defined?(ActiveRecord::Base) require 'fixture_dependencies/sequel' if defined?(Sequel::Model) class << FixtureDependencies attr_reader :fixtures, :loaded attr_accessor :verbose, :fixture_path private # Add a fixture to the fixture hash (does not add to the database, # just makes it available to be add to the database via use). def add(model_name, name, attributes) (fixtures[model_name.to_sym]||={})[name.to_sym] = attributes end # Get the model instance that already exists in the database using # the fixture name. def get(record) model_name, name = split_name(record) model = model_name.camelize.constantize model_method(:model_find, model_type(model), model, fixtures[model_name.to_sym][name.to_sym][model.primary_key.to_sym]) end # Adds all fixtures in the yaml fixture file for the model to the fixtures # hash (does not add them to the database, see add). def load_yaml(model_name) raise(ArgumentError, "No fixture_path set. Use FixtureDependencies.fixture_path = ...") unless fixture_path filename = model_name.camelize.constantize.table_name yaml_path = File.join(fixture_path, "#{filename}.yml") if File.exist?(yaml_path) yaml = YAML.load(File.read(yaml_path)) elsif File.exist?("#{yaml_path}.erb") yaml = YAML.load(ERB.new(File.read("#{yaml_path}.erb")).result) else raise(ArgumentError, "No valid fixture found at #{yaml_path}[.erb]") end yaml.each do |name, attributes| symbol_attrs = {} attributes.each{|k,v| symbol_attrs[k.to_sym] = v} add(model_name.to_sym, name, symbol_attrs) end loaded[model_name.to_sym] = true end # Delegate to the correct method based on mtype def model_method(meth, mtype, *args, &block) send("#{meth}_#{mtype}", *args, &block) end # A symbol representing the base class of the model, currently # ActiveRecord::Base and Sequel::Model are supported. def model_type(model) if model.ancestors.map{|x| x.to_s}.include?('ActiveRecord::Base') :AR elsif model.ancestors.map{|x| x.to_s}.include?('Sequel::Model') :S else raise TypeError, 'not ActiveRecord or Sequel model' end end # Split the fixture name into the name of the model and the name of # the individual fixture. def split_name(name) name.to_s.split('__', 2) end # Load the individual fixture into the database, by loading all necessary # belongs_to dependencies before saving the model, and all has_* # dependencies after saving the model. If the model already exists in # the database, return it. Will check the yaml file for fixtures if no # fixtures yet exist for the model. If the fixture isn't in the fixture # hash, raise an error. def use(record, loading = [], procs = {}) spaces = " " * loading.length puts "#{spaces}using #{record}" if verbose > 0 puts "#{spaces}load stack:#{loading.inspect}" if verbose > 1 loading.push(record) model_name, name = split_name(record) model = model_name.camelize.constantize unless loaded[model_name.to_sym] puts "#{spaces}loading #{model.table_name}.yml" if verbose > 0 load_yaml(model_name) end mtype = model_type(model) model_method(:raise_model_error, mtype, "Couldn't use fixture #{record.inspect}") unless attributes = fixtures[model_name.to_sym][name.to_sym] # return if object has already been loaded into the database if existing_obj = model_method(:model_find_by_pk, mtype, model, attributes[model.primary_key.to_sym]) puts "#{spaces}using #{record}: already in database" if verbose > 2 loading.pop return existing_obj end obj = model.respond_to?(:sti_key) ? attributes[model.sti_key].to_s.camelize.constantize.new : model.new puts "#{spaces}#{model} STI plugin detected, initializing instance of #{obj}" if (verbose > 1 && model.sti_dataset) many_associations = [] attributes.each do |attr, value| if reflection = model_method(:reflection, mtype, model, attr.to_sym) if [:belongs_to, :many_to_one].include?(model_method(:reflection_type, mtype, reflection)) dep_name = "#{model_method(:reflection_class, mtype, reflection).name.underscore}__#{value}".to_sym if dep_name == record # Self referential record, use primary key puts "#{spaces}#{record}.#{attr}: belongs_to self-referential" if verbose > 1 attr = model_method(:reflection_key, mtype, reflection) value = attributes[model.primary_key.to_sym] elsif loading.include?(dep_name) # Association cycle detected, set foreign key for this model afterward using procs # This is will fail if the column is set to not null or validates_presence_of puts "#{spaces}#{record}.#{attr}: belongs-to cycle detected:#{dep_name}" if verbose > 1 (procs[dep_name] ||= []) << Proc.new do |assoc| m = model_method(:model_find, mtype, model, attributes[model.primary_key.to_sym]) m.send("#{attr}=", assoc) model_method(:model_save, mtype, m) end value = nil else # Regular assocation, load it puts "#{spaces}#{record}.#{attr}: belongs_to:#{dep_name}" if verbose > 1 use(dep_name, loading, procs) value = get(dep_name) end elsif many_associations << [attr, reflection, model_method(:reflection_type, mtype, reflection) == :has_one ? [value] : value] next end end puts "#{spaces}#{record}.#{attr} = #{value.inspect}" if verbose > 2 obj.send("#{attr}=", value) end puts "#{spaces}saving #{record}" if verbose > 1 model_method(:model_save, mtype, obj) # after saving the model, we set the primary key within the fixture hash, in case it was not explicitly specified in the fixture and was generated by an auto_increment / serial field fixtures[model_name.to_sym][name.to_sym][model.primary_key.to_sym] ||= obj[model.primary_key.to_sym] loading.pop # Update the circular references if procs[record] procs[record].each{|p| p.call(obj)} procs.delete(record) end # Update the has_many and habtm associations many_associations.each do |attr, reflection, values| values.each do |value| dep_name = "#{model_method(:reflection_class, mtype, reflection).name.underscore}__#{value}".to_sym rtype = model_method(:reflection_type, mtype, reflection) if verbose > 1 if dep_name == record # Self referential, add association puts "#{spaces}#{record}.#{attr}: #{rtype} self-referential" if verbose > 1 model_method(:add_associated_object, mtype, reflection, attr, obj, obj) elsif loading.include?(dep_name) # Cycle Detected, add association to this object after saving other object puts "#{spaces}#{record}.#{attr}: #{rtype} cycle detected:#{dep_name}" if verbose > 1 (procs[dep_name] ||= []) << Proc.new do |assoc| model_method(:add_associated_object, mtype, reflection, attr, obj, assoc) end else # Regular association, add it puts "#{spaces}#{record}.#{attr}: #{rtype}:#{dep_name}" if verbose > 1 model_method(:add_associated_object, mtype, reflection, attr, obj, use(dep_name, loading, procs)) end end end obj end end Fix verbose mode if STI is not enabled require('sequel/extensions/inflector') unless [:singularize, :camelize, :underscore, :constantize].all?{|meth| "".respond_to?(meth)} require 'erb' class FixtureDependencies @fixtures = {} @loaded = {} @verbose = 0 # Load all record arguments into the database. If a single argument is # given and it corresponds to a single fixture, return the the model # instance corresponding to that fixture. If a single argument if given # and it corresponds to a model, return all model instances corresponding # to that model. If multiple arguments are given, return a list of # model instances (for single fixture arguments) or list of model instances # (for model fixture arguments). If no arguments, return the empty list. # If any of the arguments is a hash, assume the key specifies the model # and the values specify the fixture, and treat it as though individual # symbols specifying both model and fixture were given. # # Examples: # * load(:posts) # All post fixtures, not recommended # * load(:posts, :comments) # All post and comment fixtures, again not recommended # * load(:post__post1) # Just the post fixture named post1 # * load(:post__post1, :post__post2) # Post fixtures named post1 and post2 # * load(:posts=>[:post1, :post2]) # Post fixtures named post1 and post2 # * load(:post__post1, :comment__comment2) # Post fixture named post1 and comment fixture named comment2 # * load({:posts=>[:post1, :post2]}, :comment__comment2) # Post fixtures named post1 and post2 and comment fixture named comment2 # # This will load the data from the yaml files for each argument whose model # is not already in the fixture hash. def self.load(*records) ret = records.map do |record| if record.is_a?(Hash) record.map do |k, vals| model = k.to_s.singularize vals.map{|v| :"#{model}__#{v}"} end else record end end.flatten.compact.map do |record| model_name, name = split_name(record) if name use(record.to_sym) else model_name = model_name.singularize unless loaded[model_name.to_sym] puts "loading #{model_name}.yml" if verbose > 0 load_yaml(model_name) end fixtures[model_name.to_sym].keys.map{|name| use(:"#{model_name}__#{name}")} end end ret.length == 1 ? ret[0] : ret end end require 'fixture_dependencies/active_record' if defined?(ActiveRecord::Base) require 'fixture_dependencies/sequel' if defined?(Sequel::Model) class << FixtureDependencies attr_reader :fixtures, :loaded attr_accessor :verbose, :fixture_path private # Add a fixture to the fixture hash (does not add to the database, # just makes it available to be add to the database via use). def add(model_name, name, attributes) (fixtures[model_name.to_sym]||={})[name.to_sym] = attributes end # Get the model instance that already exists in the database using # the fixture name. def get(record) model_name, name = split_name(record) model = model_name.camelize.constantize model_method(:model_find, model_type(model), model, fixtures[model_name.to_sym][name.to_sym][model.primary_key.to_sym]) end # Adds all fixtures in the yaml fixture file for the model to the fixtures # hash (does not add them to the database, see add). def load_yaml(model_name) raise(ArgumentError, "No fixture_path set. Use FixtureDependencies.fixture_path = ...") unless fixture_path filename = model_name.camelize.constantize.table_name yaml_path = File.join(fixture_path, "#{filename}.yml") if File.exist?(yaml_path) yaml = YAML.load(File.read(yaml_path)) elsif File.exist?("#{yaml_path}.erb") yaml = YAML.load(ERB.new(File.read("#{yaml_path}.erb")).result) else raise(ArgumentError, "No valid fixture found at #{yaml_path}[.erb]") end yaml.each do |name, attributes| symbol_attrs = {} attributes.each{|k,v| symbol_attrs[k.to_sym] = v} add(model_name.to_sym, name, symbol_attrs) end loaded[model_name.to_sym] = true end # Delegate to the correct method based on mtype def model_method(meth, mtype, *args, &block) send("#{meth}_#{mtype}", *args, &block) end # A symbol representing the base class of the model, currently # ActiveRecord::Base and Sequel::Model are supported. def model_type(model) if model.ancestors.map{|x| x.to_s}.include?('ActiveRecord::Base') :AR elsif model.ancestors.map{|x| x.to_s}.include?('Sequel::Model') :S else raise TypeError, 'not ActiveRecord or Sequel model' end end # Split the fixture name into the name of the model and the name of # the individual fixture. def split_name(name) name.to_s.split('__', 2) end # Load the individual fixture into the database, by loading all necessary # belongs_to dependencies before saving the model, and all has_* # dependencies after saving the model. If the model already exists in # the database, return it. Will check the yaml file for fixtures if no # fixtures yet exist for the model. If the fixture isn't in the fixture # hash, raise an error. def use(record, loading = [], procs = {}) spaces = " " * loading.length puts "#{spaces}using #{record}" if verbose > 0 puts "#{spaces}load stack:#{loading.inspect}" if verbose > 1 loading.push(record) model_name, name = split_name(record) model = model_name.camelize.constantize unless loaded[model_name.to_sym] puts "#{spaces}loading #{model.table_name}.yml" if verbose > 0 load_yaml(model_name) end mtype = model_type(model) model_method(:raise_model_error, mtype, "Couldn't use fixture #{record.inspect}") unless attributes = fixtures[model_name.to_sym][name.to_sym] # return if object has already been loaded into the database if existing_obj = model_method(:model_find_by_pk, mtype, model, attributes[model.primary_key.to_sym]) puts "#{spaces}using #{record}: already in database" if verbose > 2 loading.pop return existing_obj end obj = model.respond_to?(:sti_key) ? attributes[model.sti_key].to_s.camelize.constantize.new : model.new puts "#{spaces}#{model} STI plugin detected, initializing instance of #{obj}" if (verbose > 1 && model.respond_to?(:sti_dataset)) many_associations = [] attributes.each do |attr, value| if reflection = model_method(:reflection, mtype, model, attr.to_sym) if [:belongs_to, :many_to_one].include?(model_method(:reflection_type, mtype, reflection)) dep_name = "#{model_method(:reflection_class, mtype, reflection).name.underscore}__#{value}".to_sym if dep_name == record # Self referential record, use primary key puts "#{spaces}#{record}.#{attr}: belongs_to self-referential" if verbose > 1 attr = model_method(:reflection_key, mtype, reflection) value = attributes[model.primary_key.to_sym] elsif loading.include?(dep_name) # Association cycle detected, set foreign key for this model afterward using procs # This is will fail if the column is set to not null or validates_presence_of puts "#{spaces}#{record}.#{attr}: belongs-to cycle detected:#{dep_name}" if verbose > 1 (procs[dep_name] ||= []) << Proc.new do |assoc| m = model_method(:model_find, mtype, model, attributes[model.primary_key.to_sym]) m.send("#{attr}=", assoc) model_method(:model_save, mtype, m) end value = nil else # Regular assocation, load it puts "#{spaces}#{record}.#{attr}: belongs_to:#{dep_name}" if verbose > 1 use(dep_name, loading, procs) value = get(dep_name) end elsif many_associations << [attr, reflection, model_method(:reflection_type, mtype, reflection) == :has_one ? [value] : value] next end end puts "#{spaces}#{record}.#{attr} = #{value.inspect}" if verbose > 2 obj.send("#{attr}=", value) end puts "#{spaces}saving #{record}" if verbose > 1 model_method(:model_save, mtype, obj) # after saving the model, we set the primary key within the fixture hash, in case it was not explicitly specified in the fixture and was generated by an auto_increment / serial field fixtures[model_name.to_sym][name.to_sym][model.primary_key.to_sym] ||= obj[model.primary_key.to_sym] loading.pop # Update the circular references if procs[record] procs[record].each{|p| p.call(obj)} procs.delete(record) end # Update the has_many and habtm associations many_associations.each do |attr, reflection, values| values.each do |value| dep_name = "#{model_method(:reflection_class, mtype, reflection).name.underscore}__#{value}".to_sym rtype = model_method(:reflection_type, mtype, reflection) if verbose > 1 if dep_name == record # Self referential, add association puts "#{spaces}#{record}.#{attr}: #{rtype} self-referential" if verbose > 1 model_method(:add_associated_object, mtype, reflection, attr, obj, obj) elsif loading.include?(dep_name) # Cycle Detected, add association to this object after saving other object puts "#{spaces}#{record}.#{attr}: #{rtype} cycle detected:#{dep_name}" if verbose > 1 (procs[dep_name] ||= []) << Proc.new do |assoc| model_method(:add_associated_object, mtype, reflection, attr, obj, assoc) end else # Regular association, add it puts "#{spaces}#{record}.#{attr}: #{rtype}:#{dep_name}" if verbose > 1 model_method(:add_associated_object, mtype, reflection, attr, obj, use(dep_name, loading, procs)) end end end obj end end
module GemsStatusMetadata VERSION = "0.2.5" end new version module GemsStatusMetadata VERSION = "0.2.6" end
desc 'rake', 'Run rake tasks in all Rails environments' def rake(*args) for env in %w[development test cucumber performance] if File.exists? "config/environments/#{env}.rb" call = ['bundle exec rake'] + args + ["RAILS_ENV=#{env}"] note_cmd call.join(' ') Util.system! *call end end end Fix rake command desc 'rake', 'Run rake tasks in all Rails environments' def rake(*args) for env in %w[development test cucumber performance] if File.exists? "config/environments/#{env}.rb" call = %w[bundle exec rake] + args + ["RAILS_ENV=#{env}"] note_cmd call.join(' ') Util.system! *call end end end
require 'singleton' module Ginger class Configuration include Singleton attr_accessor :scenarios, :aliases def initialize @scenarios = [] @aliases = {} end def self.detect_scenario_file require 'ginger_scenarios' if File.exists?("ginger_scenarios.rb") end end end allow scenarios file to reside in spec or test folders as well as the root require 'singleton' module Ginger class Configuration include Singleton attr_accessor :scenarios, :aliases def initialize @scenarios = [] @aliases = {} end def self.detect_scenario_file ['.','spec','test'].each do |path| require "#{path}/ginger_scenarios" and break if File.exists?("#{path}/ginger_scenarios.rb") end end end end
# frozen_string_literal: true module GitHubPages VERSION = 214 end Bump :gem: to v215 # frozen_string_literal: true module GitHubPages VERSION = 215 end
require "json" require "sinatra/base" require "github-trello/version" require "github-trello/http" module GithubTrello class Server < Sinatra::Base #Recieves payload post "/posthook" do #Get environment variables for configuration oauth_token = ENV["oauth_token"] api_key = ENV["api_key"] board_id = ENV["board_id"] start_list_target_id = ENV["start_list_target_id"] finish_list_target_id = ENV["finish_list_target_id"] deployed_list_target_id = ENV["deployed_list_target_id"] #Set up HTTP Wrapper http = GithubTrello::HTTP.new(oauth_token, api_key) #Get payload payload = JSON.parse(params[:payload]) #Get branch branch = payload["ref"].gsub("refs/heads/", "") payload["commits"].each do |commit| # Figure out the card short id match = commit["message"].match(/((start|card|close|fix)e?s? \D?([0-9]+))/i) next unless match and match[3].to_i > 0 results = http.get_card(board_id, match[3].to_i) unless results puts "[ERROR] Cannot find card matching ID #{match[3]}" next end results = JSON.parse(results) # Add the commit comment message = "#{commit["author"]["name"]}: #{commit["message"]}\n\n[#{branch}] #{commit["url"]}" message.gsub!(match[1], "") message.gsub!(/\(\)$/, "") http.add_comment(results["id"], message) #Determine the action to take new_list_id = case match[2].downcase when "start", "card" then start_list_target_id when "close", "fix" then finish_list_target_id end next unless !new_list_id.nil? #Modify it if needed to_update = {} unless results["idList"] == new_list_id to_update[:idList] = new_list_id end unless to_update.empty? http.update_card(results["id"], to_update) end end "" end get "/" do "" end def self.http; @http end end end first commit in listening for deployed message require "json" require "sinatra/base" require "github-trello/version" require "github-trello/http" module GithubTrello class Server < Sinatra::Base #Recieves payload post "/posthook" do #Get environment variables for configuration oauth_token = ENV["oauth_token"] api_key = ENV["api_key"] board_id = ENV["board_id"] start_list_target_id = ENV["start_list_target_id"] finish_list_target_id = ENV["finish_list_target_id"] deployed_list_target_id = ENV["deployed_list_target_id"] #Set up HTTP Wrapper http = GithubTrello::HTTP.new(oauth_token, api_key) #Get payload payload = JSON.parse(params[:payload]) #Get branch branch = payload["ref"].gsub("refs/heads/", "") payload["commits"].each do |commit| # Figure out the card short id match = commit["message"].match(/((start|card|close|fix)e?s? \D?([0-9]+))/i) next unless match and match[3].to_i > 0 results = http.get_card(board_id, match[3].to_i) unless results puts "[ERROR] Cannot find card matching ID #{match[3]}" next end results = JSON.parse(results) # Add the commit comment message = "#{commit["author"]["name"]}: #{commit["message"]}\n\n[#{branch}] #{commit["url"]}" message.gsub!(match[1], "") message.gsub!(/\(\)$/, "") http.add_comment(results["id"], message) #Determine the action to take new_list_id = case match[2].downcase when "start", "card" then start_list_target_id when "close", "fix" then finish_list_target_id when "*" then deployed_list_target_id end next unless !new_list_id.nil? #Modify it if needed to_update = {} unless results["idList"] == new_list_id to_update[:idList] = new_list_id end unless to_update.empty? http.update_card(results["id"], to_update) end end "" end get "/" do "" end def self.http; @http end end end
require 'fileutils' require_relative "../build.rb" require_relative "../build/info.rb" require_relative '../build/omnibus_trigger' require_relative "../ohai_helper.rb" require_relative '../version.rb' require_relative "../util.rb" require_relative "../package_size" require 'net/http' require 'json' namespace :build do desc 'Start project build' task project: ["cache:purge", "check:no_changes"] do Gitlab::Util.section('build:project') do Build.exec('gitlab') || raise('Build failed') end Rake::Task["license:check"].invoke Rake::Task["build:package:move_to_platform_dir"].invoke Rake::Task["build:package:generate_checksums"].invoke Rake::Task["build:package:generate_sizefile"].invoke end namespace :docker do desc 'Show latest available tag. Includes unstable releases.' task :latest_tag do puts Build::Info.latest_tag end desc 'Show latest stable tag.' task :latest_stable_tag do puts Build::Info.latest_stable_tag end end namespace :package do desc "Move packages to OS specific directory" task :move_to_platform_dir do FileUtils.mv("pkg/version-manifest.json", "pkg/#{Build::Info.package}_#{Build::Info.release_version}.version-manifest.json") platform_dir = OhaiHelper.platform_dir FileUtils.mv("pkg", platform_dir) FileUtils.mkdir("pkg") FileUtils.mv(platform_dir, "pkg") end desc "Generate checksums for each file" task :generate_checksums do Gitlab::Util.section('build:package:generate_checksums') do files = Dir.glob('pkg/**/*.{deb,rpm}').select { |f| File.file? f } files.each do |file| system('sha256sum', file, out: "#{file}.sha256") end end end desc "Generate sizefile for each file" task :generate_sizefile do Gitlab::Util.section('build:package:generate_sizefile') do files = Dir.glob('pkg/**/*.{deb,rpm}').select { |f| File.file? f } if files.empty? # We are probably inside Trigger:package_size_check job. PackageSizeCheck.fetch_sizefile else PackageSizeCheck.generate_sizefiles(files) end end end desc "Sync packages to aws" task :sync do Gitlab::Util.section('build:package:sync') do release_bucket = Build::Info.release_bucket release_bucket_region = Build::Info.release_bucket_region release_bucket_s3_endpoint = Build::Info.release_bucket_s3_endpoint system(*%W[aws s3 --endpoint-url https://#{release_bucket_s3_endpoint} sync pkg/ s3://#{release_bucket} --no-progress --acl public-read --region #{release_bucket_region}]) files = Dir.glob('pkg/**/*').select { |f| File.file? f } files.each do |file| puts file.gsub('pkg', "https://#{release_bucket}.#{release_bucket_s3_endpoint}").gsub('+', '%2B') end end end end desc "Trigger package and QA builds" task :trigger do # We need to set the following variables to be able to post a comment with # the "downstream" pipeline on the commit under test Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_PROJECT', Gitlab::Util.get_env('CI_PROJECT_PATH')) Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_JOB', Gitlab::Util.get_env('CI_JOB_URL')) Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_SHA', Gitlab::Util.get_env('CI_COMMIT_SHA')) Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_REF', Gitlab::Util.get_env('CI_COMMIT_REF_NAME')) Gitlab::Util.section('build:trigger') do Build::OmnibusTrigger.invoke!(post_comment: true).wait! end end desc 'Print the current version' task :version do # We don't differentiate between CE and EE here since they use the same version file puts Gitlab::Version.new('gitlab-rails').print end desc 'Print SHAs of GitLab components' task :component_shas do version_manifest_file = Dir.glob('pkg/**/*version-manifest.json').first return unless version_manifest_file Gitlab::Util.section('build:component_shas') do puts "#### SHAs of GitLab Components" json_content = JSON.parse(File.read(version_manifest_file)) %w[gitlab-rails gitaly gitlab-pages gitlab-shell].each do |component| puts "#{component} : #{json_content['software'][component]['locked_version']}" end end end desc 'Write build related facts to file' task :generate_facts do FileUtils.rm_rf('build_facts') FileUtils.mkdir_p('build_facts') [ :latest_stable_tag, :latest_tag ].each do |fact| content = Build::Info.send(fact) # rubocop:disable GitlabSecurity/PublicSend File.write("build_facts/#{fact}", content) unless content.nil? end end end Do not collapse build:package:sync logs on non-tag pipelines Most of the time when we push a branch to dev, we are looking at output of this section to get directl URL to a package. Signed-off-by: Balasankar "Balu" C <250a398eb3bfb9862062144cc742cc8f9bdd8d78@gitlab.com> require 'fileutils' require_relative "../build.rb" require_relative "../build/info.rb" require_relative '../build/omnibus_trigger' require_relative "../ohai_helper.rb" require_relative '../version.rb' require_relative "../util.rb" require_relative "../package_size" require 'net/http' require 'json' namespace :build do desc 'Start project build' task project: ["cache:purge", "check:no_changes"] do Gitlab::Util.section('build:project') do Build.exec('gitlab') || raise('Build failed') end Rake::Task["license:check"].invoke Rake::Task["build:package:move_to_platform_dir"].invoke Rake::Task["build:package:generate_checksums"].invoke Rake::Task["build:package:generate_sizefile"].invoke end namespace :docker do desc 'Show latest available tag. Includes unstable releases.' task :latest_tag do puts Build::Info.latest_tag end desc 'Show latest stable tag.' task :latest_stable_tag do puts Build::Info.latest_stable_tag end end namespace :package do desc "Move packages to OS specific directory" task :move_to_platform_dir do FileUtils.mv("pkg/version-manifest.json", "pkg/#{Build::Info.package}_#{Build::Info.release_version}.version-manifest.json") platform_dir = OhaiHelper.platform_dir FileUtils.mv("pkg", platform_dir) FileUtils.mkdir("pkg") FileUtils.mv(platform_dir, "pkg") end desc "Generate checksums for each file" task :generate_checksums do Gitlab::Util.section('build:package:generate_checksums') do files = Dir.glob('pkg/**/*.{deb,rpm}').select { |f| File.file? f } files.each do |file| system('sha256sum', file, out: "#{file}.sha256") end end end desc "Generate sizefile for each file" task :generate_sizefile do Gitlab::Util.section('build:package:generate_sizefile') do files = Dir.glob('pkg/**/*.{deb,rpm}').select { |f| File.file? f } if files.empty? # We are probably inside Trigger:package_size_check job. PackageSizeCheck.fetch_sizefile else PackageSizeCheck.generate_sizefiles(files) end end end desc "Sync packages to aws" task :sync do Gitlab::Util.section('build:package:sync', collapsed: Build::Check.on_tag?) do release_bucket = Build::Info.release_bucket release_bucket_region = Build::Info.release_bucket_region release_bucket_s3_endpoint = Build::Info.release_bucket_s3_endpoint system(*%W[aws s3 --endpoint-url https://#{release_bucket_s3_endpoint} sync pkg/ s3://#{release_bucket} --no-progress --acl public-read --region #{release_bucket_region}]) files = Dir.glob('pkg/**/*').select { |f| File.file? f } files.each do |file| puts file.gsub('pkg', "https://#{release_bucket}.#{release_bucket_s3_endpoint}").gsub('+', '%2B') end end end end desc "Trigger package and QA builds" task :trigger do # We need to set the following variables to be able to post a comment with # the "downstream" pipeline on the commit under test Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_PROJECT', Gitlab::Util.get_env('CI_PROJECT_PATH')) Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_JOB', Gitlab::Util.get_env('CI_JOB_URL')) Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_SHA', Gitlab::Util.get_env('CI_COMMIT_SHA')) Gitlab::Util.set_env_if_missing('TOP_UPSTREAM_SOURCE_REF', Gitlab::Util.get_env('CI_COMMIT_REF_NAME')) Gitlab::Util.section('build:trigger') do Build::OmnibusTrigger.invoke!(post_comment: true).wait! end end desc 'Print the current version' task :version do # We don't differentiate between CE and EE here since they use the same version file puts Gitlab::Version.new('gitlab-rails').print end desc 'Print SHAs of GitLab components' task :component_shas do version_manifest_file = Dir.glob('pkg/**/*version-manifest.json').first return unless version_manifest_file Gitlab::Util.section('build:component_shas') do puts "#### SHAs of GitLab Components" json_content = JSON.parse(File.read(version_manifest_file)) %w[gitlab-rails gitaly gitlab-pages gitlab-shell].each do |component| puts "#{component} : #{json_content['software'][component]['locked_version']}" end end end desc 'Write build related facts to file' task :generate_facts do FileUtils.rm_rf('build_facts') FileUtils.mkdir_p('build_facts') [ :latest_stable_tag, :latest_tag ].each do |fact| content = Build::Info.send(fact) # rubocop:disable GitlabSecurity/PublicSend File.write("build_facts/#{fact}", content) unless content.nil? end end end
require 'fileutils' require_relative "../build.rb" require_relative "../build/info.rb" require_relative "../ohai_helper.rb" require 'net/http' require 'json' namespace :build do desc 'Start project build' task project: ["cache:purge", "check:no_changes"] do Build.exec('gitlab') Rake::Task["license:check"].invoke Rake::Task["build:package:move_to_platform_dir"].invoke end namespace :docker do desc 'Show latest available tag. Includes unstable releases.' task :latest_tag do puts Build::Info.latest_tag end desc 'Show latest stable tag.' task :latest_stable_tag do puts Build::Info.latest_stable_tag end end namespace :package do desc "Move packages to OS specific directory" task :move_to_platform_dir do platform_dir = OhaiHelper.platform_dir FileUtils.mv("pkg", platform_dir) FileUtils.mkdir("pkg") FileUtils.mv(platform_dir, "pkg") end desc "Sync packages to aws" task :sync do release_bucket = Build::Info.release_bucket release_bucket_region = "eu-west-1" system("aws s3 sync pkg/ s3://#{release_bucket} --acl public-read --region #{release_bucket_region}") files = Dir.glob('pkg/**/*').select { |f| File.file? f } files.each do |file| puts file.gsub('pkg', "https://#{release_bucket}.s3.amazonaws.com").gsub('+', '%2B') end end end desc "Trigger package and QA builds" task :trigger do uri = URI("https://gitlab.com/api/v4/projects/#{ENV['CI_PROJECT_ID']}/trigger/pipeline") params = Build::Info.get_trigger_params res = Net::HTTP.post_form(uri, params) pipeline_id = JSON.parse(res.body)['id'] if pipeline_id.nil? puts "Trigger failed. The response from trigger is: " puts res.body else puts "Triggered pipeline can be found at #{ENV['CI_PROJECT_URL']}/pipelines/#{pipeline_id}" end end end Build failure should stop `build:package` Build.exec is implemented in terms of Kernel#system, which returns true or false if the command succeeded. This was not being checked, so a failed build would not fail the wrapping rake task. Here we check it and call fail if it wasn't successful. require 'fileutils' require_relative "../build.rb" require_relative "../build/info.rb" require_relative "../ohai_helper.rb" require 'net/http' require 'json' namespace :build do desc 'Start project build' task project: ["cache:purge", "check:no_changes"] do Build.exec('gitlab') || raise('Build failed') Rake::Task["license:check"].invoke Rake::Task["build:package:move_to_platform_dir"].invoke end namespace :docker do desc 'Show latest available tag. Includes unstable releases.' task :latest_tag do puts Build::Info.latest_tag end desc 'Show latest stable tag.' task :latest_stable_tag do puts Build::Info.latest_stable_tag end end namespace :package do desc "Move packages to OS specific directory" task :move_to_platform_dir do platform_dir = OhaiHelper.platform_dir FileUtils.mv("pkg", platform_dir) FileUtils.mkdir("pkg") FileUtils.mv(platform_dir, "pkg") end desc "Sync packages to aws" task :sync do release_bucket = Build::Info.release_bucket release_bucket_region = "eu-west-1" system("aws s3 sync pkg/ s3://#{release_bucket} --acl public-read --region #{release_bucket_region}") files = Dir.glob('pkg/**/*').select { |f| File.file? f } files.each do |file| puts file.gsub('pkg', "https://#{release_bucket}.s3.amazonaws.com").gsub('+', '%2B') end end end desc "Trigger package and QA builds" task :trigger do uri = URI("https://gitlab.com/api/v4/projects/#{ENV['CI_PROJECT_ID']}/trigger/pipeline") params = Build::Info.get_trigger_params res = Net::HTTP.post_form(uri, params) pipeline_id = JSON.parse(res.body)['id'] if pipeline_id.nil? puts "Trigger failed. The response from trigger is: " puts res.body else puts "Triggered pipeline can be found at #{ENV['CI_PROJECT_URL']}/pipelines/#{pipeline_id}" end end end
module Given # Does this platform support natural assertions? RBX_IN_USE = (defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx') JRUBY_IN_USE = defined?(JRUBY_VERSION) OLD_JRUBY_IN_USE = JRUBY_IN_USE && (Gem::Version.new(JRUBY_VERSION) < Gem::Version.new('1.7.5')) NATURAL_ASSERTIONS_SUPPORTED = ! (OLD_JRUBY_IN_USE || RBX_IN_USE) def self.framework @_gvn_framework end def self.framework=(framework) @_gvn_framework = framework end def self.source_caching_disabled @_gvn_source_caching_disabled end def self.source_caching_disabled=(value) @_gvn_source_caching_disabled = value end # Globally enable/disable natural assertions. # # There is a similar function in Extensions that works at a # describe or context scope. def self.use_natural_assertions(enabled=true) ok_to_use_natural_assertions(enabled) @natural_assertions_enabled = enabled end # TRUE if natural assertions are globally enabled? def self.natural_assertions_enabled? @natural_assertions_enabled end # Is is OK to use natural assertions on this platform. # # An error is raised if the the platform does not support natural # assertions and the flag is attempting to enable them. def self.ok_to_use_natural_assertions(enabled) if enabled && ! NATURAL_ASSERTIONS_SUPPORTED fail ArgumentError, "Natural Assertions are disabled for JRuby" end end # Return file and line number where the block is defined. def self.location_of(block) eval "[__FILE__, __LINE__]", block.binding end # Methods forwarded to the framework object. # Fail an example with the given messages. def self.fail_with(*args) Given.framework.fail_with(*args) end # Mark the start of a Then assertion evaluation. def self.start_evaluation(*args) Given.framework.start_evaluation(*args) end # Were there any explicit framework assertions made during the # execution of the Then block? def self.explicit_assertions?(*args) Given.framework.explicit_assertions?(*args) end # Increment the number of assertions made in the framework. def self.count_assertion(*args) Given.framework.count_assertion(*args) end # Error object used by the current framework to indicate a pending # example. def self.pending_error Given.framework.pending_error end end fix typo module Given # Does this platform support natural assertions? RBX_IN_USE = (defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx') JRUBY_IN_USE = defined?(JRUBY_VERSION) OLD_JRUBY_IN_USE = JRUBY_IN_USE && (Gem::Version.new(JRUBY_VERSION) < Gem::Version.new('1.7.5')) NATURAL_ASSERTIONS_SUPPORTED = ! (OLD_JRUBY_IN_USE || RBX_IN_USE) def self.framework @_gvn_framework end def self.framework=(framework) @_gvn_framework = framework end def self.source_caching_disabled @_gvn_source_caching_disabled end def self.source_caching_disabled=(value) @_gvn_source_caching_disabled = value end # Globally enable/disable natural assertions. # # There is a similar function in Extensions that works at a # describe or context scope. def self.use_natural_assertions(enabled=true) ok_to_use_natural_assertions(enabled) @natural_assertions_enabled = enabled end # TRUE if natural assertions are globally enabled? def self.natural_assertions_enabled? @natural_assertions_enabled end # It is OK to use natural assertions on this platform. # # An error is raised if the the platform does not support natural # assertions and the flag is attempting to enable them. def self.ok_to_use_natural_assertions(enabled) if enabled && ! NATURAL_ASSERTIONS_SUPPORTED fail ArgumentError, "Natural Assertions are disabled for JRuby" end end # Return file and line number where the block is defined. def self.location_of(block) eval "[__FILE__, __LINE__]", block.binding end # Methods forwarded to the framework object. # Fail an example with the given messages. def self.fail_with(*args) Given.framework.fail_with(*args) end # Mark the start of a Then assertion evaluation. def self.start_evaluation(*args) Given.framework.start_evaluation(*args) end # Were there any explicit framework assertions made during the # execution of the Then block? def self.explicit_assertions?(*args) Given.framework.explicit_assertions?(*args) end # Increment the number of assertions made in the framework. def self.count_assertion(*args) Given.framework.count_assertion(*args) end # Error object used by the current framework to indicate a pending # example. def self.pending_error Given.framework.pending_error end end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "active_admin/state_machine/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "active_admin-state_machine" s.version = ActiveAdmin::StateMachine::VERSION s.authors = ["Matt Brewer"] s.email = ["matt.brewer@me.com"] s.homepage = "https://github.com/macfanatic/active_admin-state_machine" s.summary = "Provides easy DSL integration between ActiveAdmin & state_machine" s.description = "Provides easy DSL integration between ActiveAdmin & state_machine" s.license = "MIT" s.metadata = { 'changelog_uri' => 'https://github.com/macfanatic/active_admin-state_machine/blob/master/CHANGELOG.md' } s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.test_files = Dir["spec/**/*"] s.add_dependency "rails", '~> 6.0' s.add_dependency "activeadmin", "~> 2.0" s.add_dependency "state_machine" s.add_development_dependency "rake", "> 10.0" s.add_development_dependency "sqlite3" s.add_development_dependency 'listen' s.add_development_dependency "pg" s.add_development_dependency "rspec-rails" s.add_development_dependency "shoulda-matchers" s.add_development_dependency "capybara", '~> 3.35' s.add_development_dependency 'selenium-webdriver', '~> 3.142' s.add_development_dependency "webdrivers", '~> 4.6' s.add_development_dependency "database_cleaner" s.add_development_dependency "factory_bot_rails" s.add_development_dependency "devise", "~> 4.0" end Remove test_files & specify some rdoc options for packaged files $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "active_admin/state_machine/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "active_admin-state_machine" s.version = ActiveAdmin::StateMachine::VERSION s.authors = ["Matt Brewer"] s.email = ["matt.brewer@me.com"] s.homepage = "https://github.com/macfanatic/active_admin-state_machine" s.summary = "Provides easy DSL integration between ActiveAdmin & state_machine" s.description = "Provides easy DSL integration between ActiveAdmin & state_machine" s.license = "MIT" s.metadata = { 'changelog_uri' => 'https://github.com/macfanatic/active_admin-state_machine/blob/master/CHANGELOG.md' } s.files = Dir["lib/**/*"] s.extra_rdoc_files = Dir["README.md", "CHANGELOG.md", "MIT-LICENSE"] s.rdoc_options += [ "--title", "ActiveAdmin StateMachine Integration", "--main", "README.md", "--line-numbers", "--inline-source", "--quiet" ] s.add_dependency "rails", '~> 6.0' s.add_dependency "activeadmin", "~> 2.0" s.add_dependency "state_machine" s.add_development_dependency "rake", "> 10.0" s.add_development_dependency "sqlite3" s.add_development_dependency 'listen' s.add_development_dependency "pg" s.add_development_dependency "rspec-rails" s.add_development_dependency "shoulda-matchers" s.add_development_dependency "capybara", '~> 3.35' s.add_development_dependency 'selenium-webdriver', '~> 3.142' s.add_development_dependency "webdrivers", '~> 4.6' s.add_development_dependency "database_cleaner" s.add_development_dependency "factory_bot_rails" s.add_development_dependency "devise", "~> 4.0" end
require "rails_helper" describe "exists? workout" do context "without arguments" do it "tells you if table is populated or not" do expect(Article.exists?).to eq(false) create(:article) expect(Article.exists?).to eq(true)#hide # expect(Article.exists?).to eq(YOUR_CODE_HERE)#show expect(Book.exists?).to eq(false)#hide # expect(Book.exists?).to eq(YOUR_CODE_HERE)#show create(:book) expect(Book.exists?).to eq(true)#hide # expect(Book.eYOUR_CODE_HERE?).to eq(true)#show expect(Country.exists?).to eq(false)#hide # expect(CoYOUR_CODE_HEREts?).to eq(false)#show create(:country) expect(Country.exists?).to eq(true)#hide # expect(Country.YOUR_CODE_HERE?).to eq(true)#show expect(Meeting.exists?).to eq(false)#hide # expect(YOUR_CODE_HERE).to eq(false)#show create(:meeting) expect(Meeting.exists?).to eq(true)#hide # expect(YOUR_CODE_HERE).to eq(YOUR_CODE_HERE)#show end end end Exercises for exists?(id_as_num_or_str) require "rails_helper" describe "exists? workout" do context "without arguments" do it "tells you if table is populated or not" do expect(Article.exists?).to eq(false) create(:article) expect(Article.exists?).to eq(true)#hide # expect(Article.exists?).to eq(YOUR_CODE_HERE)#show expect(Book.exists?).to eq(false)#hide # expect(Book.exists?).to eq(YOUR_CODE_HERE)#show create(:book) expect(Book.exists?).to eq(true)#hide # expect(Book.eYOUR_CODE_HERE?).to eq(true)#show expect(Country.exists?).to eq(false)#hide # expect(CoYOUR_CODE_HEREts?).to eq(false)#show create(:country) expect(Country.exists?).to eq(true)#hide # expect(Country.YOUR_CODE_HERE?).to eq(true)#show expect(Meeting.exists?).to eq(false)#hide # expect(YOUR_CODE_HERE).to eq(false)#show create(:meeting) expect(Meeting.exists?).to eq(true)#hide # expect(YOUR_CODE_HERE).to eq(YOUR_CODE_HERE)#show end end context "with Integer or String id argument" do it "tells you if record with the given primary key exists" do create(:meeting, id: 111) expect(Meeting.exists?(111)).to eq(true) expect(Meeting.exists?(111.to_s)).to eq(true) expect(Meeting.exists?(222)).to eq(false)#hide # expect(Meeting.exists?(222)).to eq(YOUR_CODE_HERE)#show expect(Meeting.exists?(222.to_s)).to eq(false)#hide # expect(Meeting.exists?(222.to_s)).to eq(YOUR_CODE_HERE)#show create(:country, id: 9876) expect(Country.exists?(9876)).to eq(true)#hide # expect(Country.exists?(YOUR_CODE_HERE)).to eq(true)#show expect(Country.exists?(9876.to_s)).to eq(true)#hide # expect(Country.YOUR_CODE_HERE(9876.to_s)).to eq(YOUR_CODE_HERE)#show expect(Country.exists?(1234)).to eq(false)#hide # expect(YOUR_CODE_HERE(1234)).to eq(false)#show expect(Country.exists?(1234.to_s)).to eq(false)#hide # expect(YOUR_CODE_HERE(YOUR_CODE_HERE.to_s)).to eq(false)#show create(:book, id: 1) expect(Book.exists?(1)).to eq(true)#hide # expect(YOUR_CODE_HERE(1)).to eq(true)#show expect(Book.exists?(1.to_s)).to eq(true)#hide # expect(YOUR_CODE_HERE(1.to_s)).to eq(true)#show expect(Book.exists?(2)).to eq(false)#hide # expect(YOUR_CODE_HERE(2)).to eq(false)#show expect(Book.exists?(2.to_s)).to eq(false)#hide # expect(YOUR_CODE_HERE(2.to_s)).to eq(false)#show end end end
require 'glue/finding' require 'set' require 'digest' class Glue::BaseTask attr_reader :findings, :warnings, :trigger, :labels attr_accessor :name attr_accessor :description attr_accessor :stage attr_accessor :appname attr_accessor :result def initialize(trigger, tracker) @findings = [] @warnings = [] @labels = Set.new @trigger = trigger @tracker = tracker @severity_filter = { :low => ['low','weak', 'informational'], :medium => ['medium','med','average'], :high => ['high','severe','critical'] } end def report description, detail, source, severity, fingerprint finding = Glue::Finding.new( @trigger.appname, description, detail, source, severity, fingerprint, self.class.name ) @findings << finding end def warn warning @warnings << warning end def name @name end def description @description end def stage @stage end def directories_with? file, exclude_dirs = [] exclude_dirs = @tracker.options[:exclude_dirs] if exclude_dirs == [] and @tracker.options[:exclude_dirs] results = [] Find.find(@trigger.path) do |path| if FileTest.directory? path Find.prune if exclude_dirs.include? File.basename(path) or exclude_dirs.include? File.basename(path) + '/' next end Find.prune unless File.basename(path) == file results << File.dirname(path) end return results end def run end def analyze end def supported? end def severity sev sev = '' if sev.nil? return 1 if @severity_filter[:low].include?(sev.strip.chomp.downcase) return 2 if @severity_filter[:medium].include?(sev.strip.chomp.downcase) return 3 if @severity_filter[:high].include?(sev.strip.chomp.downcase) return 0 end end added 'info' to severity filter require 'glue/finding' require 'set' require 'digest' class Glue::BaseTask attr_reader :findings, :warnings, :trigger, :labels attr_accessor :name attr_accessor :description attr_accessor :stage attr_accessor :appname attr_accessor :result def initialize(trigger, tracker) @findings = [] @warnings = [] @labels = Set.new @trigger = trigger @tracker = tracker @severity_filter = { :low => ['low','weak', 'informational', 'info'], :medium => ['medium','med','average'], :high => ['high','severe','critical'] } end def report description, detail, source, severity, fingerprint finding = Glue::Finding.new( @trigger.appname, description, detail, source, severity, fingerprint, self.class.name ) @findings << finding end def warn warning @warnings << warning end def name @name end def description @description end def stage @stage end def directories_with? file, exclude_dirs = [] exclude_dirs = @tracker.options[:exclude_dirs] if exclude_dirs == [] and @tracker.options[:exclude_dirs] results = [] Find.find(@trigger.path) do |path| if FileTest.directory? path Find.prune if exclude_dirs.include? File.basename(path) or exclude_dirs.include? File.basename(path) + '/' next end Find.prune unless File.basename(path) == file results << File.dirname(path) end return results end def run end def analyze end def supported? end def severity sev sev = '' if sev.nil? return 1 if @severity_filter[:low].include?(sev.strip.chomp.downcase) return 2 if @severity_filter[:medium].include?(sev.strip.chomp.downcase) return 3 if @severity_filter[:high].include?(sev.strip.chomp.downcase) puts "unsupperted severity found: " + sev return 0 end end
# Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '1ed050557d36927f93a686b5d28c7eec9c2af50259dc2c59e2e6bba1d34e08d6216829fd0256c40bf49ef244ffb124c98d70a68a09d77bd410c0b1f95b108179' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '0b491cba6d410675c2ded24987f33af6bef1d98c52e11c23ede053cbbe33c71ba416b9c3d612fc5155379f933d46ffadb4163bb4f7d491f7e331d944b4a5b3c8' # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 1..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end Working on Logout # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` on Rails 4+ applications as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = '1ed050557d36927f93a686b5d28c7eec9c2af50259dc2c59e2e6bba1d34e08d6216829fd0256c40bf49ef244ffb124c98d70a68a09d77bd410c0b1f95b108179' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 10. If # using other encryptors, it sets how many times you want the password re-encrypted. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # encryptor), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 10 # Setup a pepper to generate the encrypted password. # config.pepper = '0b491cba6d410675c2ded24987f33af6bef1d98c52e11c23ede053cbbe33c71ba416b9c3d612fc5155379f933d46ffadb4163bb4f7d491f7e331d944b4a5b3c8' # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. Default is 0.days, meaning # the user cannot access the website without confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 1..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. # config.email_regexp = /\A[^@]+@[^@]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another encryption algorithm besides bcrypt (default). You can use # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) # and :restful_authentication_sha1 (then you should set stretches to 10, and copy # REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. # config.sign_out_via = :delete config.sign_out_via = :get # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' end
# Script used to convert a plist file to json require 'bundler/setup' require 'CFPropertyList' require 'set' require 'pathname' require 'JSON' if (__FILE__) == $0 if ARGV.count == 0 || ARGV.count > 2 puts "Usage : #{$0} input_plist_file (output_json_file)" exit end # Compute input file file_path = Pathname.new(File.expand_path(ARGV[0])) if !file_path.exist? puts "Error : \"#{file_path}\" not found" return end # Compute output file if (ARGV.count == 1) dest_path = Pathname.new(file_path.to_s.sub(".plist", "").concat(".json")) else dest_path = Pathname.new(ARGV[1]) end # Try to load file content input_file_content_plist = CFPropertyList::List.new(:file => file_path) if input_file_content_plist == nil puts "Error : cannot load \"#{file_path}\"" return end # Load plist content data = CFPropertyList.native_types(input_file_content_plist.value) # Convert to json if (dest_path.exist?()) dest_path.delete() end # Open output file dest_path.open('w') # Write JSON dest_path.write(JSON.generate(data)); end Fixed return # Script used to convert a plist file to json require 'bundler/setup' require 'CFPropertyList' require 'set' require 'pathname' require 'JSON' if (__FILE__) == $0 if ARGV.count == 0 || ARGV.count > 2 puts "Usage : #{$0} input_plist_file (output_json_file)" exit end # Compute input file file_path = Pathname.new(File.expand_path(ARGV[0])) if !file_path.exist? puts "Error : \"#{file_path}\" not found" exit end # Compute output file if (ARGV.count == 1) dest_path = Pathname.new(file_path.to_s.sub(".plist", "").concat(".json")) else dest_path = Pathname.new(ARGV[1]) end # Try to load file content input_file_content_plist = CFPropertyList::List.new(:file => file_path) if input_file_content_plist == nil puts "Error : cannot load \"#{file_path}\"" exit end # Load plist content data = CFPropertyList.native_types(input_file_content_plist.value) # Convert to json if (dest_path.exist?()) dest_path.delete() end # Open output file dest_path.open('w') # Write JSON dest_path.write(JSON.generate(data)); end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "payola_spy/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "payola_spy" s.version = PayolaSpy::VERSION s.authors = ["TODO: Your name"] s.email = ["TODO: Your email"] s.homepage = "TODO" s.summary = "TODO: Summary of PayolaSpy." s.description = "TODO: Description of PayolaSpy." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.1.8" s.add_dependency "payola-payments", "~> 1.2.4" s.add_dependency 'bootstrap-sass', '~> 3.2.0.0' s.add_dependency 'sass-rails', '>= 3.2' s.add_dependency 'kaminari', '~> 0.16.2' s.add_development_dependency "sqlite3" end Update gemspec $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "payola_spy/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "payola_spy" s.version = PayolaSpy::VERSION s.authors = ["Jeremy Green"] s.email = ["jeremy@octolabs.com"] s.homepage = "https://github.com/jagthedrummer/payola_spy" s.summary = "A quick and dirty Rails engine for watching Payola payment activity." s.description = "A quick and dirty Rails engine for watching Payola payment activity." s.license = "MIT" s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.rdoc"] s.test_files = Dir["test/**/*"] s.add_dependency "rails", "~> 4.1.8" s.add_dependency "payola-payments", "~> 1.2.4" s.add_dependency 'bootstrap-sass', '~> 3.2.0.0' s.add_dependency 'sass-rails', '>= 3.2' s.add_dependency 'kaminari', '~> 0.16.2' s.add_development_dependency "sqlite3" end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{paypal_nvp} s.version = "0.1.3" s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version= s.authors = ["Olivier BONNAURE - Direct Interactive LLC"] s.date = %q{2010-05-28} s.description = %q{Paypal NVP API Class.} s.email = %q{o.bonnaure@directinteractive.com} s.extra_rdoc_files = ["lib/paypal_nvp.rb", "README.rdoc"] s.files = ["init.rb", "lib/paypal_nvp.rb", "Manifest", "Rakefile", "README.rdoc", "paypal_nvp.gemspec"] s.homepage = %q{http://github.com/solisoft/paypal_nvp} s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Paypal_nvp", "--main", "README.rdoc"] s.require_paths = ["lib"] s.rubyforge_project = %q{paypal_nvp} s.rubygems_version = %q{1.3.5} s.summary = %q{Paypal NVP API Class.} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end gemspec 0.1.4 # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{paypal_nvp} s.version = "0.1.4" s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version= s.authors = ["Olivier BONNAURE - Direct Interactive LLC"] s.date = %q{2010-05-28} s.description = %q{Paypal NVP API Class.} s.email = %q{o.bonnaure@directinteractive.com} s.extra_rdoc_files = ["lib/paypal_nvp.rb", "README.rdoc"] s.files = ["init.rb", "lib/paypal_nvp.rb", "Manifest", "Rakefile", "README.rdoc", "paypal_nvp.gemspec"] s.homepage = %q{http://github.com/solisoft/paypal_nvp} s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Paypal_nvp", "--main", "README.rdoc"] s.require_paths = ["lib"] s.rubyforge_project = %q{paypal_nvp} s.rubygems_version = %q{1.3.5} s.summary = %q{Paypal NVP API Class.} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end
# encoding: utf-8 $:.push File.expand_path("../lib", __FILE__) require "payson_api/version" Gem::Specification.new do |s| s.name = "payson_api" s.version = PaysonAPI::VERSION s.authors = ["Christopher Svensson"] s.email = ["stoffus@stoffus.com"] s.homepage = "https://github.com/stoffus/payson_api" s.summary = %q{Client for Payson API} s.description = %q{Client that enables access to the Payson payment gateway API.} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency 'httpclient' end Updated dependencies # encoding: utf-8 $:.push File.expand_path("../lib", __FILE__) require "payson_api/version" Gem::Specification.new do |s| s.name = "payson_api" s.version = PaysonAPI::VERSION s.authors = ["Christopher Svensson"] s.email = ["stoffus@stoffus.com"] s.homepage = "https://github.com/stoffus/payson_api" s.summary = %q{Client for Payson API} s.description = %q{Client that enables access to the Payson payment gateway API.} s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.require_paths = ["lib"] s.add_dependency 'httpclient' s.add_development_dependency 'rake' s.add_development_dependency 'guard-test' end
module ActiveCMIS class Object include Internal::Caching attr_reader :repository, :used_parameters attr_reader :key alias id key def initialize(repository, data, parameters) @repository = repository @data = data @updated_attributes = [] if @data.nil? # Creating a new type from scratch raise "This type is not creatable" unless self.class.creatable @key = parameters["id"] @allowable_actions = {} @parent_folders = [] # start unlinked else @key = parameters["id"] || attribute('cmis:objectId') @self_link = data.xpath("at:link[@rel = 'self']/@href", NS::COMBINED).first @self_link = @self_link.text end @used_parameters = parameters # FIXME: decide? parameters to use?? always same ? or parameter with reload ? end def method_missing(method, *parameters) string = method.to_s if string[-1] == ?= assignment = true string = string[0..-2] end if attributes.keys.include? string if assignment update(string => parameters.first) else attribute(string) end elsif self.class.attribute_prefixes.include? string if assignment raise "Mass assignment not yet supported to prefix" else @attribute_prefix ||= {} @attribute_prefix[method] ||= AttributePrefix.new(self, string) end else super end end def inspect "#<#{self.class.inspect} @key=#{key}>" end def name attribute('cmis:name') end cache :name attr_reader :updated_attributes def attribute(name) attributes[name] end def attributes self.class.attributes.inject({}) do |hash, (key, attr)| if data.nil? if key == "cmis:objectTypeId" hash[key] = self.class.id else hash[key] = nil end else properties = data.xpath("cra:object/c:properties", NS::COMBINED) values = attr.extract_property(properties) hash[key] = if values.nil? || values.empty? if attr.repeating [] else nil end elsif attr.repeating values.map do |value| attr.property_type.cmis2rb(value) end else attr.property_type.cmis2rb(values.first) end end hash end end cache :attributes # Updates the given attributes, without saving the document # Use save to make these changes permanent and visible outside this instance of the document # (other #reload after save on other instances of this document to reflect the changes) def update(attributes) attributes.each do |key, value| if (property = self.class.attributes[key.to_s]).nil? raise "You are trying to add an unknown attribute (#{key})" else property.validate_ruby_value(value) end end self.updated_attributes.concat(attributes.keys).uniq! self.attributes.merge!(attributes) end # WARNING: because of the way CMIS is constructed the save operation is not atomic if updates happen to different aspects of the object # (parent folders, attributes, content stream, acl), we can't work around this because there is no transaction in CMIS either def save # FIXME: find a way to handle errors? # FIXME: what if multiple objects are created in the course of a save operation? result = self updated_aspects.each do |hash| result = result.send(hash[:message], *hash[:parameters]) end result end def allowable_actions actions = {} _allowable_actions.children.map do |node| actions[node.name.sub("can", "")] = case t = node.text when "true", "1"; true when "false", "0"; false else t end end actions end cache :allowable_actions # :section: Relationships # FIXME: this needs to be Folder and Document only def target_relations query = "at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href" link = data.xpath(query, NS::COMBINED) if link.length == 1 link = Internal::Utils.append_parameters(link.text, "relationshipDirection" => "target", "includeSubRelationshipTypes" => true) Collection.new(repository, link) else raise "Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder" end end cache :target_relations def source_relations query = "at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href" link = data.xpath(query, NS::COMBINED) if link.length == 1 link = Internal::Utils.append_parameters(link.text, "relationshipDirection" => "source", "includeSubRelationshipTypes" => true) Collection.new(repository, link) else raise "Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder" end end cache :source_relations # :section: ACL # All 4 subtypes can have an acl def acl if repository.acls_readable? && allowable_actions["GetACL"] # FIXME: actual query should perhaps look at CMIS version before deciding which relation is applicable? query = "at:link[@rel = '#{Rel[repository.cmis_version][:acl]}']/@href" link = data.xpath(query, NS::COMBINED) if link.length == 1 Acl.new(repository, self, link.first.text, data.xpath("cra:object/c:acl", NS::COMBINED)) else raise "Expected exactly 1 acl for #{key}, got #{link.length}" end end end # :section: Fileable # Depending on the repository there can be more than 1 parent folder # Always returns [] for relationships, policies may also return [] def parent_folders parent_feed = Internal::Utils.extract_links(data, 'up', 'application/atom+xml','type' => 'feed') unless parent_feed.empty? Collection.new(repository, parent_feed.first) else parent_entry = Internal::Utils.extract_links(data, 'up', 'application/atom+xml','type' => 'entries') unless parent_entry.empty? e = conn.get_atom_entry(parent_entry.first) [ActiveCMIS::Object.from_atom_entry(repository, e)] else [] end end end cache :parent_folders def file(folder) raise "Not supported" unless self.class.fileable @original_parent_folders ||= parent_folders.dup if repository.capabilities["MultiFiling"] @parent_folders << folder else @parent_folders = [folder] end end # FIXME: should throw exception if folder is not actually in @parent_folders? def unfile(folder = nil) raise "Not supported" unless self.class.fileable @original_parent_folders ||= parent_folders.dup if repository.capabilities["UnFiling"] if folder.nil? @parent_folders = [] else @parent_folders.delete(folder) end elsif @parent_folders.length > 1 @parent_folders.delete(folder) else raise "Unfiling not supported by the repository" end end def reload if @self_link.nil? raise "Can't reload unsaved object" else __reload @updated_attributes = [] @original_parent_folders = nil end end private def self_link(options = {}) url = @self_link if options.empty? url else Internal::Utils.append_parameters(url, options) end #repository.object_by_id_url(options.merge("id" => id)) end def data parameters = {"includeAllowableActions" => true, "renditionFilter" => "*", "includeACL" => true} data = conn.get_atom_entry(self_link(parameters)) @used_parameters = parameters data end cache :data def conn @repository.conn end def _allowable_actions if actions = data.xpath('cra:object/c:allowableActions', NS::COMBINED).first actions else links = data.xpath("at:link[@rel = '#{Rel[repository.cmis_version][:allowableactions]}']/@href", NS::COMBINED) if link = links.first conn.get_xml(link.text) else nil end end end # Optional parameters: # - properties: a hash key/definition pairs of properties to be rendered (defaults to all attributes) # - attributes: a hash key/value pairs used to determine the values rendered (defaults to self.attributes) def render_atom_entry(properties = self.class.attributes, attributes = self.attributes) builder = Nokogiri::XML::Builder.new do |xml| xml.entry(NS::COMBINED) do xml.parent.namespace = xml.parent.namespace_definitions.detect {|ns| ns.prefix == "at"} xml["at"].author do xml["at"].name conn.user # FIXME: find reliable way to set author? end xml["cra"].object do xml["c"].properties do properties.each do |key, definition| definition.render_property(xml, attributes[key]) end end end end end builder.to_xml end attr_writer :updated_attributes def updated_aspects(checkin = nil) result = [] if key.nil? result << {:message => :save_new_object, :parameters => []} if parent_folders.length > 1 # We started from 0 folders, we already added the first when creating the document # Note: to keep a save operation at least somewhat atomic this might be better done in save_new_object result << {:message => :save_folders, :parameters => [parent_folders]} end else if !updated_attributes.empty? result << {:message => :save_attributes, :parameters => [updated_attributes, attributes, checkin]} end if @original_parent_folders result << {:message => :save_folders, :parameters => [parent_folders, checkin && !updated_attributes]} end end if acl && acl.updated # We need to be able to do this for newly created documents and merge the two result << {:message => :save_acl, :parameters => [acl]} end if result.empty? && checkin # NOTE: this needs some thinking through: in particular this may not work well if there would be an updated content stream result << {:message => :save_attributes, :parameters => [[], [], checkin]} end result end def save_new_object if self.class.required_attributes.any? {|a, _| attribute(a).nil? } raise "Not all required attributes are filled in" end properties = self.class.attributes.reject do |key, definition| !updated_attributes.include?(key) && !definition.required end body = render_atom_entry(properties) url = create_url response = conn.post(create_url, body, "Content-Type" => "application/atom+xml;type=entry") # XXX: Currently ignoring Location header in response response_data = Nokogiri::XML::parse(response).xpath("at:entry", NS::COMBINED) # Assume that a response indicates success? @self_link = response_data.xpath("at:link[@rel = 'self']/@href", NS::COMBINED).first @self_link = @self_link.text reload @key = attribute("cmis:objectId") self end def save_attributes(attributes, values, checkin = nil) if attributes.empty? && checkin.nil? raise "Error: saving attributes but nothing to do" end properties = self.class.attributes.reject {|key,_| !attributes.include?(key)} body = render_atom_entry(properties, values) if checkin.nil? parameters = {} else checkin, major, comment = *checkin parameters = {"checkin" => checkin} if checkin parameters.merge! "major" => !!major, "checkinComment" => Internal::Utils.escape_url_parameter(comment) if properties.empty? body = nil end end end # NOTE: Spec says Entity Tag should be used for changeTokens, that does not seem to work if ct = attribute("cmis:changeToken") parameters.merge! "changeToken" => Internal::Utils.escape_url_parameter(ct) end uri = self_link(parameters) response = conn.put(uri, body) data = Nokogiri::XML.parse(response).xpath("at:entry", NS::COMBINED) if data.xpath("cra:object/c:properties/c:propertyId[@propertyDefinitionId = 'cmis:objectId']/c:value", NS::COMBINED).text == id reload @data = data self else reload # Updated attributes should be forgotten here ActiveCMIS::Object.from_atom_entry(repository, data) end end def save_folders(requested_parent_folders, checkin = nil) current = parent_folders.to_a future = requested_parent_folders.to_a common_folders = future.map {|f| f.id}.select {|id| current.any? {|f| f.id == id } } added = future.select {|f1| current.all? {|f2| f1.id != f2.id } } removed = current.select {|f1| future.all? {|f2| f1.id != f2.id } } # NOTE: an absent atom:content is important here according to the spec, for the moment I did not suffer from this body = render_atom_entry("cmis:objectId" => self.class.attributes["cmis:objectId"]) # Note: change token does not seem to matter here # FIXME: currently we assume the data returned by post is not important, I'm not sure that this is always true if added.empty? removed.each do |folder| url = repository.unfiled.url url = Internal::Utils.append_parameters(url, "removeFrom" => Internal::Utils.escape_url_parameter(removed.id)) conn.post(url, body, "Content-Type" => "application/atom+xml;type=entry") end elsif removed.empty? added.each do |folder| conn.post(folder.items.url, body, "Content-Type" => "application/atom+xml;type=entry") end else removed.zip(added) do |r, a| url = a.items.url url = Internal::Utils.append_parameters(url, "sourceFolderId" => Internal::Utils.escape_url_parameter(r.id)) conn.post(url, body, "Content-Type" => "application/atom+xml;type=entry") end if extra = added[removed.length..-1] extra.each do |folder| conn.post(folder.items.url, body, "Content-Type" => "application/atom+xml;type=entry") end end end self end def save_acl(acl) acl.save reload self end class << self attr_reader :repository def from_atom_entry(repository, data, parameters = {}) query = "cra:object/c:properties/c:propertyId[@propertyDefinitionId = '%s']/c:value" type_id = data.xpath(query % "cmis:objectTypeId", NS::COMBINED).text klass = repository.type_by_id(type_id) if klass if klass <= self klass.new(repository, data, parameters) else raise "You tried to do from_atom_entry on a type which is not a supertype of the type of the document you identified" end else raise "The object #{extract_property(data, "String", 'cmis:name')} has an unrecognized type #{type_id}" end end def from_parameters(repository, parameters) url = repository.object_by_id_url(parameters) data = repository.conn.get_atom_entry(url) from_atom_entry(repository, data, parameters) end def attributes(inherited = false) {} end def key raise NotImplementedError end end end end Small fixes module ActiveCMIS class Object include Internal::Caching attr_reader :repository, :used_parameters attr_reader :key alias id key def initialize(repository, data, parameters) @repository = repository @data = data @updated_attributes = [] if @data.nil? # Creating a new type from scratch raise "This type is not creatable" unless self.class.creatable @key = parameters["id"] @allowable_actions = {} @parent_folders = [] # start unlinked else @key = parameters["id"] || attribute('cmis:objectId') @self_link = data.xpath("at:link[@rel = 'self']/@href", NS::COMBINED).first @self_link = @self_link.text end @used_parameters = parameters # FIXME: decide? parameters to use?? always same ? or parameter with reload ? end def method_missing(method, *parameters) string = method.to_s if string[-1] == ?= assignment = true string = string[0..-2] end if attributes.keys.include? string if assignment update(string => parameters.first) else attribute(string) end elsif self.class.attribute_prefixes.include? string if assignment raise "Mass assignment not yet supported to prefix" else @attribute_prefix ||= {} @attribute_prefix[method] ||= AttributePrefix.new(self, string) end else super end end def inspect "#<#{self.class.inspect} @key=#{key}>" end def name attribute('cmis:name') end cache :name attr_reader :updated_attributes def attribute(name) attributes[name] end def attributes self.class.attributes.inject({}) do |hash, (key, attr)| if data.nil? if key == "cmis:objectTypeId" hash[key] = self.class.id else hash[key] = nil end else properties = data.xpath("cra:object/c:properties", NS::COMBINED) values = attr.extract_property(properties) hash[key] = if values.nil? || values.empty? if attr.repeating [] else nil end elsif attr.repeating values.map do |value| attr.property_type.cmis2rb(value) end else attr.property_type.cmis2rb(values.first) end end hash end end cache :attributes # Updates the given attributes, without saving the document # Use save to make these changes permanent and visible outside this instance of the document # (other #reload after save on other instances of this document to reflect the changes) def update(attributes) attributes.each do |key, value| if (property = self.class.attributes[key.to_s]).nil? raise "You are trying to add an unknown attribute (#{key})" else property.validate_ruby_value(value) end end self.updated_attributes.concat(attributes.keys).uniq! self.attributes.merge!(attributes) end # WARNING: because of the way CMIS is constructed the save operation is not atomic if updates happen to different aspects of the object # (parent folders, attributes, content stream, acl), we can't work around this because there is no transaction in CMIS either def save # FIXME: find a way to handle errors? # FIXME: what if multiple objects are created in the course of a save operation? result = self updated_aspects.each do |hash| result = result.send(hash[:message], *hash[:parameters]) end result end def allowable_actions actions = {} _allowable_actions.children.map do |node| actions[node.name.sub("can", "")] = case t = node.text when "true", "1"; true when "false", "0"; false else t end end actions end cache :allowable_actions # :section: Relationships # FIXME: this needs to be Folder and Document only def target_relations query = "at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href" link = data.xpath(query, NS::COMBINED) if link.length == 1 link = Internal::Utils.append_parameters(link.text, "relationshipDirection" => "target", "includeSubRelationshipTypes" => true) Collection.new(repository, link) else raise "Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder" end end cache :target_relations def source_relations query = "at:link[@rel = '#{Rel[repository.cmis_version][:relationships]}']/@href" link = data.xpath(query, NS::COMBINED) if link.length == 1 link = Internal::Utils.append_parameters(link.text, "relationshipDirection" => "source", "includeSubRelationshipTypes" => true) Collection.new(repository, link) else raise "Expected exactly 1 relationships link for #{key}, got #{link.length}, are you sure this is a document/folder" end end cache :source_relations # :section: ACL # All 4 subtypes can have an acl def acl if repository.acls_readable? && allowable_actions["GetACL"] # FIXME: actual query should perhaps look at CMIS version before deciding which relation is applicable? query = "at:link[@rel = '#{Rel[repository.cmis_version][:acl]}']/@href" link = data.xpath(query, NS::COMBINED) if link.length == 1 Acl.new(repository, self, link.first.text, data.xpath("cra:object/c:acl", NS::COMBINED)) else raise "Expected exactly 1 acl for #{key}, got #{link.length}" end end end # :section: Fileable # Depending on the repository there can be more than 1 parent folder # Always returns [] for relationships, policies may also return [] def parent_folders parent_feed = Internal::Utils.extract_links(data, 'up', 'application/atom+xml','type' => 'feed') unless parent_feed.empty? Collection.new(repository, parent_feed.first) else parent_entry = Internal::Utils.extract_links(data, 'up', 'application/atom+xml','type' => 'entries') unless parent_entry.empty? e = conn.get_atom_entry(parent_entry.first) [ActiveCMIS::Object.from_atom_entry(repository, e)] else [] end end end cache :parent_folders def file(folder) raise "Not supported" unless self.class.fileable @original_parent_folders ||= parent_folders.dup if repository.capabilities["MultiFiling"] @parent_folders << folder else @parent_folders = [folder] end end # FIXME: should throw exception if folder is not actually in @parent_folders? def unfile(folder = nil) raise "Not supported" unless self.class.fileable @original_parent_folders ||= parent_folders.dup if repository.capabilities["UnFiling"] if folder.nil? @parent_folders = [] else @parent_folders.delete(folder) end elsif @parent_folders.length > 1 @parent_folders.delete(folder) else raise "Unfiling not supported by the repository" end end def reload if @self_link.nil? raise "Can't reload unsaved object" else __reload @updated_attributes = [] @original_parent_folders = nil end end private def self_link(options = {}) url = @self_link if options.empty? url else Internal::Utils.append_parameters(url, options) end #repository.object_by_id_url(options.merge("id" => id)) end def data parameters = {"includeAllowableActions" => true, "renditionFilter" => "*", "includeACL" => true} data = conn.get_atom_entry(self_link(parameters)) @used_parameters = parameters data end cache :data def conn @repository.conn end def _allowable_actions if actions = data.xpath('cra:object/c:allowableActions', NS::COMBINED).first actions else links = data.xpath("at:link[@rel = '#{Rel[repository.cmis_version][:allowableactions]}']/@href", NS::COMBINED) if link = links.first conn.get_xml(link.text) else nil end end end # Optional parameters: # - properties: a hash key/definition pairs of properties to be rendered (defaults to all attributes) # - attributes: a hash key/value pairs used to determine the values rendered (defaults to self.attributes) def render_atom_entry(properties = self.class.attributes, attributes = self.attributes) builder = Nokogiri::XML::Builder.new do |xml| xml.entry(NS::COMBINED) do xml.parent.namespace = xml.parent.namespace_definitions.detect {|ns| ns.prefix == "at"} xml["at"].author do xml["at"].name conn.user # FIXME: find reliable way to set author? end xml["cra"].object do xml["c"].properties do properties.each do |key, definition| definition.render_property(xml, attributes[key]) end end end end end builder.to_xml end attr_writer :updated_attributes def updated_aspects(checkin = nil) result = [] if key.nil? result << {:message => :save_new_object, :parameters => []} if parent_folders.length > 1 # We started from 0 folders, we already added the first when creating the document # Note: to keep a save operation at least somewhat atomic this might be better done in save_new_object result << {:message => :save_folders, :parameters => [parent_folders]} end else if !updated_attributes.empty? result << {:message => :save_attributes, :parameters => [updated_attributes, attributes, checkin]} end if @original_parent_folders result << {:message => :save_folders, :parameters => [parent_folders, checkin && !updated_attributes]} end end if acl && acl.updated # We need to be able to do this for newly created documents and merge the two result << {:message => :save_acl, :parameters => [acl]} end if result.empty? && checkin # NOTE: this needs some thinking through: in particular this may not work well if there would be an updated content stream result << {:message => :save_attributes, :parameters => [[], [], checkin]} end result end def save_new_object if self.class.required_attributes.any? {|a, _| attribute(a).nil? } raise "Not all required attributes are filled in" end properties = self.class.attributes.reject do |key, definition| !updated_attributes.include?(key) && !definition.required end body = render_atom_entry(properties) url = create_url response = conn.post(create_url, body, "Content-Type" => "application/atom+xml;type=entry") # XXX: Currently ignoring Location header in response response_data = Nokogiri::XML::parse(response).xpath("at:entry", NS::COMBINED) # Assume that a response indicates success? @self_link = response_data.xpath("at:link[@rel = 'self']/@href", NS::COMBINED).first @self_link = @self_link.text reload @key = attribute("cmis:objectId") self end def save_attributes(attributes, values, checkin = nil) if attributes.empty? && checkin.nil? raise "Error: saving attributes but nothing to do" end properties = self.class.attributes.reject {|key,_| !updated_attributes.include?(key)} body = render_atom_entry(properties, values) if checkin.nil? parameters = {} else checkin, major, comment = *checkin parameters = {"checkin" => checkin} if checkin parameters.merge! "major" => !!major, "checkinComment" => Internal::Utils.escape_url_parameter(comment) if properties.empty? # The standard specifies that we can have an empty body here, that does not seem to be true for OpenCMIS # body = "" end end end # NOTE: Spec says Entity Tag should be used for changeTokens, that does not seem to work if ct = attribute("cmis:changeToken") parameters.merge! "changeToken" => Internal::Utils.escape_url_parameter(ct) end uri = self_link(parameters) response = conn.put(uri, body) data = Nokogiri::XML.parse(response).xpath("at:entry", NS::COMBINED) if data.xpath("cra:object/c:properties/c:propertyId[@propertyDefinitionId = 'cmis:objectId']/c:value", NS::COMBINED).text == id reload @data = data self else reload # Updated attributes should be forgotten here ActiveCMIS::Object.from_atom_entry(repository, data) end end def save_folders(requested_parent_folders, checkin = nil) current = parent_folders.to_a future = requested_parent_folders.to_a common_folders = future.map {|f| f.id}.select {|id| current.any? {|f| f.id == id } } added = future.select {|f1| current.all? {|f2| f1.id != f2.id } } removed = current.select {|f1| future.all? {|f2| f1.id != f2.id } } # NOTE: an absent atom:content is important here according to the spec, for the moment I did not suffer from this body = render_atom_entry("cmis:objectId" => self.class.attributes["cmis:objectId"]) # Note: change token does not seem to matter here # FIXME: currently we assume the data returned by post is not important, I'm not sure that this is always true if added.empty? removed.each do |folder| url = repository.unfiled.url url = Internal::Utils.append_parameters(url, "removeFrom" => Internal::Utils.escape_url_parameter(removed.id)) conn.post(url, body, "Content-Type" => "application/atom+xml;type=entry") end elsif removed.empty? added.each do |folder| conn.post(folder.items.url, body, "Content-Type" => "application/atom+xml;type=entry") end else removed.zip(added) do |r, a| url = a.items.url url = Internal::Utils.append_parameters(url, "sourceFolderId" => Internal::Utils.escape_url_parameter(r.id)) conn.post(url, body, "Content-Type" => "application/atom+xml;type=entry") end if extra = added[removed.length..-1] extra.each do |folder| conn.post(folder.items.url, body, "Content-Type" => "application/atom+xml;type=entry") end end end self end def save_acl(acl) acl.save reload self end class << self attr_reader :repository def from_atom_entry(repository, data, parameters = {}) query = "cra:object/c:properties/c:propertyId[@propertyDefinitionId = '%s']/c:value" type_id = data.xpath(query % "cmis:objectTypeId", NS::COMBINED).text klass = repository.type_by_id(type_id) if klass if klass <= self klass.new(repository, data, parameters) else raise "You tried to do from_atom_entry on a type which is not a supertype of the type of the document you identified" end else raise "The object #{extract_property(data, "String", 'cmis:name')} has an unrecognized type #{type_id}" end end def from_parameters(repository, parameters) url = repository.object_by_id_url(parameters) data = repository.conn.get_atom_entry(url) from_atom_entry(repository, data, parameters) end def attributes(inherited = false) {} end def key raise NotImplementedError end end end end
module ActsAsItem module ModelMethods def self.included(base) base.extend ClassMethods end module ClassMethods def item? return true if self.respond_to?(:item) false end def acts_as_item acts_as_rateable belongs_to :user has_many :taggings, :as => :taggable has_many :tags, :through => :taggings has_many :comments, :as => :commentable, :order => 'created_at ASC' include ActsAsItem::ModelMethods::InstanceMethods end def icon 'item_icons/' + self.to_s.underscore + '.png' end end module InstanceMethods def icon self.class.icon end def string_tags= arg # Take a list of tag, space separated and assign them to the object @string_tags = arg arg.split(' ').each do |tag_name| tag = Tag.find_by_name(tag_name) || Tag.new(:name => tag_name) self.taggings.build(:tag => tag) end end def string_tags # Return space separated tag names return @string_tags if @string_tags tags.collect { |t| t.name }.join(' ') if tags && tags.size > 0 end def associated_workspaces= workspace_ids self.workspaces.delete_all workspace_ids.each { |w| self.items.build(:workspace_id => w) } end def accepts_role? role, user begin auth_method = "accepts_#{role.downcase}?" return (send(auth_method, user)) if defined?(auth_method) raise("Auth method not defined") rescue Exception => e p(e) and raise(e) end end private # Is user authorized to consult this item? def accepts_consultation? user # Admin return true if user.is_admin? # Author return true if self.user == user # Member of one assigned WS self.workspaces.each do |ws| return true if ws.users.include?(user) end false end # Is user authorized to delete this item? def accepts_deletion? user # Admin return true if user.is_admin? # Author return true if self.user == user false end # Is user authorized to edit this item? def accepts_edition? user # Admin return true if user.is_admin? # Author return true if self.user == user # TODO: Allow creator or moderator of WS to edit items false end # Is user authorized to create one item? def accepts_creation? user true if user end end end end Fixed: duplication of tags on edit module ActsAsItem module ModelMethods def self.included(base) base.extend ClassMethods end module ClassMethods def item? return true if self.respond_to?(:item) false end def acts_as_item acts_as_rateable belongs_to :user has_many :taggings, :as => :taggable has_many :tags, :through => :taggings has_many :comments, :as => :commentable, :order => 'created_at ASC' include ActsAsItem::ModelMethods::InstanceMethods end def icon 'item_icons/' + self.to_s.underscore + '.png' end end module InstanceMethods def icon self.class.icon end # Take a list of tag, space separated and assign them to the object def string_tags= arg @string_tags = arg tag_names = arg.split(' ') # Delete all tags that are no more associated taggings.each do |tagging| tagging.destroy unless tag_names.delete(tagging.tag.name) end # Insert new tags tag_names.each do |tag_name| tag = Tag.find_by_name(tag_name) || Tag.new(:name => tag_name) self.taggings.build(:tag => tag) end end def string_tags # Return space separated tag names return @string_tags if @string_tags tags.collect { |t| t.name }.join(' ') if tags && tags.size > 0 end def associated_workspaces= workspace_ids self.workspaces.delete_all workspace_ids.each { |w| self.items.build(:workspace_id => w) } end def accepts_role? role, user begin auth_method = "accepts_#{role.downcase}?" return (send(auth_method, user)) if defined?(auth_method) raise("Auth method not defined") rescue Exception => e p(e) and raise(e) end end private # Is user authorized to consult this item? def accepts_consultation? user # Admin return true if user.is_admin? # Author return true if self.user == user # Member of one assigned WS self.workspaces.each do |ws| return true if ws.users.include?(user) end false end # Is user authorized to delete this item? def accepts_deletion? user # Admin return true if user.is_admin? # Author return true if self.user == user false end # Is user authorized to edit this item? def accepts_edition? user # Admin return true if user.is_admin? # Author return true if self.user == user # TODO: Allow creator or moderator of WS to edit items false end # Is user authorized to create one item? def accepts_creation? user true if user end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'peerflixrb/version' Gem::Specification.new do |spec| spec.name = 'peerflixrb' spec.version = Peerflixrb::VERSION spec.authors = ['David Marchante'] spec.email = ['davidmarchan@gmail.com'] spec.summary = 'Wrapper for peerflix with automatic search through KickAss Torrents, Yifysubtitles and Addic7ed.' spec.description = %q{With peerflixrb you can search for movies and TV shows and stream them directly on your favorite video player! You can choose the torrent and the subtitles file or you can let it choose the best for you.} spec.homepage = 'https://github.com/iovis9/peerflixrb' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = 'peerflixrb' spec.require_paths = ['lib'] spec.add_runtime_dependency 'addic7ed_downloader', '~> 1.0' spec.add_runtime_dependency 'extratorrent_search', '~> 1.0' spec.add_runtime_dependency 'nokogiri', '~> 1.6' spec.add_runtime_dependency 'highline', '~> 1.7' spec.add_runtime_dependency 'httparty', '~> 0.13' spec.add_runtime_dependency 'rubyzip', '~> 1.2' spec.add_development_dependency 'bundler', '~> 1.12' spec.add_development_dependency 'rake', '~> 11.1' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'guard-rspec', '~> 4.6' spec.add_development_dependency 'factory_girl', '~> 4.5' spec.add_development_dependency 'webmock', '~> 2.0' spec.add_development_dependency 'pry', '~> 0.10' spec.add_development_dependency 'pry-byebug', '~> 3.3' end Came back to zooqle # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'peerflixrb/version' Gem::Specification.new do |spec| spec.name = 'peerflixrb' spec.version = Peerflixrb::VERSION spec.authors = ['David Marchante'] spec.email = ['davidmarchan@gmail.com'] spec.summary = 'Wrapper for peerflix with automatic search through KickAss Torrents, Yifysubtitles and Addic7ed.' spec.description = %q{With peerflixrb you can search for movies and TV shows and stream them directly on your favorite video player! You can choose the torrent and the subtitles file or you can let it choose the best for you.} spec.homepage = 'https://github.com/iovis9/peerflixrb' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = 'peerflixrb' spec.require_paths = ['lib'] spec.add_runtime_dependency 'addic7ed_downloader', '~> 1.0' spec.add_runtime_dependency 'zooqle_search', '~> 1.0' spec.add_runtime_dependency 'nokogiri', '~> 1.6' spec.add_runtime_dependency 'highline', '~> 1.7' spec.add_runtime_dependency 'httparty', '~> 0.13' spec.add_runtime_dependency 'rubyzip', '~> 1.2' spec.add_development_dependency 'bundler', '~> 1.12' spec.add_development_dependency 'rake', '~> 11.1' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'guard-rspec', '~> 4.6' spec.add_development_dependency 'factory_girl', '~> 4.5' spec.add_development_dependency 'webmock', '~> 2.0' spec.add_development_dependency 'pry', '~> 0.10' spec.add_development_dependency 'pry-byebug', '~> 3.3' end
module Adminpanel VERSION = '3.3.3' end bump version module Adminpanel VERSION = '3.3.4' end
module Alexandrie VERSION = '0.1.5.2' end Increment version number module Alexandrie VERSION = '0.1.6.1' end
Adding root cups module module Algorithmable module Cups autoload :Primitives, 'algorithmable/cups/primitives' end end
# ~*~ encoding: utf-8 ~*~ module Gollum # Responsible for handling the commit process for a Wiki. It sets up the # Git index, provides methods for modifying the tree, and stores callbacks # to be fired after the commit has been made. This is specifically # designed to handle multiple updated pages in a single commit. class Committer # Gets the instance of the Gollum::Wiki that is being updated. attr_reader :wiki # Gets a Hash of commit options. attr_reader :options # Initializes the Committer. # # wiki - The Gollum::Wiki instance that is being updated. # options - The commit Hash details: # :message - The String commit message. # :name - The String author full name. # :email - The String email address. # :parent - Optional Gollum::Git::Commit parent to this update. # :tree - Optional String SHA of the tree to create the # index from. # :committer - Optional Gollum::Committer instance. If provided, # assume that this operation is part of batch of # updates and the commit happens later. # # Returns the Committer instance. def initialize(wiki, options = {}) @wiki = wiki @options = options @callbacks = [] end # Public: References the Git index for this commit. # # Returns a Gollum::Git::Index. def index @index ||= begin idx = @wiki.repo.index if (tree = options[:tree]) idx.read_tree(tree) elsif (parent = parents.first) idx.read_tree(parent.tree.id) end idx end end # Public: The committer for this commit. # # Returns a Gollum::Git::Actor. def actor @actor ||= begin @options[:name] = @wiki.default_committer_name if @options[:name].nil? @options[:email] = @wiki.default_committer_email if @options[:email].nil? Gollum::Git::Actor.new(@options[:name], @options[:email]) end end # Public: The parent commits to this pending commit. # # Returns an array of Gollum::Git::Commit instances. def parents @parents ||= begin arr = [@options[:parent] || @wiki.repo.commit(@wiki.ref)] arr.flatten! arr.compact! arr end end # Adds a page to the given Index. # # dir - The String subdirectory of the Gollum::Page without any # prefix or suffix slashes (e.g. "foo/bar"). # name - The String Gollum::Page filename_stripped. # format - The Symbol Gollum::Page format. # data - The String wiki data to store in the tree map. # # Raises Gollum::DuplicatePageError if a matching filename already exists. # This way, pages are not inadvertently overwritten. # # Returns nothing (modifies the Index in place). def add_to_index(dir, name, format, data) path = @wiki.page_file_name(name, format) dir = '/' if dir.strip.empty? fullpath = ::File.join(*[dir, path]) fullpath = fullpath[1..-1] if fullpath =~ /^\// if index.current_tree && (tree = index.current_tree / (@wiki.page_file_dir || '/')) tree = tree / dir unless tree.nil? end if tree downpath = path.downcase.sub(/\.\w+$/, '') tree.blobs.each do |blob| next if page_path_scheduled_for_deletion?(index.tree, fullpath) existing_file = blob.name.downcase.sub(/\.\w+$/, '') existing_file_ext = ::File.extname(blob.name).sub(/^\./, '') new_file_ext = ::File.extname(path).sub(/^\./, '') if downpath == existing_file && (new_file_ext == existing_file_ext) raise DuplicatePageError.new(dir, blob.name, path) end end end # TODO Remove once grit is deprecated if Gollum::GIT_ADAPTER == 'grit' fullpath = fullpath.force_encoding('ascii-8bit') if fullpath.respond_to?(:force_encoding) end begin data = @wiki.normalize(data) rescue ArgumentError => err # Swallow errors that arise from data being binary raise err unless err.message.include?('invalid byte sequence') end index.add(fullpath, data) end # Update the given file in the repository's working directory if there # is a working directory present. # # dir - The String directory in which the file lives. # name - The String name of the page or the stripped filename # (should be pre-canonicalized if required). # format - The Symbol format of the page. # # Returns nothing. def update_working_dir(dir, name, format) $stderr.puts "args to update_working_dir are: #{dir} and #{name} and #{format}" unless @wiki.repo.bare if @wiki.page_file_dir && dir !~ /^#{@wiki.page_file_dir}/ dir = dir.size.zero? ? @wiki.page_file_dir : ::File.join(@wiki.page_file_dir, dir) end path = if dir == '' @wiki.page_file_name(name, format) else ::File.join(dir, @wiki.page_file_name(name, format)) end if Gollum::GIT_ADAPTER == 'grit' path = path.force_encoding('ascii-8bit') if path.respond_to?(:force_encoding) end Dir.chdir(::File.join(@wiki.repo.path, '..')) do if file_path_scheduled_for_deletion?(index.tree, path) @wiki.repo.git.rm(path, :force => true) else @wiki.repo.git.checkout(path, 'HEAD') end end end end # Writes the commit to Git and runs the after_commit callbacks. # # Returns the String SHA1 of the new commit. def commit sha1 = index.commit(@options[:message], parents, actor, nil, @wiki.ref) @callbacks.each do |cb| cb.call(self, sha1) end Hook.execute(:post_commit, self, sha1) sha1 end # Adds a callback to be fired after a commit. # # block - A block that expects this Committer instance and the created # commit's SHA1 as the arguments. # # Returns nothing. def after_commit(&block) @callbacks << block end # Determine if a given page (regardless of format) is scheduled to be # deleted in the next commit for the given Index. # # map - The Hash map: # key - The String directory or filename. # val - The Hash submap or the String contents of the file. # path - The String path of the page file. This may include the format # extension in which case it will be ignored. # # Returns the Boolean response. def page_path_scheduled_for_deletion?(map, path) parts = path.split('/') if parts.size == 1 deletions = map.keys.select { |k| !map[k] } downfile = parts.first.downcase.sub(/\.\w+$/, '') deletions.any? { |d| d.downcase.sub(/\.\w+$/, '') == downfile } else part = parts.shift if (rest = map[part]) page_path_scheduled_for_deletion?(rest, parts.join('/')) else false end end end # Determine if a given file is scheduled to be deleted in the next commit # for the given Index. # # map - The Hash map: # key - The String directory or filename. # val - The Hash submap or the String contents of the file. # path - The String path of the file including extension. # # Returns the Boolean response. def file_path_scheduled_for_deletion?(map, path) parts = path.split('/') if parts.size == 1 deletions = map.keys.select { |k| !map[k] } deletions.any? { |d| d == parts.first } else part = parts.shift if (rest = map[part]) file_path_scheduled_for_deletion?(rest, parts.join('/')) else false end end end # Proxies methods t def method_missing(name, *args) args.map! { |item| item.respond_to?(:force_encoding) ? item.force_encoding('ascii-8bit') : item } if Gollum::GIT_ADAPTER == 'grit' index.send(name, *args) end end end Remove debugging statement. # ~*~ encoding: utf-8 ~*~ module Gollum # Responsible for handling the commit process for a Wiki. It sets up the # Git index, provides methods for modifying the tree, and stores callbacks # to be fired after the commit has been made. This is specifically # designed to handle multiple updated pages in a single commit. class Committer # Gets the instance of the Gollum::Wiki that is being updated. attr_reader :wiki # Gets a Hash of commit options. attr_reader :options # Initializes the Committer. # # wiki - The Gollum::Wiki instance that is being updated. # options - The commit Hash details: # :message - The String commit message. # :name - The String author full name. # :email - The String email address. # :parent - Optional Gollum::Git::Commit parent to this update. # :tree - Optional String SHA of the tree to create the # index from. # :committer - Optional Gollum::Committer instance. If provided, # assume that this operation is part of batch of # updates and the commit happens later. # # Returns the Committer instance. def initialize(wiki, options = {}) @wiki = wiki @options = options @callbacks = [] end # Public: References the Git index for this commit. # # Returns a Gollum::Git::Index. def index @index ||= begin idx = @wiki.repo.index if (tree = options[:tree]) idx.read_tree(tree) elsif (parent = parents.first) idx.read_tree(parent.tree.id) end idx end end # Public: The committer for this commit. # # Returns a Gollum::Git::Actor. def actor @actor ||= begin @options[:name] = @wiki.default_committer_name if @options[:name].nil? @options[:email] = @wiki.default_committer_email if @options[:email].nil? Gollum::Git::Actor.new(@options[:name], @options[:email]) end end # Public: The parent commits to this pending commit. # # Returns an array of Gollum::Git::Commit instances. def parents @parents ||= begin arr = [@options[:parent] || @wiki.repo.commit(@wiki.ref)] arr.flatten! arr.compact! arr end end # Adds a page to the given Index. # # dir - The String subdirectory of the Gollum::Page without any # prefix or suffix slashes (e.g. "foo/bar"). # name - The String Gollum::Page filename_stripped. # format - The Symbol Gollum::Page format. # data - The String wiki data to store in the tree map. # # Raises Gollum::DuplicatePageError if a matching filename already exists. # This way, pages are not inadvertently overwritten. # # Returns nothing (modifies the Index in place). def add_to_index(dir, name, format, data) path = @wiki.page_file_name(name, format) dir = '/' if dir.strip.empty? fullpath = ::File.join(*[dir, path]) fullpath = fullpath[1..-1] if fullpath =~ /^\// if index.current_tree && (tree = index.current_tree / (@wiki.page_file_dir || '/')) tree = tree / dir unless tree.nil? end if tree downpath = path.downcase.sub(/\.\w+$/, '') tree.blobs.each do |blob| next if page_path_scheduled_for_deletion?(index.tree, fullpath) existing_file = blob.name.downcase.sub(/\.\w+$/, '') existing_file_ext = ::File.extname(blob.name).sub(/^\./, '') new_file_ext = ::File.extname(path).sub(/^\./, '') if downpath == existing_file && (new_file_ext == existing_file_ext) raise DuplicatePageError.new(dir, blob.name, path) end end end # TODO Remove once grit is deprecated if Gollum::GIT_ADAPTER == 'grit' fullpath = fullpath.force_encoding('ascii-8bit') if fullpath.respond_to?(:force_encoding) end begin data = @wiki.normalize(data) rescue ArgumentError => err # Swallow errors that arise from data being binary raise err unless err.message.include?('invalid byte sequence') end index.add(fullpath, data) end # Update the given file in the repository's working directory if there # is a working directory present. # # dir - The String directory in which the file lives. # name - The String name of the page or the stripped filename # (should be pre-canonicalized if required). # format - The Symbol format of the page. # # Returns nothing. def update_working_dir(dir, name, format) unless @wiki.repo.bare if @wiki.page_file_dir && dir !~ /^#{@wiki.page_file_dir}/ dir = dir.size.zero? ? @wiki.page_file_dir : ::File.join(@wiki.page_file_dir, dir) end path = if dir == '' @wiki.page_file_name(name, format) else ::File.join(dir, @wiki.page_file_name(name, format)) end if Gollum::GIT_ADAPTER == 'grit' path = path.force_encoding('ascii-8bit') if path.respond_to?(:force_encoding) end Dir.chdir(::File.join(@wiki.repo.path, '..')) do if file_path_scheduled_for_deletion?(index.tree, path) @wiki.repo.git.rm(path, :force => true) else @wiki.repo.git.checkout(path, 'HEAD') end end end end # Writes the commit to Git and runs the after_commit callbacks. # # Returns the String SHA1 of the new commit. def commit sha1 = index.commit(@options[:message], parents, actor, nil, @wiki.ref) @callbacks.each do |cb| cb.call(self, sha1) end Hook.execute(:post_commit, self, sha1) sha1 end # Adds a callback to be fired after a commit. # # block - A block that expects this Committer instance and the created # commit's SHA1 as the arguments. # # Returns nothing. def after_commit(&block) @callbacks << block end # Determine if a given page (regardless of format) is scheduled to be # deleted in the next commit for the given Index. # # map - The Hash map: # key - The String directory or filename. # val - The Hash submap or the String contents of the file. # path - The String path of the page file. This may include the format # extension in which case it will be ignored. # # Returns the Boolean response. def page_path_scheduled_for_deletion?(map, path) parts = path.split('/') if parts.size == 1 deletions = map.keys.select { |k| !map[k] } downfile = parts.first.downcase.sub(/\.\w+$/, '') deletions.any? { |d| d.downcase.sub(/\.\w+$/, '') == downfile } else part = parts.shift if (rest = map[part]) page_path_scheduled_for_deletion?(rest, parts.join('/')) else false end end end # Determine if a given file is scheduled to be deleted in the next commit # for the given Index. # # map - The Hash map: # key - The String directory or filename. # val - The Hash submap or the String contents of the file. # path - The String path of the file including extension. # # Returns the Boolean response. def file_path_scheduled_for_deletion?(map, path) parts = path.split('/') if parts.size == 1 deletions = map.keys.select { |k| !map[k] } deletions.any? { |d| d == parts.first } else part = parts.shift if (rest = map[part]) file_path_scheduled_for_deletion?(rest, parts.join('/')) else false end end end # Proxies methods t def method_missing(name, *args) args.map! { |item| item.respond_to?(:force_encoding) ? item.force_encoding('ascii-8bit') : item } if Gollum::GIT_ADAPTER == 'grit' index.send(name, *args) end end end
# encoding: utf-8 require 'rest-client' require_relative '../helpers/auth_helpers' require_relative 'connection' require_relative 'object_factory' require_relative '../mixins/inspector' module GoodData module Rest # User's interface to GoodData Platform. # # MUST provide way to use - DELETE, GET, POST, PUT # SHOULD provide way to use - HEAD, Bulk GET ... class Client ################################# # Constants ################################# DEFAULT_CONNECTION_IMPLEMENTATION = GoodData::Rest::Connection ################################# # Class variables ################################# @@instance = nil # rubocop:disable ClassVars ################################# # Getters/Setters ################################# # Decide if we need provide direct access to connection attr_reader :connection # TODO: Decide if we need provide direct access to factory attr_reader :factory attr_reader :opts include Mixin::Inspector inspector :object_id ################################# # Class methods ################################# class << self # Globally available way to connect (and create client and set global instance) # # ## HACK # To make transition from old implementation to new one following HACK IS TEMPORARILY ENGAGED! # # 1. First call of #connect sets the GoodData::Rest::Client.instance (static, singleton instance) # 2. There are METHOD functions with same signature as their CLASS counterparts using singleton instance # # ## Example # # client = GoodData.connect('jon.smith@goodddata.com', 's3cr3tp4sw0rd') # # @param username [String] Username to be used for authentication # @param password [String] Password to be used for authentication # @return [GoodData::Rest::Client] Client def connect(username, password, opts = { :verify_ssl => true }) if username.nil? && password.nil? username = ENV['GD_GEM_USER'] password = ENV['GD_GEM_PASSWORD'] end new_opts = opts.dup if username.is_a?(Hash) && username.key?(:sst_token) new_opts[:sst_token] = username[:sst_token] elsif username.is_a? Hash new_opts[:username] = username[:login] || username[:user] || username[:username] new_opts[:password] = username[:password] elsif username.nil? && password.nil? && (opts.nil? || opts.empty?) new_opts = Helpers::AuthHelper.read_credentials else new_opts[:username] = username new_opts[:password] = password end unless new_opts[:sst_token] fail ArgumentError, 'No username specified' if new_opts[:username].nil? fail ArgumentError, 'No password specified' if new_opts[:password].nil? end if username.is_a?(Hash) && username.key?(:server) new_opts[:server] = username[:server] end client = Client.new(new_opts) if client at_exit do puts client.connection.stats_table if client && client.connection end end # HACK: This line assigns class instance # if not done yet @@instance = client # rubocop:disable ClassVars client end def disconnect if @@instance # rubocop:disable ClassVars, Style/GuardClause @@instance.disconnect # rubocop:disable ClassVars @@instance = nil # rubocop:disable ClassVars end end def connection @@instance # rubocop:disable ClassVars end # Retry block if exception thrown def retryable(options = {}, &block) GoodData::Rest::Connection.retryable(options, &block) end alias_method :client, :connection end # Constructor of client # @param opts [Hash] Client options # @option opts [String] :username Username used for authentication # @option opts [String] :password Password used for authentication # @option opts :connection_factory Object able to create new instances of GoodData::Rest::Connection # @option opts [GoodData::Rest::Connection] :connection Existing GoodData::Rest::Connection def initialize(opts) # TODO: Decide if we want to pass the options directly or not @opts = opts @connection_factory = @opts[:connection_factory] || DEFAULT_CONNECTION_IMPLEMENTATION # TODO: See previous TODO # Create connection @connection = opts[:connection] || @connection_factory.new(opts) # Connect connect # Create factory bound to previously created connection @factory = ObjectFactory.new(self) end def create_project(options = { title: 'Project', auth_token: ENV['GD_PROJECT_TOKEN'] }) GoodData::Project.create({ client: self }.merge(options)) end def create_project_from_blueprint(blueprint, options = {}) GoodData::Model::ProjectCreator.migrate(spec: blueprint, token: options[:auth_token], client: self) end def domain(domain_name) GoodData::Domain[domain_name, :client => self] end def projects(id = :all) GoodData::Project[id, client: self] end def processes(id = :all) GoodData::Process[id, client: self] end def connect username = @opts[:username] password = @opts[:password] @connection.connect(username, password, @opts) end def disconnect @connection.disconnect end ####################### # Factory stuff ###################### def create(klass, data = {}, opts = {}) @factory.create(klass, data, opts) end def find(klass, opts = {}) @factory.find(klass, opts) end # Gets resource by name def resource(res_name) puts "Getting resource '#{res_name}'" nil end def user(id = nil) if id create(GoodData::Profile, get(id)) else create(GoodData::Profile, @connection.user) end end ####################### # Rest ####################### # HTTP DELETE # # @param uri [String] Target URI def delete(uri, opts = {}) @connection.delete uri, opts end # HTTP GET # # @param uri [String] Target URI def get(uri, opts = {}, & block) @connection.get uri, opts, & block end # FIXME: Invstigate _file argument def get_project_webdav_path(_file, opts = { :project => GoodData.project }) p = opts[:project] fail ArgumentError, 'No :project specified' if p.nil? project = GoodData::Project[p, opts] fail ArgumentError, 'Wrong :project specified' if project.nil? u = URI(project.links['uploads']) URI.join(u.to_s.chomp(u.path.to_s), '/project-uploads/', "#{project.pid}/") end # FIXME: Invstigate _file argument def get_user_webdav_path(_file, opts = { :project => GoodData.project }) p = opts[:project] fail ArgumentError, 'No :project specified' if p.nil? project = GoodData::Project[p, opts] fail ArgumentError, 'Wrong :project specified' if project.nil? u = URI(project.links['uploads']) URI.join(u.to_s.chomp(u.path.to_s), '/uploads/') end # Generalizaton of poller. Since we have quite a variation of how async proceses are handled # this is a helper that should help you with resources where the information about "Are we done" # is the http code of response. By default we repeat as long as the code == 202. You can # change the code if necessary. It expects the URI as an input where it can poll. It returns the # value of last poll. In majority of cases these are the data that you need. # # @param link [String] Link for polling # @param options [Hash] Options # @return [Hash] Result of polling def poll_on_code(link, options = {}) code = options[:code] || 202 sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL response = get(link, :process => false) while response.code == code sleep sleep_interval GoodData::Rest::Client.retryable(:tries => 3, :refresh_token => proc { connection.refresh_token }) do sleep sleep_interval response = get(link, :process => false) end end if options[:process] == false response else get(link) end end # Generalizaton of poller. Since we have quite a variation of how async proceses are handled # this is a helper that should help you with resources where the information about "Are we done" # is inside the response. It expects the URI as an input where it can poll and a block that should # return either true -> 'meaning we are done' or false -> meaning sleep and repeat. It returns the # value of last poll. In majority of cases these are the data that you need # # @param link [String] Link for polling # @param options [Hash] Options # @return [Hash] Result of polling def poll_on_response(link, options = {}, &bl) sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL response = get(link) while bl.call(response) sleep sleep_interval GoodData::Rest::Client.retryable(:tries => 3, :refresh_token => proc { connection.refresh_token }) do sleep sleep_interval response = get(link) end end response end # HTTP PUT # # @param uri [String] Target URI def put(uri, data, opts = {}) @connection.put uri, data, opts end # HTTP POST # # @param uri [String] Target URI def post(uri, data, opts = {}) @connection.post uri, data, opts end # Uploads file to staging # # @param file [String] file to be uploaded # @param options [Hash] must contain :staging_url key (file will be uploaded to :staging_url + File.basename(file)) def upload(file, options = {}) @connection.upload file, options end # Downloads file from staging # # @param source_relative_path [String] path relative to @param options[:staging_url] # @param target_file_path [String] path to be downloaded to # @param options [Hash] must contain :staging_url key (file will be downloaded from :staging_url + source_relative_path) def download(source_relative_path, target_file_path, options = {}) @connection.download source_relative_path, target_file_path, options end def download_from_user_webdav(source_relative_path, target_file_path, options = { :client => GoodData.client, :project => project }) download(source_relative_path, target_file_path, options.merge( :directory => options[:directory], :staging_url => get_user_webdav_url(options) )) end def upload_to_user_webdav(file, options = {}) upload(file, options.merge( :directory => options[:directory], :staging_url => get_user_webdav_url(options) )) end def with_project(pid, &block) GoodData.with_project(pid, client: self, &block) end ###################### PRIVATE ###################### private def get_user_webdav_url(options = {}) p = options[:project] fail ArgumentError, 'No :project specified' if p.nil? project = options[:project] || GoodData::Project[p, options] fail ArgumentError, 'Wrong :project specified' if project.nil? u = URI(project.links['uploads']) us = u.to_s ws = options[:client].opts[:webdav_server] if !us.empty? && !us.downcase.start_with?('http') && !ws.empty? u = URI.join(ws, us) end URI.join(u.to_s.chomp(u.path.to_s), '/uploads/') end end end end Stats support # encoding: utf-8 require 'rest-client' require_relative '../helpers/auth_helpers' require_relative 'connection' require_relative 'object_factory' require_relative '../mixins/inspector' module GoodData module Rest # User's interface to GoodData Platform. # # MUST provide way to use - DELETE, GET, POST, PUT # SHOULD provide way to use - HEAD, Bulk GET ... class Client ################################# # Constants ################################# DEFAULT_CONNECTION_IMPLEMENTATION = GoodData::Rest::Connection ################################# # Class variables ################################# @@instance = nil # rubocop:disable ClassVars ################################# # Getters/Setters ################################# # Decide if we need provide direct access to connection attr_reader :connection # TODO: Decide if we need provide direct access to factory attr_reader :factory attr_reader :opts include Mixin::Inspector inspector :object_id ################################# # Class methods ################################# class << self # Globally available way to connect (and create client and set global instance) # # ## HACK # To make transition from old implementation to new one following HACK IS TEMPORARILY ENGAGED! # # 1. First call of #connect sets the GoodData::Rest::Client.instance (static, singleton instance) # 2. There are METHOD functions with same signature as their CLASS counterparts using singleton instance # # ## Example # # client = GoodData.connect('jon.smith@goodddata.com', 's3cr3tp4sw0rd') # # @param username [String] Username to be used for authentication # @param password [String] Password to be used for authentication # @return [GoodData::Rest::Client] Client def connect(username, password, opts = { :verify_ssl => true }) if username.nil? && password.nil? username = ENV['GD_GEM_USER'] password = ENV['GD_GEM_PASSWORD'] end new_opts = opts.dup if username.is_a?(Hash) && username.key?(:sst_token) new_opts[:sst_token] = username[:sst_token] elsif username.is_a? Hash new_opts[:username] = username[:login] || username[:user] || username[:username] new_opts[:password] = username[:password] elsif username.nil? && password.nil? && (opts.nil? || opts.empty?) new_opts = Helpers::AuthHelper.read_credentials else new_opts[:username] = username new_opts[:password] = password end unless new_opts[:sst_token] fail ArgumentError, 'No username specified' if new_opts[:username].nil? fail ArgumentError, 'No password specified' if new_opts[:password].nil? end if username.is_a?(Hash) && username.key?(:server) new_opts[:server] = username[:server] end client = Client.new(new_opts) if client at_exit do puts client.connection.stats_table if client && client.connection && (GoodData.stats_on? || client.stats_on?) end end # HACK: This line assigns class instance # if not done yet @@instance = client # rubocop:disable ClassVars client end def disconnect if @@instance # rubocop:disable ClassVars, Style/GuardClause @@instance.disconnect # rubocop:disable ClassVars @@instance = nil # rubocop:disable ClassVars end end def connection @@instance # rubocop:disable ClassVars end # Retry block if exception thrown def retryable(options = {}, &block) GoodData::Rest::Connection.retryable(options, &block) end alias_method :client, :connection end # Constructor of client # @param opts [Hash] Client options # @option opts [String] :username Username used for authentication # @option opts [String] :password Password used for authentication # @option opts :connection_factory Object able to create new instances of GoodData::Rest::Connection # @option opts [GoodData::Rest::Connection] :connection Existing GoodData::Rest::Connection def initialize(opts) # TODO: Decide if we want to pass the options directly or not @opts = opts @connection_factory = @opts[:connection_factory] || DEFAULT_CONNECTION_IMPLEMENTATION # TODO: See previous TODO # Create connection @connection = opts[:connection] || @connection_factory.new(opts) # Connect connect # Create factory bound to previously created connection @factory = ObjectFactory.new(self) end def create_project(options = { title: 'Project', auth_token: ENV['GD_PROJECT_TOKEN'] }) GoodData::Project.create({ client: self }.merge(options)) end def create_project_from_blueprint(blueprint, options = {}) GoodData::Model::ProjectCreator.migrate(spec: blueprint, token: options[:auth_token], client: self) end def domain(domain_name) GoodData::Domain[domain_name, :client => self] end def projects(id = :all) GoodData::Project[id, client: self] end def processes(id = :all) GoodData::Process[id, client: self] end def connect username = @opts[:username] password = @opts[:password] @connection.connect(username, password, @opts) end def disconnect @connection.disconnect end ####################### # Factory stuff ###################### def create(klass, data = {}, opts = {}) @factory.create(klass, data, opts) end def find(klass, opts = {}) @factory.find(klass, opts) end # Gets resource by name def resource(res_name) puts "Getting resource '#{res_name}'" nil end def user(id = nil) if id create(GoodData::Profile, get(id)) else create(GoodData::Profile, @connection.user) end end def stats_off @stats = false end def stats_on @stats = true end def stats_on? @stats end ####################### # Rest ####################### # HTTP DELETE # # @param uri [String] Target URI def delete(uri, opts = {}) @connection.delete uri, opts end # HTTP GET # # @param uri [String] Target URI def get(uri, opts = {}, & block) @connection.get uri, opts, & block end # FIXME: Invstigate _file argument def get_project_webdav_path(_file, opts = { :project => GoodData.project }) p = opts[:project] fail ArgumentError, 'No :project specified' if p.nil? project = GoodData::Project[p, opts] fail ArgumentError, 'Wrong :project specified' if project.nil? u = URI(project.links['uploads']) URI.join(u.to_s.chomp(u.path.to_s), '/project-uploads/', "#{project.pid}/") end # FIXME: Invstigate _file argument def get_user_webdav_path(_file, opts = { :project => GoodData.project }) p = opts[:project] fail ArgumentError, 'No :project specified' if p.nil? project = GoodData::Project[p, opts] fail ArgumentError, 'Wrong :project specified' if project.nil? u = URI(project.links['uploads']) URI.join(u.to_s.chomp(u.path.to_s), '/uploads/') end # Generalizaton of poller. Since we have quite a variation of how async proceses are handled # this is a helper that should help you with resources where the information about "Are we done" # is the http code of response. By default we repeat as long as the code == 202. You can # change the code if necessary. It expects the URI as an input where it can poll. It returns the # value of last poll. In majority of cases these are the data that you need. # # @param link [String] Link for polling # @param options [Hash] Options # @return [Hash] Result of polling def poll_on_code(link, options = {}) code = options[:code] || 202 sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL response = get(link, :process => false) while response.code == code sleep sleep_interval GoodData::Rest::Client.retryable(:tries => 3, :refresh_token => proc { connection.refresh_token }) do sleep sleep_interval response = get(link, :process => false) end end if options[:process] == false response else get(link) end end # Generalizaton of poller. Since we have quite a variation of how async proceses are handled # this is a helper that should help you with resources where the information about "Are we done" # is inside the response. It expects the URI as an input where it can poll and a block that should # return either true -> 'meaning we are done' or false -> meaning sleep and repeat. It returns the # value of last poll. In majority of cases these are the data that you need # # @param link [String] Link for polling # @param options [Hash] Options # @return [Hash] Result of polling def poll_on_response(link, options = {}, &bl) sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL response = get(link) while bl.call(response) sleep sleep_interval GoodData::Rest::Client.retryable(:tries => 3, :refresh_token => proc { connection.refresh_token }) do sleep sleep_interval response = get(link) end end response end # HTTP PUT # # @param uri [String] Target URI def put(uri, data, opts = {}) @connection.put uri, data, opts end # HTTP POST # # @param uri [String] Target URI def post(uri, data, opts = {}) @connection.post uri, data, opts end # Uploads file to staging # # @param file [String] file to be uploaded # @param options [Hash] must contain :staging_url key (file will be uploaded to :staging_url + File.basename(file)) def upload(file, options = {}) @connection.upload file, options end # Downloads file from staging # # @param source_relative_path [String] path relative to @param options[:staging_url] # @param target_file_path [String] path to be downloaded to # @param options [Hash] must contain :staging_url key (file will be downloaded from :staging_url + source_relative_path) def download(source_relative_path, target_file_path, options = {}) @connection.download source_relative_path, target_file_path, options end def download_from_user_webdav(source_relative_path, target_file_path, options = { :client => GoodData.client, :project => project }) download(source_relative_path, target_file_path, options.merge( :directory => options[:directory], :staging_url => get_user_webdav_url(options) )) end def upload_to_user_webdav(file, options = {}) upload(file, options.merge( :directory => options[:directory], :staging_url => get_user_webdav_url(options) )) end def with_project(pid, &block) GoodData.with_project(pid, client: self, &block) end ###################### PRIVATE ###################### private def get_user_webdav_url(options = {}) p = options[:project] fail ArgumentError, 'No :project specified' if p.nil? project = options[:project] || GoodData::Project[p, options] fail ArgumentError, 'Wrong :project specified' if project.nil? u = URI(project.links['uploads']) us = u.to_s ws = options[:client].opts[:webdav_server] if !us.empty? && !us.downcase.start_with?('http') && !ws.empty? u = URI.join(ws, us) end URI.join(u.to_s.chomp(u.path.to_s), '/uploads/') end end end end
# Provides calls for simplifying the loading and use of the Google Visualization API # # For use with rails, include this Module in ApplicationHelper # See the Readme for usage details # # written by Jeremy Olliver module GoogleVisualization attr_accessor :google_visualizations, :visualization_packages ####################################################################### # Place these method calls inside the <head> tag in your layout file. # ####################################################################### # Include the Visualization API code from google. # (Omit this call if you prefer to include the API in your own js package) def include_visualization_api raw(%Q(<!--Load the AJAX API--><script type="text/javascript" src="http://www.google.com/jsapi"></script>)) end # This code actually inserts the visualization data def render_visualizations if @google_visualizations package_list = [] @visualization_packages.uniq.each do |p| package_list << "\'#{p.to_s.camelize.downcase}\'" end output = %Q( <script type="text/javascript"> google.load('visualization', '1', {'packages':[#{package_list.uniq.join(',')}]}); google.setOnLoadCallback(drawCharts); var chartData = {}; var visualizationCharts = {}; function drawCharts() { ) @google_visualizations.each do |id, vis| output += generate_visualization(id, vis[0], vis[1], vis[2]) end output += "} </script>" raw(output + "<!-- Rendered Google Visualizations /-->") else raw("<!-- No graphs on this page /-->") end end ######################################################################## # Call this method from the view to insert the visualization data here # # Will output a div with given id, and add the chart data to be # # rendered from the head of the page # ######################################################################## def visualization(id, chart_type, options = {}, &block) init chart_type = chart_type.camelize # Camelize the chart type, as the Google API follows Camel Case conventions (e.g. ColumnChart, MotionChart) options.stringify_keys! # Ensure consistent hash access @visualization_packages << chart_type # Add the chart type to the packages needed to be loaded # Initialize the data table (with hashed options), and pass it the block for cleaner adding of attributes within the block table = DataTable.new(options.delete("data"), options.delete("columns"), options) if block_given? yield table end # Extract the html options html_options = options.delete("html") || {} # Add our chart to the list to be rendered in the head tag @google_visualizations.merge!(id => [chart_type, table, options]) # Output a div with given id, that our graph will be embedded into html = "" html_options.each do |key, value| html += %Q(#{key}="#{value}" ) end concat %Q(<div id="#{id}" #{html}><!-- /--></div>), block.binding nil end protected # Initialize instance variables def init @google_visualizations ||= {} @visualization_packages ||=[] end ################################################### # Internal methods for building the script data # ################################################### def generate_visualization(id, chart, table, options={}) # Generate the js chart data output = "chartData['#{id}'] = new google.visualization.DataTable();" table.columns.each do |col| output += "chartData['#{id}'].addColumn('#{table.column_types[col]}', '#{col}');" end option_str = [] options.each do |key, val| option_str << "#{key}: #{val}" end output += %Q( chartData['#{id}'].addRows(#{table.js_format_data}); visualizationCharts['#{id}'] = new google.visualization.#{chart.to_s.camelize}(document.getElementById('#{id}')); visualizationCharts['#{id}'].draw(chartData['#{id}'], {#{option_str.join(',')}}); ) end end Update concat usage for rails 3 # Provides calls for simplifying the loading and use of the Google Visualization API # # For use with rails, include this Module in ApplicationHelper # See the Readme for usage details # # written by Jeremy Olliver module GoogleVisualization attr_accessor :google_visualizations, :visualization_packages ####################################################################### # Place these method calls inside the <head> tag in your layout file. # ####################################################################### # Include the Visualization API code from google. # (Omit this call if you prefer to include the API in your own js package) def include_visualization_api raw(%Q(<!--Load the AJAX API--><script type="text/javascript" src="http://www.google.com/jsapi"></script>)) end # This code actually inserts the visualization data def render_visualizations if @google_visualizations package_list = [] @visualization_packages.uniq.each do |p| package_list << "\'#{p.to_s.camelize.downcase}\'" end output = %Q( <script type="text/javascript"> google.load('visualization', '1', {'packages':[#{package_list.uniq.join(',')}]}); google.setOnLoadCallback(drawCharts); var chartData = {}; var visualizationCharts = {}; function drawCharts() { ) @google_visualizations.each do |id, vis| output += generate_visualization(id, vis[0], vis[1], vis[2]) end output += "} </script>" raw(output + "<!-- Rendered Google Visualizations /-->") else raw("<!-- No graphs on this page /-->") end end ######################################################################## # Call this method from the view to insert the visualization data here # # Will output a div with given id, and add the chart data to be # # rendered from the head of the page # ######################################################################## def visualization(id, chart_type, options = {}, &block) init chart_type = chart_type.camelize # Camelize the chart type, as the Google API follows Camel Case conventions (e.g. ColumnChart, MotionChart) options.stringify_keys! # Ensure consistent hash access @visualization_packages << chart_type # Add the chart type to the packages needed to be loaded # Initialize the data table (with hashed options), and pass it the block for cleaner adding of attributes within the block table = DataTable.new(options.delete("data"), options.delete("columns"), options) if block_given? yield table end # Extract the html options html_options = options.delete("html") || {} # Add our chart to the list to be rendered in the head tag @google_visualizations.merge!(id => [chart_type, table, options]) # Output a div with given id, that our graph will be embedded into html = "" html_options.each do |key, value| html += %Q(#{key}="#{value}" ) end concat raw(%Q(<div id="#{id}" #{html}><!-- /--></div>)) nil end protected # Initialize instance variables def init @google_visualizations ||= {} @visualization_packages ||=[] end ################################################### # Internal methods for building the script data # ################################################### def generate_visualization(id, chart, table, options={}) # Generate the js chart data output = "chartData['#{id}'] = new google.visualization.DataTable();" table.columns.each do |col| output += "chartData['#{id}'].addColumn('#{table.column_types[col]}', '#{col}');" end option_str = [] options.each do |key, val| option_str << "#{key}: #{val}" end output += %Q( chartData['#{id}'].addRows(#{table.js_format_data}); visualizationCharts['#{id}'] = new google.visualization.#{chart.to_s.camelize}(document.getElementById('#{id}')); visualizationCharts['#{id}'].draw(chartData['#{id}'], {#{option_str.join(',')}}); ) end end
class GovukRailsTemplate def initialize(app) @app = app @instructions = [] app.source_paths << File.dirname(File.expand_path("..", __FILE__)) end def apply; end def print_instructions return if instructions.empty? block_width = 30 puts puts "=" * block_width puts "POST-BUILD INSTRUCTIONS" puts "=" * block_width puts instructions.join("\n" + ("-" * block_width) + "\n") puts "=" * block_width end private attr_reader :app attr_accessor :instructions def create_bare_rails_app app.run "bundle install" app.git :init app.git add: "." command = "#{File.basename($0)} #{ARGV.join(' ')}" commit "Bare Rails application\n\nGenerated using https://github.com/alphagov/govuk-rails-app-template\nCommand: #{command}" end def add_gemfile app.remove_file "Gemfile" app.copy_file "templates/Gemfile", "Gemfile" app.run "bundle install" commit "Start with a lean Gemfile" end def setup_database return if @database_created add_test_gem "sqlite3", comment: "Remove this when you choose a production database" add_gem "database_cleaner" add_gem "deprecated_columns" app.run "bundle install" system("bundle exec rake db:create:all") system("bundle exec rake db:migrate") system("bundle exec rake db:test:prepare") app.git add: "." commit "Set up development and test databases" app.inject_into_file "spec/rails_helper.rb", after: "RSpec.configure do |config|\n" do <<-"RUBY" config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| if example.metadata[:skip_cleaning] example.run else DatabaseCleaner.cleaning { example.run } end end RUBY end @database_created = true end def add_gds_sso setup_database add_gem "gds-sso" add_gem "plek" app.run "bundle install" app.copy_file "templates/config/initializers/gds-sso.rb", "config/initializers/gds-sso.rb" app.copy_file "templates/spec/support/authentication_helper.rb", "spec/support/authentication_helper.rb" app.inject_into_file "app/controllers/application_controller.rb", after: "class ApplicationController < ActionController::Base\n" do <<-"RUBY" include GDS::SSO::ControllerMethods before_action :authenticate_user!! RUBY end app.inject_into_file "spec/rails_helper.rb", after: %{require "spec_helper"\n} do <<-"RUBY" require "database_cleaner" RUBY end app.inject_into_file "spec/rails_helper.rb", after: "RSpec.configure do |config|\n" do <<-"RUBY" config.include AuthenticationHelper::RequestMixin, type: :request config.include AuthenticationHelper::ControllerMixin, type: :controller config.after do GDS::SSO.test_user = nil end [:controller, :request].each do |spec_type| config.before :each, type: spec_type do login_as_stub_user end end RUBY end app.copy_file "templates/app/models/user.rb", "app/models/user.rb" app.copy_file "templates/spec/factories/user.rb", "spec/factories/user.rb" app.copy_file "templates/db/migrate/20160622154200_create_users.rb", "db/migrate/20160622154200_create_users.rb" system("bundle exec rake db:migrate") system("bundle exec rake db:test:prepare") end def add_test_framework add_test_gem "rspec-rails" add_test_gem "webmock", require: false add_test_gem "timecop" add_test_gem "factory_girl_rails" app.run "bundle install" app.generate("rspec:install") app.remove_file "spec/spec_helper.rb" app.remove_file "spec/rails_helper.rb" app.copy_file "templates/spec/spec_helper.rb", "spec/spec_helper.rb" app.copy_file "templates/spec/rails_helper.rb", "spec/rails_helper.rb" app.remove_dir("test") commit "Add rspec-rails and useful testing tools" end def add_linter add_test_gem "govuk-lint" app.run "bundle install" commit "Add govuk-lint for enforcing GOV.UK styleguide" end def lock_ruby_version app.add_file ".ruby-version", "2.4.2\n" app.prepend_to_file("Gemfile") { %{ruby File.read(".ruby-version").strip\n\n} } commit "Lock Ruby version" end def add_readme_and_licence app.remove_file "README.rdoc" app.template "templates/README.md.erb", "README.md" app.template "templates/LICENCE.erb", "LICENCE" commit "Add README.md and LICENCE" end def add_jenkins_script app.template "templates/Jenkinsfile", "Jenkinsfile" commit "Add Jenkinsfile" end def add_test_coverage_reporter add_test_gem "simplecov", require: false add_test_gem "simplecov-rcov", require: false app.run "bundle install" app.prepend_to_file "spec/rails_helper.rb" do <<-'RUBY' if ENV["RCOV"] require "simplecov" require "simplecov-rcov" SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start "rails" end RUBY end app.inject_into_file "spec/rails_helper.rb", "export RCOV=1\n", before: %{if bundle exec rake ${TEST_TASK:-"default"}; then\n} app.append_to_file ".gitignore", "/coverage\n" commit "Use simplecov for code coverage reporting" end def add_health_check app.route %{get "/healthcheck", to: proc { [200, {}, ["OK"]] }} app.copy_file "templates/spec/requests/healthcheck_spec.rb", "spec/requests/healthcheck_spec.rb" commit "Add healthcheck endpoint" end def add_govuk_app_config add_gem "govuk_app_config" app.run "bundle install" app.copy_file "templates/config/unicorn.rb", "config/unicorn.rb" commit "Add govuk_app_config for error reporting, stats, logging and unicorn" end def add_debuggers # byebug is included in the Gemfile as a Rails convention add_test_gem "pry" app.run "bundle install" app.prepend_to_file "spec/spec_helper.rb" do <<-'RUBY' require "pry" require "byebug" RUBY end commit "Add common debuggers" end def add_form_builder add_gem "selectize-rails" add_gem "generic_form_builder" app.run "bundle install" app.application do <<-'RUBY' # Better forms require "admin_form_builder" config.action_view.default_form_builder = AdminFormBuilder config.action_view.field_error_proc = proc {|html_tag, _| html_tag } RUBY end app.copy_file "templates/lib/admin_form_builder.rb", "lib/admin_form_builder.rb" commit "Add a form builder" end def add_frontend_development_libraries add_gem "sass-rails" add_gem "uglifier" add_gem "quiet_assets" app.run "bundle install" commit "Add frontend development libraries" end def add_govuk_admin_frontend_template add_gem "govuk_admin_template" app.run "bundle install" commit "Add the admin frontend template" instructions << "Setup the admin template as per https://github.com/alphagov/govuk_admin_template#govuk-admin-template" end def add_browser_testing_framework add_gem "capybara" add_gem "poltergeist" app.run "bundle install" commit "Add a browser testing framework" instructions << "Please test browser interactions as per the styleguide https://github.com/alphagov/styleguides/blob/master/testing.md" end def add_gds_api_adapters # The version of mime-types which rest-client relies on must be below 3.0 add_gem "mime-types" app.run "bundle update mime-types" add_gem "gds-api-adapters" app.run "bundle install" commit "Add GDS API adapters" end def add_sidekiq add_gem "govuk_sidekiq" app.run "bundle install" commit "Add govuk_sidekiq" instructions << "Setup sidekiq as per https://github.com/alphagov/govuk_sidekiq" end def add_content_schema_helpers # The version of addressable which json-schema relies on must be ~> 2.3.7 add_gem "addressable" app.run "bundle update addressable" add_gem "govuk-content-schema-test-helpers" app.run "bundle install" commit "Add GOV.UK content schema test helpers" instructions << "GOV.UK content schema test helpers have been added to help you integrate with the publishing API or content store" end def add_frontend_application_libraries add_gem "slimmer" add_gem "govuk_frontend_toolkit" app.run "bundle install" commit "Add frontend application libraries" instructions << "Hook in these templating libraries: https://github.com/alphagov/slimmer https://github.com/alphagov/govuk_frontend_toolkit" end def gem_string(name, version, require, comment) string = %{gem "#{name}"} string += %{, "#{version}"} if version string += ", require: false" if require == false string += " # #{comment}" if comment string end def add_gem(name, version = nil, require: nil, comment: nil) # This produces a cleaner Gemfile than using the `gem` helper. app.inject_into_file "Gemfile", "#{gem_string(name, version, require, comment)}\n", before: "group :development, :test do\n" end def add_test_gem(name, version = nil, require: nil, comment: nil) # This produces a cleaner Gemfile than using the `gem` helper. app.inject_into_file "Gemfile", " #{gem_string(name, version, require, comment)}\n", after: "group :development, :test do\n" end def commit(message) app.git add: "." app.git commit: %{-a -m "#{message}"} end end Bump ruby version to 2.4.4 class GovukRailsTemplate def initialize(app) @app = app @instructions = [] app.source_paths << File.dirname(File.expand_path("..", __FILE__)) end def apply; end def print_instructions return if instructions.empty? block_width = 30 puts puts "=" * block_width puts "POST-BUILD INSTRUCTIONS" puts "=" * block_width puts instructions.join("\n" + ("-" * block_width) + "\n") puts "=" * block_width end private attr_reader :app attr_accessor :instructions def create_bare_rails_app app.run "bundle install" app.git :init app.git add: "." command = "#{File.basename($0)} #{ARGV.join(' ')}" commit "Bare Rails application\n\nGenerated using https://github.com/alphagov/govuk-rails-app-template\nCommand: #{command}" end def add_gemfile app.remove_file "Gemfile" app.copy_file "templates/Gemfile", "Gemfile" app.run "bundle install" commit "Start with a lean Gemfile" end def setup_database return if @database_created add_test_gem "sqlite3", comment: "Remove this when you choose a production database" add_gem "database_cleaner" add_gem "deprecated_columns" app.run "bundle install" system("bundle exec rake db:create:all") system("bundle exec rake db:migrate") system("bundle exec rake db:test:prepare") app.git add: "." commit "Set up development and test databases" app.inject_into_file "spec/rails_helper.rb", after: "RSpec.configure do |config|\n" do <<-"RUBY" config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.around(:each) do |example| if example.metadata[:skip_cleaning] example.run else DatabaseCleaner.cleaning { example.run } end end RUBY end @database_created = true end def add_gds_sso setup_database add_gem "gds-sso" add_gem "plek" app.run "bundle install" app.copy_file "templates/config/initializers/gds-sso.rb", "config/initializers/gds-sso.rb" app.copy_file "templates/spec/support/authentication_helper.rb", "spec/support/authentication_helper.rb" app.inject_into_file "app/controllers/application_controller.rb", after: "class ApplicationController < ActionController::Base\n" do <<-"RUBY" include GDS::SSO::ControllerMethods before_action :authenticate_user!! RUBY end app.inject_into_file "spec/rails_helper.rb", after: %{require "spec_helper"\n} do <<-"RUBY" require "database_cleaner" RUBY end app.inject_into_file "spec/rails_helper.rb", after: "RSpec.configure do |config|\n" do <<-"RUBY" config.include AuthenticationHelper::RequestMixin, type: :request config.include AuthenticationHelper::ControllerMixin, type: :controller config.after do GDS::SSO.test_user = nil end [:controller, :request].each do |spec_type| config.before :each, type: spec_type do login_as_stub_user end end RUBY end app.copy_file "templates/app/models/user.rb", "app/models/user.rb" app.copy_file "templates/spec/factories/user.rb", "spec/factories/user.rb" app.copy_file "templates/db/migrate/20160622154200_create_users.rb", "db/migrate/20160622154200_create_users.rb" system("bundle exec rake db:migrate") system("bundle exec rake db:test:prepare") end def add_test_framework add_test_gem "rspec-rails" add_test_gem "webmock", require: false add_test_gem "timecop" add_test_gem "factory_girl_rails" app.run "bundle install" app.generate("rspec:install") app.remove_file "spec/spec_helper.rb" app.remove_file "spec/rails_helper.rb" app.copy_file "templates/spec/spec_helper.rb", "spec/spec_helper.rb" app.copy_file "templates/spec/rails_helper.rb", "spec/rails_helper.rb" app.remove_dir("test") commit "Add rspec-rails and useful testing tools" end def add_linter add_test_gem "govuk-lint" app.run "bundle install" commit "Add govuk-lint for enforcing GOV.UK styleguide" end def lock_ruby_version app.add_file ".ruby-version", "2.4.4\n" app.prepend_to_file("Gemfile") { %{ruby File.read(".ruby-version").strip\n\n} } commit "Lock Ruby version" end def add_readme_and_licence app.remove_file "README.rdoc" app.template "templates/README.md.erb", "README.md" app.template "templates/LICENCE.erb", "LICENCE" commit "Add README.md and LICENCE" end def add_jenkins_script app.template "templates/Jenkinsfile", "Jenkinsfile" commit "Add Jenkinsfile" end def add_test_coverage_reporter add_test_gem "simplecov", require: false add_test_gem "simplecov-rcov", require: false app.run "bundle install" app.prepend_to_file "spec/rails_helper.rb" do <<-'RUBY' if ENV["RCOV"] require "simplecov" require "simplecov-rcov" SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter SimpleCov.start "rails" end RUBY end app.inject_into_file "spec/rails_helper.rb", "export RCOV=1\n", before: %{if bundle exec rake ${TEST_TASK:-"default"}; then\n} app.append_to_file ".gitignore", "/coverage\n" commit "Use simplecov for code coverage reporting" end def add_health_check app.route %{get "/healthcheck", to: proc { [200, {}, ["OK"]] }} app.copy_file "templates/spec/requests/healthcheck_spec.rb", "spec/requests/healthcheck_spec.rb" commit "Add healthcheck endpoint" end def add_govuk_app_config add_gem "govuk_app_config" app.run "bundle install" app.copy_file "templates/config/unicorn.rb", "config/unicorn.rb" commit "Add govuk_app_config for error reporting, stats, logging and unicorn" end def add_debuggers # byebug is included in the Gemfile as a Rails convention add_test_gem "pry" app.run "bundle install" app.prepend_to_file "spec/spec_helper.rb" do <<-'RUBY' require "pry" require "byebug" RUBY end commit "Add common debuggers" end def add_form_builder add_gem "selectize-rails" add_gem "generic_form_builder" app.run "bundle install" app.application do <<-'RUBY' # Better forms require "admin_form_builder" config.action_view.default_form_builder = AdminFormBuilder config.action_view.field_error_proc = proc {|html_tag, _| html_tag } RUBY end app.copy_file "templates/lib/admin_form_builder.rb", "lib/admin_form_builder.rb" commit "Add a form builder" end def add_frontend_development_libraries add_gem "sass-rails" add_gem "uglifier" add_gem "quiet_assets" app.run "bundle install" commit "Add frontend development libraries" end def add_govuk_admin_frontend_template add_gem "govuk_admin_template" app.run "bundle install" commit "Add the admin frontend template" instructions << "Setup the admin template as per https://github.com/alphagov/govuk_admin_template#govuk-admin-template" end def add_browser_testing_framework add_gem "capybara" add_gem "poltergeist" app.run "bundle install" commit "Add a browser testing framework" instructions << "Please test browser interactions as per the styleguide https://github.com/alphagov/styleguides/blob/master/testing.md" end def add_gds_api_adapters # The version of mime-types which rest-client relies on must be below 3.0 add_gem "mime-types" app.run "bundle update mime-types" add_gem "gds-api-adapters" app.run "bundle install" commit "Add GDS API adapters" end def add_sidekiq add_gem "govuk_sidekiq" app.run "bundle install" commit "Add govuk_sidekiq" instructions << "Setup sidekiq as per https://github.com/alphagov/govuk_sidekiq" end def add_content_schema_helpers # The version of addressable which json-schema relies on must be ~> 2.3.7 add_gem "addressable" app.run "bundle update addressable" add_gem "govuk-content-schema-test-helpers" app.run "bundle install" commit "Add GOV.UK content schema test helpers" instructions << "GOV.UK content schema test helpers have been added to help you integrate with the publishing API or content store" end def add_frontend_application_libraries add_gem "slimmer" add_gem "govuk_frontend_toolkit" app.run "bundle install" commit "Add frontend application libraries" instructions << "Hook in these templating libraries: https://github.com/alphagov/slimmer https://github.com/alphagov/govuk_frontend_toolkit" end def gem_string(name, version, require, comment) string = %{gem "#{name}"} string += %{, "#{version}"} if version string += ", require: false" if require == false string += " # #{comment}" if comment string end def add_gem(name, version = nil, require: nil, comment: nil) # This produces a cleaner Gemfile than using the `gem` helper. app.inject_into_file "Gemfile", "#{gem_string(name, version, require, comment)}\n", before: "group :development, :test do\n" end def add_test_gem(name, version = nil, require: nil, comment: nil) # This produces a cleaner Gemfile than using the `gem` helper. app.inject_into_file "Gemfile", " #{gem_string(name, version, require, comment)}\n", after: "group :development, :test do\n" end def commit(message) app.git add: "." app.git commit: %{-a -m "#{message}"} end end
# -*- encoding : utf-8 -*- require 'guacamole/query' require 'guacamole/aql_query' require 'ashikawa-core' require 'active_support' require 'active_support/concern' require 'active_support/core_ext/string/inflections' module Guacamole # A collection persists and offers querying for models # # You use this as a mixin in your collection classes. Per convention, # they are the plural form of your model with the suffix `Collection`. # For example the collection of `Blogpost` models would be `BlogpostsCollection`. # Including `Guacamole::Collection` will add a number of class methods to # the collection. See the `ClassMethods` submodule for details module Collection extend ActiveSupport::Concern # The class methods added to the class via the mixin # # @!method model_to_document(model) # Convert a model to a document to save it to the database # # You can use this method for your hand made storage or update methods. # Most of the time it makes more sense to call save or replace though, # they do the conversion and handle the communication with the database # # @param [Model] model The model to be converted # @return [Ashikawa::Core::Document] The converted document module ClassMethods extend Forwardable def_delegators :mapper, :model_to_document def_delegator :connection, :fetch, :fetch_document attr_accessor :connection, :mapper, :database # The raw `Database` object that was configured # # You can use this method for low level communication with the database. # Details can be found in the Ashikawa::Core documentation. # # @see http://rubydoc.info/gems/ashikawa-core/Ashikawa/Core/Database # @return [Ashikawa::Core::Database] def database @database ||= Guacamole.configuration.database end # The raw `Collection` object for this collection # # You can use this method for low level communication with the collection. # Details can be found in the Ashikawa::Core documentation. # # @note We're well aware that we return a Ashikawa::Core::Collection here # but naming it a connection. We think the name `connection` still # fits better in this context. # @see http://rubydoc.info/gems/ashikawa-core/Ashikawa/Core/Collection # @return [Ashikawa::Core::Collection] def connection @connection ||= database[collection_name] end # The DocumentModelMapper for this collection # # @api private # @return [DocumentModelMapper] def mapper @mapper ||= Guacamole.configuration.default_mapper.new(model_class) end # The name of the collection in ArangoDB # # Use this method in your hand crafted AQL queries, for debugging etc. # # @return [String] The name def collection_name @collection_name ||= name.gsub(/Collection\z/, '').underscore end # The class of the resulting models # # @return [Class] The model class def model_class @model_class ||= collection_name.singularize.camelcase.constantize end # Find a model by its key # # The key is the unique identifier of a document within a collection, # this concept is similar to the concept of IDs in most databases. # # @param [String] key # @return [Model] The model with the given key # @example Find a podcast by its key # podcast = PodcastsCollection.by_key('27214247') def by_key(key) raise Ashikawa::Core::DocumentNotFoundException unless key mapper.document_to_model connection.fetch(key) end # Persist a model in the collection or replace it in the database, depending if it is already persisted # # * If {Model#persisted? model#persisted?} is `false`, the model will be saved in the collection. # Timestamps, revision and key will be set on the model. # * If {Model#persisted? model#persisted?} is `true`, it replaces the currently saved version of the model with # its new version. It searches for the entry in the database # by key. This will change the updated_at timestamp and revision # of the provided model. # # See also {#create create} and {#replace replace} for explicit usage. # # @param [Model] model The model to be saved # @return [Model] The provided model # @example Save a podcast to the database # podcast = Podcast.new(title: 'Best Show', guest: 'Dirk Breuer') # PodcastsCollection.save(podcast) # podcast.key #=> '27214247' # @example Get a podcast, update its title, replace it # podcast = PodcastsCollection.by_key('27214247') # podcast.title = 'Even better' # PodcastsCollection.save(podcast) def save(model) model.persisted? ? replace(model) : create(model) end # Persist a model in the collection # # The model will be saved in the collection. Timestamps, revision # and key will be set on the model. # # @param [Model] model The model to be saved # @return [Model] The provided model # @example Save a podcast to the database # podcast = Podcast.new(title: 'Best Show', guest: 'Dirk Breuer') # PodcastsCollection.save(podcast) # podcast.key #=> '27214247' def create(model) return false unless model.valid? add_timestamps_to_model(model) callbacks(model).run_callbacks :create do create_document_from(model) end model end def callbacks(model) Callbacks.callbacks_for(model) end # Delete a model from the database # # @param [String, Model] model_or_key The key of the model or a model # @return [String] The key # @example Delete a podcast by key # PodcastsCollection.delete(podcast.key) # @example Delete a podcast by model # PodcastsCollection.delete(podcast) def delete(model_or_key) key = if model_or_key.respond_to? :key model_or_key.key else model_or_key end fetch_document(key).delete key end # Replace a model in the database with its new version # # Replaces the currently saved version of the model with # its new version. It searches for the entry in the database # by key. This will change the updated_at timestamp and revision # of the provided model. # # @param [Model] model The model to be replaced # @return [Model] The model # @example Get a podcast, update its title, replace it # podcast = PodcastsCollection.by_key('27214247') # podcast.title = 'Even better' # PodcastsCollection.replace(podcast) def replace(model) return false unless model.valid? model.updated_at = Time.now replace_document_from(model) model end # Find models by the provided attributes # # Search for models in the collection where the attributes are equal # to those that you provided. # This returns a Query object, where you can provide additional information # like limiting the results. See the documentation of Query or the examples # for more information. # All methods of the Enumerable module and `.to_a` will lead to the execution # of the query. # # @param [Hash] example The attributes and their values # @return [Query] # @example Get all podcasts with the title 'Best Podcast' # podcasts = PodcastsCollection.by_example(title: 'Best Podcast').to_a # @example Get the second batch of podcasts for batches of 10 with the title 'Best Podcast' # podcasts = PodcastsCollection.by_example(title: 'Best Podcast').skip(10).limit(10).to_a # @example Iterate over all podcasts with the title 'Best Podcasts' # PodcastsCollection.by_example(title: 'Best Podcast').each do |podcast| # p podcast # end def by_example(example) query = all query.example = example query end # Find models with simple AQL queries # # Since Simple Queries are quite limited in their possibilities you will need to # use AQL for more advanced data retrieval. Currently there is only a very basic # and experimental support for AQL. Eventually we will replace it with an advanced # query builder DSL. Due to this, we deactivated this feature per default. You # need to activate it with {Configuration#aql_support}: # # Guacamole::Configuration.aql_support = :experimental # # If not activated it we will raise an error. # # @param [String] aql_fragment An AQL string that will will be put between the # `FOR x IN coll` and the `RETURN x` part. # @param [Hash<Symbol, String>] bind_parameters The parameters to be passed into the query # @param [Hash] options Additional options for the query execution # @option options [String] :return_as ('RETURN #{model_name}') A custom `RETURN` statement # @option options [Boolean] :mapping (true) Should the mapping be performed? # @return [Query] # @raise [AQLNotSupportedError] If `aql_support` was not activated # @note Please use always bind parameters since they provide at least some form # of protection from AQL injection. # @see https://www.arangodb.org/manuals/2/Aql.html AQL Documentation def by_aql(aql_fragment, bind_parameters = {}, options = {}) raise AQLNotSupportedError unless Guacamole.configuration.experimental_features.include?(:aql_support) query = AqlQuery.new(self, mapper, options) query.aql_fragment = aql_fragment query.bind_parameters = bind_parameters query end # Get all Models stored in the collection # # The result can be limited (and should be for most datasets) # This can be done one the returned Query object. # All methods of the Enumerable module and `.to_a` will lead to the execution # of the query. # # @return [Query] # @example Get all podcasts # podcasts = PodcastsCollection.all.to_a # @example Get the first 50 podcasts # podcasts = PodcastsCollection.all.limit(50).to_a def all Query.new(connection.query, mapper) end # Specify details on the mapping # # The method is called with a block where you can specify # details about the way that the data from the database # is mapped to models. # # See `DocumentModelMapper` for details on how to configure # the mapper. def map(&block) mapper.instance_eval(&block) end # Timestamp a fresh model # # @api private def add_timestamps_to_model(model) timestamp = Time.now model.created_at = timestamp model.updated_at = timestamp end # Create a document from a model # # @api private # @todo Currently we only save the associated models if those never have been # persisted. In future versions we should add something like `:autosave` # to always save associated models. def create_document_from(model) create_referenced_models_of model document = connection.create_document(model_to_document(model)) model.key = document.key model.rev = document.revision create_referenced_by_models_of model document end # Creates all not yet persisted referenced models of `model` # # Referenced models needs to be created before the parent model, because it needs their `key` # # @api private # @todo This method should be considered 'work in progress'. We already know we need to change this. # @return [void] def create_referenced_models_of(model) mapper.referenced_models.each do |ref_model_name| ref_collection = mapper.collection_for(ref_model_name) ref_model = model.send(ref_model_name) next unless ref_model ref_collection.save ref_model unless ref_model.persisted? end end # Creates all not yet persisted models which are referenced by `model` # # Referenced by models needs to created after the parent model, because they need its `key` # # @api private # @todo This method should be considered 'work in progress'. We already know we need to change this. # @return [void] def create_referenced_by_models_of(model) mapper.referenced_by_models.each do |ref_model_name| ref_collection = mapper.collection_for(ref_model_name) ref_models = model.send(ref_model_name) ref_models.each do |ref_model| ref_model.send("#{model.class.name.demodulize.underscore}=", model) ref_collection.save ref_model unless ref_model.persisted? end end end # Replace a document in the database with this model # # @api private # @note This will **not** update associated models (see {#create}) def replace_document_from(model) document = model_to_document(model) response = connection.replace(model.key, document) model.rev = response['_rev'] document end end end end Collection: Consistent naming # -*- encoding : utf-8 -*- require 'guacamole/query' require 'guacamole/aql_query' require 'ashikawa-core' require 'active_support' require 'active_support/concern' require 'active_support/core_ext/string/inflections' module Guacamole # A collection persists and offers querying for models # # You use this as a mixin in your collection classes. Per convention, # they are the plural form of your model with the suffix `Collection`. # For example the collection of `Blogpost` models would be `BlogpostsCollection`. # Including `Guacamole::Collection` will add a number of class methods to # the collection. See the `ClassMethods` submodule for details module Collection extend ActiveSupport::Concern # The class methods added to the class via the mixin # # @!method model_to_document(model) # Convert a model to a document to save it to the database # # You can use this method for your hand made storage or update methods. # Most of the time it makes more sense to call save or replace though, # they do the conversion and handle the communication with the database # # @param [Model] model The model to be converted # @return [Ashikawa::Core::Document] The converted document module ClassMethods extend Forwardable def_delegators :mapper, :model_to_document def_delegator :connection, :fetch, :fetch_document attr_accessor :connection, :mapper, :database # The raw `Database` object that was configured # # You can use this method for low level communication with the database. # Details can be found in the Ashikawa::Core documentation. # # @see http://rubydoc.info/gems/ashikawa-core/Ashikawa/Core/Database # @return [Ashikawa::Core::Database] def database @database ||= Guacamole.configuration.database end # The raw `Collection` object for this collection # # You can use this method for low level communication with the collection. # Details can be found in the Ashikawa::Core documentation. # # @note We're well aware that we return a Ashikawa::Core::Collection here # but naming it a connection. We think the name `connection` still # fits better in this context. # @see http://rubydoc.info/gems/ashikawa-core/Ashikawa/Core/Collection # @return [Ashikawa::Core::Collection] def connection @connection ||= database[collection_name] end # The DocumentModelMapper for this collection # # @api private # @return [DocumentModelMapper] def mapper @mapper ||= Guacamole.configuration.default_mapper.new(model_class) end # The name of the collection in ArangoDB # # Use this method in your hand crafted AQL queries, for debugging etc. # # @return [String] The name def collection_name @collection_name ||= name.gsub(/Collection\z/, '').underscore end # The class of the resulting models # # @return [Class] The model class def model_class @model_class ||= collection_name.singularize.camelcase.constantize end # Find a model by its key # # The key is the unique identifier of a document within a collection, # this concept is similar to the concept of IDs in most databases. # # @param [String] key # @return [Model] The model with the given key # @example Find a podcast by its key # podcast = PodcastsCollection.by_key('27214247') def by_key(key) raise Ashikawa::Core::DocumentNotFoundException unless key mapper.document_to_model fetch_document(key) end # Persist a model in the collection or replace it in the database, depending if it is already persisted # # * If {Model#persisted? model#persisted?} is `false`, the model will be saved in the collection. # Timestamps, revision and key will be set on the model. # * If {Model#persisted? model#persisted?} is `true`, it replaces the currently saved version of the model with # its new version. It searches for the entry in the database # by key. This will change the updated_at timestamp and revision # of the provided model. # # See also {#create create} and {#replace replace} for explicit usage. # # @param [Model] model The model to be saved # @return [Model] The provided model # @example Save a podcast to the database # podcast = Podcast.new(title: 'Best Show', guest: 'Dirk Breuer') # PodcastsCollection.save(podcast) # podcast.key #=> '27214247' # @example Get a podcast, update its title, replace it # podcast = PodcastsCollection.by_key('27214247') # podcast.title = 'Even better' # PodcastsCollection.save(podcast) def save(model) model.persisted? ? replace(model) : create(model) end # Persist a model in the collection # # The model will be saved in the collection. Timestamps, revision # and key will be set on the model. # # @param [Model] model The model to be saved # @return [Model] The provided model # @example Save a podcast to the database # podcast = Podcast.new(title: 'Best Show', guest: 'Dirk Breuer') # PodcastsCollection.save(podcast) # podcast.key #=> '27214247' def create(model) return false unless model.valid? add_timestamps_to_model(model) callbacks(model).run_callbacks :create do create_document_from(model) end model end def callbacks(model) Callbacks.callbacks_for(model) end # Delete a model from the database # # @param [String, Model] model_or_key The key of the model or a model # @return [String] The key # @example Delete a podcast by key # PodcastsCollection.delete(podcast.key) # @example Delete a podcast by model # PodcastsCollection.delete(podcast) def delete(model_or_key) key = if model_or_key.respond_to? :key model_or_key.key else model_or_key end fetch_document(key).delete key end # Replace a model in the database with its new version # # Replaces the currently saved version of the model with # its new version. It searches for the entry in the database # by key. This will change the updated_at timestamp and revision # of the provided model. # # @param [Model] model The model to be replaced # @return [Model] The model # @example Get a podcast, update its title, replace it # podcast = PodcastsCollection.by_key('27214247') # podcast.title = 'Even better' # PodcastsCollection.replace(podcast) def replace(model) return false unless model.valid? model.updated_at = Time.now replace_document_from(model) model end # Find models by the provided attributes # # Search for models in the collection where the attributes are equal # to those that you provided. # This returns a Query object, where you can provide additional information # like limiting the results. See the documentation of Query or the examples # for more information. # All methods of the Enumerable module and `.to_a` will lead to the execution # of the query. # # @param [Hash] example The attributes and their values # @return [Query] # @example Get all podcasts with the title 'Best Podcast' # podcasts = PodcastsCollection.by_example(title: 'Best Podcast').to_a # @example Get the second batch of podcasts for batches of 10 with the title 'Best Podcast' # podcasts = PodcastsCollection.by_example(title: 'Best Podcast').skip(10).limit(10).to_a # @example Iterate over all podcasts with the title 'Best Podcasts' # PodcastsCollection.by_example(title: 'Best Podcast').each do |podcast| # p podcast # end def by_example(example) query = all query.example = example query end # Find models with simple AQL queries # # Since Simple Queries are quite limited in their possibilities you will need to # use AQL for more advanced data retrieval. Currently there is only a very basic # and experimental support for AQL. Eventually we will replace it with an advanced # query builder DSL. Due to this, we deactivated this feature per default. You # need to activate it with {Configuration#aql_support}: # # Guacamole::Configuration.aql_support = :experimental # # If not activated it we will raise an error. # # @param [String] aql_fragment An AQL string that will will be put between the # `FOR x IN coll` and the `RETURN x` part. # @param [Hash<Symbol, String>] bind_parameters The parameters to be passed into the query # @param [Hash] options Additional options for the query execution # @option options [String] :return_as ('RETURN #{model_name}') A custom `RETURN` statement # @option options [Boolean] :mapping (true) Should the mapping be performed? # @return [Query] # @raise [AQLNotSupportedError] If `aql_support` was not activated # @note Please use always bind parameters since they provide at least some form # of protection from AQL injection. # @see https://www.arangodb.org/manuals/2/Aql.html AQL Documentation def by_aql(aql_fragment, bind_parameters = {}, options = {}) raise AQLNotSupportedError unless Guacamole.configuration.experimental_features.include?(:aql_support) query = AqlQuery.new(self, mapper, options) query.aql_fragment = aql_fragment query.bind_parameters = bind_parameters query end # Get all Models stored in the collection # # The result can be limited (and should be for most datasets) # This can be done one the returned Query object. # All methods of the Enumerable module and `.to_a` will lead to the execution # of the query. # # @return [Query] # @example Get all podcasts # podcasts = PodcastsCollection.all.to_a # @example Get the first 50 podcasts # podcasts = PodcastsCollection.all.limit(50).to_a def all Query.new(connection.query, mapper) end # Specify details on the mapping # # The method is called with a block where you can specify # details about the way that the data from the database # is mapped to models. # # See `DocumentModelMapper` for details on how to configure # the mapper. def map(&block) mapper.instance_eval(&block) end # Timestamp a fresh model # # @api private def add_timestamps_to_model(model) timestamp = Time.now model.created_at = timestamp model.updated_at = timestamp end # Create a document from a model # # @api private # @todo Currently we only save the associated models if those never have been # persisted. In future versions we should add something like `:autosave` # to always save associated models. def create_document_from(model) create_referenced_models_of model document = connection.create_document(model_to_document(model)) model.key = document.key model.rev = document.revision create_referenced_by_models_of model document end # Creates all not yet persisted referenced models of `model` # # Referenced models needs to be created before the parent model, because it needs their `key` # # @api private # @todo This method should be considered 'work in progress'. We already know we need to change this. # @return [void] def create_referenced_models_of(model) mapper.referenced_models.each do |ref_model_name| ref_collection = mapper.collection_for(ref_model_name) ref_model = model.send(ref_model_name) next unless ref_model ref_collection.save ref_model unless ref_model.persisted? end end # Creates all not yet persisted models which are referenced by `model` # # Referenced by models needs to created after the parent model, because they need its `key` # # @api private # @todo This method should be considered 'work in progress'. We already know we need to change this. # @return [void] def create_referenced_by_models_of(model) mapper.referenced_by_models.each do |ref_model_name| ref_collection = mapper.collection_for(ref_model_name) ref_models = model.send(ref_model_name) ref_models.each do |ref_model| ref_model.send("#{model.class.name.demodulize.underscore}=", model) ref_collection.save ref_model unless ref_model.persisted? end end end # Replace a document in the database with this model # # @api private # @note This will **not** update associated models (see {#create}) def replace_document_from(model) document = model_to_document(model) response = connection.replace(model.key, document) model.rev = response['_rev'] document end end end end
module Haml # This module makes Haml work with Rails using the template handler API. class Plugin < ActionView::Template::Handlers::ERB.superclass # Rails 3.1+, template handlers don't inherit from anything. In <= 3.0, they # do. To avoid messy logic figuring this out, we just inherit from whatever # the ERB handler does. # In Rails 3.1+, we don't need to include Compilable. if ActionPack::VERSION::MAJOR < 3 || (ActionPack::VERSION::MAJOR == 3 && ActionPack::VERSION::MINOR < 1) include ActionView::Template::Handlers::Compilable end def handles_encoding?; true; end def compile(template) options = Haml::Template.options.dup options[:mime_type] = template.mime_type if template.respond_to? :mime_type options[:filename] = template.identifier Haml::Engine.new(template.source, options).compiler.precompiled_with_ambles([]) end # In Rails 3.1+, #call takes the place of #compile def self.call(template) new.compile(template) end def cache_fragment(block, name = {}, options = nil) @view.fragment_for(block, name, options) do eval("_hamlout.buffer", block.binding) end end end end ActionView::Template.register_template_handler(:haml, Haml::Plugin) Use type instead of mime_type in plugin.rb Template#mime_type method is deprecated in Rails 4. Use Template#type in template/plugin.rb if it's available. module Haml # This module makes Haml work with Rails using the template handler API. class Plugin < ActionView::Template::Handlers::ERB.superclass # Rails 3.1+, template handlers don't inherit from anything. In <= 3.0, they # do. To avoid messy logic figuring this out, we just inherit from whatever # the ERB handler does. # In Rails 3.1+, we don't need to include Compilable. if ActionPack::VERSION::MAJOR < 3 || (ActionPack::VERSION::MAJOR == 3 && ActionPack::VERSION::MINOR < 1) include ActionView::Template::Handlers::Compilable end def handles_encoding?; true; end def compile(template) options = Haml::Template.options.dup if template.respond_to? :type options[:mime_type] = template.type elsif template.respond_to? :mime_type options[:mime_type] = template.mime_type end options[:filename] = template.identifier Haml::Engine.new(template.source, options).compiler.precompiled_with_ambles([]) end # In Rails 3.1+, #call takes the place of #compile def self.call(template) new.compile(template) end def cache_fragment(block, name = {}, options = nil) @view.fragment_for(block, name, options) do eval("_hamlout.buffer", block.binding) end end end end ActionView::Template.register_template_handler(:haml, Haml::Plugin)
module HasSearcher VERSION = "0.0.5" end bump to 0.0.5.1 module HasSearcher VERSION = "0.0.5.1" end
# # The MIT License (MIT) # # Copyright (C) 2014 hellosign.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # module HelloSign module Api # # OAuth allows you to perform actions on behalf of other users after they grant you the authorization to do so. # For example, you could send signature requests on behalf of your users. This page lays out the basic steps to do that. # IMPORTANT # # With OAuth, you (the app owner) will be charged for all signature requests sent on behalf of other users via your app. # # @author [hellosign] # module OAuth # # Return the oath url where users can give permission for your application to perform actions on their behalf. # @param state [String] used for security and must match throughout the flow for a given user. # It can be set to the value of your choice (preferably something random). You should verify it matches the expected value when validating the OAuth callback. # @return [type] [description] def oauth_url(state) "#{self.oauth_end_point}/oauth/authorize?response_type=code&client_id=#{self.client_id}&state=#{state}" end # # Retrieving the OAuth token # # @option opts [String] state variable that was used when you created oauth_url for a specific user # @option opts [String] code The authorization code passed to your callback when the user granted access # # @return [Hash] oauth data of the user # # @example # client = HelloSign::Client.new :api_key => '%apikey%', :client_id => 'cc91c61d00f8bb2ece1428035716b', :client_secret => '1d14434088507ffa390e6f5528465' # client.get_oauth_token :state => '900e06e2', :code =>'1b0d28d90c86c141' def get_oauth_token(opts) opts[:client_id] = self.client_id opts[:client_secret] = self.client_secret opts[:grant_type] = 'authorization_code' post('/oauth/token', { :body => opts, :oauth_request => true }) end # # refresh user oauth token. # # @return [Hash] refreshed oauth info # @example # client = HelloSign::Client.new :api_key => '%apikey%', :client_id => 'cc91c61d00f8bb2ece1428035716b', :client_secret => '1d14434088507ffa390e6f5528465' # # @example # client.refresh_oauth_token :refresh_token => 'hNTI2MTFmM2VmZDQxZTZjOWRmZmFjZmVmMGMyNGFjMzI2MGI5YzgzNmE3' def refresh_oauth_token(opts) opts[:client_id] = self.client_id opts[:client_secret] = self.client_secret opts[:grant_type] = 'refresh_token' post('/oauth/token', { :body => opts, :oauth_request => true }) end # # Create new user and get their OAuth token. The user will receive an email asking them to confirm the access being granted. Your app will not be able to perform actions on behalf of this user until they confirm. # @option opts [String] email_address new user email address # # @return [Hash] details about new user, including oath data def oauth_create_account(opts) opts[:client_id] = self.client_id opts[:client_secret] = self.client_secret HelloSign::Resource::Account.new post('/account/create', { :body => opts }) end end end end Update OAuth endpoint parameters # # The MIT License (MIT) # # Copyright (C) 2014 hellosign.com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # module HelloSign module Api # # OAuth allows you to perform actions on behalf of other users after they grant you the authorization to do so. # For example, you could send signature requests on behalf of your users. # For more information, see our OAuth API documentation (https://app.hellosign.com/api/oauthWalkthrough). # # IMPORTANT: With some OAuth scopes, you (the app owner) will be charged for all signature requests sent on behalf of other users via your app. # # @author [hellosign] # module OAuth # # Returns the OAuth URL where users can give permission for your application to perform actions on their behalf. # # @param state [String] used for security and must match throughout the flow for a given user. # It can be set to the value of your choice (preferably something random). You should verify it matches the expected value when validating the OAuth callback. # @return [type] [description] def oauth_url(state) "#{self.oauth_end_point}/oauth/authorize?response_type=code&client_id=#{self.client_id}&state=#{state}" end # # Retrieves the OAuth token # # @option opts [String] state Random value that was used when you created oauth_url for a specific user. # @option opts [String] code The code passed to your callback when the user granted access. # @option opts [String] client_id The API App Client ID. # @option opts [String] client_secret The secret token of your API App. # # @return [Hash] OAuth data of the user # # @example # client = HelloSign::Client.new :api_key => '%apikey%', :client_id => 'cc91c61d00f8bb2ece1428035716b', :client_secret => '1d14434088507ffa390e6f5528465' # client.get_oauth_token :state => '900e06e2', :code =>'1b0d28d90c86c141' def get_oauth_token(opts) opts[:client_id] = self.client_id opts[:client_secret] = self.client_secret opts[:grant_type] = 'authorization_code' post('/oauth/token', { :body => opts, :oauth_request => true }) end # # Refreshes the user's OAuth token. # # @option opts [String] refresh_token The refresh provided when the access token has expired. # # @return [Hash] Refreshed OAuth info # # @example # client.refresh_oauth_token :refresh_token => 'hNTI2MTFmM2VmZDQxZTZjOWRmZmFjZmVmMGMyNGFjMzI2MGI5YzgzNmE3' def refresh_oauth_token(opts) opts[:client_id] = self.client_id opts[:client_secret] = self.client_secret opts[:grant_type] = 'refresh_token' post('/oauth/token', { :body => opts, :oauth_request => true }) end # # Create new user and get their OAuth token. The user will receive an email asking them to confirm the access being granted. # Your app will not be able to perform actions on behalf of this user until they confirm. # # @option opts [String] email_address New user email address. # # @example # client.oauth_create_account :email_address => 'new_user@example.com' # # @return [Hash] details about new user, including OAuth data def oauth_create_account(opts) opts[:client_id] = self.client_id opts[:client_secret] = self.client_secret HelloSign::Resource::Account.new post('/account/create', { :body => opts }) end end end end
# frozen_string_literal: true module AMA module Styles VERSION = '1.24.0' end end updating version # frozen_string_literal: true module AMA module Styles VERSION = '1.25.0' end end
# encoding: utf-8 module AMQ module Client VERSION = "0.7.0.beta12.pre" end end 0.7.0.beta12 # encoding: utf-8 module AMQ module Client VERSION = "0.7.0.beta12" end end
require 'heroku_subdomain/git' require 'heroku_subdomain/base' module HerokuSubdomain class App < Base attr_accessor :name, :git_url def initialize(options=nil) super @name, @git_url = @options.delete(:name), @options.delete(:git_url) end def self.create(name) self.new wrapper(:post_app, {name: name}) end def self.get_app(name) self.new wrapper(:get_app, name) end def update_repo Git.add_remote name, git_url unless Git.remotes.include?(name) Git.push name end def clone(new_name) app = self.class.create(new_name) app.addons(self.addons_names) app.vars(self.vars) end def addons_names Addon.by_app(self).map(&:name) end def addons(val=nil) if val.nil? Addon.by_app(self) else Addon.create(val, self) if val.any? end end def vars(val={}) if val.blank? self.class.heroku.get_config_vars(name).body else vars.each do |key, val| self.class.heroku.put_config_vars(name, {key => val}) end end end end end Added stack cedar to deploy require 'heroku_subdomain/git' require 'heroku_subdomain/base' module HerokuSubdomain class App < Base attr_accessor :name, :git_url def initialize(options=nil) super @name, @git_url = @options.delete(:name), @options.delete(:git_url) end def self.create(name) self.new wrapper(:post_app, {name: name, stack: :cedar}) end def self.get_app(name) self.new wrapper(:get_app, name) end def update_repo Git.add_remote name, git_url unless Git.remotes.include?(name) Git.push name end def clone(new_name) app = self.class.create(new_name) app.addons(self.addons_names) app.vars(self.vars) end def addons_names Addon.by_app(self).map(&:name) end def addons(val=nil) if val.nil? Addon.by_app(self) else Addon.create(val, self) if val.any? end end def vars(val={}) if val.blank? self.class.heroku.get_config_vars(name).body else vars.each do |key, val| self.class.heroku.put_config_vars(name, {key => val}) end end end end end
module Homeflow module API YAML::ENGINE.yamler = "syck" class Request include HTTParty attr_accessor :resource_class, :request_specification def initialize(request_specification) @request_specification = request_specification end def perform begin response = body_of_request(perform_request) rescue Errno::ECONNREFUSED => e raise Homeflow::API::Exceptions::APIConnectionError, "Connection error. Homeflow might be down?" end response end def perform_request if request_specification.is_a? Query url = "#{Homeflow::API.config.source}/#{request_specification.resource_class.resource_uri}" else url = "#{Homeflow::API.config.source}/#{request_specification.resource_uri}" end query_params = @request_specification.to_params.merge(constant_params) post_params = (@request_specification.respond_to?(:post_params) ? @request_specification.post_params : {}) if Homeflow::API.config.show_debug && Homeflow::API.configuration.logger log_line = [] log_line << "Destination - #{url}" log_line << "Request params:\n#{query_params.to_json}\n" log_line << "Post params:\n#{post_params.to_json}\n" log_line << "request_specification:\n#{request_specification.to_json}\n" log_line << "@request_specification:\n#{@request_specification.to_json}\n" Homeflow::API.configuration.logger.info(log_line.join("\n")) end if request_specification.is_a? Query return (self.class.get(url, :query => query_params)) elsif request_specification.is_a? ResourceIdentifier return (self.class.get(url, :query => query_params)) elsif request_specification.is_a? Delete return (self.class.delete(url, :query => query_params)) elsif request_specification.is_a? Put return (self.class.put(url, :query => query_params, :body => post_params)) elsif request_specification.is_a? Post return (self.class.post(url, :query => query_params, :body => post_params)) end end def body_of_request(request) if request.respond_to? :body request.body else body end end def constant_params {:api_key=> Homeflow::API.config.api_key} end class << self def run_for(request_specification) r = Request.new(request_specification) Response.new_from_json(r.perform) end end end end end Default to the request if it doesn't respond to body module Homeflow module API YAML::ENGINE.yamler = "syck" class Request include HTTParty attr_accessor :resource_class, :request_specification def initialize(request_specification) @request_specification = request_specification end def perform begin response = body_of_request(perform_request) rescue Errno::ECONNREFUSED => e raise Homeflow::API::Exceptions::APIConnectionError, "Connection error. Homeflow might be down?" end response end def perform_request if request_specification.is_a? Query url = "#{Homeflow::API.config.source}/#{request_specification.resource_class.resource_uri}" else url = "#{Homeflow::API.config.source}/#{request_specification.resource_uri}" end query_params = @request_specification.to_params.merge(constant_params) post_params = (@request_specification.respond_to?(:post_params) ? @request_specification.post_params : {}) if Homeflow::API.config.show_debug && Homeflow::API.configuration.logger log_line = [] log_line << "Destination - #{url}" log_line << "Request params:\n#{query_params.to_json}\n" log_line << "Post params:\n#{post_params.to_json}\n" log_line << "request_specification:\n#{request_specification.to_json}\n" log_line << "@request_specification:\n#{@request_specification.to_json}\n" Homeflow::API.configuration.logger.info(log_line.join("\n")) end if request_specification.is_a? Query return (self.class.get(url, :query => query_params)) elsif request_specification.is_a? ResourceIdentifier return (self.class.get(url, :query => query_params)) elsif request_specification.is_a? Delete return (self.class.delete(url, :query => query_params)) elsif request_specification.is_a? Put return (self.class.put(url, :query => query_params, :body => post_params)) elsif request_specification.is_a? Post return (self.class.post(url, :query => query_params, :body => post_params)) end end def body_of_request(request) if request.respond_to? :body request.body else request end end def constant_params {:api_key=> Homeflow::API.config.api_key} end class << self def run_for(request_specification) r = Request.new(request_specification) Response.new_from_json(r.perform) end end end end end
require "delegate" class Hookup class PostCheckout attr_reader :old_sha, :new_sha, :env, :hook def partial? @partial end def schema_dir @schema_dir ||= File.join(working_dir, env['HOOKUP_SCHEMA_DIR']).gsub(/^\.\//, "") end def possible_schemas %w(development_structure.sql schema.rb structure.sql).map do |file| File.join schema_dir, file end end def working_dir env['HOOKUP_WORKING_DIR'] || '.' end def initialize(hook, environment, *args) @hook = hook @env ||= environment.to_hash.dup require 'optparse' opts = OptionParser.new opts.banner = "Usage: hookup post-checkout <old> <new> <full>" opts.on('-Cdirectory', 'cd to directory') do |directory| env['HOOKUP_WORKING_DIR'] = directory end opts.on('--schema-dir=DIRECTORY', 'Path to DIRECTORY containing schema.rb and migrate/') do |directory| env['HOOKUP_SCHEMA_DIR'] = directory end opts.on('--load-schema=COMMAND', 'Run COMMAND on migration failure') do |command| env['HOOKUP_LOAD_SCHEMA'] = command end opts.parse!(args) @old_sha = args.shift if @old_sha == '0000000000000000000000000000000000000000' @old_sha = EMPTY_DIR elsif @old_sha.nil? @old_sha = '@{-1}' end @new_sha = args.shift || 'HEAD' @partial = (args.shift == '0') debug "#{hook}: #{old_sha} -> #{new_sha}" env['HOOKUP_SCHEMA_DIR'] = 'db' unless env['HOOKUP_SCHEMA_DIR'] && File.directory?(schema_dir) end def run return if skipped? || no_change? || checkout_during_rebase? || partial? update_submodules bundle migrate yarn_install end def update_submodules system "git submodule update --init" end def bundler? File.exist?('Gemfile') end def bundle return unless bundler? if changes.grep(/^Gemfile|\.gemspec$/).any? begin # If Bundler in turn spawns Git, it can get confused by $GIT_DIR git_dir = ENV.delete('GIT_DIR') unless rbenv_system("bundle check > /dev/null 2> /dev/null") Dir.chdir(working_dir) do rbenv_system("bundle") end end ensure ENV['GIT_DIR'] = git_dir end end end def migrate schemas = possible_schemas.select do |schema| change = changes[schema] rake 'db:create' if change && change.added? change && !change.deleted? end return if schemas.empty? migrations = changes.grep(/^#{schema_dir}\/migrate/) begin migrations.select { |migration| migration.deleted? || migration.modified? }.reverse.each do |migration| file = migration.file begin system 'git', 'checkout', old_sha, '--', file rake 'db:migrate:down', "VERSION=#{File.basename(file)}" ensure if migration.deleted? system 'git', 'rm', '--force', '--quiet', '--', file else system 'git', 'checkout', new_sha, '--', file end end end if migrations.any? { |migration| migration.added? || migration.modified? } rake 'db:migrate' end ensure _changes = x("git diff --name-status #{new_sha} -- #{schemas.join(' ')}") unless _changes.empty? puts "\e[33mSchema out of sync.\e[0m" system 'git', 'checkout', '--', *schemas fallback = env['HOOKUP_LOAD_SCHEMA'] if fallback && fallback != '' puts "Trying #{fallback}..." rbenv_system fallback end end end end def rake(*args) Dir.chdir(working_dir) do if File.executable?('bin/rake') rbenv_system 'bin/rake', *args elsif bundler? rbenv_system 'bundle', 'exec', 'rake', *args else rbenv_system 'rake', *args end end end def rbenv? File.exist?('.ruby-version') end def rbenv_version return unless rbenv? File.open(".ruby-version", "r") do |f| f.gets.gsub(/\n/, "") end end def rbenv_path version = rbenv_version return unless version path = File.join(ENV["RBENV_ROOT"], "versions", version, "bin") Dir.exist?(path) ? path : nil end def yarn? File.exist?('yarn.lock') end def yarn_install return unless yarn? system 'yarn install' end def skipped? env['SKIP_HOOKUP'] end def checkout_during_rebase? debug "GIT_REFLOG_ACTION: #{env['GIT_REFLOG_ACTION']}" hook == "post-checkout" && env['GIT_REFLOG_ACTION'] =~ /^(?:pull|rebase)/ end def no_change? old_sha == new_sha end def system(*args) puts "\e[90m[#{File.basename Dir.pwd}] #{args.join(" ")}\e[0m" super end def rbenv_system(*args) begin original_version = ENV["RBENV_VERSION"] original_path = ENV["PATH"] temp_version = rbenv_version temp_path = rbenv_path ENV["RBENV_VERSION"] = temp_version if temp_version ENV["PATH"] = "#{temp_path}:#{ENV["PATH"]}" if temp_path system(*args) ensure ENV["RBENV_VERSION"] = original_version ENV["PATH"] = original_path end end def x(command) puts "\e[90m[#{File.basename Dir.pwd}] #{command}\e[0m" %x{#{command}} end def debug(message) Hookup.debug(message) end def changes @changes ||= DiffChanges.new(x("git diff --name-status #{old_sha} #{new_sha}")) end class DiffChange < Struct.new(:type, :file) def added? type == "A" end def copied? type == "C" end def deleted? type == "D" end def modified? type == "M" end def renamed? type == "R" end def type_changed? type == "T" end def unmerged? type == "U" end def broken? type == "B" end end class DiffChanges < SimpleDelegator def initialize(diff) super diff.to_s.scan(/^([^\t]+)\t(.*)$/).map { |(type, file)| DiffChange.new(type, file) } end def grep(regex) __getobj__.select { |change| change.file =~ regex } end def [](filename) __getobj__.detect { |change| change.file == filename } end end end end [skip] Made yarn install step more robust (10m) Checks for any yarn.lock files in subdirectories and runs yarn for each it finds. Makes sure to exclude any found in `node_modules`. require "delegate" class Hookup class PostCheckout attr_reader :old_sha, :new_sha, :env, :hook def partial? @partial end def schema_dir @schema_dir ||= File.join(working_dir, env['HOOKUP_SCHEMA_DIR']).gsub(/^\.\//, "") end def possible_schemas %w(development_structure.sql schema.rb structure.sql).map do |file| File.join schema_dir, file end end def working_dir env['HOOKUP_WORKING_DIR'] || '.' end def initialize(hook, environment, *args) @hook = hook @env ||= environment.to_hash.dup require 'optparse' opts = OptionParser.new opts.banner = "Usage: hookup post-checkout <old> <new> <full>" opts.on('-Cdirectory', 'cd to directory') do |directory| env['HOOKUP_WORKING_DIR'] = directory end opts.on('--schema-dir=DIRECTORY', 'Path to DIRECTORY containing schema.rb and migrate/') do |directory| env['HOOKUP_SCHEMA_DIR'] = directory end opts.on('--load-schema=COMMAND', 'Run COMMAND on migration failure') do |command| env['HOOKUP_LOAD_SCHEMA'] = command end opts.parse!(args) @old_sha = args.shift if @old_sha == '0000000000000000000000000000000000000000' @old_sha = EMPTY_DIR elsif @old_sha.nil? @old_sha = '@{-1}' end @new_sha = args.shift || 'HEAD' @partial = (args.shift == '0') debug "#{hook}: #{old_sha} -> #{new_sha}" env['HOOKUP_SCHEMA_DIR'] = 'db' unless env['HOOKUP_SCHEMA_DIR'] && File.directory?(schema_dir) end def run return if skipped? || no_change? || checkout_during_rebase? || partial? update_submodules bundle yarn_install migrate end def update_submodules system "git submodule update --init" end def bundler? File.exist?('Gemfile') end def bundle return unless bundler? if changes.grep(/^Gemfile|\.gemspec$/).any? begin # If Bundler in turn spawns Git, it can get confused by $GIT_DIR git_dir = ENV.delete('GIT_DIR') unless rbenv_system("bundle check > /dev/null 2> /dev/null") Dir.chdir(working_dir) do rbenv_system("bundle") end end ensure ENV['GIT_DIR'] = git_dir end end end def migrate schemas = possible_schemas.select do |schema| change = changes[schema] rake 'db:create' if change && change.added? change && !change.deleted? end return if schemas.empty? migrations = changes.grep(/^#{schema_dir}\/migrate/) begin migrations.select { |migration| migration.deleted? || migration.modified? }.reverse.each do |migration| file = migration.file begin system 'git', 'checkout', old_sha, '--', file rake 'db:migrate:down', "VERSION=#{File.basename(file)}" ensure if migration.deleted? system 'git', 'rm', '--force', '--quiet', '--', file else system 'git', 'checkout', new_sha, '--', file end end end if migrations.any? { |migration| migration.added? || migration.modified? } rake 'db:migrate' end ensure _changes = x("git diff --name-status #{new_sha} -- #{schemas.join(' ')}") unless _changes.empty? puts "\e[33mSchema out of sync.\e[0m" system 'git', 'checkout', '--', *schemas fallback = env['HOOKUP_LOAD_SCHEMA'] if fallback && fallback != '' puts "Trying #{fallback}..." rbenv_system fallback end end end end def rake(*args) Dir.chdir(working_dir) do if File.executable?('bin/rake') rbenv_system 'bin/rake', *args elsif bundler? rbenv_system 'bundle', 'exec', 'rake', *args else rbenv_system 'rake', *args end end end def rbenv? File.exist?('.ruby-version') end def rbenv_version return unless rbenv? File.open(".ruby-version", "r") do |f| f.gets.gsub(/\n/, "") end end def rbenv_path version = rbenv_version return unless version path = File.join(ENV["RBENV_ROOT"], "versions", version, "bin") Dir.exist?(path) ? path : nil end def yarn? yarn_lock_files.any? end def yarn_install return unless yarn? yarn_lock_files.each do |lock_file| Dir.chdir(File.dirname(lock_file)) do system "yarn install" end end end def yarn_lock_files @yarn_lock_files ||= Dir.glob("**/yarn.lock").reject { |path| path =~ /node_modules/ } end def skipped? env['SKIP_HOOKUP'] end def checkout_during_rebase? debug "GIT_REFLOG_ACTION: #{env['GIT_REFLOG_ACTION']}" hook == "post-checkout" && env['GIT_REFLOG_ACTION'] =~ /^(?:pull|rebase)/ end def no_change? old_sha == new_sha end def system(*args) puts "\e[90m[#{File.basename Dir.pwd}] #{args.join(" ")}\e[0m" super end def rbenv_system(*args) begin original_version = ENV["RBENV_VERSION"] original_path = ENV["PATH"] temp_version = rbenv_version temp_path = rbenv_path ENV["RBENV_VERSION"] = temp_version if temp_version ENV["PATH"] = "#{temp_path}:#{ENV["PATH"]}" if temp_path system(*args) ensure ENV["RBENV_VERSION"] = original_version ENV["PATH"] = original_path end end def x(command) puts "\e[90m[#{File.basename Dir.pwd}] #{command}\e[0m" %x{#{command}} end def debug(message) Hookup.debug(message) end def changes @changes ||= DiffChanges.new(x("git diff --name-status #{old_sha} #{new_sha}")) end class DiffChange < Struct.new(:type, :file) def added? type == "A" end def copied? type == "C" end def deleted? type == "D" end def modified? type == "M" end def renamed? type == "R" end def type_changed? type == "T" end def unmerged? type == "U" end def broken? type == "B" end end class DiffChanges < SimpleDelegator def initialize(diff) super diff.to_s.scan(/^([^\t]+)\t(.*)$/).map { |(type, file)| DiffChange.new(type, file) } end def grep(regex) __getobj__.select { |change| change.file =~ regex } end def [](filename) __getobj__.detect { |change| change.file == filename } end end end end
# frozen_string_literal: true module HTMLProofer VERSION = '3.18.2' end :gem: bump to 3.18.3 # frozen_string_literal: true module HTMLProofer VERSION = '3.18.3' end
module HTMLProofer VERSION = '3.0.5' end :gem: bump to 3.0.6: module HTMLProofer VERSION = '3.0.6' end
require 'tilt' require 'mime/types' require 'yaml' require 'ostruct' require File.dirname(__FILE__) + "/mockup_template" module HtmlMockup class Template # The source attr_accessor :source # Store the frontmatter attr_accessor :data # The actual Tilt template attr_accessor :template # The path to the source file for this template attr_accessor :source_path class << self def open(path, options = {}) raise "Unknown file #{path}" unless File.exist?(path) self.new(File.read(path), options.update(:source_path => path)) end end # @option options [String,Pathname] :source_path The path to the source of the template being processed # @option options [String,Pathname] :layouts_path The path to where all layouts reside # @option options [String,Pathname] :partials_path The path to where all partials reside def initialize(source, options = {}) @options = options self.source_path = options[:source_path] self.data, self.source = extract_front_matter(source) self.template = Tilt.new(self.source_path.to_s){ self.source } if self.data[:layout] && layout_template_path = self.find_template(self.data[:layout], :layouts_path) @layout_template = Tilt.new(layout_template_path.to_s) end end def render(env = {}) context = TemplateContext.new(self, env) locals = {:document => OpenStruct.new(self.data)} if @layout_template @layout_template.render(context, locals) do self.template.render(context, locals) end else self.template.render(context, locals) end end def find_template(name, path_type) raise(ArgumentError, "path_type must be one of :partials_path or :layouts_path") unless [:partials_path, :layouts_path].include?(path_type) @resolvers ||= {} @resolvers[path_type] ||= Resolver.new(@options[path_type]) @resolvers[path_type].url_to_path(name) end # Try to infer the final extension of the output file. def target_extension return @target_extension if @target_extension if type = MIME::Types[self.target_mime_type].first # Dirty little hack to enforce the use of .html instead of .htm if type.sub_type == "html" @target_extension = "html" else @target_extension = type.extensions.first end else @target_extension = File.extname(self.source_path.to_s).sub(/^\./, "") end end def source_extension parts = File.basename(File.basename(self.source_path.to_s)).split(".") if parts.size > 2 parts[-2..-1].join(".") else File.extname(self.source_path.to_s).sub(/^\./, "") end end # Try to figure out the mime type based on the Tilt class and if that doesn't # work we try to infer the type by looking at extensions (needed for .erb) def target_mime_type mime = self.template.class.default_mime_type return mime if mime path = File.basename(self.source_path.to_s) mime = MIME::Types.type_for(path).first return mime.to_s if mime parts = File.basename(path).split(".") if parts.size > 2 mime = MIME::Types.type_for(parts[0..-2].join(".")).first return mime.to_s if mime else nil end end protected # Get the front matter portion of the file and extract it. def extract_front_matter(source) fm_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m if match = source.match(fm_regex) source = source.sub(fm_regex, "") begin data = (YAML.load(match[1]) || {}).inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} rescue *YAML_ERRORS => e puts "YAML Exception: #{e.message}" return false end else return [{}, source] end [data, source] rescue [{}, source] end end class TemplateContext def initialize(template, env={}) @_template, @_env = template, env end def template @_template end def env @_env end def partial(name, options = {}) if template_path = self.template.find_template(name, :partials_path) # puts "Rendering partial #{name}, with template #{template_path}" partial_template = Tilt.new(template_path.to_s) partial_template.render(self, options[:locals] || {}) elsif template_path = self.template.find_template(name + ".part", :partials_path) # puts "Rendering old-style partial #{name}, with template #{template_path}" template = Tilt::ERBTemplate.new(template_path.to_s) context = MockupTemplate::TemplateContext.new(options[:locals] || {}) template.render(context, :env => self.env) else raise ArgumentError, "No such partial #{name}, referenced from #{self.template.source_path}" end end end end Remove debugging code require 'tilt' require 'mime/types' require 'yaml' require 'ostruct' require File.dirname(__FILE__) + "/mockup_template" module HtmlMockup class Template # The source attr_accessor :source # Store the frontmatter attr_accessor :data # The actual Tilt template attr_accessor :template # The path to the source file for this template attr_accessor :source_path class << self def open(path, options = {}) raise "Unknown file #{path}" unless File.exist?(path) self.new(File.read(path), options.update(:source_path => path)) end end # @option options [String,Pathname] :source_path The path to the source of the template being processed # @option options [String,Pathname] :layouts_path The path to where all layouts reside # @option options [String,Pathname] :partials_path The path to where all partials reside def initialize(source, options = {}) @options = options self.source_path = options[:source_path] self.data, self.source = extract_front_matter(source) self.template = Tilt.new(self.source_path.to_s){ self.source } if self.data[:layout] && layout_template_path = self.find_template(self.data[:layout], :layouts_path) @layout_template = Tilt.new(layout_template_path.to_s) end end def render(env = {}) context = TemplateContext.new(self, env) locals = {:document => OpenStruct.new(self.data)} if @layout_template @layout_template.render(context, locals) do self.template.render(context, locals) end else self.template.render(context, locals) end end def find_template(name, path_type) raise(ArgumentError, "path_type must be one of :partials_path or :layouts_path") unless [:partials_path, :layouts_path].include?(path_type) @resolvers ||= {} @resolvers[path_type] ||= Resolver.new(@options[path_type]) @resolvers[path_type].url_to_path(name) end # Try to infer the final extension of the output file. def target_extension return @target_extension if @target_extension if type = MIME::Types[self.target_mime_type].first # Dirty little hack to enforce the use of .html instead of .htm if type.sub_type == "html" @target_extension = "html" else @target_extension = type.extensions.first end else @target_extension = File.extname(self.source_path.to_s).sub(/^\./, "") end end def source_extension parts = File.basename(File.basename(self.source_path.to_s)).split(".") if parts.size > 2 parts[-2..-1].join(".") else File.extname(self.source_path.to_s).sub(/^\./, "") end end # Try to figure out the mime type based on the Tilt class and if that doesn't # work we try to infer the type by looking at extensions (needed for .erb) def target_mime_type mime = self.template.class.default_mime_type return mime if mime path = File.basename(self.source_path.to_s) mime = MIME::Types.type_for(path).first return mime.to_s if mime parts = File.basename(path).split(".") if parts.size > 2 mime = MIME::Types.type_for(parts[0..-2].join(".")).first return mime.to_s if mime else nil end end protected # Get the front matter portion of the file and extract it. def extract_front_matter(source) fm_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m if match = source.match(fm_regex) source = source.sub(fm_regex, "") begin data = (YAML.load(match[1]) || {}).inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} rescue *YAML_ERRORS => e puts "YAML Exception: #{e.message}" return false end else return [{}, source] end [data, source] rescue [{}, source] end end class TemplateContext def initialize(template, env={}) @_template, @_env = template, env end def template @_template end def env @_env end def partial(name, options = {}) if template_path = self.template.find_template(name, :partials_path) partial_template = Tilt.new(template_path.to_s) partial_template.render(self, options[:locals] || {}) elsif template_path = self.template.find_template(name + ".part", :partials_path) template = Tilt::ERBTemplate.new(template_path.to_s) context = MockupTemplate::TemplateContext.new(options[:locals] || {}) template.render(context, :env => self.env) else raise ArgumentError, "No such partial #{name}, referenced from #{self.template.source_path}" end end end end
require 'i18n/tasks/data_traversal' require 'i18n/tasks/key_pattern_matching' module I18n::Tasks module Data class Yaml include ::I18n::Tasks::DataTraversal include ::I18n::Tasks::KeyPatternMatching attr_reader :config DEFAULTS = { read: ['config/locales/%{locale}.yml'], write: ['config/locales/%{locale}.yml'] }.with_indifferent_access def initialize(config = {}) self.config = config end def config=(config) opt = (config || {}).with_indifferent_access if opt.key?(:paths) opt[:read] ||= opt.delete(:paths) ::I18n::Tasks.warn_deprecated 'please rename "data.paths" key to "data.read" in config/i18n-tasks.yml' end opt = DEFAULTS.deep_merge(opt) @read = opt[:read] @write = opt[:write].map { |x| x.is_a?(String) ? ['*', x] : x }.map { |x| [compile_key_pattern(x[0]), x[1]] } @locale_data = {} end attr_reader :config # get locale tree def get(locale) locale = locale.to_s @locale_data[locale] ||= begin @read.map do |path| Dir.glob path % {locale: locale} end.flatten.map do |locale_file| YAML.load_file locale_file end.inject({}) do |hash, locale_data| hash.deep_merge! locale_data || {} hash end[locale.to_s] || {} end end alias [] get # set locale tree def set(locale, value_tree) out = {} traverse value_tree do |key, value| route = @write.detect { |route| route[0] =~ key } key_match = $~ path = route[1] % {locale: locale} path.gsub!(/[\\]\d+/) { |m| key_match[m[1..-1].to_i] } (out[path] ||= []) << [key, value] end out.each do |path, data| File.open(path, 'w') { |f| f.write({locale.to_s => list_to_tree(data)}.to_yaml) } end end alias []= set end end end Update yaml.rb require 'i18n/tasks/data_traversal' require 'i18n/tasks/key_pattern_matching' module I18n::Tasks module Data class Yaml include ::I18n::Tasks::DataTraversal include ::I18n::Tasks::KeyPatternMatching attr_reader :config DEFAULTS = { read: ['config/locales/%{locale}.yml'], write: ['config/locales/%{locale}.yml'] }.with_indifferent_access def initialize(config = {}) self.config = config end def config=(config) opt = (config || {}).with_indifferent_access if opt.key?(:paths) opt[:read] ||= opt.delete(:paths) ::I18n::Tasks.warn_deprecated 'please rename "data.paths" key to "data.read" in config/i18n-tasks.yml' end opt = DEFAULTS.deep_merge(opt) @read = opt[:read] @write = opt[:write].map { |x| x.is_a?(String) ? ['*', x] : x }.map { |x| [compile_key_pattern(x[0]), x[1]] } @locale_data = {} end # get locale tree def get(locale) locale = locale.to_s @locale_data[locale] ||= begin @read.map do |path| Dir.glob path % {locale: locale} end.flatten.map do |locale_file| YAML.load_file locale_file end.inject({}) do |hash, locale_data| hash.deep_merge! locale_data || {} hash end[locale.to_s] || {} end end alias [] get # set locale tree def set(locale, value_tree) out = {} traverse value_tree do |key, value| route = @write.detect { |route| route[0] =~ key } key_match = $~ path = route[1] % {locale: locale} path.gsub!(/[\\]\d+/) { |m| key_match[m[1..-1].to_i] } (out[path] ||= []) << [key, value] end out.each do |path, data| File.open(path, 'w') { |f| f.write({locale.to_s => list_to_tree(data)}.to_yaml) } end end alias []= set end end end
module Import class BaseResource include Import::Helper attr_reader :resource, :remote_id, :errors def initialize(resource, *args) handle_args(resource, *args) initialize_associations_states import(resource, *args) return if @resource.blank? store_associations(:after, @resource) end def import_class raise NoMethodError, "#{self.class.name} has no implementation of the needed 'import_class' method" end def source import_class_namespace end def remote_id(resource, *_args) @remote_id ||= resource.delete(:id) end def action return :failed if errors.present? return :skipped if !@resource return :unchanged if !attributes_changed? return :created if created? :updated end def attributes_changed? changed_attributes.present? || changed_associations.present? end def changed_attributes return if @resource.blank? # dry run return @resource.changes if @resource.changed? # live run @resource.previous_changes end def changed_associations changes = {} tracked_associations.each do |association| next if @associations[:before][association] == @associations[:after][association] changes[association] = [@associations[:before][association], @associations[:after][association]] end changes end def created? return false if @resource.blank? # dry run return @resource.created_at.nil? if @resource.changed? # live run @resource.created_at == @resource.updated_at end private def initialize_associations_states @associations = {} %i(before after).each do |state| @associations[state] ||= {} end end def import(resource, *args) create_or_update(map(resource, *args), *args) rescue => e # Don't catch own thrown exceptions from above raise if e.is_a?(NoMethodError) handle_error(e) end def create_or_update(resource, *args) return if updated?(resource, *args) create(resource, *args) end def updated?(resource, *args) @resource = lookup_existing(resource, *args) return false if !@resource # delete since we have an update and # the record is already created resource.delete(:created_by_id) @resource.assign_attributes(resource) # the return value here is kind of misleading # and should not be trusted to indicate if a # resource was actually updated. # Use .action instead return true if !attributes_changed? return true if @dry_run @resource.save true end def lookup_existing(resource, *_args) synced_instance = ExternalSync.find_by( source: source, source_id: remote_id(resource), object: import_class.name, ) return if !synced_instance instance = import_class.find_by(id: synced_instance.o_id) store_associations(:before, instance) instance end def store_associations(state, instance) @associations[state] = associations_state(instance) end def associations_state(instance) state = {} tracked_associations.each do |association| state[association] = instance.send(association) end state end def tracked_associations # loop over all reflections import_class.reflect_on_all_associations.collect do |reflection| # refection name is something like groups or organization (singular/plural) reflection_name = reflection.name.to_s # key is something like group_id or organization_id (singular) key = reflection.klass.name.foreign_key # add trailing 's' to get pluralized key if reflection_name.singularize != reflection_name key = "#{key}s" end key.to_sym end end def create(resource, *_args) @resource = import_class.new(resource) return if @dry_run @resource.save external_sync_create( local: @resource, remote: resource, ) end def external_sync_create(local:, remote:) ExternalSync.create( source: source, source_id: remote_id(remote), object: import_class.name, o_id: local.id ) end def defaults(_resource, *_args) { created_by_id: 1, updated_by_id: 1, } end def map(resource, *args) mapped = from_mapping(resource, *args) attributes = defaults(resource, *args).merge(mapped) attributes.symbolize_keys end def from_mapping(resource, *args) mapping = mapping(*args) return resource if !mapping ExternalSync.map( mapping: mapping, source: resource ) end def mapping(*args) Setting.get(mapping_config(*args)) end def mapping_config(*_args) import_class_namespace.gsub('::', '_').underscore + '_mapping' end def import_class_namespace self.class.name.to_s.sub('Import::', '') end def handle_args(_resource, *args) return if !args return if !args.is_a?(Array) return if args.empty? last_arg = args.last return if !last_arg.is_a?(Hash) handle_modifiers(last_arg) end def handle_modifiers(modifiers) @dry_run = modifiers.fetch(:dry_run, false) end def handle_error(e) @errors ||= [] @errors.push(e) Rails.logger.error e end end end Fixed bug: Failed save actions for import resources should throw an exception instead of just returning false. module Import class BaseResource include Import::Helper attr_reader :resource, :remote_id, :errors def initialize(resource, *args) handle_args(resource, *args) initialize_associations_states import(resource, *args) return if @resource.blank? store_associations(:after, @resource) end def import_class raise NoMethodError, "#{self.class.name} has no implementation of the needed 'import_class' method" end def source import_class_namespace end def remote_id(resource, *_args) @remote_id ||= resource.delete(:id) end def action return :failed if errors.present? return :skipped if !@resource return :unchanged if !attributes_changed? return :created if created? :updated end def attributes_changed? changed_attributes.present? || changed_associations.present? end def changed_attributes return if @resource.blank? # dry run return @resource.changes if @resource.changed? # live run @resource.previous_changes end def changed_associations changes = {} tracked_associations.each do |association| next if @associations[:before][association] == @associations[:after][association] changes[association] = [@associations[:before][association], @associations[:after][association]] end changes end def created? return false if @resource.blank? # dry run return @resource.created_at.nil? if @resource.changed? # live run @resource.created_at == @resource.updated_at end private def initialize_associations_states @associations = {} %i(before after).each do |state| @associations[state] ||= {} end end def import(resource, *args) create_or_update(map(resource, *args), *args) rescue => e # Don't catch own thrown exceptions from above raise if e.is_a?(NoMethodError) handle_error(e) end def create_or_update(resource, *args) return if updated?(resource, *args) create(resource, *args) end def updated?(resource, *args) @resource = lookup_existing(resource, *args) return false if !@resource # delete since we have an update and # the record is already created resource.delete(:created_by_id) @resource.assign_attributes(resource) # the return value here is kind of misleading # and should not be trusted to indicate if a # resource was actually updated. # Use .action instead return true if !attributes_changed? return true if @dry_run @resource.save! true end def lookup_existing(resource, *_args) synced_instance = ExternalSync.find_by( source: source, source_id: remote_id(resource), object: import_class.name, ) return if !synced_instance instance = import_class.find_by(id: synced_instance.o_id) store_associations(:before, instance) instance end def store_associations(state, instance) @associations[state] = associations_state(instance) end def associations_state(instance) state = {} tracked_associations.each do |association| state[association] = instance.send(association) end state end def tracked_associations # loop over all reflections import_class.reflect_on_all_associations.collect do |reflection| # refection name is something like groups or organization (singular/plural) reflection_name = reflection.name.to_s # key is something like group_id or organization_id (singular) key = reflection.klass.name.foreign_key # add trailing 's' to get pluralized key if reflection_name.singularize != reflection_name key = "#{key}s" end key.to_sym end end def create(resource, *_args) @resource = import_class.new(resource) return if @dry_run @resource.save! external_sync_create( local: @resource, remote: resource, ) end def external_sync_create(local:, remote:) ExternalSync.create( source: source, source_id: remote_id(remote), object: import_class.name, o_id: local.id ) end def defaults(_resource, *_args) { created_by_id: 1, updated_by_id: 1, } end def map(resource, *args) mapped = from_mapping(resource, *args) attributes = defaults(resource, *args).merge(mapped) attributes.symbolize_keys end def from_mapping(resource, *args) mapping = mapping(*args) return resource if !mapping ExternalSync.map( mapping: mapping, source: resource ) end def mapping(*args) Setting.get(mapping_config(*args)) end def mapping_config(*_args) import_class_namespace.gsub('::', '_').underscore + '_mapping' end def import_class_namespace self.class.name.to_s.sub('Import::', '') end def handle_args(_resource, *args) return if !args return if !args.is_a?(Array) return if args.empty? last_arg = args.last return if !last_arg.is_a?(Hash) handle_modifiers(last_arg) end def handle_modifiers(modifiers) @dry_run = modifiers.fetch(:dry_run, false) end def handle_error(e) @errors ||= [] @errors.push(e) Rails.logger.error e end end end
require 'optparse' require 'internet-sampler/application' module InternetSampler class CLI def initialize args sinatra_options = { port: 9292, bind: 'localhost', } sampler_options = { tracks: [] } opt = OptionParser.new opt.on('-p port', '--port port', 'port to listen (default is 9292)') { |i| sinatra_options[:port] = i.to_i } opt.on('-b host', '--bind host', 'host to bind (default is localhost)') { |i| sinatra_options[:bind] = i } opt.on('-t slug:url', '--track slug:url', 'sample sound to serve (note that `url\' is not path to file but URL to serve)') { |i| if track = i.match(/^([^:]*):(.*)$/) sampler_options[:tracks] << { slug: track[1], path: track[2] } end } opt.parse! args InternetSampler::Application.run_with_sampler_options! sampler_options, sinatra_options end end end treat env require 'optparse' require 'internet-sampler/application' module InternetSampler class CLI def initialize args sinatra_options = { port: 9292, bind: 'localhost', environment: :development, } sampler_options = { tracks: [] } opt = OptionParser.new opt.on('-p port', '--port port', 'port to listen (default is 9292)') { |i| sinatra_options[:port] = i.to_i } opt.on('-b host', '--bind host', 'host to bind (default is localhost)') { |i| sinatra_options[:bind] = i } opt.on('-e env', '--environment env', 'environment to run (production, test or development; default is development)') { |i| if %w{development test production}.include? i sinatra_options[:environment] = i.to_sym end } opt.on('-t slug:url', '--track slug:url', 'sample sound to serve (note that `url\' is not path to file but URL to serve)') { |i| if track = i.match(/^([^:]*):(.*)$/) sampler_options[:tracks] << { slug: track[1], path: track[2] } end } opt.parse! args InternetSampler::Application.run_with_sampler_options! sampler_options, sinatra_options end end end
class Iterm2mintty VERSION = "0.0.2" end 0.0.3 Removed pry require. class Iterm2mintty VERSION = "0.0.3" end
# Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. require 'yaml' module TrisanoHelper #Define constants for standard resources FORM = "forms" # Constants for the tab names DEMOGRAPHICS = "Demographics" CLINICAL = "Clinical" LABORATORY = "Laboratory" CONTACTS = "Contacts" ENCOUNTERS = "Encounters" EPI = "Epidemiological" REPORTING = "Reporting" INVESTIGATION = "Investigation" NOTES = "Notes" ADMIN = "Administrative" OUTBREAK = "Outbreak" # Tabs for place events PLACE = "Place" # Constants for element id prefixes VIEW_ID_PREFIX = "view_" CORE_VIEW_ID_PREFIX = "core_view_" CORE_FIELD_ID_PREFIX = "core_field_" BEFORE_CORE_FIELD_ID_PREFIX = "before_core_field_" AFTER_CORE_FIELD_ID_PREFIX = "after_core_field_" SECTION_ID_PREFIX = "section_" GROUP_ID_PREFIX = "group_" QUESTION_ID_PREFIX = "question_" FOLLOW_UP_ID_PREFIX = "follow_up_" VALUE_SET_ID_PREFIX = "value_set_" INVESTIGATOR_QUESTION_ID_PREFIX = "question_investigate_" INVESTIGATOR_ANSWER_ID_PREFIX = "investigator_answer_" TAB_ELEMENT_IDS_BY_NAME = { DEMOGRAPHICS => "demographic_tab", CLINICAL => "clinical_tab", LABORATORY => "lab_info_tab", CONTACTS => "contacts_tab", ENCOUNTERS => "encounters_tab", EPI => "epi_tab", REPORTING => "reporting_tab", NOTES => 'notes_tab', ADMIN => "administrative_tab", PLACE => "place_tab", OUTBREAK => "outbreak_tab" } def wait_for_element_present(name, browser=nil) browser = @browser.nil? ? browser : @browser !60.times{ break if (browser.is_element_present(name) rescue false); sleep 1 } end def wait_for_element_not_present(name, browser=nil) browser = @browser.nil? ? browser : @browser !60.times{ break unless (browser.is_element_present(name) rescue true); sleep 1 } end # Use set_fields after you navigate to any location by passing in a hash of # fields and values and this method will set them all. It will work for # updating existing items or creating new ones. cmr_helper_example shows how # to create a complete CMR with the helper. The hash created in this example # could be helpful for other tests. Note that this method does not submit # for you. def set_fields(browser, value_hash) fields = browser.get_all_fields value_hash.each_pair do |key, value| if fields.index(key) != nil browser.type(key, value) else begin browser.select(key,"label=" + value) rescue StandardError => err #TODO - Make this work for auto-complete fields by using the name instead of the ID in a type command #The problem with using the name is that it won't show up as a field in get_all_fields, and it won't be selectable #I'm trying to do something in the rescue block to detect the error from trying to select it. # if err == "Specified element is not a Select (has no options)" #This is usually because the element is the name of a auto-complete field # browser.type(key, value) # else puts("WARNING: Field " + key + " not found. Value not set.") # end end end end end # Use get_full_cmr to create a cmr with every field filled in (excludes repeating elements) # It uses random words for text fields def create_cmr_from_hash(browser, cmr_hash) click_nav_new_cmr(browser) browser.wait_for_page_to_load($load_time) set_fields(browser,cmr_hash) browser.click('morbidity_event_submit') browser.wait_for_page_to_load($load_time) return save_cmr(browser) end # Use get_full_cmr to create a cmr with only the last name filled in # It uses random words for the last name field def get_nil_cmr() end def current_user(browser = @browser) browser.get_selected_label("user_id") end #Use click_core_tab to change tabs in CMR views def click_core_tab(browser, tab_name) case tab_name when DEMOGRAPHICS browser.click('//li[1]/a/em') when CLINICAL browser.click('//li[2]/a/em') when LABORATORY browser.click('//li[3]/a/em') when CONTACTS browser.click('//li[4]/a/em') when ENCOUNTERS browser.click('//li[5]/a/em') when EPI browser.click('//li[6]/a/em') when REPORTING browser.click('//li[7]/a/em') when INVESTIGATION browser.click('//li[8]/a/em') when NOTES browser.click('//li[9]/a/em') when ADMIN browser.click('//li[10]/a/em') when PLACE browser.click('//li[1]/a/em') else puts("TAB NOT FOUND: " + tab_name) end end def get_random_disease() wordlist = YAML.load_file(File.join(RAILS_ROOT, 'db', 'defaults', 'diseases.yml')).collect { |k,v| v[:diseases] }.flatten.collect{ |d| d[:disease_name] }.uniq wordlist[rand(wordlist.size)] end def get_random_jurisdiction() wordlist = ["Out of State","Weber-Morgan Health Department","Wasatch County Health Department","Utah State","Utah County Health Department","TriCounty Health Department","Tooele County Health Department","Summit County Public Health Department","Southwest Utah Public Health Department","Southeastern Utah District Health Department","Salt Lake Valley Health Department","Davis County Health Department","Central Utah Public Health Department","Bear River Health Department","Unassigned"] wordlist[rand(wordlist.size)] end def get_random_jurisdiction_by_short_name() wordlist = ["Unassigned", "Bear River", "Central Utah", "Davis County", "Salt Lake Valley", "Southeastern Utah", "Southwest Utah", "Summit County", "Tooele County", "TriCounty", "Utah County", "Utah State", "Wasatch County", "Weber-Morgan", "Out of State"] wordlist[rand(wordlist.size)] end # # General navigation and controls # def click_logo(browser) browser.click 'logo' browser.wait_for_page_to_load($load_time) end def click_nav_new_cmr(browser) browser.open "/trisano/cmrs/new" browser.wait_for_page_to_load($load_time) return (browser.is_text_present("New Morbidity Event") and browser.is_text_present("New CMR") and browser.is_element_present("link=< Back to list") and browser.is_element_present("disable_tabs")) end def click_nav_cmrs(browser) browser.click 'link=EVENTS' browser.wait_for_page_to_load($load_time) return (browser.is_text_present("List Morbidity Events") and browser.is_element_present("link=EVENTS")) end def click_nav_search(browser) browser.click 'link=SEARCH' browser.wait_for_page_to_load($load_time) return browser.is_text_present("Event Search") end def click_nav_forms(browser) click_nav_admin(browser) browser.click 'link=Manage Forms' browser.wait_for_page_to_load($load_time) return (browser.is_text_present("Form Information") and browser.is_text_present("Diseases") and browser.is_text_present("Jurisdiction") and browser.is_text_present("Event Type") and browser.is_element_present("//input[@value='Upload']") and browser.is_element_present("//input[@id='form_import']") and browser.is_element_present("//input[@value='Create New Form']") ) end def click_nav_admin(browser) unless browser.is_element_present("link=ADMIN") @browser.open "/trisano/cmrs" @browser.wait_for_page_to_load($load_time) end browser.click 'link=ADMIN' browser.wait_for_page_to_load($load_time) return(browser.is_text_present("Admin Dashboard")) end def edit_cmr(browser) browser.click "link=Edit" browser.wait_for_page_to_load($load_time) return(browser.get_html_source.include?("Person Information") and browser.get_html_source.include?("Street number")) end def show_cmr(browser) browser.click "link=Show" browser.wait_for_page_to_load($load_time) return(browser.is_text_present("Person Information") and browser.is_text_present("Street number")) end def save_and_exit(browser) browser.click "save_and_exit_btn" browser.wait_for_page_to_load($load_time) browser.is_text_present("successfully").should be_true return true end def save_cmr(browser) save_and_exit(browser) end def save_and_continue(browser) browser.click "save_and_continue_btn" browser.wait_for_page_to_load($load_time) return(browser.is_text_present("successfully")) end # Clicks the print button and points the browser at the print window. # # To close the window after inspecting it, do something like the following: # @browser.close() # @browser.select_window 'null' def print_cmr(browser, note = 0) if note == 1 browser.click "link=With Notes" else browser.click "link=Print" end wait_for_element_present("//div[contains(@id, 'printing_controls')]") browser.click "print_all" browser.get_eval("selenium.browserbot.findElement(\"//form[contains(@action, 'print')]\").target='doit';") browser.open_window("", "doit"); browser.click "print_btn" browser.wait_for_pop_up("doit", $load_time) browser.select_window("doit") return(browser.get_html_source.include?('Confidential Case Report') && browser.get_html_source.include?('Printed')) end def navigate_to_people_search(browser) click_nav_search(browser) @browser.click('link=People Search') @browser.wait_for_page_to_load($load_time) return(browser.is_text_present("People Search") and browser.is_text_present("Name") and browser.is_text_present("Date of birth")) end def navigate_to_cmr_search(browser) click_nav_search(browser) return(browser.is_text_present("Name Criteria")) end #Use click_link_by_order to click the Nth element in a list of links of the same element type def click_link_by_order(browser, element_id_prefix, order) links = browser.get_all_links links.delete_if{|link| link.index(element_id_prefix) == nil} browser.click(links[order-1]) end def type_field_by_order(browser, element_id_prefix, order, value) fields = browser.get_all_fields fields.delete_if{|field| field.index(element_id_prefix) != 0} browser.type(fields[order], value) end # Use click_resource methods from any standard resource index page def click_resource_edit(browser, resource, name) id = get_resource_id(browser, name) if (id > 0) browser.click "//a[contains(@href, '/trisano/" + resource + "/" + id.to_s + "/edit')]" browser.wait_for_page_to_load "30000" return 0 else return -1 end end def click_resource_show(browser, resource, name) id = get_resource_id(browser, name) if id > 0 browser.click "//a[contains(@onclick, '/trisano/" + resource + "/" + id.to_s + "')]" browser.wait_for_page_to_load "30000" return 0 else return -1 end end def create_simplest_cmr(browser, last_name) click_nav_new_cmr(browser) browser.type "morbidity_event_interested_party_attributes_person_entity_attributes_person_attributes_last_name", last_name yield browser if block_given? return save_cmr(browser) end def create_basic_investigatable_cmr(browser, last_name, disease_label, jurisdiction_label=nil) click_nav_new_cmr(browser) browser.type "morbidity_event_interested_party_attributes_person_entity_attributes_person_attributes_last_name", last_name browser.type("morbidity_event_address_attributes_street_number", "22") browser.type("morbidity_event_address_attributes_street_name", "Happy St.") click_core_tab(browser, CLINICAL) browser.select "morbidity_event_disease_event_attributes_disease_id", "label=#{disease_label}" click_core_tab(browser, ADMIN) browser.select "morbidity_event_jurisdiction_attributes_secondary_entity_id", "label=#{jurisdiction_label}" if jurisdiction_label yield browser if block_given? return save_cmr(browser) end def answer_investigator_question(browser, question_text, answer, html_source=nil) answer_id = get_investigator_answer_id(browser, question_text, html_source) begin browser.type("#{INVESTIGATOR_ANSWER_ID_PREFIX}#{answer_id}", answer) == "OK" rescue return false end return true end def watch_for_core_field_spinner(core_field, browser=@browser, &proc) css_selector = %Q{img[id$="#{core_field}_spinner"]} watch_for_spinner(css_selector, browser, &proc) end def watch_for_answer_spinner(question_text, browser=@browser, &proc) answer_id = get_investigator_answer_id(browser, question_text) css_selector = "img[id=investigator_answer_#{answer_id}_spinner]" watch_for_spinner(css_selector, browser, &proc) end def watch_for_spinner(css_selector, browser=@browser, &proc) script = "selenium.browserbot.getCurrentWindow().$$('#{css_selector}').first().visible()" proc.call unless proc.nil? browser.wait_for_condition("#{script} == true", 3000).should == "OK" browser.wait_for_condition("#{script} == false", 3000).should == "OK" end def answer_multi_select_investigator_question(browser, question_text, answer) answer_id = get_investigator_answer_id(browser, question_text) begin browser.select("#{INVESTIGATOR_ANSWER_ID_PREFIX}#{answer_id}", answer) == "OK" rescue return false end return true end def answer_check_investigator_question(browser, question_text, answer) answer_id = get_investigator_click_answer_id(browser, question_text) begin browser.click("//input[contains(@id, 'investigator_answer_#{answer_id}') and @value='#{answer}']") == "OK" rescue return false end return true end def answer_radio_investigator_question(browser, question_text, answer) answer_id = get_investigator_click_answer_id(browser, question_text) begin browser.click("//input[contains(@id, 'investigator_answer_#{answer_id}') and @value='#{answer}']") == "OK" rescue return false end return true end def switch_user(browser, user_id) current_user = @browser.get_selected_label("user_id") if current_user != user_id browser.select("user_id", "label=#{user_id}") browser.wait_for_page_to_load return browser.is_text_present("#{user_id}:") end end #TODO def click_question(browser, question, action) case action when "edit" q_id = get_form_element_id(browser, question, QUESTION_ID_PREFIX) browser.click("edit-question-" + q_id.to_s) sleep 2 #TODO replacing the wait below until it works properly #wait_for_element_present("edit-question-form") when "delete" q_id = get_form_element_id(browser, question, QUESTION_ID_PREFIX) browser.click("delete-question-" + q_id.to_s) sleep 2 #TODO - should probably replace this with the element name, if there is one when "Add value set" #TODO else #TODO - this is an error end end #Get a unique name with the input number of words in it def get_unique_name(words=1) if words > 1000 words = 1000 else if words < 1 words = 1 end end ret = get_random_word for i in 2..words ret = ret + " " + get_random_word end return ret end def num_times_text_appears(browser, text) browser.get_html_source.scan(/#{text}/).size end def assert_tab_contains_question(browser, tab_name, question_text, html_source=nil) html_source = browser.get_html_source if html_source.nil? question_position = html_source.index(question_text) id_start_position = html_source.rindex(INVESTIGATOR_QUESTION_ID_PREFIX, question_position) id_end_position = html_source.index("\"", id_start_position) -1 answer_input_element_id = html_source[id_start_position..id_end_position] tab_element_id = TAB_ELEMENT_IDS_BY_NAME[tab_name] assert_contains(browser, tab_element_id, answer_input_element_id) end def get_record_number(browser) html_source = browser.get_html_source text_position = html_source.index("Record number</label>") record_number_start_position = html_source.index(Time.now.year.to_s, text_position) record_number_end_position = html_source.index("</span>", record_number_start_position) -1 html_source[record_number_start_position..record_number_end_position] end def get_full_cmr_hash() @cmr_fields = { # Patient fields "morbidity_event_active_patient__person_last_name" => get_unique_name(1), "morbidity_event_active_patient__person_first_name" => get_unique_name(1), "morbidity_event_active_patient__person_middle_name" => get_unique_name(1), "morbidity_event_active_patient__person_birth_date" => "1/1/1974", "morbidity_event_active_patient__person_approximate_age_no_birthday" => "22", "morbidity_event_active_patient__person_date_of_death" => "1/1/1974", "morbidity_event_active_patient__person_birth_gender_id" => "Female", "morbidity_event_active_patient__person_ethnicity_id" => "Not Hispanic or Latino", "morbidity_event_active_patient__person_primary_language_id" => "Hmong", "morbidity_event_active_patient__address_street_number" => "123", "morbidity_event_active_patient__address_street_name" => get_unique_name(1), "morbidity_event_active_patient__address_unit_number" => "2", "morbidity_event_active_patient__address_city" => get_unique_name(1), "morbidity_event_active_patient__address_postal_code" => "84601", "morbidity_event_active_patient__address_county_id" => "Beaver", "morbidity_event_active_patient__address_state_id" => "Utah", "morbidity_event_active_patient__new_telephone_attributes__entity_location_type_id" => 'Work', "morbidity_event_active_patient__new_telephone_attributes__area_code" => "801", "morbidity_event_active_patient__new_telephone_attributes__phone_number" => "555-7894", "morbidity_event_active_patient__new_telephone_attributes__extension" => "147", "morbidity_event_active_patient__race_ids" => "Asian", #Disease fields "morbidity_event_disease_disease_onset_date" => "1/1/1974", "morbidity_event_disease_date_diagnosed" => "1/1/1974", "morbidity_event_disease_disease_id" => "Amebiasis", #Status fields "morbidity_event_disease_died_id" => "Yes", "morbidity_event_imported_from_id" => "Utah", #Hospital fields "morbidity_event_new_hospital_attributes__admission_date" => "1/1/1974", "morbidity_event_new_hospital_attributes__discharge_date" => "1/1/1974", "morbidity_event_new_hospital_attributes__secondary_entity_id" => "Ashley Regional Medical Center", "morbidity_event_disease_hospitalized_id" => "Yes", #Diagnosis field "morbidity_event_new_diagnostic_attributes__secondary_entity_id" => "Alta View Hospital", #Treatment fields "morbidity_event_active_patient__new_treatment_attributes__treatment_given_yn_id" => "Yes", "morbidity_event_active_patient__new_treatment_attributes__treatment" => NedssHelper.get_unique_name(1), #Clinician fields "morbidity_event_new_clinician_attributes__last_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_clinician_attributes__first_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_clinician_attributes__middle_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_clinician_attributes__area_code" => "501", "morbidity_event_new_clinician_attributes__phone_number" => "555-1645", "morbidity_event_new_clinician_attributes__extension" => "1645", #lab result fields "event[new_lab_attributes][][name]" => NedssHelper.get_unique_name(2), "morbidity_event_new_lab_attributes__specimen_source_id" => "Blood", "morbidity_event_new_lab_attributes__specimen_sent_to_state_id" => "Yes", "morbidity_event_new_lab_attributes__lab_result_text" => NedssHelper.get_unique_name(1), "morbidity_event_new_lab_attributes__collection_date" => "1/1/1974", "morbidity_event_new_lab_attributes__lab_test_date" => "1/1/1974", #contact fields "morbidity_event_new_contact_attributes__last_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_contact_attributes__first_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_contact_attributes__area_code" => "840", "morbidity_event_new_contact_attributes__phone_number" => "555-7457", "morbidity_event_new_contact_attributes__extension" => "4557" } return(@cmr_fields) end def get_question_investigate_div_id(browser, question_text) element_id_prefix = "question_investigate_" html_source = browser.get_html_source name_position = html_source.index(question_text) id_start_position = html_source.rindex("#{element_id_prefix}", name_position) + element_id_prefix.length id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end def case_checkboxes(browser) browser.get_all_fields().select do |id| %w(Unknown Confirmed Probable Suspect Not_a_Case Chronic_Carrier Discarded).include? id end end def enter_note(browser, note_text, options={:is_admin => false}) browser.type('css=textarea[id$=_note]', note_text) browser.click('css=input[id$=_note_type]') if options[:is_admin] end def note_count(browser, note_type="All") if note_type == "All" return browser.get_eval(%Q{selenium.browserbot.getCurrentWindow().$$('span.note-type').length}).to_i else browser.get_eval("selenium.browserbot.getCurrentWindow().$$('span.note-type').findAll(function(n) { return n.innerHTML.indexOf('#{note_type}') > 0; }).length").to_i end end def add_task(browser, task_attributes={}) browser.click("link=Add Task") browser.wait_for_page_to_load($load_time) browser.type("task_name", task_attributes[:task_name]) browser.type("task_notes", task_attributes[:task_notes]) if task_attributes[:task_notes] browser.select("task_category_id", task_attributes[:task_category]) if task_attributes[:task_category] browser.select("task_priority", task_attributes[:task_priority]) if task_attributes[:task_priority] browser.type("task_due_date", task_attributes[:task_due_date]) if task_attributes[:task_due_date] browser.type("task_until_date", task_attributes[:task_until_date]) if task_attributes[:task_until_date] browser.select("task_repeating_interval", task_attributes[:task_repeating_interval]) if task_attributes[:task_repeating_interval] browser.select("task_user_id", task_attributes[:task_user_id]) if task_attributes[:task_user_id] browser.click("task_submit") browser.wait_for_page_to_load($load_time) return browser.is_text_present("Task was successfully created.") end # Debt: Dups add_task def edit_task(browser, task_attributes={}) browser.click("link=Edit task") browser.wait_for_page_to_load($load_time) browser.type("task_name", task_attributes[:task_name]) browser.type("task_notes", task_attributes[:task_notes]) if task_attributes[:task_notes] browser.select("task_category_id", task_attributes[:task_category]) if task_attributes[:task_category] browser.select("task_status", task_attributes[:task_status]) if task_attributes[:task_status] browser.select("task_priority", task_attributes[:task_priority]) if task_attributes[:task_priority] browser.type("task_due_date", task_attributes[:task_due_date]) if task_attributes[:task_due_date] browser.select("task_user_id", task_attributes[:task_user_id]) if task_attributes[:task_user_id] browser.click("task_submit") browser.wait_for_page_to_load($load_time) return browser.is_text_present("Task was successfully updated.") end def update_task_status(browser, status_label) browser.select('css=select[id^=task-status-change-]', "label=#{status_label}") sleep 3 # Debt: Feed off something else so this sleep can get dumped end def change_task_filter(browser, options = {}) browser.click("link=Change filter") sleep 3 browser.type("look_ahead", options[:look_ahead]) unless options[:look_ahead].nil? browser.type("look_back", options[:look_back]) unless options[:look_back].nil? browser.click("update_tasks_filter") browser.wait_for_page_to_load($load_time) end def is_text_present_in(browser, html_id, text) result = browser.get_eval("selenium.browserbot.getCurrentWindow().$('#{html_id}').innerHTML.indexOf('#{text}') > 0") (result == "false") ? false : true end def date_for_calendar_select(date) date.strftime("%B %d, %Y") end def change_cmr_view(browser, attributes) @browser.click "link=Change View" attributes[:diseases].each do |disease| @browser.add_selection("//div[@id='change_view']//select[@id='diseases_selector']", "label=#{disease}") end if attributes[:diseases] @browser.click "change_view_btn" @browser.wait_for_page_to_load($load_time) # Fill in the rest... end # # Demographic Tab # def add_demographic_info(browser, attributes) click_core_tab(browser, DEMOGRAPHICS) browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_last_name')]", attributes[:last_name]) if attributes[:last_name] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_first_name')]", attributes[:first_name]) if attributes[:first_name] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_middle_name')]", attributes[:middle_name]) if attributes[:middle_name] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_street_number')]", attributes[:street_number]) if attributes[:street_number] # //div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_street_name')] # //div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_unit_number')] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_city')]", attributes[:city]) if attributes[:city] browser.select("//div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_county_id')]", "label=#{attributes[:county]}") if attributes[:county] browser.select("//div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_state_id')]", "label=#{attributes[:state]}") if attributes[:state] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_postal_code')]", attributes[:postal_code]) if attributes[:postal_code] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_approximate_age_no_birthday')]", attributes[:approximate_age_no_birthday]) if attributes[:approximate_age_no_birthday] browser.select("//div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_birth_gender_id')]", "label=#{attributes[:birth_gender]}") if attributes[:birth_gender] # //div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_ethnicity_id')] # Fill in the rest... end # # Clinical Tab # def add_clinical_info(browser, attributes) click_core_tab(browser, CLINICAL) browser.select("//div[@id='clinical_tab']//select[contains(@id, '_disease_id')]", "label=#{attributes[:disease]}") if attributes[:disease] browser.select("//div[@id='clinical_tab']//select[contains(@id, '_died_id')]", "label=#{attributes[:died]}") if attributes[:died] browser.select("//div[@id='clinical_tab']//select[contains(@id, '_pregnant_id')]", "label=#{attributes[:pregnant]}") if attributes[:pregnant] # Fill in the rest... end def add_diagnostic_facility(browser, attributes) click_core_tab(browser, CLINICAL) browser.click "link=Add a diagnostic facility" sleep(1) browser.type("//div[@id='diagnostic_facilities']//div[@class='diagnostic']//input[contains(@id, '_place_entity_attributes_place_attributes_name')]", attributes[:name]) browser.click("//div[@id='diagnostic_facilities']//div[@class='diagnostic']//input[contains(@id, '_place_attributes_place_type_#{attributes[:place_type]}')]") if attributes[:place_type] end def remove_diagnostic_facility(browser, index=1) browser.click("//div[@id='diagnostic_facilities']//div[@class='existing_diagnostic'][#{index}]//input[contains(@id, '_delete')]") end def add_hospital(browser, attributes, index = 1) click_core_tab(browser, CLINICAL) browser.click "link=Add a Hospitalization Facility" unless index == 1 sleep(1) browser.select("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//select[contains(@id, '_secondary_entity_id')]", "label=#{attributes[:name]}") browser.type("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_admission_date')]", attributes[:admission_date]) if attributes[:admission_date] browser.type("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_discharge_date')]", attributes[:discharge_date]) if attributes[:discharge_date] browser.type("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_medical_record_number')]", attributes[:medical_record_number]) if attributes[:medical_record_number] end def remove_hospital(browser, index = 1) browser.click("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_delete')]") end def add_treatment(browser, attributes, index = 1) click_core_tab(browser, CLINICAL) browser.click("link=Add a Treatment") unless index == 1 sleep(1) browser.select("//div[@class='treatment'][#{index}]//select", attributes[:treatment_given]) browser.type("//div[@class='treatment'][#{index}]//input[contains(@name, '[treatment]')]", attributes[:treatment]) browser.type("//div[@class='treatment'][#{index}]//input[contains(@name, 'treatment_date')]", attributes[:treatment_date]) end def add_clinician(browser, attributes, index = 1) click_core_tab(browser, CLINICAL) browser.click("link=Add a Clinician") unless index == 1 sleep(1) browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_last_name')]", attributes[:last_name]) browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_first_name')]", attributes[:first_name]) if attributes[:first_name] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_middle_name')]", attributes[:middle_name]) if attributes[:middle_name] browser.select("//div[@id='clinicians']//div[@class='clinician'][#{index}]//select[contains(@id, '_entity_location_type_id')]", "label=#{attributes[:phone_type]}") if attributes[:phone_type] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_area_code')]", attributes[:area_code]) if attributes[:area_code] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_phone_number')]", attributes[:phone_number]) if attributes[:phone_number] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_extension')]", attributes[:extension]) if attributes[:extension] end def remove_clinician(browser, index=1) browser.click("//div[@id='clinicians']//div[@class='existing_clinician'][#{index}]//input[contains(@id, '_delete')]") end # # Lab Tab # def add_lab_result(browser, attributes, lab_index = 1, result_index = 1) click_core_tab(browser, LABORATORY) browser.click("link=Add a new lab result") unless lab_index == 1 sleep(1) browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//input[contains(@id, '_place_entity_attributes_place_attributes_name')]", attributes[:lab_name]) if attributes[:lab_name] browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//input[contains(@id, '_lab_result_text')]", attributes[:lab_result_text]) if attributes[:lab_result_text] browser.select("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//select[contains(@id, '_interpretation_id')]", "label=#{attributes[:lab_interpretation]}") if attributes[:lab_interpretation] browser.select("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//select[contains(@id, '_specimen_source_id')]", "label=#{attributes[:lab_specimen_source]}") if attributes[:lab_specimen_source] browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//input[contains(@id, '_collection_date')]", attributes[:lab_collection_date]) if attributes[:lab_collection_date] browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//input[contains(@id, '_lab_test_date')]", attributes[:lab_test_date]) if attributes[:lab_test_date] browser.select("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//select[contains(@id, '_specimen_sent_to_state_id')]", "label=#{attributes[:sent_to_state]}") if attributes[:sent_to_state] end # # Encounters Tab # def add_encounter(browser, attributes, index = 1) click_core_tab(browser, ENCOUNTERS) sleep(1) browser.select("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//select[contains(@id, '_user_id')]", "label=#{attributes[:user]}") if attributes[:user] browser.type("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//input[contains(@id, '_encounter_date')]", attributes[:encounter_date]) if attributes[:encounter_date] browser.type("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//textarea[contains(@id, '_description')]", attributes[:description]) if attributes[:description] browser.select("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//select[contains(@id, '_location_type')]", "label=#{attributes[:location_type]}") if attributes[:location_type] end # # Reporting Tab # def add_reporting_info(browser, attributes) click_core_tab(browser, REPORTING) sleep(1) browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_name')]", attributes[:name]) if attributes[:name] browser.click("//div[@id='reporting_agencies']//input[contains(@id, '_place_attributes_place_type_#{attributes[:place_type]}')]") if attributes[:place_type] browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_area_code')]", attributes[:area_code]) if attributes[:area_code] browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_phone_number')]", attributes[:phone_number]) if attributes[:phone_number] browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_extension')]", attributes[:extension]) if attributes[:extension] browser.type("//div[@id='reporter']//input[contains(@id, '_last_name')]", attributes[:last_name]) if attributes[:last_name] browser.type("//div[@id='reporter']//input[contains(@id, '_last_name')]", attributes[:first_name]) if attributes[:first_name] browser.type("//div[@id='reporter']//input[contains(@id, '_area_code')]", attributes[:area_code]) if attributes[:area_code] browser.type("//div[@id='reporter']//input[contains(@id, '_phone_number')]", attributes[:phone_number]) if attributes[:phone_number] browser.type("//div[@id='reporter']//input[contains(@id, '_extension')]", attributes[:extension]) if attributes[:extension] browser.type("//div[@id='reported_dates']//input[contains(@id, '_clinician_date')]", attributes[:clinician_date]) if attributes[:clinician_date] browser.type("//div[@id='reported_dates']//input[contains(@id, '_PH_date')]", attributes[:PH_date]) if attributes[:PH_date] end # # Admin Tab # def add_admin_info(browser, attributes) click_core_tab(browser, ADMIN) sleep(1) browser.select("//div[@id='administrative_tab']//select[contains(@id, '_event_status')]", "label=#{attributes[:event_status]}") if attributes[:event_status] browser.select("//div[@id='administrative_tab']//select[contains(@id, '_state_case_status_id')]", "label=#{attributes[:state_case_status]}") if attributes[:state_case_status] # Fill in the rest... end private def assert_contains(browser, container_element, element) begin result = browser.get_eval("window.document.getElementById(\"#{element}\").descendantOf(\"#{container_element}\")") rescue result = false end return (result == "true") ? true : false end def add_question_to_element(browser, element_name, element_id_prefix, question_attributes, expect_error=false) element_id = get_form_element_id(browser, element_name, element_id_prefix) add_question_attributes(browser, element_id, question_attributes, expect_error) end def add_question_to_core_field_config(browser, element_name, element_id_prefix, question_attributes) element_id = get_form_element_id_for_core_field(browser, element_name, element_id_prefix) add_question_attributes(browser, element_id, question_attributes) end def add_question_attributes(browser, element_id, question_attributes, expect_error=false) browser.click("add-question-#{element_id}") wait_for_element_present("new-question-form", browser) fill_in_question_attributes(browser, question_attributes) browser.click "//input[contains(@id, 'create_question_submit')]" unless expect_error wait_for_element_not_present("new-question-form", browser) else sleep 1 end if browser.is_text_present(question_attributes[:question_text]) return true else return false end end def fill_in_question_attributes(browser, question_attributes, options={ :mode => :add }) browser.type("question_element_question_attributes_question_text", question_attributes[:question_text]) if question_attributes.include? :question_text browser.select("question_element_question_attributes_data_type", "label=#{question_attributes[:data_type]}") unless options[:mode] == :edit browser.select("question_element_export_column_id", "label=#{question_attributes[:export_column_id]}") if question_attributes.include? :export_column_id browser.select("question_element_question_attributes_style", "label=#{question_attributes[:style]}") if question_attributes.include? :style browser.click("question_element_is_active_#{question_attributes[:is_active].to_s}") if question_attributes.include? :is_active browser.type("question_element_question_attributes_short_name", question_attributes[:short_name]) if question_attributes.include? :short_name browser.type("question_element_question_attributes_help_text", question_attributes[:help_text]) if question_attributes[:help_text] end def add_follow_up_to_element(browser, element_name, element_id_prefix, condition, core_label=nil) element_id = get_form_element_id(browser, element_name, element_id_prefix) browser.click("add-follow-up-#{element_id}") wait_for_element_present("new-follow-up-form", browser) if core_label.nil? browser.type "follow_up_element_condition", condition else browser.type "model_auto_completer_tf", condition end browser.select "follow_up_element_core_path", "label=#{core_label}" unless core_label.nil? browser.click "//input[contains(@id, 'create_follow_up_submit')]" wait_for_element_not_present("new-follow-up-form", browser) end def add_follow_up_to_core_field_config(browser, element_name, element_id_prefix, condition, core_label=nil) element_id = get_form_element_id_for_core_field(browser, element_name, element_id_prefix) browser.click("add-follow-up-#{element_id}") wait_for_element_present("new-follow-up-form", browser) if core_label.nil? browser.type "follow_up_element_condition", condition else browser.type "model_auto_completer_tf", condition end browser.select "follow_up_element_core_path", "label=#{core_label}" unless core_label.nil? browser.click "//input[contains(@id, 'create_follow_up_submit')]" wait_for_element_not_present("new-follow-up-form", browser) end # Goes in reverse from the name provided, looking for the magic string of # element_prefix_<id> # # The retry accounts for the fact that you may run into paths that just so # happen to contain the element prefix string. def get_form_element_id(browser, name, element_id_prefix) retry_count = 0 element_prefix_length = element_id_prefix.size html_source = browser.get_html_source # Start from form_children to avoid finding something up in the top portion of the page name_position = html_source.index(name, html_source.index("form_children")) begin id_start_position = html_source.rindex("#{element_id_prefix}", name_position) + element_prefix_length raise if html_source[id_start_position..id_start_position+1].to_i == 0 rescue retry_count += 1 name_position = id_start_position - (element_prefix_length+1) retry if retry_count < 5 end id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end def get_library_element_id(browser, name, element_id_prefix) retry_count = 0 element_prefix_length = element_id_prefix.size html_source = browser.get_html_source # Start from form_children to avoid finding something up in the top portion of the page name_position = html_source.index(name, html_source.index("Library Administration")) begin id_start_position = html_source.rindex("#{element_id_prefix}", name_position) + element_prefix_length raise if html_source[id_start_position..id_start_position+1].to_i == 0 rescue retry_count += 1 id_start_position.nil? ? name_position = 1 : name_position = id_start_position - (element_prefix_length+1) retry if retry_count < 5 end id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end # Same as get_form_element_id except it doesn't do a reverse index looking for the start position. # Core field configs are different in that the name of the main core field config preceeds the two # containers for before and after configs. def get_form_element_id_for_core_field(browser, name, element_id_prefix) element_prefix_length = element_id_prefix.size html_source = browser.get_html_source name_position = html_source.index(name) id_start_position = html_source.index("#{element_id_prefix}", name_position) + element_prefix_length id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end def get_investigator_answer_id(browser, question_text, html_source=nil) html_source = browser.get_html_source if html_source.nil? question_position = html_source.index(question_text) id_start_position = html_source.index(INVESTIGATOR_ANSWER_ID_PREFIX, question_position) + 20 id_end_position = html_source.index("\"", id_start_position) -1 # This is a kluge that will go hunting for quot; if the id looks too big. Needed for reporting agency at least. id_end_position = html_source.index("quot;", id_start_position)-3 if (id_end_position-id_start_position > 10) html_source[id_start_position..id_end_position] end # This only works for investigator questions on contact events def get_investigator_click_answer_id(browser, question_text) html_source = browser.get_html_source question_position = html_source.index(question_text) id_start_position = html_source.index("investigator_answer_", question_position) + 20 id_end_position = html_source.index("_", id_start_position) -1 html_source[id_start_position..id_end_position] end def get_random_word wordlist = ["Lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing","elit","Duis","sodales","dignissim","enim","Nunc","rhoncus","quam","ut","quam","Quisque","vitae","urna","Duis","nec","sapien","Proin","mollis","congue","mauris","Fusce","lobortis","tristique","elit","Phasellus","aliquam","dui","id","placerat","hendrerit","dolor","augue","posuere","tellus","at","ultricies","libero","leo","vel","leo","Nulla","purus","Ut","lacus","felis","tempus","at","egestas","nec","cursus","nec","magna","Ut","fringilla","aliquet","arcu","Vestibulum","ante","ipsum","primis","in","faucibus","orci","luctus","et","ultrices","posuere","cubilia","Curae","Etiam","vestibulum","urna","sit","amet","sem","Nunc","ac","ipsum","In","consectetuer","quam","nec","lectus","Maecenas","magna","Nulla","ut","mi","eu","elit","accumsan","gravida","Praesent","ornare","urna","a","lectus","dapibus","luctus","Integer","interdum","bibendum","neque","Nulla","id","dui","Aenean","tincidunt","dictum","tortor","Proin","sagittis","accumsan","nulla","Etiam","consectetuer","Etiam","eget","nibh","ut","sem","mollis","luctus","Etiam","mi","eros","blandit","in","suscipit","ut","vestibulum","et","velit","Fusce","laoreet","nulla","nec","neque","Nam","non","nulla","ut","justo","ullamcorper","egestas","In","porta","ipsum","nec","neque","Cras","non","metus","id","massa","ultrices","rhoncus","Donec","mattis","odio","sagittis","nunc","Vivamus","vehicula","justo","vitae","tincidunt","posuere","risus","pede","lacinia","dolor","quis","placerat","justo","arcu","ut","tortor","Aliquam","malesuada","lectus","id","condimentum","sollicitudin","arcu","mauris","adipiscing","turpis","a","sollicitudin","erat","metus","vel","magna","Proin","scelerisque","neque","id","urna","lobortis","vulputate","In","porta","pulvinar","urna","Cras","id","nulla","In","dapibus","vestibulum","pede","In","ut","velit","Aliquam","in","turpis","vitae","nunc","hendrerit","ullamcorper","Aliquam","rutrum","erat","sit","amet","velit","Nullam","pharetra","neque","id","pede","Phasellus","suscipit","ornare","mi","Ut","malesuada","consequat","ipsum","Suspendisse","suscipit","aliquam","nisl","Suspendisse","iaculis","magna","eu","ligula","Sed","porttitor","eros","id","euismod","auctor","dolor","lectus","convallis","justo","ut","elementum","magna","magna","congue","nulla","Pellentesque","eget","ipsum","Pellentesque","tempus","leo","id","magna","Cras","mi","dui","pellentesque","in","pellentesque","nec","blandit","nec","odio","Pellentesque","eget","risus","In","venenatis","metus","id","magna","Etiam","blandit","Integer","a","massa","vitae","lacus","dignissim","auctor","Mauris","libero","metus","aliquet","in","rhoncus","sed","volutpat","quis","libero","Nam","urna"] begin result = wordlist[rand(wordlist.size)] raise if result.nil? rescue Exception => ex result = wordlist[rand(wordlist.size)] end result end def get_resource_id(browser, name) html_source = browser.get_html_source pos1 = html_source.index(name) pos2 = html_source.index(/\d\/edit['"]/, pos1) pos3 = html_source.rindex("/", pos2)+1 id = html_source[pos3..pos2] return id.to_i rescue => err return -1 end # using the form name, get the form id from the forms index page def get_form_id(browser, form_name) html_source = browser.get_html_source pos1 = html_source.index(form_name) pos2 = html_source.index('forms/builder/', pos1) + 14 pos3 = html_source.index('"', pos2) html_source[pos2...pos3] end def copy_form_and_open_in_form_builder(browser, form_name) browser.click("copy_form_#{get_form_id(browser, form_name)}") browser.wait_for_page_to_load($load_time) browser.is_text_present('Form was successfully copied.').should be_true browser.click('//input[@id="form_submit"]') browser.wait_for_page_to_load($load_time) browser.is_text_present('Form was successfully updated.').should be_true browser.is_text_present('Not Published').should be_true browser.click('link=Builder') browser.wait_for_page_to_load($load_time) true end def assert_tooltip_exists(browser, tool_tip_text) browser.is_element_present("//img[contains(@src, 'help.png')]").should be_true browser.get_html_source.include?(tool_tip_text).should be_true browser.is_visible("//span[contains(@id,'_help_text')]").should be_false browser.is_visible("//div[@id='WzTtDiV']").should be_false browser.mouse_over("//a[contains(@id,'_help_text')]") browser.mouse_move("//a[contains(@id,'_help_text')]") sleep(2) browser.is_visible("//div[@id='WzTtDiV']").should be_true browser.mouse_out("//a[contains(@id, '_help_text')]") sleep(2) browser.is_visible("//div[@id='WzTtDiV']").should be_false return true end def is_disease_active(browser, disease_name) html_source = browser.get_html_source start = html_source.index(disease_name) + disease_name.length html_source[start..start+100].index("Active").nil? ? false : true end def is_disease_inactive(browser, disease_name) html_source = browser.get_html_source start = html_source.index(disease_name) + disease_name.length html_source[start..start+100].index("Inactive").nil? ? false : true end def get_record_number(browser) source = browser.get_html_source label = '<label>Record number</label>' index_start = source.index(label) + label.length index_end = source.index('</span>', index_start) source[index_start...index_end].strip end end fixed deleting clinicians code for enhanced features # Copyright (C) 2007, 2008, 2009, 2010 The Collaborative Software Foundation # # This file is part of TriSano. # # TriSano is free software: you can redistribute it and/or modify it under the # terms of the GNU Affero General Public License as published by the # Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # TriSano is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with TriSano. If not, see http://www.gnu.org/licenses/agpl-3.0.txt. require 'yaml' module TrisanoHelper #Define constants for standard resources FORM = "forms" # Constants for the tab names DEMOGRAPHICS = "Demographics" CLINICAL = "Clinical" LABORATORY = "Laboratory" CONTACTS = "Contacts" ENCOUNTERS = "Encounters" EPI = "Epidemiological" REPORTING = "Reporting" INVESTIGATION = "Investigation" NOTES = "Notes" ADMIN = "Administrative" OUTBREAK = "Outbreak" # Tabs for place events PLACE = "Place" # Constants for element id prefixes VIEW_ID_PREFIX = "view_" CORE_VIEW_ID_PREFIX = "core_view_" CORE_FIELD_ID_PREFIX = "core_field_" BEFORE_CORE_FIELD_ID_PREFIX = "before_core_field_" AFTER_CORE_FIELD_ID_PREFIX = "after_core_field_" SECTION_ID_PREFIX = "section_" GROUP_ID_PREFIX = "group_" QUESTION_ID_PREFIX = "question_" FOLLOW_UP_ID_PREFIX = "follow_up_" VALUE_SET_ID_PREFIX = "value_set_" INVESTIGATOR_QUESTION_ID_PREFIX = "question_investigate_" INVESTIGATOR_ANSWER_ID_PREFIX = "investigator_answer_" TAB_ELEMENT_IDS_BY_NAME = { DEMOGRAPHICS => "demographic_tab", CLINICAL => "clinical_tab", LABORATORY => "lab_info_tab", CONTACTS => "contacts_tab", ENCOUNTERS => "encounters_tab", EPI => "epi_tab", REPORTING => "reporting_tab", NOTES => 'notes_tab', ADMIN => "administrative_tab", PLACE => "place_tab", OUTBREAK => "outbreak_tab" } def wait_for_element_present(name, browser=nil) browser = @browser.nil? ? browser : @browser !60.times{ break if (browser.is_element_present(name) rescue false); sleep 1 } end def wait_for_element_not_present(name, browser=nil) browser = @browser.nil? ? browser : @browser !60.times{ break unless (browser.is_element_present(name) rescue true); sleep 1 } end # Use set_fields after you navigate to any location by passing in a hash of # fields and values and this method will set them all. It will work for # updating existing items or creating new ones. cmr_helper_example shows how # to create a complete CMR with the helper. The hash created in this example # could be helpful for other tests. Note that this method does not submit # for you. def set_fields(browser, value_hash) fields = browser.get_all_fields value_hash.each_pair do |key, value| if fields.index(key) != nil browser.type(key, value) else begin browser.select(key,"label=" + value) rescue StandardError => err #TODO - Make this work for auto-complete fields by using the name instead of the ID in a type command #The problem with using the name is that it won't show up as a field in get_all_fields, and it won't be selectable #I'm trying to do something in the rescue block to detect the error from trying to select it. # if err == "Specified element is not a Select (has no options)" #This is usually because the element is the name of a auto-complete field # browser.type(key, value) # else puts("WARNING: Field " + key + " not found. Value not set.") # end end end end end # Use get_full_cmr to create a cmr with every field filled in (excludes repeating elements) # It uses random words for text fields def create_cmr_from_hash(browser, cmr_hash) click_nav_new_cmr(browser) browser.wait_for_page_to_load($load_time) set_fields(browser,cmr_hash) browser.click('morbidity_event_submit') browser.wait_for_page_to_load($load_time) return save_cmr(browser) end # Use get_full_cmr to create a cmr with only the last name filled in # It uses random words for the last name field def get_nil_cmr() end def current_user(browser = @browser) browser.get_selected_label("user_id") end #Use click_core_tab to change tabs in CMR views def click_core_tab(browser, tab_name) case tab_name when DEMOGRAPHICS browser.click('//li[1]/a/em') when CLINICAL browser.click('//li[2]/a/em') when LABORATORY browser.click('//li[3]/a/em') when CONTACTS browser.click('//li[4]/a/em') when ENCOUNTERS browser.click('//li[5]/a/em') when EPI browser.click('//li[6]/a/em') when REPORTING browser.click('//li[7]/a/em') when INVESTIGATION browser.click('//li[8]/a/em') when NOTES browser.click('//li[9]/a/em') when ADMIN browser.click('//li[10]/a/em') when PLACE browser.click('//li[1]/a/em') else puts("TAB NOT FOUND: " + tab_name) end end def get_random_disease() wordlist = YAML.load_file(File.join(RAILS_ROOT, 'db', 'defaults', 'diseases.yml')).collect { |k,v| v[:diseases] }.flatten.collect{ |d| d[:disease_name] }.uniq wordlist[rand(wordlist.size)] end def get_random_jurisdiction() wordlist = ["Out of State","Weber-Morgan Health Department","Wasatch County Health Department","Utah State","Utah County Health Department","TriCounty Health Department","Tooele County Health Department","Summit County Public Health Department","Southwest Utah Public Health Department","Southeastern Utah District Health Department","Salt Lake Valley Health Department","Davis County Health Department","Central Utah Public Health Department","Bear River Health Department","Unassigned"] wordlist[rand(wordlist.size)] end def get_random_jurisdiction_by_short_name() wordlist = ["Unassigned", "Bear River", "Central Utah", "Davis County", "Salt Lake Valley", "Southeastern Utah", "Southwest Utah", "Summit County", "Tooele County", "TriCounty", "Utah County", "Utah State", "Wasatch County", "Weber-Morgan", "Out of State"] wordlist[rand(wordlist.size)] end # # General navigation and controls # def click_logo(browser) browser.click 'logo' browser.wait_for_page_to_load($load_time) end def click_nav_new_cmr(browser) browser.open "/trisano/cmrs/new" browser.wait_for_page_to_load($load_time) return (browser.is_text_present("New Morbidity Event") and browser.is_text_present("New CMR") and browser.is_element_present("link=< Back to list") and browser.is_element_present("disable_tabs")) end def click_nav_cmrs(browser) browser.click 'link=EVENTS' browser.wait_for_page_to_load($load_time) return (browser.is_text_present("List Morbidity Events") and browser.is_element_present("link=EVENTS")) end def click_nav_search(browser) browser.click 'link=SEARCH' browser.wait_for_page_to_load($load_time) return browser.is_text_present("Event Search") end def click_nav_forms(browser) click_nav_admin(browser) browser.click 'link=Manage Forms' browser.wait_for_page_to_load($load_time) return (browser.is_text_present("Form Information") and browser.is_text_present("Diseases") and browser.is_text_present("Jurisdiction") and browser.is_text_present("Event Type") and browser.is_element_present("//input[@value='Upload']") and browser.is_element_present("//input[@id='form_import']") and browser.is_element_present("//input[@value='Create New Form']") ) end def click_nav_admin(browser) unless browser.is_element_present("link=ADMIN") @browser.open "/trisano/cmrs" @browser.wait_for_page_to_load($load_time) end browser.click 'link=ADMIN' browser.wait_for_page_to_load($load_time) return(browser.is_text_present("Admin Dashboard")) end def edit_cmr(browser) browser.click "link=Edit" browser.wait_for_page_to_load($load_time) return(browser.get_html_source.include?("Person Information") and browser.get_html_source.include?("Street number")) end def show_cmr(browser) browser.click "link=Show" browser.wait_for_page_to_load($load_time) return(browser.is_text_present("Person Information") and browser.is_text_present("Street number")) end def save_and_exit(browser) browser.click "save_and_exit_btn" browser.wait_for_page_to_load($load_time) browser.is_text_present("successfully").should be_true return true end def save_cmr(browser) save_and_exit(browser) end def save_and_continue(browser) browser.click "save_and_continue_btn" browser.wait_for_page_to_load($load_time) return(browser.is_text_present("successfully")) end # Clicks the print button and points the browser at the print window. # # To close the window after inspecting it, do something like the following: # @browser.close() # @browser.select_window 'null' def print_cmr(browser, note = 0) if note == 1 browser.click "link=With Notes" else browser.click "link=Print" end wait_for_element_present("//div[contains(@id, 'printing_controls')]") browser.click "print_all" browser.get_eval("selenium.browserbot.findElement(\"//form[contains(@action, 'print')]\").target='doit';") browser.open_window("", "doit"); browser.click "print_btn" browser.wait_for_pop_up("doit", $load_time) browser.select_window("doit") return(browser.get_html_source.include?('Confidential Case Report') && browser.get_html_source.include?('Printed')) end def navigate_to_people_search(browser) click_nav_search(browser) @browser.click('link=People Search') @browser.wait_for_page_to_load($load_time) return(browser.is_text_present("People Search") and browser.is_text_present("Name") and browser.is_text_present("Date of birth")) end def navigate_to_cmr_search(browser) click_nav_search(browser) return(browser.is_text_present("Name Criteria")) end #Use click_link_by_order to click the Nth element in a list of links of the same element type def click_link_by_order(browser, element_id_prefix, order) links = browser.get_all_links links.delete_if{|link| link.index(element_id_prefix) == nil} browser.click(links[order-1]) end def type_field_by_order(browser, element_id_prefix, order, value) fields = browser.get_all_fields fields.delete_if{|field| field.index(element_id_prefix) != 0} browser.type(fields[order], value) end # Use click_resource methods from any standard resource index page def click_resource_edit(browser, resource, name) id = get_resource_id(browser, name) if (id > 0) browser.click "//a[contains(@href, '/trisano/" + resource + "/" + id.to_s + "/edit')]" browser.wait_for_page_to_load "30000" return 0 else return -1 end end def click_resource_show(browser, resource, name) id = get_resource_id(browser, name) if id > 0 browser.click "//a[contains(@onclick, '/trisano/" + resource + "/" + id.to_s + "')]" browser.wait_for_page_to_load "30000" return 0 else return -1 end end def create_simplest_cmr(browser, last_name) click_nav_new_cmr(browser) browser.type "morbidity_event_interested_party_attributes_person_entity_attributes_person_attributes_last_name", last_name yield browser if block_given? return save_cmr(browser) end def create_basic_investigatable_cmr(browser, last_name, disease_label, jurisdiction_label=nil) click_nav_new_cmr(browser) browser.type "morbidity_event_interested_party_attributes_person_entity_attributes_person_attributes_last_name", last_name browser.type("morbidity_event_address_attributes_street_number", "22") browser.type("morbidity_event_address_attributes_street_name", "Happy St.") click_core_tab(browser, CLINICAL) browser.select "morbidity_event_disease_event_attributes_disease_id", "label=#{disease_label}" click_core_tab(browser, ADMIN) browser.select "morbidity_event_jurisdiction_attributes_secondary_entity_id", "label=#{jurisdiction_label}" if jurisdiction_label yield browser if block_given? return save_cmr(browser) end def answer_investigator_question(browser, question_text, answer, html_source=nil) answer_id = get_investigator_answer_id(browser, question_text, html_source) begin browser.type("#{INVESTIGATOR_ANSWER_ID_PREFIX}#{answer_id}", answer) == "OK" rescue return false end return true end def watch_for_core_field_spinner(core_field, browser=@browser, &proc) css_selector = %Q{img[id$="#{core_field}_spinner"]} watch_for_spinner(css_selector, browser, &proc) end def watch_for_answer_spinner(question_text, browser=@browser, &proc) answer_id = get_investigator_answer_id(browser, question_text) css_selector = "img[id=investigator_answer_#{answer_id}_spinner]" watch_for_spinner(css_selector, browser, &proc) end def watch_for_spinner(css_selector, browser=@browser, &proc) script = "selenium.browserbot.getCurrentWindow().$$('#{css_selector}').first().visible()" proc.call unless proc.nil? browser.wait_for_condition("#{script} == true", 3000).should == "OK" browser.wait_for_condition("#{script} == false", 3000).should == "OK" end def answer_multi_select_investigator_question(browser, question_text, answer) answer_id = get_investigator_answer_id(browser, question_text) begin browser.select("#{INVESTIGATOR_ANSWER_ID_PREFIX}#{answer_id}", answer) == "OK" rescue return false end return true end def answer_check_investigator_question(browser, question_text, answer) answer_id = get_investigator_click_answer_id(browser, question_text) begin browser.click("//input[contains(@id, 'investigator_answer_#{answer_id}') and @value='#{answer}']") == "OK" rescue return false end return true end def answer_radio_investigator_question(browser, question_text, answer) answer_id = get_investigator_click_answer_id(browser, question_text) begin browser.click("//input[contains(@id, 'investigator_answer_#{answer_id}') and @value='#{answer}']") == "OK" rescue return false end return true end def switch_user(browser, user_id) current_user = @browser.get_selected_label("user_id") if current_user != user_id browser.select("user_id", "label=#{user_id}") browser.wait_for_page_to_load return browser.is_text_present("#{user_id}:") end end #TODO def click_question(browser, question, action) case action when "edit" q_id = get_form_element_id(browser, question, QUESTION_ID_PREFIX) browser.click("edit-question-" + q_id.to_s) sleep 2 #TODO replacing the wait below until it works properly #wait_for_element_present("edit-question-form") when "delete" q_id = get_form_element_id(browser, question, QUESTION_ID_PREFIX) browser.click("delete-question-" + q_id.to_s) sleep 2 #TODO - should probably replace this with the element name, if there is one when "Add value set" #TODO else #TODO - this is an error end end #Get a unique name with the input number of words in it def get_unique_name(words=1) if words > 1000 words = 1000 else if words < 1 words = 1 end end ret = get_random_word for i in 2..words ret = ret + " " + get_random_word end return ret end def num_times_text_appears(browser, text) browser.get_html_source.scan(/#{text}/).size end def assert_tab_contains_question(browser, tab_name, question_text, html_source=nil) html_source = browser.get_html_source if html_source.nil? question_position = html_source.index(question_text) id_start_position = html_source.rindex(INVESTIGATOR_QUESTION_ID_PREFIX, question_position) id_end_position = html_source.index("\"", id_start_position) -1 answer_input_element_id = html_source[id_start_position..id_end_position] tab_element_id = TAB_ELEMENT_IDS_BY_NAME[tab_name] assert_contains(browser, tab_element_id, answer_input_element_id) end def get_record_number(browser) html_source = browser.get_html_source text_position = html_source.index("Record number</label>") record_number_start_position = html_source.index(Time.now.year.to_s, text_position) record_number_end_position = html_source.index("</span>", record_number_start_position) -1 html_source[record_number_start_position..record_number_end_position] end def get_full_cmr_hash() @cmr_fields = { # Patient fields "morbidity_event_active_patient__person_last_name" => get_unique_name(1), "morbidity_event_active_patient__person_first_name" => get_unique_name(1), "morbidity_event_active_patient__person_middle_name" => get_unique_name(1), "morbidity_event_active_patient__person_birth_date" => "1/1/1974", "morbidity_event_active_patient__person_approximate_age_no_birthday" => "22", "morbidity_event_active_patient__person_date_of_death" => "1/1/1974", "morbidity_event_active_patient__person_birth_gender_id" => "Female", "morbidity_event_active_patient__person_ethnicity_id" => "Not Hispanic or Latino", "morbidity_event_active_patient__person_primary_language_id" => "Hmong", "morbidity_event_active_patient__address_street_number" => "123", "morbidity_event_active_patient__address_street_name" => get_unique_name(1), "morbidity_event_active_patient__address_unit_number" => "2", "morbidity_event_active_patient__address_city" => get_unique_name(1), "morbidity_event_active_patient__address_postal_code" => "84601", "morbidity_event_active_patient__address_county_id" => "Beaver", "morbidity_event_active_patient__address_state_id" => "Utah", "morbidity_event_active_patient__new_telephone_attributes__entity_location_type_id" => 'Work', "morbidity_event_active_patient__new_telephone_attributes__area_code" => "801", "morbidity_event_active_patient__new_telephone_attributes__phone_number" => "555-7894", "morbidity_event_active_patient__new_telephone_attributes__extension" => "147", "morbidity_event_active_patient__race_ids" => "Asian", #Disease fields "morbidity_event_disease_disease_onset_date" => "1/1/1974", "morbidity_event_disease_date_diagnosed" => "1/1/1974", "morbidity_event_disease_disease_id" => "Amebiasis", #Status fields "morbidity_event_disease_died_id" => "Yes", "morbidity_event_imported_from_id" => "Utah", #Hospital fields "morbidity_event_new_hospital_attributes__admission_date" => "1/1/1974", "morbidity_event_new_hospital_attributes__discharge_date" => "1/1/1974", "morbidity_event_new_hospital_attributes__secondary_entity_id" => "Ashley Regional Medical Center", "morbidity_event_disease_hospitalized_id" => "Yes", #Diagnosis field "morbidity_event_new_diagnostic_attributes__secondary_entity_id" => "Alta View Hospital", #Treatment fields "morbidity_event_active_patient__new_treatment_attributes__treatment_given_yn_id" => "Yes", "morbidity_event_active_patient__new_treatment_attributes__treatment" => NedssHelper.get_unique_name(1), #Clinician fields "morbidity_event_new_clinician_attributes__last_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_clinician_attributes__first_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_clinician_attributes__middle_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_clinician_attributes__area_code" => "501", "morbidity_event_new_clinician_attributes__phone_number" => "555-1645", "morbidity_event_new_clinician_attributes__extension" => "1645", #lab result fields "event[new_lab_attributes][][name]" => NedssHelper.get_unique_name(2), "morbidity_event_new_lab_attributes__specimen_source_id" => "Blood", "morbidity_event_new_lab_attributes__specimen_sent_to_state_id" => "Yes", "morbidity_event_new_lab_attributes__lab_result_text" => NedssHelper.get_unique_name(1), "morbidity_event_new_lab_attributes__collection_date" => "1/1/1974", "morbidity_event_new_lab_attributes__lab_test_date" => "1/1/1974", #contact fields "morbidity_event_new_contact_attributes__last_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_contact_attributes__first_name" => NedssHelper.get_unique_name(1), "morbidity_event_new_contact_attributes__area_code" => "840", "morbidity_event_new_contact_attributes__phone_number" => "555-7457", "morbidity_event_new_contact_attributes__extension" => "4557" } return(@cmr_fields) end def get_question_investigate_div_id(browser, question_text) element_id_prefix = "question_investigate_" html_source = browser.get_html_source name_position = html_source.index(question_text) id_start_position = html_source.rindex("#{element_id_prefix}", name_position) + element_id_prefix.length id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end def case_checkboxes(browser) browser.get_all_fields().select do |id| %w(Unknown Confirmed Probable Suspect Not_a_Case Chronic_Carrier Discarded).include? id end end def enter_note(browser, note_text, options={:is_admin => false}) browser.type('css=textarea[id$=_note]', note_text) browser.click('css=input[id$=_note_type]') if options[:is_admin] end def note_count(browser, note_type="All") if note_type == "All" return browser.get_eval(%Q{selenium.browserbot.getCurrentWindow().$$('span.note-type').length}).to_i else browser.get_eval("selenium.browserbot.getCurrentWindow().$$('span.note-type').findAll(function(n) { return n.innerHTML.indexOf('#{note_type}') > 0; }).length").to_i end end def add_task(browser, task_attributes={}) browser.click("link=Add Task") browser.wait_for_page_to_load($load_time) browser.type("task_name", task_attributes[:task_name]) browser.type("task_notes", task_attributes[:task_notes]) if task_attributes[:task_notes] browser.select("task_category_id", task_attributes[:task_category]) if task_attributes[:task_category] browser.select("task_priority", task_attributes[:task_priority]) if task_attributes[:task_priority] browser.type("task_due_date", task_attributes[:task_due_date]) if task_attributes[:task_due_date] browser.type("task_until_date", task_attributes[:task_until_date]) if task_attributes[:task_until_date] browser.select("task_repeating_interval", task_attributes[:task_repeating_interval]) if task_attributes[:task_repeating_interval] browser.select("task_user_id", task_attributes[:task_user_id]) if task_attributes[:task_user_id] browser.click("task_submit") browser.wait_for_page_to_load($load_time) return browser.is_text_present("Task was successfully created.") end # Debt: Dups add_task def edit_task(browser, task_attributes={}) browser.click("link=Edit task") browser.wait_for_page_to_load($load_time) browser.type("task_name", task_attributes[:task_name]) browser.type("task_notes", task_attributes[:task_notes]) if task_attributes[:task_notes] browser.select("task_category_id", task_attributes[:task_category]) if task_attributes[:task_category] browser.select("task_status", task_attributes[:task_status]) if task_attributes[:task_status] browser.select("task_priority", task_attributes[:task_priority]) if task_attributes[:task_priority] browser.type("task_due_date", task_attributes[:task_due_date]) if task_attributes[:task_due_date] browser.select("task_user_id", task_attributes[:task_user_id]) if task_attributes[:task_user_id] browser.click("task_submit") browser.wait_for_page_to_load($load_time) return browser.is_text_present("Task was successfully updated.") end def update_task_status(browser, status_label) browser.select('css=select[id^=task-status-change-]', "label=#{status_label}") sleep 3 # Debt: Feed off something else so this sleep can get dumped end def change_task_filter(browser, options = {}) browser.click("link=Change filter") sleep 3 browser.type("look_ahead", options[:look_ahead]) unless options[:look_ahead].nil? browser.type("look_back", options[:look_back]) unless options[:look_back].nil? browser.click("update_tasks_filter") browser.wait_for_page_to_load($load_time) end def is_text_present_in(browser, html_id, text) result = browser.get_eval("selenium.browserbot.getCurrentWindow().$('#{html_id}').innerHTML.indexOf('#{text}') > 0") (result == "false") ? false : true end def date_for_calendar_select(date) date.strftime("%B %d, %Y") end def change_cmr_view(browser, attributes) @browser.click "link=Change View" attributes[:diseases].each do |disease| @browser.add_selection("//div[@id='change_view']//select[@id='diseases_selector']", "label=#{disease}") end if attributes[:diseases] @browser.click "change_view_btn" @browser.wait_for_page_to_load($load_time) # Fill in the rest... end # # Demographic Tab # def add_demographic_info(browser, attributes) click_core_tab(browser, DEMOGRAPHICS) browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_last_name')]", attributes[:last_name]) if attributes[:last_name] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_first_name')]", attributes[:first_name]) if attributes[:first_name] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_middle_name')]", attributes[:middle_name]) if attributes[:middle_name] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_street_number')]", attributes[:street_number]) if attributes[:street_number] # //div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_street_name')] # //div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_unit_number')] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_city')]", attributes[:city]) if attributes[:city] browser.select("//div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_county_id')]", "label=#{attributes[:county]}") if attributes[:county] browser.select("//div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_state_id')]", "label=#{attributes[:state]}") if attributes[:state] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_postal_code')]", attributes[:postal_code]) if attributes[:postal_code] browser.type("//div[@id='demographic_tab']//div[@id='person_form']//input[contains(@id, '_approximate_age_no_birthday')]", attributes[:approximate_age_no_birthday]) if attributes[:approximate_age_no_birthday] browser.select("//div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_birth_gender_id')]", "label=#{attributes[:birth_gender]}") if attributes[:birth_gender] # //div[@id='demographic_tab']//div[@id='person_form']//select[contains(@id, '_ethnicity_id')] # Fill in the rest... end # # Clinical Tab # def add_clinical_info(browser, attributes) click_core_tab(browser, CLINICAL) browser.select("//div[@id='clinical_tab']//select[contains(@id, '_disease_id')]", "label=#{attributes[:disease]}") if attributes[:disease] browser.select("//div[@id='clinical_tab']//select[contains(@id, '_died_id')]", "label=#{attributes[:died]}") if attributes[:died] browser.select("//div[@id='clinical_tab']//select[contains(@id, '_pregnant_id')]", "label=#{attributes[:pregnant]}") if attributes[:pregnant] # Fill in the rest... end def add_diagnostic_facility(browser, attributes) click_core_tab(browser, CLINICAL) browser.click "link=Add a diagnostic facility" sleep(1) browser.type("//div[@id='diagnostic_facilities']//div[@class='diagnostic']//input[contains(@id, '_place_entity_attributes_place_attributes_name')]", attributes[:name]) browser.click("//div[@id='diagnostic_facilities']//div[@class='diagnostic']//input[contains(@id, '_place_attributes_place_type_#{attributes[:place_type]}')]") if attributes[:place_type] end def remove_diagnostic_facility(browser, index=1) browser.click("//div[@id='diagnostic_facilities']//div[@class='existing_diagnostic'][#{index}]//input[contains(@id, '_delete')]") end def add_hospital(browser, attributes, index = 1) click_core_tab(browser, CLINICAL) browser.click "link=Add a Hospitalization Facility" unless index == 1 sleep(1) browser.select("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//select[contains(@id, '_secondary_entity_id')]", "label=#{attributes[:name]}") browser.type("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_admission_date')]", attributes[:admission_date]) if attributes[:admission_date] browser.type("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_discharge_date')]", attributes[:discharge_date]) if attributes[:discharge_date] browser.type("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_medical_record_number')]", attributes[:medical_record_number]) if attributes[:medical_record_number] end def remove_hospital(browser, index = 1) browser.click("//div[@id='hospitalization_facilities']//div[@class='hospital'][#{index}]//input[contains(@id, '_delete')]") end def add_treatment(browser, attributes, index = 1) click_core_tab(browser, CLINICAL) browser.click("link=Add a Treatment") unless index == 1 sleep(1) browser.select("//div[@class='treatment'][#{index}]//select", attributes[:treatment_given]) browser.type("//div[@class='treatment'][#{index}]//input[contains(@name, '[treatment]')]", attributes[:treatment]) browser.type("//div[@class='treatment'][#{index}]//input[contains(@name, 'treatment_date')]", attributes[:treatment_date]) end def add_clinician(browser, attributes, index = 1) click_core_tab(browser, CLINICAL) browser.click("link=Add a Clinician") unless index == 1 sleep(1) browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_last_name')]", attributes[:last_name]) browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_first_name')]", attributes[:first_name]) if attributes[:first_name] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_middle_name')]", attributes[:middle_name]) if attributes[:middle_name] browser.select("//div[@id='clinicians']//div[@class='clinician'][#{index}]//select[contains(@id, '_entity_location_type_id')]", "label=#{attributes[:phone_type]}") if attributes[:phone_type] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_area_code')]", attributes[:area_code]) if attributes[:area_code] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_phone_number')]", attributes[:phone_number]) if attributes[:phone_number] browser.type("//div[@id='clinicians']//div[@class='clinician'][#{index}]//input[contains(@id, '_extension')]", attributes[:extension]) if attributes[:extension] end def remove_clinician(browser, index=1) browser.click("//div[@id='clinicians']//div[@class='existing_clinician'][#{index}]//input[contains(@id, '_destroy')]") end # # Lab Tab # def add_lab_result(browser, attributes, lab_index = 1, result_index = 1) click_core_tab(browser, LABORATORY) browser.click("link=Add a new lab result") unless lab_index == 1 sleep(1) browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//input[contains(@id, '_place_entity_attributes_place_attributes_name')]", attributes[:lab_name]) if attributes[:lab_name] browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//input[contains(@id, '_lab_result_text')]", attributes[:lab_result_text]) if attributes[:lab_result_text] browser.select("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//select[contains(@id, '_interpretation_id')]", "label=#{attributes[:lab_interpretation]}") if attributes[:lab_interpretation] browser.select("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//select[contains(@id, '_specimen_source_id')]", "label=#{attributes[:lab_specimen_source]}") if attributes[:lab_specimen_source] browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//input[contains(@id, '_collection_date')]", attributes[:lab_collection_date]) if attributes[:lab_collection_date] browser.type("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//input[contains(@id, '_lab_test_date')]", attributes[:lab_test_date]) if attributes[:lab_test_date] browser.select("//div[@id='labs']//div[@class='lab'][#{lab_index}]//div[@class='lab_result'][#{result_index}]//select[contains(@id, '_specimen_sent_to_state_id')]", "label=#{attributes[:sent_to_state]}") if attributes[:sent_to_state] end # # Encounters Tab # def add_encounter(browser, attributes, index = 1) click_core_tab(browser, ENCOUNTERS) sleep(1) browser.select("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//select[contains(@id, '_user_id')]", "label=#{attributes[:user]}") if attributes[:user] browser.type("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//input[contains(@id, '_encounter_date')]", attributes[:encounter_date]) if attributes[:encounter_date] browser.type("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//textarea[contains(@id, '_description')]", attributes[:description]) if attributes[:description] browser.select("//div[@id='encounter_child_events']//div[@class='encounter'][#{index}]//select[contains(@id, '_location_type')]", "label=#{attributes[:location_type]}") if attributes[:location_type] end # # Reporting Tab # def add_reporting_info(browser, attributes) click_core_tab(browser, REPORTING) sleep(1) browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_name')]", attributes[:name]) if attributes[:name] browser.click("//div[@id='reporting_agencies']//input[contains(@id, '_place_attributes_place_type_#{attributes[:place_type]}')]") if attributes[:place_type] browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_area_code')]", attributes[:area_code]) if attributes[:area_code] browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_phone_number')]", attributes[:phone_number]) if attributes[:phone_number] browser.type("//div[@id='reporting_agencies']//input[contains(@id, '_extension')]", attributes[:extension]) if attributes[:extension] browser.type("//div[@id='reporter']//input[contains(@id, '_last_name')]", attributes[:last_name]) if attributes[:last_name] browser.type("//div[@id='reporter']//input[contains(@id, '_last_name')]", attributes[:first_name]) if attributes[:first_name] browser.type("//div[@id='reporter']//input[contains(@id, '_area_code')]", attributes[:area_code]) if attributes[:area_code] browser.type("//div[@id='reporter']//input[contains(@id, '_phone_number')]", attributes[:phone_number]) if attributes[:phone_number] browser.type("//div[@id='reporter']//input[contains(@id, '_extension')]", attributes[:extension]) if attributes[:extension] browser.type("//div[@id='reported_dates']//input[contains(@id, '_clinician_date')]", attributes[:clinician_date]) if attributes[:clinician_date] browser.type("//div[@id='reported_dates']//input[contains(@id, '_PH_date')]", attributes[:PH_date]) if attributes[:PH_date] end # # Admin Tab # def add_admin_info(browser, attributes) click_core_tab(browser, ADMIN) sleep(1) browser.select("//div[@id='administrative_tab']//select[contains(@id, '_event_status')]", "label=#{attributes[:event_status]}") if attributes[:event_status] browser.select("//div[@id='administrative_tab']//select[contains(@id, '_state_case_status_id')]", "label=#{attributes[:state_case_status]}") if attributes[:state_case_status] # Fill in the rest... end private def assert_contains(browser, container_element, element) begin result = browser.get_eval("window.document.getElementById(\"#{element}\").descendantOf(\"#{container_element}\")") rescue result = false end return (result == "true") ? true : false end def add_question_to_element(browser, element_name, element_id_prefix, question_attributes, expect_error=false) element_id = get_form_element_id(browser, element_name, element_id_prefix) add_question_attributes(browser, element_id, question_attributes, expect_error) end def add_question_to_core_field_config(browser, element_name, element_id_prefix, question_attributes) element_id = get_form_element_id_for_core_field(browser, element_name, element_id_prefix) add_question_attributes(browser, element_id, question_attributes) end def add_question_attributes(browser, element_id, question_attributes, expect_error=false) browser.click("add-question-#{element_id}") wait_for_element_present("new-question-form", browser) fill_in_question_attributes(browser, question_attributes) browser.click "//input[contains(@id, 'create_question_submit')]" unless expect_error wait_for_element_not_present("new-question-form", browser) else sleep 1 end if browser.is_text_present(question_attributes[:question_text]) return true else return false end end def fill_in_question_attributes(browser, question_attributes, options={ :mode => :add }) browser.type("question_element_question_attributes_question_text", question_attributes[:question_text]) if question_attributes.include? :question_text browser.select("question_element_question_attributes_data_type", "label=#{question_attributes[:data_type]}") unless options[:mode] == :edit browser.select("question_element_export_column_id", "label=#{question_attributes[:export_column_id]}") if question_attributes.include? :export_column_id browser.select("question_element_question_attributes_style", "label=#{question_attributes[:style]}") if question_attributes.include? :style browser.click("question_element_is_active_#{question_attributes[:is_active].to_s}") if question_attributes.include? :is_active browser.type("question_element_question_attributes_short_name", question_attributes[:short_name]) if question_attributes.include? :short_name browser.type("question_element_question_attributes_help_text", question_attributes[:help_text]) if question_attributes[:help_text] end def add_follow_up_to_element(browser, element_name, element_id_prefix, condition, core_label=nil) element_id = get_form_element_id(browser, element_name, element_id_prefix) browser.click("add-follow-up-#{element_id}") wait_for_element_present("new-follow-up-form", browser) if core_label.nil? browser.type "follow_up_element_condition", condition else browser.type "model_auto_completer_tf", condition end browser.select "follow_up_element_core_path", "label=#{core_label}" unless core_label.nil? browser.click "//input[contains(@id, 'create_follow_up_submit')]" wait_for_element_not_present("new-follow-up-form", browser) end def add_follow_up_to_core_field_config(browser, element_name, element_id_prefix, condition, core_label=nil) element_id = get_form_element_id_for_core_field(browser, element_name, element_id_prefix) browser.click("add-follow-up-#{element_id}") wait_for_element_present("new-follow-up-form", browser) if core_label.nil? browser.type "follow_up_element_condition", condition else browser.type "model_auto_completer_tf", condition end browser.select "follow_up_element_core_path", "label=#{core_label}" unless core_label.nil? browser.click "//input[contains(@id, 'create_follow_up_submit')]" wait_for_element_not_present("new-follow-up-form", browser) end # Goes in reverse from the name provided, looking for the magic string of # element_prefix_<id> # # The retry accounts for the fact that you may run into paths that just so # happen to contain the element prefix string. def get_form_element_id(browser, name, element_id_prefix) retry_count = 0 element_prefix_length = element_id_prefix.size html_source = browser.get_html_source # Start from form_children to avoid finding something up in the top portion of the page name_position = html_source.index(name, html_source.index("form_children")) begin id_start_position = html_source.rindex("#{element_id_prefix}", name_position) + element_prefix_length raise if html_source[id_start_position..id_start_position+1].to_i == 0 rescue retry_count += 1 name_position = id_start_position - (element_prefix_length+1) retry if retry_count < 5 end id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end def get_library_element_id(browser, name, element_id_prefix) retry_count = 0 element_prefix_length = element_id_prefix.size html_source = browser.get_html_source # Start from form_children to avoid finding something up in the top portion of the page name_position = html_source.index(name, html_source.index("Library Administration")) begin id_start_position = html_source.rindex("#{element_id_prefix}", name_position) + element_prefix_length raise if html_source[id_start_position..id_start_position+1].to_i == 0 rescue retry_count += 1 id_start_position.nil? ? name_position = 1 : name_position = id_start_position - (element_prefix_length+1) retry if retry_count < 5 end id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end # Same as get_form_element_id except it doesn't do a reverse index looking for the start position. # Core field configs are different in that the name of the main core field config preceeds the two # containers for before and after configs. def get_form_element_id_for_core_field(browser, name, element_id_prefix) element_prefix_length = element_id_prefix.size html_source = browser.get_html_source name_position = html_source.index(name) id_start_position = html_source.index("#{element_id_prefix}", name_position) + element_prefix_length id_end_position = html_source.index("\"", id_start_position)-1 html_source[id_start_position..id_end_position] end def get_investigator_answer_id(browser, question_text, html_source=nil) html_source = browser.get_html_source if html_source.nil? question_position = html_source.index(question_text) id_start_position = html_source.index(INVESTIGATOR_ANSWER_ID_PREFIX, question_position) + 20 id_end_position = html_source.index("\"", id_start_position) -1 # This is a kluge that will go hunting for quot; if the id looks too big. Needed for reporting agency at least. id_end_position = html_source.index("quot;", id_start_position)-3 if (id_end_position-id_start_position > 10) html_source[id_start_position..id_end_position] end # This only works for investigator questions on contact events def get_investigator_click_answer_id(browser, question_text) html_source = browser.get_html_source question_position = html_source.index(question_text) id_start_position = html_source.index("investigator_answer_", question_position) + 20 id_end_position = html_source.index("_", id_start_position) -1 html_source[id_start_position..id_end_position] end def get_random_word wordlist = ["Lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing","elit","Duis","sodales","dignissim","enim","Nunc","rhoncus","quam","ut","quam","Quisque","vitae","urna","Duis","nec","sapien","Proin","mollis","congue","mauris","Fusce","lobortis","tristique","elit","Phasellus","aliquam","dui","id","placerat","hendrerit","dolor","augue","posuere","tellus","at","ultricies","libero","leo","vel","leo","Nulla","purus","Ut","lacus","felis","tempus","at","egestas","nec","cursus","nec","magna","Ut","fringilla","aliquet","arcu","Vestibulum","ante","ipsum","primis","in","faucibus","orci","luctus","et","ultrices","posuere","cubilia","Curae","Etiam","vestibulum","urna","sit","amet","sem","Nunc","ac","ipsum","In","consectetuer","quam","nec","lectus","Maecenas","magna","Nulla","ut","mi","eu","elit","accumsan","gravida","Praesent","ornare","urna","a","lectus","dapibus","luctus","Integer","interdum","bibendum","neque","Nulla","id","dui","Aenean","tincidunt","dictum","tortor","Proin","sagittis","accumsan","nulla","Etiam","consectetuer","Etiam","eget","nibh","ut","sem","mollis","luctus","Etiam","mi","eros","blandit","in","suscipit","ut","vestibulum","et","velit","Fusce","laoreet","nulla","nec","neque","Nam","non","nulla","ut","justo","ullamcorper","egestas","In","porta","ipsum","nec","neque","Cras","non","metus","id","massa","ultrices","rhoncus","Donec","mattis","odio","sagittis","nunc","Vivamus","vehicula","justo","vitae","tincidunt","posuere","risus","pede","lacinia","dolor","quis","placerat","justo","arcu","ut","tortor","Aliquam","malesuada","lectus","id","condimentum","sollicitudin","arcu","mauris","adipiscing","turpis","a","sollicitudin","erat","metus","vel","magna","Proin","scelerisque","neque","id","urna","lobortis","vulputate","In","porta","pulvinar","urna","Cras","id","nulla","In","dapibus","vestibulum","pede","In","ut","velit","Aliquam","in","turpis","vitae","nunc","hendrerit","ullamcorper","Aliquam","rutrum","erat","sit","amet","velit","Nullam","pharetra","neque","id","pede","Phasellus","suscipit","ornare","mi","Ut","malesuada","consequat","ipsum","Suspendisse","suscipit","aliquam","nisl","Suspendisse","iaculis","magna","eu","ligula","Sed","porttitor","eros","id","euismod","auctor","dolor","lectus","convallis","justo","ut","elementum","magna","magna","congue","nulla","Pellentesque","eget","ipsum","Pellentesque","tempus","leo","id","magna","Cras","mi","dui","pellentesque","in","pellentesque","nec","blandit","nec","odio","Pellentesque","eget","risus","In","venenatis","metus","id","magna","Etiam","blandit","Integer","a","massa","vitae","lacus","dignissim","auctor","Mauris","libero","metus","aliquet","in","rhoncus","sed","volutpat","quis","libero","Nam","urna"] begin result = wordlist[rand(wordlist.size)] raise if result.nil? rescue Exception => ex result = wordlist[rand(wordlist.size)] end result end def get_resource_id(browser, name) html_source = browser.get_html_source pos1 = html_source.index(name) pos2 = html_source.index(/\d\/edit['"]/, pos1) pos3 = html_source.rindex("/", pos2)+1 id = html_source[pos3..pos2] return id.to_i rescue => err return -1 end # using the form name, get the form id from the forms index page def get_form_id(browser, form_name) html_source = browser.get_html_source pos1 = html_source.index(form_name) pos2 = html_source.index('forms/builder/', pos1) + 14 pos3 = html_source.index('"', pos2) html_source[pos2...pos3] end def copy_form_and_open_in_form_builder(browser, form_name) browser.click("copy_form_#{get_form_id(browser, form_name)}") browser.wait_for_page_to_load($load_time) browser.is_text_present('Form was successfully copied.').should be_true browser.click('//input[@id="form_submit"]') browser.wait_for_page_to_load($load_time) browser.is_text_present('Form was successfully updated.').should be_true browser.is_text_present('Not Published').should be_true browser.click('link=Builder') browser.wait_for_page_to_load($load_time) true end def assert_tooltip_exists(browser, tool_tip_text) browser.is_element_present("//img[contains(@src, 'help.png')]").should be_true browser.get_html_source.include?(tool_tip_text).should be_true browser.is_visible("//span[contains(@id,'_help_text')]").should be_false browser.is_visible("//div[@id='WzTtDiV']").should be_false browser.mouse_over("//a[contains(@id,'_help_text')]") browser.mouse_move("//a[contains(@id,'_help_text')]") sleep(2) browser.is_visible("//div[@id='WzTtDiV']").should be_true browser.mouse_out("//a[contains(@id, '_help_text')]") sleep(2) browser.is_visible("//div[@id='WzTtDiV']").should be_false return true end def is_disease_active(browser, disease_name) html_source = browser.get_html_source start = html_source.index(disease_name) + disease_name.length html_source[start..start+100].index("Active").nil? ? false : true end def is_disease_inactive(browser, disease_name) html_source = browser.get_html_source start = html_source.index(disease_name) + disease_name.length html_source[start..start+100].index("Inactive").nil? ? false : true end def get_record_number(browser) source = browser.get_html_source label = '<label>Record number</label>' index_start = source.index(label) + label.length index_end = source.index('</span>', index_start) source[index_start...index_end].strip end end
require "muzak" require "readline" require "shellwords" opts = { debug: ARGV.include?("--debug") || ARGV.include?("-d"), verbose: ARGV.include?("--verbose") || ARGV.include?("-v"), batch: ARGV.include?("--batch") || ARGV.include?("-b") } muzak = Muzak::Instance.new(opts) COMMANDS = Muzak::Cmd.humanize_commands! CONFIG_REGEX = /^config-(get)|(set)|(del)/ ARTIST_REGEX = Regexp.union COMMANDS.select{ |c| c =~ /artist/ }.map { |c| /^#{c} / } ALBUM_REGEX = Regexp.union COMMANDS.select{ |c| c =~ /album/ }.map { |c| /^#{c} / } comp = proc do |s| case Readline.line_buffer when CONFIG_REGEX muzak.config.keys.grep(Regexp.new(Regexp.escape(s))) when ARTIST_REGEX muzak.index.artists.grep(Regexp.new(Regexp.escape(s))) when ALBUM_REGEX muzak.index.album_names.grep(Regexp.new(Regexp.escape(s))) else COMMANDS.grep(Regexp.new(Regexp.escape(s))) end end Readline.completion_append_character = " " Readline.completion_proc = comp while line = Readline.readline("muzak> ", true) cmd_argv = Shellwords.split(line) next if cmd_argv.empty? muzak.send Muzak::Cmd.resolve_command(cmd_argv.shift), *cmd_argv end muzak: Make artist completion smarter. Ruby's readline implementation doesn't allow for full-line completion procs, so it's a dead-end in terms of tab completing complicated song names. require "muzak" require "readline" require "shellwords" opts = { debug: ARGV.include?("--debug") || ARGV.include?("-d"), verbose: ARGV.include?("--verbose") || ARGV.include?("-v"), batch: ARGV.include?("--batch") || ARGV.include?("-b") } muzak = Muzak::Instance.new(opts) COMMANDS = Muzak::Cmd.humanize_commands! CONFIG_REGEX = /^config-(get)|(set)|(del)/ ARTIST_REGEX = Regexp.union COMMANDS.select{ |c| c =~ /artist/ }.map { |c| /^#{c}/ } ALBUM_REGEX = Regexp.union COMMANDS.select{ |c| c =~ /album/ }.map { |c| /^#{c}/ } comp = proc do |s| case Readline.line_buffer when CONFIG_REGEX muzak.config.keys.grep(Regexp.new(Regexp.escape(s))) when ARTIST_REGEX ss = Readline.line_buffer.split(" ") muzak.index.artists.grep(Regexp.new(Regexp.escape(ss[1..-1].join(" ")))) when ALBUM_REGEX muzak.index.album_names.grep(Regexp.new(Regexp.escape(s))) else COMMANDS.grep(Regexp.new(Regexp.escape(s))) end end Readline.completion_append_character = " " Readline.completion_proc = comp while line = Readline.readline("muzak> ", true) cmd_argv = Shellwords.split(line) next if cmd_argv.empty? muzak.send Muzak::Cmd.resolve_command(cmd_argv.shift), *cmd_argv end
require 'backlog_kit/error' require 'backlog_kit/response' require 'backlog_kit/version' require 'backlog_kit/client/authorization' require 'backlog_kit/client/git' require 'backlog_kit/client/group' require 'backlog_kit/client/issue' require 'backlog_kit/client/notification' require 'backlog_kit/client/priority' require 'backlog_kit/client/project' require 'backlog_kit/client/resolution' require 'backlog_kit/client/space' require 'backlog_kit/client/star' require 'backlog_kit/client/status' require 'backlog_kit/client/user' require 'backlog_kit/client/watching' require 'backlog_kit/client/wiki' require 'backlog_kit/response/file_parser' require 'backlog_kit/response/raise_error' require 'backlog_kit/hash_extensions' module BacklogKit # Client for the Backlog API # # @see http://developer.nulab-inc.com/docs/backlog class Client include BacklogKit::Client::Authorization include BacklogKit::Client::Git include BacklogKit::Client::Group include BacklogKit::Client::Issue include BacklogKit::Client::Notification include BacklogKit::Client::Priority include BacklogKit::Client::Project include BacklogKit::Client::Resolution include BacklogKit::Client::Space include BacklogKit::Client::Star include BacklogKit::Client::Status include BacklogKit::Client::User include BacklogKit::Client::Watching include BacklogKit::Client::Wiki USER_AGENT = "BacklogKit Ruby Gem #{BacklogKit::VERSION}".freeze attr_accessor( :space_id, :top_level_domain, :api_key, :client_id, :client_secret, :refresh_token, :redirect_uri, :state, :access_token ) # Initialize a new Client object with given options # # @param options [Hash] Initialize options # @option options [String] :space_id Backlog space id # @option options [String] :top_level_domain Backlog top level domain # @option options [String] :api_key Backlog api key # @option options [String] :client_id Backlog OAuth client id # @option options [String] :client_secret Backlog OAuth client secret # @option options [String] :refresh_token Backlog OAuth refresh token def initialize(options = {}) @space_id = ENV['BACKLOG_SPACE_ID'] @top_level_domain = ENV['BACKLOG_TOP_DOMAIN'] || 'jp' @api_key = ENV['BACKLOG_API_KEY'] @client_id = ENV['BACKLOG_OAUTH_CLIENT_ID'] @client_secret = ENV['BACKLOG_OAUTH_CLIENT_SECRET'] @refresh_token = ENV['BACKLOG_OAUTH_REFRESH_TOKEN'] options.each do |key, value| instance_variable_set(:"@#{key}", value) end end # Generate an OAuth authorization URL # # @return [String] OAuth authorization URL def authorization_url url = "#{host}/OAuth2AccessRequest.action?response_type=code&client_id=#{@client_id}" url += "&redirect_uri=#{URI.escape(@redirect_uri)}" if @redirect_uri url += "&state=#{@state}" if @state url end # Make a HTTP GET request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def get(path, params = {}) request(:get, path, params) end # Make a HTTP POST request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def post(path, params = {}) request(:post, path, params) end # Make a HTTP PUT request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def put(path, params = {}) request(:put, path, params) end # Make a HTTP PATCH request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def patch(path, params = {}) request(:patch, path, params) end # Make a HTTP DELETE request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def delete(path, params = {}) request(:delete, path, params) end private def request(method, path, params = {}, raw_params = false) params.camelize_keys! unless raw_params faraday_response = connection.send(method, request_path(path), params) BacklogKit::Response.new(faraday_response) rescue Faraday::ConnectionFailed => e raise BacklogKit::Error, "#{BacklogKit::ConnectionError.name.demodulize} - #{e.message}" end def connection Faraday.new(url: host, headers: request_headers) do |faraday| faraday.request(:multipart) faraday.request(:url_encoded) faraday.response(:json, content_type: /application\/json/) faraday.response(:file_parser) faraday.response(:error) faraday.adapter(Faraday.default_adapter) end end def host "https://#{space_id}.backlog.#{top_level_domain}" end def request_headers headers = { 'User-Agent' => USER_AGENT } headers['Authorization'] = "Bearer #{@access_token}" if oauth_request? headers end def oauth_request? !@api_key && @access_token end def request_path(path) path = "/api/v2/#{URI.escape(path)}" path += "?apiKey=#{URI.escape(@api_key.to_s)}" if @api_key path end end end fix typo require 'backlog_kit/error' require 'backlog_kit/response' require 'backlog_kit/version' require 'backlog_kit/client/authorization' require 'backlog_kit/client/git' require 'backlog_kit/client/group' require 'backlog_kit/client/issue' require 'backlog_kit/client/notification' require 'backlog_kit/client/priority' require 'backlog_kit/client/project' require 'backlog_kit/client/resolution' require 'backlog_kit/client/space' require 'backlog_kit/client/star' require 'backlog_kit/client/status' require 'backlog_kit/client/user' require 'backlog_kit/client/watching' require 'backlog_kit/client/wiki' require 'backlog_kit/response/file_parser' require 'backlog_kit/response/raise_error' require 'backlog_kit/hash_extensions' module BacklogKit # Client for the Backlog API # # @see http://developer.nulab-inc.com/docs/backlog class Client include BacklogKit::Client::Authorization include BacklogKit::Client::Git include BacklogKit::Client::Group include BacklogKit::Client::Issue include BacklogKit::Client::Notification include BacklogKit::Client::Priority include BacklogKit::Client::Project include BacklogKit::Client::Resolution include BacklogKit::Client::Space include BacklogKit::Client::Star include BacklogKit::Client::Status include BacklogKit::Client::User include BacklogKit::Client::Watching include BacklogKit::Client::Wiki USER_AGENT = "BacklogKit Ruby Gem #{BacklogKit::VERSION}".freeze attr_accessor( :space_id, :top_level_domain, :api_key, :client_id, :client_secret, :refresh_token, :redirect_uri, :state, :access_token ) # Initialize a new Client object with given options # # @param options [Hash] Initialize options # @option options [String] :space_id Backlog space id # @option options [String] :top_level_domain Backlog top level domain # @option options [String] :api_key Backlog api key # @option options [String] :client_id Backlog OAuth client id # @option options [String] :client_secret Backlog OAuth client secret # @option options [String] :refresh_token Backlog OAuth refresh token def initialize(options = {}) @space_id = ENV['BACKLOG_SPACE_ID'] @top_level_domain = ENV['BACKLOG_TOP_LEVEL_DOMAIN'] || 'jp' @api_key = ENV['BACKLOG_API_KEY'] @client_id = ENV['BACKLOG_OAUTH_CLIENT_ID'] @client_secret = ENV['BACKLOG_OAUTH_CLIENT_SECRET'] @refresh_token = ENV['BACKLOG_OAUTH_REFRESH_TOKEN'] options.each do |key, value| instance_variable_set(:"@#{key}", value) end end # Generate an OAuth authorization URL # # @return [String] OAuth authorization URL def authorization_url url = "#{host}/OAuth2AccessRequest.action?response_type=code&client_id=#{@client_id}" url += "&redirect_uri=#{URI.escape(@redirect_uri)}" if @redirect_uri url += "&state=#{@state}" if @state url end # Make a HTTP GET request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def get(path, params = {}) request(:get, path, params) end # Make a HTTP POST request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def post(path, params = {}) request(:post, path, params) end # Make a HTTP PUT request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def put(path, params = {}) request(:put, path, params) end # Make a HTTP PATCH request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def patch(path, params = {}) request(:patch, path, params) end # Make a HTTP DELETE request # # @param path [String] Path for request # @param params [Hash] Request parameters # @return [BacklogKit::Response] Response from API server def delete(path, params = {}) request(:delete, path, params) end private def request(method, path, params = {}, raw_params = false) params.camelize_keys! unless raw_params faraday_response = connection.send(method, request_path(path), params) BacklogKit::Response.new(faraday_response) rescue Faraday::ConnectionFailed => e raise BacklogKit::Error, "#{BacklogKit::ConnectionError.name.demodulize} - #{e.message}" end def connection Faraday.new(url: host, headers: request_headers) do |faraday| faraday.request(:multipart) faraday.request(:url_encoded) faraday.response(:json, content_type: /application\/json/) faraday.response(:file_parser) faraday.response(:error) faraday.adapter(Faraday.default_adapter) end end def host "https://#{space_id}.backlog.#{top_level_domain}" end def request_headers headers = { 'User-Agent' => USER_AGENT } headers['Authorization'] = "Bearer #{@access_token}" if oauth_request? headers end def oauth_request? !@api_key && @access_token end def request_path(path) path = "/api/v2/#{URI.escape(path)}" path += "?apiKey=#{URI.escape(@api_key.to_s)}" if @api_key path end end end
#!/usr/bin/env ruby require 'rubygems' require 'thor' require 'plist' require 'uri' require 'fileutils' class PlaylistExporter < Thor desc "process", "process playlist" method_option :verbose, :type => :boolean, :default => false, :aliases => "-v", :desc => "running in verbose mode will also show each file as it's copied" method_option :debug, :type => :boolean, :default => false, :aliases => "-d", :desc => "in debug mode files will not actually be copied" method_option :force, :type => :boolean, :default => false, :aliases => "-f", :desc => "normally, copying a file is skipped if a file with the same name and size already exists in the destination. Force mode always copies." def process puts "*** Verbose Mode" if options.verbose? puts "*** Debug Mode" if options.debug? puts "*** Force Mode" if options.force? get_exported_file get_target_directory read_plist initialize_catalog process_tracks copy_catalog end private def get_exported_file found = false until found @exported_file = ask("Location of Playlist [~/Desktop/usb/playlist.xml]") @exported_file = "~/Desktop/usb/playlist.xml" if @exported_file == "" @exported_file = File.expand_path(@exported_file) if File.exists?(@exported_file) found = true else say "File #{@exported_file} does not exist", :red end end end def get_target_directory found = false until found @target_directory = ask("Location to which music should be copied [~/Desktop/usb]") @target_directory = "~/Desktop/usb/" if @target_directory == "" @target_directory += "/" unless ("/" == @target_directory[-1]) @target_directory = File.expand_path(@target_directory) if File.exists?(@target_directory) found = true else say "Directory #{@target_directory} does not exist", :red end end end def read_plist say "Reading #{@exported_file}", :green @export = Plist::parse_xml(@exported_file) @tracks = @export["Tracks"] end def initialize_catalog @catalog = {} end def process_tracks @tracks.each do |id, info| add_track_to_catalog(info) end end def add_track_to_catalog(info) name = clean_string(info["Name"]) album = clean_string(info["Album"], 25) genre = clean_string(info["Genre"], 20) track_number = info["Track Number"] || 0 begin file_uri = URI(info["Location"]) original_file = URI.decode(file_uri.path) original_file =~ /.*\.(.*)/ file_type = $1 @catalog[genre] ||= {} @catalog[genre][album] ||= [] if options.verbose? puts " Cataloging : #{name} / #{album} / #{genre} / #{track_number}" end target_name = ("%02d-" % track_number) + "#{name}.#{file_type}" @catalog[genre][album] << {:name => target_name, :file => original_file} rescue puts "** Error trying to process:\n\t#{name}: #{info}" end end def clean_string(s, cutoff_at = nil) unless s.is_a?(String) s = 'Blank' end if cutoff_at s = s[0, cutoff_at] end s && s.gsub(/\/|\(|\)/, '_') end def copy_catalog say "Beginning Copy", :green @catalog.each do |genre, albums| puts "Genre: #{genre}" genre_path = "#{@target_directory}/#{genre}" unless options.debug? FileUtils.mkdir(genre_path) unless File.exists?(genre_path) end albums.each do |album, tracks| puts " Album: #{album}" album_path = "#{@target_directory}/#{genre}/#{album}" unless options.debug? FileUtils.mkdir(album_path) unless File.exists?(album_path) end tracks.each do |track| full_destination = "#{@target_directory}/#{genre}/#{album}/#{track[:name]}" source = track[:file] if options.verbose? puts " Creating : #{track[:name]}" puts " source : #{track[:file]}" end if File.exists?(source) if options.force? copy_file(source, full_destination) else if File.exists?(full_destination) && (File.size(source) == File.size(full_destination)) puts " *** Destination file already exists: #{track[:name]}" else copy_file(source, full_destination) end end else puts " *** Source does not exist" end end end end end def copy_file(source, full_destination) unless options.debug? FileUtils.copy_file(source, full_destination) end end end PlaylistExporter.start gracefully handle files without locations #!/usr/bin/env ruby require 'rubygems' require 'thor' require 'plist' require 'uri' require 'fileutils' class PlaylistExporter < Thor desc "process", "process playlist" method_option :verbose, :type => :boolean, :default => false, :aliases => "-v", :desc => "running in verbose mode will also show each file as it's copied" method_option :debug, :type => :boolean, :default => false, :aliases => "-d", :desc => "in debug mode files will not actually be copied" method_option :force, :type => :boolean, :default => false, :aliases => "-f", :desc => "normally, copying a file is skipped if a file with the same name and size already exists in the destination. Force mode always copies." def process puts "*** Verbose Mode" if options.verbose? puts "*** Debug Mode" if options.debug? puts "*** Force Mode" if options.force? get_exported_file get_target_directory read_plist initialize_catalog process_tracks copy_catalog end private def get_exported_file found = false until found @exported_file = ask("Location of Playlist [~/Desktop/usb/playlist.xml]") @exported_file = "~/Desktop/usb/playlist.xml" if @exported_file == "" @exported_file = File.expand_path(@exported_file) if File.exists?(@exported_file) found = true else say "File #{@exported_file} does not exist", :red end end end def get_target_directory found = false until found @target_directory = ask("Location to which music should be copied [~/Desktop/usb]") @target_directory = "~/Desktop/usb/" if @target_directory == "" @target_directory += "/" unless ("/" == @target_directory[-1]) @target_directory = File.expand_path(@target_directory) if File.exists?(@target_directory) found = true else say "Directory #{@target_directory} does not exist", :red end end end def read_plist say "Reading #{@exported_file}", :green @export = Plist::parse_xml(@exported_file) @tracks = @export["Tracks"] end def initialize_catalog @catalog = {} end def process_tracks @tracks.each do |id, info| add_track_to_catalog(info) end end def add_track_to_catalog(info) name = clean_string(info["Name"]) album = clean_string(info["Album"], 25) genre = clean_string(info["Genre"], 20) track_number = info["Track Number"] || 0 begin location = info["Location"] if location.nil? || location.empty? puts "** Error -- Song does not have a location on disk. Stored in Apple Music?" return end file_uri = URI(info["Location"]) original_file = URI.decode(file_uri.path) original_file =~ /.*\.(.*)/ file_type = $1 @catalog[genre] ||= {} @catalog[genre][album] ||= [] if options.verbose? puts " Cataloging : #{name} / #{album} / #{genre} / #{track_number}" end target_name = ("%02d-" % track_number) + "#{name}.#{file_type}" @catalog[genre][album] << {:name => target_name, :file => original_file} rescue puts "** Error trying to process:\n\t#{name}: #{info}" end end def clean_string(s, cutoff_at = nil) unless s.is_a?(String) s = 'Blank' end if cutoff_at s = s[0, cutoff_at] end s && s.gsub(/\/|\(|\)/, '_') end def copy_catalog say "Beginning Copy", :green @catalog.each do |genre, albums| puts "Genre: #{genre}" genre_path = "#{@target_directory}/#{genre}" unless options.debug? FileUtils.mkdir(genre_path) unless File.exists?(genre_path) end albums.each do |album, tracks| puts " Album: #{album}" album_path = "#{@target_directory}/#{genre}/#{album}" unless options.debug? FileUtils.mkdir(album_path) unless File.exists?(album_path) end tracks.each do |track| full_destination = "#{@target_directory}/#{genre}/#{album}/#{track[:name]}" source = track[:file] if options.verbose? puts " Creating : #{track[:name]}" puts " source : #{track[:file]}" end if File.exists?(source) if options.force? copy_file(source, full_destination) else if File.exists?(full_destination) && (File.size(source) == File.size(full_destination)) puts " *** Destination file already exists: #{track[:name]}" else copy_file(source, full_destination) end end else puts " *** Source does not exist" end end end end end def copy_file(source, full_destination) unless options.debug? FileUtils.copy_file(source, full_destination) end end end PlaylistExporter.start
require "set" module KiskoSuits class Compiler attr_reader :path, :output_filename, :included_filenames def initialize(path) @path = path @output_filename = nil @included_filenames = Set.new end def render @included_filenames.clear abort "Suits file '#{path}' not found" unless File.exists?(path) open_output_file do |output| File.foreach(path) do |line| output.write(process_line(File.dirname(path), line)) end end end private def process_line(root_dir, line) if match = line.match(/\s*include:\s*([\w\.\/]+)/) included_path = "#{root_dir}/#{match[1]}" if File.exists?(included_path) @included_filenames << included_path File.foreach(included_path).map { |included_line| process_line(File.dirname(included_path), included_line) }.join else puts "Include #{included_path} can't be found" "" end else line end end def open_output_file(&block) @output_filename = path.gsub(".suits", "") abort "Problem with config file (should end with .suits)" if path == @output_filename File.open(@output_filename, 'w', &block) end end end Removes comments from markdown require "set" module KiskoSuits class Compiler attr_reader :path, :output_filename, :included_filenames def initialize(path) @path = path @output_filename = nil @included_filenames = Set.new end def render @included_filenames.clear abort "Suits file '#{path}' not found" unless File.exists?(path) open_output_file do |output| File.foreach(path) do |line| output.write(process_line(File.dirname(path), line)) end end end private def process_line(root_dir, line) if line.start_with?('[//]:') # It's a comment elsif match = line.match(/\s*include:\s*([\w\.\/]+)/) included_path = "#{root_dir}/#{match[1]}" if File.exists?(included_path) @included_filenames << included_path File.foreach(included_path).map { |included_line| process_line(File.dirname(included_path), included_line) }.join else puts "Include #{included_path} can't be found" "" end else line end end def open_output_file(&block) @output_filename = path.gsub(".suits", "") abort "Problem with config file (should end with .suits)" if path == @output_filename File.open(@output_filename, 'w', &block) end end end
module KnapsackPro VERSION = '0.45.0' end Bump version 0.46.0 module KnapsackPro VERSION = '0.46.0' end
MiniTest = Test = Module.new module MiniTest module Unit class TestCase # @see skip SKIP = Object.new # # Hooks to perform MiniTest -> MacBacon translations # def self.inherited(subclass) name = subclass.to_s.sub(/^Test/, '') context = describe name do before do @test_case = subclass.new @test_case.setup if @test_case.respond_to?(:setup) end after do @test_case.teardown if @test_case.respond_to?(:teardown) @test_case = nil end end subclass.instance_variable_set(:@context, context) end def self.method_added(meth) return unless meth =~ /^test_/ name = meth.sub(/^test_/, '').tr('_', ' ') @context.it name do skipped = catch SKIP do @test_case.__send__(meth) end if skipped Bacon::Counter[:requirements] += 1 # Convince Bacon that tests passed end end end # # Test control # def skip throw SKIP, true end def pass(_=nil) assert true end # # Assertions # # @see assert_operator UNDEFINED = Object.new def assert(test, msg=nil) if msg.nil? test.should.be.true? else Bacon::Should.new(nil).satisfy(msg) { test } end true end def refute(test, msg=nil) if msg.nil? test.should.be.false? else !assert(!test, msg) end end def assert_empty(obj, msg=nil) if msg.nil? obj.should.be.empty? else assert obj.empty?, msg end end def refute_empty(obj, msg=nil) if msg.nil? obj.should.not.be.empty? else refute obj.empty?, msg end end def assert_equal(exp, act, msg=nil) if msg.nil? act.should == exp else assert act == exp, msg end end def refute_equal(exp, act, msg=nil) if msg.nil? act.should != exp else refute act == exp, msg end end alias_method :assert_not_equal, :refute_equal def assert_in_delta(exp, act, delta=0.001, msg=nil) if msg.nil? act.should.be.close?(exp, delta) else assert delta >= (act-exp).abs, msg end end def refute_in_delta(exp, act, delta=0.001, msg=nil) if msg.nil? act.should.not.be.close?(exp, delta) else refute delta >= (act-exp).abs, msg end end def assert_in_epsilon(exp, act, epsilon=0.001, msg=nil) delta = epsilon * [exp.abs, act.abs].min assert_in_delta exp, act, delta, msg end def refute_in_epsilon(exp, act, epsilon=0.001, msg=nil) delta = epsilon * [exp.abs, act.abs].min refute_in_delta exp, act, delta, msg end def assert_includes(collection, obj, msg=nil) if msg.nil? collection.should.include?(obj) else assert collection.include?(obj), msg end end def refute_includes(collection, obj, msg=nil) if msg.nil? collection.should.not.include?(obj) else refute collection.include?(obj), msg end end def assert_instance_of(cls, obj, msg=nil) if msg.nil? obj.should.be.instance_of?(cls) else assert obj.instance_of?(cls), msg end end def refute_instance_of(cls, obj, msg=nil) if msg.nil? obj.should.not.be.instance_of?(cls) else refute obj.instance_of?(cls), msg end end def assert_kind_of(cls, obj, msg=nil) if msg.nil? obj.should.be.kind_of?(cls) else assert obj.kind_of?(cls), msg end end def refute_kind_of(cls, obj, msg=nil) if msg.nil? obj.should.not.be.kind_of?(cls) else refute obj.kind_of?(cls), msg end end def assert_match(matcher, obj, msg=nil) matcher = /#{Regexp.escape(matcher)}/ if String === matcher if msg.nil? obj.should =~ matcher else assert matcher =~ obj, msg end end def refute_match(matcher, obj, msg=nil) matcher = /#{Regexp.escape(matcher)}/ if String === matcher if msg.nil? obj.should !~ matcher else refute matcher =~ obj, msg end end alias_method :assert_no_match, :refute_match def assert_nil(obj, msg=nil) if msg.nil? obj.should.be.nil? else assert obj.nil?, msg end end def refute_nil(obj, msg=nil) if msg.nil? obj.should.not.be.nil? else refute obj.nil?, msg end end alias_method :assert_not_nil, :refute_nil def assert_operator(obj1, op, obj2=UNDEFINED, msg=nil) args = obj2 == UNDEFINED ? [op] : [op, obj2] if msg.nil? obj1.should.public_send(*args) else assert obj1.__send__(*args), msg end end def refute_operator(obj1, op, obj2=UNDEFINED, msg=nil) args = obj2 == UNDEFINED ? [op] : [op, obj2] if msg.nil? obj1.should.not.public_send(*args) else refute obj1.__send__(*args), msg end end def assert_output raise NotImplementedError end def assert_predicate(obj, predicate, msg=nil) if msg.nil? obj.should.public_send(predicate) else assert obj.__send__(predicate), msg end end def refute_predicate(obj, predicate, msg=nil) if msg.nil? obj.should.not.public_send(predicate) else refute obj.__send__(predicate), msg end end def assert_raises(*exceptions, &block) msg = exceptions.last if String === exceptions.last if msg.nil? block.should.raise?(*exceptions) else assert block.raise?(*exceptions), msg end end alias_method :assert_raise, :assert_raises def refute_raises(msg=nil) msg = exceptions.last if String === exceptions.last if msg.nil? block.should.not.raise?(*exceptions) else refute block.raise?(*exceptions), msg end end alias_method :assert_nothing_raised, :refute_raises def assert_respond_to(obj, meth, msg=nil) if msg.nil? obj.should.respond_to?(meth) else assert obj.respond_to?(meth), msg end end def refute_respond_to(obj, meth, msg=nil) if msg.nil? obj.should.not.respond_to?(meth) else refute obj.respond_to?(meth), msg end end def assert_same(exp, act, msg=nil) if msg.nil? act.should.equal?(exp) else assert act.equal?(exp), msg end end def refute_same(exp, act, msg=nil) if msg.nil? act.should.not.equal?(exp) else refute act.equal?(exp), msg end end alias_method :assert_not_same, :refute_same def assert_send(send_ary, msg=nil) obj, meth, *args = send_ary if msg.nil? obj.should.public_send(meth, *args) else assert obj.__send__(meth, *args), msg end end def refute_send(send_ary, msg=nil) obj, meth, *args = send_ary if msg.nil? obj.should.not.public_send(meth, *args) else refute obj.__send__(meth, *args), msg end end alias_method :assert_not_send, :refute_send def assert_throws(tag, msg=nil, &block) if msg.nil? block.should.throw?(tag) else assert block.throw?(tag), msg end end def refute_throws(msg=nil) if msg.nil? block.should.not.throw?(tag) else refute block.throw?(tag), msg end end alias_method :assert_nothing_thrown, :refute_throws def assert_block(msg=nil, &block) if msg.nil? block.should.call else assert yield, msg end end end end end Negate expectation in refute_matcher MiniTest = Test = Module.new module MiniTest module Unit class TestCase # @see skip SKIP = Object.new # # Hooks to perform MiniTest -> MacBacon translations # def self.inherited(subclass) name = subclass.to_s.sub(/^Test/, '') context = describe name do before do @test_case = subclass.new @test_case.setup if @test_case.respond_to?(:setup) end after do @test_case.teardown if @test_case.respond_to?(:teardown) @test_case = nil end end subclass.instance_variable_set(:@context, context) end def self.method_added(meth) return unless meth =~ /^test_/ name = meth.sub(/^test_/, '').tr('_', ' ') @context.it name do skipped = catch SKIP do @test_case.__send__(meth) end if skipped Bacon::Counter[:requirements] += 1 # Convince Bacon that tests passed end end end # # Test control # def skip throw SKIP, true end def pass(_=nil) assert true end # # Assertions # # @see assert_operator UNDEFINED = Object.new def assert(test, msg=nil) if msg.nil? test.should.be.true? else Bacon::Should.new(nil).satisfy(msg) { test } end true end def refute(test, msg=nil) if msg.nil? test.should.be.false? else !assert(!test, msg) end end def assert_empty(obj, msg=nil) if msg.nil? obj.should.be.empty? else assert obj.empty?, msg end end def refute_empty(obj, msg=nil) if msg.nil? obj.should.not.be.empty? else refute obj.empty?, msg end end def assert_equal(exp, act, msg=nil) if msg.nil? act.should == exp else assert act == exp, msg end end def refute_equal(exp, act, msg=nil) if msg.nil? act.should != exp else refute act == exp, msg end end alias_method :assert_not_equal, :refute_equal def assert_in_delta(exp, act, delta=0.001, msg=nil) if msg.nil? act.should.be.close?(exp, delta) else assert delta >= (act-exp).abs, msg end end def refute_in_delta(exp, act, delta=0.001, msg=nil) if msg.nil? act.should.not.be.close?(exp, delta) else refute delta >= (act-exp).abs, msg end end def assert_in_epsilon(exp, act, epsilon=0.001, msg=nil) delta = epsilon * [exp.abs, act.abs].min assert_in_delta exp, act, delta, msg end def refute_in_epsilon(exp, act, epsilon=0.001, msg=nil) delta = epsilon * [exp.abs, act.abs].min refute_in_delta exp, act, delta, msg end def assert_includes(collection, obj, msg=nil) if msg.nil? collection.should.include?(obj) else assert collection.include?(obj), msg end end def refute_includes(collection, obj, msg=nil) if msg.nil? collection.should.not.include?(obj) else refute collection.include?(obj), msg end end def assert_instance_of(cls, obj, msg=nil) if msg.nil? obj.should.be.instance_of?(cls) else assert obj.instance_of?(cls), msg end end def refute_instance_of(cls, obj, msg=nil) if msg.nil? obj.should.not.be.instance_of?(cls) else refute obj.instance_of?(cls), msg end end def assert_kind_of(cls, obj, msg=nil) if msg.nil? obj.should.be.kind_of?(cls) else assert obj.kind_of?(cls), msg end end def refute_kind_of(cls, obj, msg=nil) if msg.nil? obj.should.not.be.kind_of?(cls) else refute obj.kind_of?(cls), msg end end def assert_match(matcher, obj, msg=nil) matcher = /#{Regexp.escape(matcher)}/ if String === matcher if msg.nil? obj.should =~ matcher else assert matcher =~ obj, msg end end def refute_match(matcher, obj, msg=nil) matcher = /#{Regexp.escape(matcher)}/ if String === matcher if msg.nil? obj.should.not =~ matcher else refute matcher =~ obj, msg end end alias_method :assert_no_match, :refute_match def assert_nil(obj, msg=nil) if msg.nil? obj.should.be.nil? else assert obj.nil?, msg end end def refute_nil(obj, msg=nil) if msg.nil? obj.should.not.be.nil? else refute obj.nil?, msg end end alias_method :assert_not_nil, :refute_nil def assert_operator(obj1, op, obj2=UNDEFINED, msg=nil) args = obj2 == UNDEFINED ? [op] : [op, obj2] if msg.nil? obj1.should.public_send(*args) else assert obj1.__send__(*args), msg end end def refute_operator(obj1, op, obj2=UNDEFINED, msg=nil) args = obj2 == UNDEFINED ? [op] : [op, obj2] if msg.nil? obj1.should.not.public_send(*args) else refute obj1.__send__(*args), msg end end def assert_output raise NotImplementedError end def assert_predicate(obj, predicate, msg=nil) if msg.nil? obj.should.public_send(predicate) else assert obj.__send__(predicate), msg end end def refute_predicate(obj, predicate, msg=nil) if msg.nil? obj.should.not.public_send(predicate) else refute obj.__send__(predicate), msg end end def assert_raises(*exceptions, &block) msg = exceptions.last if String === exceptions.last if msg.nil? block.should.raise?(*exceptions) else assert block.raise?(*exceptions), msg end end alias_method :assert_raise, :assert_raises def refute_raises(msg=nil) msg = exceptions.last if String === exceptions.last if msg.nil? block.should.not.raise?(*exceptions) else refute block.raise?(*exceptions), msg end end alias_method :assert_nothing_raised, :refute_raises def assert_respond_to(obj, meth, msg=nil) if msg.nil? obj.should.respond_to?(meth) else assert obj.respond_to?(meth), msg end end def refute_respond_to(obj, meth, msg=nil) if msg.nil? obj.should.not.respond_to?(meth) else refute obj.respond_to?(meth), msg end end def assert_same(exp, act, msg=nil) if msg.nil? act.should.equal?(exp) else assert act.equal?(exp), msg end end def refute_same(exp, act, msg=nil) if msg.nil? act.should.not.equal?(exp) else refute act.equal?(exp), msg end end alias_method :assert_not_same, :refute_same def assert_send(send_ary, msg=nil) obj, meth, *args = send_ary if msg.nil? obj.should.public_send(meth, *args) else assert obj.__send__(meth, *args), msg end end def refute_send(send_ary, msg=nil) obj, meth, *args = send_ary if msg.nil? obj.should.not.public_send(meth, *args) else refute obj.__send__(meth, *args), msg end end alias_method :assert_not_send, :refute_send def assert_throws(tag, msg=nil, &block) if msg.nil? block.should.throw?(tag) else assert block.throw?(tag), msg end end def refute_throws(msg=nil) if msg.nil? block.should.not.throw?(tag) else refute block.throw?(tag), msg end end alias_method :assert_nothing_thrown, :refute_throws def assert_block(msg=nil, &block) if msg.nil? block.should.call else assert yield, msg end end end end end
require "fileutils" require "language_pack" require "language_pack/rack" # Rails 2 Language Pack. This is for any Rails 2.x apps. class LanguagePack::Rails2 < LanguagePack::Ruby # detects if this is a valid Rails 2 app # @return [Boolean] true if it's a Rails 2 app def self.use? if gemfile_lock? rails_version = LanguagePack::Ruby.gem_version('railties') rails_version >= Gem::Version.new('2.0.0') && rails_version < Gem::Version.new('3.0.0') if rails_version end end def name "Ruby/Rails" end def default_config_vars super.merge({ "RAILS_ENV" => "production", "RACK_ENV" => "production" }) end def default_process_types web_process = gem_is_bundled?("thin") ? "bundle exec thin start -e $RAILS_ENV -p $PORT" : "bundle exec ruby script/server -p $PORT" super.merge({ "web" => web_process, "worker" => "bundle exec rake jobs:work", "console" => "bundle exec script/console" }) end def compile super install_plugins end private # list of plugins to be installed # @return [Array] resulting list in a String Array def plugins %w( rails_log_stdout ) end # the root path of where the plugins are to be installed from # @return [String] the resulting path def plugin_root File.expand_path("../../../vendor/plugins", __FILE__) end # vendors all the plugins into the slug def install_plugins topic "Rails plugin injection" plugins.each { |plugin| install_plugin(plugin) } end # vendors an individual plugin # @param [String] name of the plugin def install_plugin(name) plugin_dir = "vendor/plugins/#{name}" return if File.exist?(plugin_dir) puts "Injecting #{name}" FileUtils.mkdir_p plugin_dir Dir.chdir(plugin_dir) do |dir| run("curl #{VENDOR_URL}/#{name}.tgz -s -o - | tar xzf -") end end # most rails apps need a database # @return [Array] shared database addon def add_dev_database_addon ['heroku-postgresql:dev'] end # sets up the profile.d script for this buildpack def setup_profiled super set_env_default "RACK_ENV", "production" set_env_default "RAILS_ENV", "production" end end rails 2 doesn't have railties require "fileutils" require "language_pack" require "language_pack/rack" # Rails 2 Language Pack. This is for any Rails 2.x apps. class LanguagePack::Rails2 < LanguagePack::Ruby # detects if this is a valid Rails 2 app # @return [Boolean] true if it's a Rails 2 app def self.use? if gemfile_lock? rails_version = LanguagePack::Ruby.gem_version('rails') rails_version >= Gem::Version.new('2.0.0') && rails_version < Gem::Version.new('3.0.0') if rails_version end end def name "Ruby/Rails" end def default_config_vars super.merge({ "RAILS_ENV" => "production", "RACK_ENV" => "production" }) end def default_process_types web_process = gem_is_bundled?("thin") ? "bundle exec thin start -e $RAILS_ENV -p $PORT" : "bundle exec ruby script/server -p $PORT" super.merge({ "web" => web_process, "worker" => "bundle exec rake jobs:work", "console" => "bundle exec script/console" }) end def compile super install_plugins end private # list of plugins to be installed # @return [Array] resulting list in a String Array def plugins %w( rails_log_stdout ) end # the root path of where the plugins are to be installed from # @return [String] the resulting path def plugin_root File.expand_path("../../../vendor/plugins", __FILE__) end # vendors all the plugins into the slug def install_plugins topic "Rails plugin injection" plugins.each { |plugin| install_plugin(plugin) } end # vendors an individual plugin # @param [String] name of the plugin def install_plugin(name) plugin_dir = "vendor/plugins/#{name}" return if File.exist?(plugin_dir) puts "Injecting #{name}" FileUtils.mkdir_p plugin_dir Dir.chdir(plugin_dir) do |dir| run("curl #{VENDOR_URL}/#{name}.tgz -s -o - | tar xzf -") end end # most rails apps need a database # @return [Array] shared database addon def add_dev_database_addon ['heroku-postgresql:dev'] end # sets up the profile.d script for this buildpack def setup_profiled super set_env_default "RACK_ENV", "production" set_env_default "RAILS_ENV", "production" end end
require "language_pack" require "language_pack/rails2" # Rails 3 Language Pack. This is for all Rails 3.x apps. class LanguagePack::Rails3 < LanguagePack::Rails2 # detects if this is a Rails 3.x app # @return [Boolean] true if it's a Rails 3.x app def self.use? instrument "rails3.use" do rails_version = bundler.gem_version('railties') return false unless rails_version is_rails3 = rails_version >= Gem::Version.new('3.0.0') && rails_version < Gem::Version.new('4.0.0') return is_rails3 end end def name "Ruby/Rails" end def default_process_types instrument "rails3.default_process_types" do # let's special case thin here web_process = bundler.has_gem?("thin") ? "bundle exec thin start -R config.ru -e $RAILS_ENV -p $PORT" : "bundle exec rails server -p $PORT" super.merge({ "web" => web_process, "console" => "bundle exec rails console" }) end end def compile instrument "rails3.compile" do super end end private def install_plugins instrument "rails3.install_plugins" do return false if bundler.has_gem?('rails_12factor') plugins = {"rails_log_stdout" => "rails_stdout_logging", "rails3_serve_static_assets" => "rails_serve_static_assets" }. reject { |plugin, gem| bundler.has_gem?(gem) } return false if plugins.empty? plugins.each do |plugin, gem| warn "Injecting plugin '#{plugin}'" end warn "Add 'rails_12factor' gem to your Gemfile to skip plugin injection" LanguagePack::Helpers::PluginsInstaller.new(plugins.keys).install end end # runs the tasks for the Rails 3.1 asset pipeline def run_assets_precompile_rake_task instrument "rails3.run_assets_precompile_rake_task" do log("assets_precompile") do if File.exists?("public/assets/manifest.yml") puts "Detected manifest.yml, assuming assets were compiled locally" return true end precompile = rake.task("assets:precompile") return true unless precompile.is_defined? topic("Preparing app for Rails asset pipeline") puts "Loading assets from saved cache" FileUtils.mkdir_p('public') cache.load "public/assets" precompile.invoke(env: rake_env) if precompile.success? log "assets_precompile", :status => "success" puts "Asset precompilation completed (#{"%.2f" % precompile.time}s)" # If 'turbo-sprockets-rails3' gem is available, run 'assets:clean_expired' and # cache assets if task was successful. if bundler.has_gem?('turbo-sprockets-rails3') log("assets_clean_expired") do clean_expired_assets = `RAILS_GROUPS=assets bundle exec rake assets:clean_expired` if clean_expired_assets log "assets_clean_expired", :status => "success" cache.store "public/assets" else log "assets_clean_expired", :status => "failure" cache.clear "public/assets" end end else cache.clear "public/assets" end else precompile_fail(precompile.output) end end end end def rake_env if user_env_hash.empty? default_env = { "RAILS_GROUPS" => ENV["RAILS_GROUPS"] || "assets", "RAILS_ENV" => ENV["RAILS_ENV"] || "production", "DATABASE_URL" => database_url } else default_env = { "RAILS_GROUPS" => "assets", "RAILS_ENV" => "production", "DATABASE_URL" => database_url } end default_env.merge(user_env_hash) end # generate a dummy database_url def database_url instrument "rails3.setup_database_url_env" do # need to use a dummy DATABASE_URL here, so rails can load the environment return env("DATABASE_URL") if env("DATABASE_URL") scheme = if bundler.has_gem?("pg") || bundler.has_gem?("jdbc-postgres") "postgres" elsif bundler.has_gem?("mysql") "mysql" elsif bundler.has_gem?("mysql2") "mysql2" elsif bundler.has_gem?("sqlite3") || bundler.has_gem?("sqlite3-ruby") "sqlite3" end "#{scheme}://user:pass@127.0.0.1/dbname" end end end clean_expired require "language_pack" require "language_pack/rails2" # Rails 3 Language Pack. This is for all Rails 3.x apps. class LanguagePack::Rails3 < LanguagePack::Rails2 # detects if this is a Rails 3.x app # @return [Boolean] true if it's a Rails 3.x app def self.use? instrument "rails3.use" do rails_version = bundler.gem_version('railties') return false unless rails_version is_rails3 = rails_version >= Gem::Version.new('3.0.0') && rails_version < Gem::Version.new('4.0.0') return is_rails3 end end def name "Ruby/Rails" end def default_process_types instrument "rails3.default_process_types" do # let's special case thin here web_process = bundler.has_gem?("thin") ? "bundle exec thin start -R config.ru -e $RAILS_ENV -p $PORT" : "bundle exec rails server -p $PORT" super.merge({ "web" => web_process, "console" => "bundle exec rails console" }) end end def compile instrument "rails3.compile" do super end end private def install_plugins instrument "rails3.install_plugins" do return false if bundler.has_gem?('rails_12factor') plugins = {"rails_log_stdout" => "rails_stdout_logging", "rails3_serve_static_assets" => "rails_serve_static_assets" }. reject { |plugin, gem| bundler.has_gem?(gem) } return false if plugins.empty? plugins.each do |plugin, gem| warn "Injecting plugin '#{plugin}'" end warn "Add 'rails_12factor' gem to your Gemfile to skip plugin injection" LanguagePack::Helpers::PluginsInstaller.new(plugins.keys).install end end # runs the tasks for the Rails 3.1 asset pipeline def run_assets_precompile_rake_task instrument "rails3.run_assets_precompile_rake_task" do log("assets_precompile") do if File.exists?("public/assets/manifest.yml") puts "Detected manifest.yml, assuming assets were compiled locally" return true end precompile = rake.task("assets:precompile") return true unless precompile.is_defined? topic("Preparing app for Rails asset pipeline") puts "Loading assets from saved cache" FileUtils.mkdir_p('public') cache.load "public/assets" precompile.invoke(env: rake_env) if precompile.success? log "assets_precompile", :status => "success" puts "Asset precompilation completed (#{"%.2f" % precompile.time}s)" # If 'turbo-sprockets-rails3' gem is available, run 'assets:clean_expired' and # cache assets if task was successful. if bundler.has_gem?('turbo-sprockets-rails3') log("assets_clean_expired") do clean_expired_assets = `cd && RAILS_GROUPS=assets bundle exec rake assets:clean_expired` if clean_expired_assets log "assets_clean_expired", :status => "success" cache.store "public/assets" else log "assets_clean_expired", :status => "failure" cache.clear "public/assets" end end else cache.clear "public/assets" end else precompile_fail(precompile.output) end end end end def rake_env if user_env_hash.empty? default_env = { "RAILS_GROUPS" => ENV["RAILS_GROUPS"] || "assets", "RAILS_ENV" => ENV["RAILS_ENV"] || "production", "DATABASE_URL" => database_url } else default_env = { "RAILS_GROUPS" => "assets", "RAILS_ENV" => "production", "DATABASE_URL" => database_url } end default_env.merge(user_env_hash) end # generate a dummy database_url def database_url instrument "rails3.setup_database_url_env" do # need to use a dummy DATABASE_URL here, so rails can load the environment return env("DATABASE_URL") if env("DATABASE_URL") scheme = if bundler.has_gem?("pg") || bundler.has_gem?("jdbc-postgres") "postgres" elsif bundler.has_gem?("mysql") "mysql" elsif bundler.has_gem?("mysql2") "mysql2" elsif bundler.has_gem?("sqlite3") || bundler.has_gem?("sqlite3-ruby") "sqlite3" end "#{scheme}://user:pass@127.0.0.1/dbname" end end end
require 'yaml' require 'erb' require 'fileutils' require 'basic_app/extensions/hash' module BasicApp # Access setting via symbolized keys or using accessor methods # # @example # # settings = Settings.new(FileUtils.pwd, {:config => 'some/file.yml'}) # # verbose = settings.to_hash[:options] ? settings.to_hash[:options][:verbose] : false # # equivalent to: # # verbose = settings.options ? settings.options.verbose : false # # @return [Hash], for pure hash use 'to_hash' instead class Settings < Hash include BasicApp::Extensions::MethodReader include BasicApp::Extensions::MethodWriter def initialize(working_dir=nil, options={}) @working_dir = working_dir || FileUtils.pwd @configuration = configure(options) # call super without args super *[] self.merge!(@configuration) end private # read options from YAML config def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO' } } # set default config if not given on command line config = options[:config] if config.nil? config = [ File.join(@working_dir, "basic_app.conf"), File.join(@working_dir, ".basic_app.conf"), File.join(@working_dir, "basic_app", "basic_app.conf"), File.join(@working_dir, ".basic_app", "basic_app.conf"), File.expand_path(File.join("~", ".basic_app.conf")), File.expand_path(File.join("~", "basic_app.conf")), File.expand_path(File.join("~", "basic_app", "basic_app.conf")), File.expand_path(File.join("~", ".basic_app", "basic_app.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # load options from the config file, overwriting hard-coded defaults logger.debug "reading configuration file: #{config}" config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if options[:config] end # store the original full config filename for later use configuration[:configuration_filename] = config configuration.recursively_symbolize_keys! # the command line options override options read from the config file configuration[:options].merge!(options) configuration end end end add 'config/basic_app.conf' to setttings search path require 'yaml' require 'erb' require 'fileutils' require 'basic_app/extensions/hash' module BasicApp # Access setting via symbolized keys or using accessor methods # # @example # # settings = Settings.new(FileUtils.pwd, {:config => 'some/file.yml'}) # # verbose = settings.to_hash[:options] ? settings.to_hash[:options][:verbose] : false # # equivalent to: # # verbose = settings.options ? settings.options.verbose : false # # @return [Hash], for pure hash use 'to_hash' instead class Settings < Hash include BasicApp::Extensions::MethodReader include BasicApp::Extensions::MethodWriter def initialize(working_dir=nil, options={}) @working_dir = working_dir || FileUtils.pwd @configuration = configure(options) # call super without args super *[] self.merge!(@configuration) end private # read options from YAML config def configure(options) # config file default options configuration = { :options => { :verbose => false, :color => 'AUTO' } } # set default config if not given on command line config = options[:config] if config.nil? config = [ File.join(@working_dir, "basic_app.conf"), File.join(@working_dir, ".basic_app.conf"), File.join(@working_dir, "basic_app", "basic_app.conf"), File.join(@working_dir, ".basic_app", "basic_app.conf"), File.join(@working_dir, "config", "basic_app.conf"), File.expand_path(File.join("~", ".basic_app.conf")), File.expand_path(File.join("~", "basic_app.conf")), File.expand_path(File.join("~", "basic_app", "basic_app.conf")), File.expand_path(File.join("~", ".basic_app", "basic_app.conf")) ].detect { |filename| File.exists?(filename) } end if config && File.exists?(config) # load options from the config file, overwriting hard-coded defaults logger.debug "reading configuration file: #{config}" config_contents = YAML.load(ERB.new(File.open(config, "rb").read).result) configuration.merge!(config_contents.symbolize_keys!) if config_contents && config_contents.is_a?(Hash) else # user specified a config file?, no error if user did not specify config file raise "config file not found" if options[:config] end # store the original full config filename for later use configuration[:configuration_filename] = config configuration.recursively_symbolize_keys! # the command line options override options read from the config file configuration[:options].merge!(options) configuration end end end
module Basil module Dispatchable def dispatch(server) msg = to_message msg.server = server logger.debug "Dispatching #{msg}" ChatHistory.store_message(msg) unless msg.chat.nil? each_plugin do |plugin| begin if match_data = match?(plugin) logger.debug "Executing #{plugin}" plugin.set_context(msg, match_data) plugin.execute end rescue => ex logger.warn ex end end end def match?(plugin) raise NotImplementedError, "#{self.class} must implement #{__method__}" end def each_plugin(&block) raise NotImplementedError, "#{self.class} must implement #{__method__}" end def to_message raise NotImplementedError, "#{self.class} must implement #{__method__}" end private def logger @logger ||= Loggers['dispatching'] end end end work around ruby-skype module Basil module Dispatchable def dispatch(server) msg = to_message # we must store message before setting server, something about the # Skype object doesn't agree with PStore ChatHistory.store_message(msg) unless msg.chat.nil? msg.server = server logger.debug "Dispatching #{msg}" each_plugin do |plugin| begin if match_data = match?(plugin) logger.debug "Executing #{plugin}" plugin.set_context(msg, match_data) plugin.execute end rescue => ex logger.warn ex end end end def match?(plugin) raise NotImplementedError, "#{self.class} must implement #{__method__}" end def each_plugin(&block) raise NotImplementedError, "#{self.class} must implement #{__method__}" end def to_message raise NotImplementedError, "#{self.class} must implement #{__method__}" end private def logger @logger ||= Loggers['dispatching'] end end end
module BceClient VERSION = '0.1.6' end version bump to 0.1.7 module BceClient VERSION = '0.1.7' end
# The MIT License (MIT) # # Copyright (c) 2016 Sylvain Daubert # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'acme-client' require_relative 'loggable' # rubocop:disable Metrics/ClassLength, Style/MultilineBlockLayout # rubocop:disable Style/BlockEndNewline, Style/BlockDelimiters module LetsCert # Class to handle ACME operations on certificates # @author Sylvain Daubert class Certificate include Loggable # @return [OpenSSL::X509::Certificate,nil] attr_reader :cert # Certification chain. Only set by {#get}. # @return [Array<OpenSSL::X509::Certificate>] attr_reader :chain # @return [Acme::Client,nil] attr_reader :client # @param [OpenSSL::X509::Certificate,nil] cert def initialize(cert) @cert = cert @chain = [] end # Get a new certificate, or renew an existing one # @param [OpenSSL::PKey::PKey,nil] account_key private key to # authenticate to ACME server # @param [OpenSSL::PKey::PKey, nil] key private key from which make a # certificate. If +nil+, generate a new one with +options[:cet_key_size]+ # bits. # @param [Hash] options option hash # @option options [Fixnum] :account_key_size ACME account private key size # in bits # @option options [Fixnum] :cert_key_size private key size used to generate # a certificate # @option options [String] :email e-mail used as ACME account # @option options [Array<String>] :files plugin names to use # @option options [Boolean] :reuse_key reuse private key when getting a new # certificate # @option options [Hash] :roots hash associating domains as keys to web # roots as values # @option options [String] :server ACME servel URL # @return [void] # @raise [Acme::Client::Error] error in protocol ACME with server # @raise [Error] issue with domain name, challenge fails,... def get(account_key, key, options) logger.info { 'create key/cert/chain...' } check_roots(options[:roots]) logger.debug { "webroots are: #{options[:roots].inspect}" } client = get_acme_client(account_key, options) do_challenges client, options[:roots] pkey = if options[:reuse_key] raise Error, 'cannot reuse a non-existing key' if key.nil? logger.info { 'Reuse existing private key' } generate_certificate_from_pkey options[:roots].keys, key else logger.info { 'Generate new private key' } generate_certificate options[:roots].keys, options[:cert_key_size] end options[:files] ||= [] options[:files].each do |plugname| IOPlugin.registered[plugname].save(account_key: client.private_key, key: pkey, cert: @cert, chain: @chain) end end # Revoke certificate # @param [OpenSSL::PKey::PKey] account_key # @param [Hash] options # @option options [Fixnum] :account_key_size ACME account private key size # in bits # @option options [String] :email e-mail used as ACME account # @option options [String] :server ACME servel URL # @return [Boolean] # @raise [Error] no certificate to revole. def revoke(account_key, options = {}) raise Error, 'no certification data to revoke' if @cert.nil? client = get_acme_client(account_key, options) result = client.revoke_certificate(@cert) if result logger.info { 'certificate is revoked' } else logger.warn { 'certificate is not revoked!' } end result end # Check if certificate is still valid for at least +valid_min+ seconds. # Also checks that +domains+ are certified by certificate. # @param [Array<String>] domains list of certificate domains # @param [Integer] valid_min minimum number of seconds of validity under # which a renewal is necessary. # @return [Boolean] def valid?(domains, valid_min = 0) if @cert.nil? logger.debug { 'no existing certificate' } return false end subjects = [] @cert.extensions.each do |ext| if ext.oid == 'subjectAltName' subjects += ext.value.split(/,\s*/).map { |s| s.sub(/DNS:/, '') } end end logger.debug { "cert SANs: #{subjects.join(', ')}" } # Check all domains are subjects of certificate unless domains.all? { |domain| subjects.include? domain } msg = 'At least one domain is not declared as a certificate subject. ' \ 'Backup and remove existing cert if you want to proceed.' raise Error, msg end !renewal_necessary?(valid_min) end # Get ACME client. # # Client is only created on first call, then it is cached. # @param [Hash] account_key # @param [Hash] options # @return [Acme::Client] def get_acme_client(account_key, options) return @client if @client key = get_account_key(account_key, options[:account_key_size]) logger.debug { "connect to #{options[:server]}" } @client = Acme::Client.new(private_key: key, endpoint: options[:server]) yield @client if block_given? if options[:email].nil? logger.warn { '--email was not provided. ACME CA will have no way to ' \ 'contact you!' } end begin logger.debug { "register with #{options[:email]}" } registration = @client.register(contact: "mailto:#{options[:email]}") rescue Acme::Client::Error::Malformed => ex raise if ex.message != 'Registration key is already in use' else # Requesting ToS make acme-client throw an exception: Connection reset # by peer (Faraday::ConnectionFailed). To investigate... #if registration.term_of_service_uri # @logger.debug { "get terms of service" } # terms = registration.get_terms # if !terms.nil? # tos_digest = OpenSSL::Digest::SHA256.digest(terms) # if tos_digest != @options[:tos_sha256] # raise Error, 'Terms Of Service mismatch' # end @logger.debug { 'agree terms of service' } registration.agree_terms # end #end end @client end private # check webroots. # @param [Hash] roots # @raise [Error] if some domains have no defined root. def check_roots(roots) no_roots = roots.select { |_k, v| v.nil? } unless no_roots.empty? raise Error, 'root for the following domain(s) are not specified: ' \ "#{no_roots.keys.join(', ')}.\nTry --default_root or " \ 'use -d example.com:/var/www/html syntax.' end end # Generate a new account key if no one is given in +data+ # @param [OpenSSL::PKey,nil] key # @param [Integer] key_size # @return [OpenSSL::PKey::PKey] def get_account_key(key, key_size) if key.nil? logger.info { 'No account key. Generate a new one...' } OpenSSL::PKey::RSA.new(key_size) else key end end # Do ACME challenges for each requested domain. # @param [Acme::Client] client # @param [Hash] roots def do_challenges(client, roots) logger.debug { 'Get authorization for all domains' } challenges = get_challenges(client, roots) challenges.each do |domain, challenge| begin path = File.join(roots[domain], File.dirname(challenge.filename)) FileUtils.mkdir_p path rescue SystemCallError => ex raise Error, ex.message end path = File.join(roots[domain], challenge.filename) logger.debug { "Save validation #{challenge.file_content} to #{path}" } File.write path, challenge.file_content challenge.request_verification wait_for_verification challenge, domain File.unlink path end end # Get challenges # @param [Acme::Client] client # @param [Hash] roots # @return [Hash] key: domain, value: authorization # @raise [Error] if any challenges does not support HTTP-01 def get_challenges(client, roots) challenges = {} roots.keys.each do |domain| authorization = client.authorize(domain: domain) challenges[domain] = authorization ? authorization.http01 : nil end logger.debug { 'Check all challenges are HTTP-01' } if challenges.values.any?(&:nil?) raise Error, 'CA did not offer http-01-only challenge. ' \ 'This client is unable to solve any other challenges.' end challenges end def wait_for_verification(challenge, domain) status = 'pending' while status == 'pending' sleep(1) status = challenge.verify_status end if status != 'valid' logger.warn { "#{domain} was not successfully verified!" } else logger.info { "#{domain} was successfully verified." } end end # Check if a renewal is necessary # @param [Number] valid_min minimum validity in seconds to ensure # @return [Boolean] def renewal_necessary?(valid_min) now = Time.now.utc diff = (@cert.not_after - now).to_i logger.debug { "Certificate expires in #{diff}s on #{@cert.not_after}" \ " (relative to #{now})" } diff < valid_min end # Generate new certificate for given domains with existing private key # @param [Array<String>] domains # @param [OpenSSL::PKey::PKey] pkey private key to use # @return [OpenSSL::PKey::PKey] +pkey+ def generate_certificate_from_pkey(domains, pkey) csr = Acme::Client::CertificateRequest.new(names: domains, private_key: pkey) acme_cert = client.new_certificate(csr) @cert = acme_cert.x509 @chain = acme_cert.x509_chain pkey end # Generate new certificate for given domains # @param [Array<String>] domains # @param [Integer] pkey_size size in bits for private key to generate # @return [OpenSSL::PKey::PKey] generated private key def generate_certificate(domains, pkey_size) pkey = OpenSSL::PKey::RSA.generate(pkey_size) generate_certificate_from_pkey domains, pkey end end end Certificate#renewal_necessary?: use ValidTime.time_in_words in log # The MIT License (MIT) # # Copyright (c) 2016 Sylvain Daubert # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'acme-client' require_relative 'loggable' # rubocop:disable Metrics/ClassLength, Style/MultilineBlockLayout # rubocop:disable Style/BlockEndNewline, Style/BlockDelimiters module LetsCert # Class to handle ACME operations on certificates # @author Sylvain Daubert class Certificate include Loggable # @return [OpenSSL::X509::Certificate,nil] attr_reader :cert # Certification chain. Only set by {#get}. # @return [Array<OpenSSL::X509::Certificate>] attr_reader :chain # @return [Acme::Client,nil] attr_reader :client # @param [OpenSSL::X509::Certificate,nil] cert def initialize(cert) @cert = cert @chain = [] end # Get a new certificate, or renew an existing one # @param [OpenSSL::PKey::PKey,nil] account_key private key to # authenticate to ACME server # @param [OpenSSL::PKey::PKey, nil] key private key from which make a # certificate. If +nil+, generate a new one with +options[:cet_key_size]+ # bits. # @param [Hash] options option hash # @option options [Fixnum] :account_key_size ACME account private key size # in bits # @option options [Fixnum] :cert_key_size private key size used to generate # a certificate # @option options [String] :email e-mail used as ACME account # @option options [Array<String>] :files plugin names to use # @option options [Boolean] :reuse_key reuse private key when getting a new # certificate # @option options [Hash] :roots hash associating domains as keys to web # roots as values # @option options [String] :server ACME servel URL # @return [void] # @raise [Acme::Client::Error] error in protocol ACME with server # @raise [Error] issue with domain name, challenge fails,... def get(account_key, key, options) logger.info { 'create key/cert/chain...' } check_roots(options[:roots]) logger.debug { "webroots are: #{options[:roots].inspect}" } client = get_acme_client(account_key, options) do_challenges client, options[:roots] pkey = if options[:reuse_key] raise Error, 'cannot reuse a non-existing key' if key.nil? logger.info { 'Reuse existing private key' } generate_certificate_from_pkey options[:roots].keys, key else logger.info { 'Generate new private key' } generate_certificate options[:roots].keys, options[:cert_key_size] end options[:files] ||= [] options[:files].each do |plugname| IOPlugin.registered[plugname].save(account_key: client.private_key, key: pkey, cert: @cert, chain: @chain) end end # Revoke certificate # @param [OpenSSL::PKey::PKey] account_key # @param [Hash] options # @option options [Fixnum] :account_key_size ACME account private key size # in bits # @option options [String] :email e-mail used as ACME account # @option options [String] :server ACME servel URL # @return [Boolean] # @raise [Error] no certificate to revole. def revoke(account_key, options = {}) raise Error, 'no certification data to revoke' if @cert.nil? client = get_acme_client(account_key, options) result = client.revoke_certificate(@cert) if result logger.info { 'certificate is revoked' } else logger.warn { 'certificate is not revoked!' } end result end # Check if certificate is still valid for at least +valid_min+ seconds. # Also checks that +domains+ are certified by certificate. # @param [Array<String>] domains list of certificate domains # @param [Integer] valid_min minimum number of seconds of validity under # which a renewal is necessary. # @return [Boolean] def valid?(domains, valid_min = 0) if @cert.nil? logger.debug { 'no existing certificate' } return false end subjects = [] @cert.extensions.each do |ext| if ext.oid == 'subjectAltName' subjects += ext.value.split(/,\s*/).map { |s| s.sub(/DNS:/, '') } end end logger.debug { "cert SANs: #{subjects.join(', ')}" } # Check all domains are subjects of certificate unless domains.all? { |domain| subjects.include? domain } msg = 'At least one domain is not declared as a certificate subject. ' \ 'Backup and remove existing cert if you want to proceed.' raise Error, msg end !renewal_necessary?(valid_min) end # Get ACME client. # # Client is only created on first call, then it is cached. # @param [Hash] account_key # @param [Hash] options # @return [Acme::Client] def get_acme_client(account_key, options) return @client if @client key = get_account_key(account_key, options[:account_key_size]) logger.debug { "connect to #{options[:server]}" } @client = Acme::Client.new(private_key: key, endpoint: options[:server]) yield @client if block_given? if options[:email].nil? logger.warn { '--email was not provided. ACME CA will have no way to ' \ 'contact you!' } end begin logger.debug { "register with #{options[:email]}" } registration = @client.register(contact: "mailto:#{options[:email]}") rescue Acme::Client::Error::Malformed => ex raise if ex.message != 'Registration key is already in use' else # Requesting ToS make acme-client throw an exception: Connection reset # by peer (Faraday::ConnectionFailed). To investigate... #if registration.term_of_service_uri # @logger.debug { "get terms of service" } # terms = registration.get_terms # if !terms.nil? # tos_digest = OpenSSL::Digest::SHA256.digest(terms) # if tos_digest != @options[:tos_sha256] # raise Error, 'Terms Of Service mismatch' # end @logger.debug { 'agree terms of service' } registration.agree_terms # end #end end @client end private # check webroots. # @param [Hash] roots # @raise [Error] if some domains have no defined root. def check_roots(roots) no_roots = roots.select { |_k, v| v.nil? } unless no_roots.empty? raise Error, 'root for the following domain(s) are not specified: ' \ "#{no_roots.keys.join(', ')}.\nTry --default_root or " \ 'use -d example.com:/var/www/html syntax.' end end # Generate a new account key if no one is given in +data+ # @param [OpenSSL::PKey,nil] key # @param [Integer] key_size # @return [OpenSSL::PKey::PKey] def get_account_key(key, key_size) if key.nil? logger.info { 'No account key. Generate a new one...' } OpenSSL::PKey::RSA.new(key_size) else key end end # Do ACME challenges for each requested domain. # @param [Acme::Client] client # @param [Hash] roots def do_challenges(client, roots) logger.debug { 'Get authorization for all domains' } challenges = get_challenges(client, roots) challenges.each do |domain, challenge| begin path = File.join(roots[domain], File.dirname(challenge.filename)) FileUtils.mkdir_p path rescue SystemCallError => ex raise Error, ex.message end path = File.join(roots[domain], challenge.filename) logger.debug { "Save validation #{challenge.file_content} to #{path}" } File.write path, challenge.file_content challenge.request_verification wait_for_verification challenge, domain File.unlink path end end # Get challenges # @param [Acme::Client] client # @param [Hash] roots # @return [Hash] key: domain, value: authorization # @raise [Error] if any challenges does not support HTTP-01 def get_challenges(client, roots) challenges = {} roots.keys.each do |domain| authorization = client.authorize(domain: domain) challenges[domain] = authorization ? authorization.http01 : nil end logger.debug { 'Check all challenges are HTTP-01' } if challenges.values.any?(&:nil?) raise Error, 'CA did not offer http-01-only challenge. ' \ 'This client is unable to solve any other challenges.' end challenges end def wait_for_verification(challenge, domain) status = 'pending' while status == 'pending' sleep(1) status = challenge.verify_status end if status != 'valid' logger.warn { "#{domain} was not successfully verified!" } else logger.info { "#{domain} was successfully verified." } end end # Check if a renewal is necessary # @param [Number] valid_min minimum validity in seconds to ensure # @return [Boolean] def renewal_necessary?(valid_min) now = Time.now.utc diff = (@cert.not_after - now).to_i if diff < valid_min true else logger.info { "Certificate expires in #{ValidTime.time_in_words diff}" \ " on #{@cert.not_after} (relative to #{now})" } false end end # Generate new certificate for given domains with existing private key # @param [Array<String>] domains # @param [OpenSSL::PKey::PKey] pkey private key to use # @return [OpenSSL::PKey::PKey] +pkey+ def generate_certificate_from_pkey(domains, pkey) csr = Acme::Client::CertificateRequest.new(names: domains, private_key: pkey) acme_cert = client.new_certificate(csr) @cert = acme_cert.x509 @chain = acme_cert.x509_chain pkey end # Generate new certificate for given domains # @param [Array<String>] domains # @param [Integer] pkey_size size in bits for private key to generate # @return [OpenSSL::PKey::PKey] generated private key def generate_certificate(domains, pkey_size) pkey = OpenSSL::PKey::RSA.generate(pkey_size) generate_certificate_from_pkey domains, pkey end end end
module Libis module Format VERSION = '0.9.3' end end Bump version: 0.9.3 module Libis module Format VERSION = '0.9.4' end end
require 'lita' require 'clever-api' require 'uri' module Lita module Handlers class Clever < Handler route(%r{^([\w .-_]+)$}i, :clever, command: true, help: { 'clever' => 'Initializes clever.' }) def self.default_config(handler_config) end def clever(response) @@client ||= ::CleverBot.new response.reply CGI.unescapeHTML(@@client.think(response.matches[0][0])) end end Lita.register_handler(Clever) end end simpler regexp require 'lita' require 'clever-api' require 'uri' module Lita module Handlers class Clever < Handler route(/.+/, :clever, command: true, help: { 'clever' => 'Initializes clever.' }) def self.default_config(handler_config) end def clever(response) @@client ||= ::CleverBot.new response.reply CGI.unescapeHTML(@@client.think(response.matches[0][0])) end end Lita.register_handler(Clever) end end
module MailAddress class Address def initialize(phrase, address, comment) @phrase = phrase @address = address @comment = comment end attr_accessor :phrase, :address, :comment ATEXT = '[\-\w !#$%&\'*+/=?^`{|}~]' def format addr = [] if !@phrase.nil? && @phrase.length > 0 then addr.push( @phrase.match(/^(?:\s*#{ATEXT}\s*)+$/) ? @phrase : @phrase.match(/(?<!\\)"/) ? @phrase : %Q("#{@phrase}") ) addr.push "<#{@address}>" if !@address.nil? && @address.length > 0 elsif !@address.nil? && @address.length > 0 then addr.push(@address) end if (!@comment.nil? && @comment.match(/\S/)) then @comment.sub!(/^\s*\(?/, '(') @comment.sub!(/\)?\s*$/, ')') end addr.push(@comment) if !@comment.nil? && @comment.length > 0 addr.join(' ') end def name phrase = @phrase addr = @address phrase = @comment unless !phrase.nil? && phrase.length > 0 name = Address._extract_name(phrase) # first.last@domain address if (name == '') && (md = addr.match(/([^\%\.\@_]+([\._][^\%\.\@_]+)+)[\@\%]/)) then name = md[1] name.gsub!(/[\._]+/, ' ') name = Address._extract_name name end if (name == '' && addr.match(%r{/g=}i)) then # X400 style address f = addr.match(%r{g=([^/]*)}i) l = addr.match(%r{s=([^/]*)}i) name = Address._extract_name "#{f[1]} #{l[1]}" end name.length > 0 ? name : nil end def host addr = @address || ''; i = addr.rindex('@') i >= 0 ? addr[i + 1 .. -1] : nil end def user addr = @address || ''; i = addr.rindex('@') i >= 0 ? addr[0 ... i] : addr end private # given a comment, attempt to extract a person's name def self._extract_name(name) # This function can be called as method as well return '' if name.nil? || name == '' # Using encodings, too hard. See Mail::Message::Field::Full. return '' if name.match(/\=\?.*?\?\=/) # trim whitespace name.sub!(/^\s+/, '') name.sub!(/\s+$/, '') name.sub!(/\s+/, ' ') # Disregard numeric names (e.g. 123456.1234@compuserve.com) return "" if name.match(/^[\d ]+$/) name.sub!(/^\((.*)\)$/, '\1') # remove outermost parenthesis name.sub!(/^"(.*)"$/, '\1') # remove outer quotation marks name.gsub!(/\(.*?\)/, '') # remove minimal embedded comments name.gsub!(/\\/, '') # remove all escapes name.sub!(/^"(.*)"$/, '\1') # remove internal quotation marks name.sub!(/^([^\s]+) ?, ?(.*)$/, '\2 \1') # reverse "Last, First M." if applicable name.sub!(/,.*/, '') # Change casing only when the name contains only upper or only # lower cased characters. unless ( name.match(/[A-Z]/) && name.match(/[a-z]/) ) then # Set the case of the name to first char upper rest lower name.gsub!(/\b(\w+)/io) {|w| $1.capitalize } # Upcase first letter on name name.gsub!(/\bMc(\w)/io) { |w| "Mc#{$1.capitalize}" } # Scottish names such as 'McLeod' name.gsub!(/\bo'(\w)/io) { |w| "O'#{$1.capitalize}" } # Irish names such as 'O'Malley, O'Reilly' name.gsub!(/\b(x*(ix)?v*(iv)?i*)\b/io) { |w| $1.upcase } # Roman numerals, eg 'Level III Support' end # some cleanup name.gsub!(/\[[^\]]*\]/, '') name.gsub!(/(^[\s'"]+|[\s'"]+$)/, '') name.gsub!(/\s{2,}/, ' ') name end end end copy object module MailAddress class Address def initialize(phrase, address, comment) @phrase = phrase @address = address @comment = comment end attr_accessor :phrase, :address, :comment ATEXT = '[\-\w !#$%&\'*+/=?^`{|}~]' def format addr = [] if !@phrase.nil? && @phrase.length > 0 then addr.push( @phrase.match(/^(?:\s*#{ATEXT}\s*)+$/) ? @phrase : @phrase.match(/(?<!\\)"/) ? @phrase : %Q("#{@phrase}") ) addr.push "<#{@address}>" if !@address.nil? && @address.length > 0 elsif !@address.nil? && @address.length > 0 then addr.push(@address) end if (!@comment.nil? && @comment.match(/\S/)) then @comment.sub!(/^\s*\(?/, '(') @comment.sub!(/\)?\s*$/, ')') end addr.push(@comment) if !@comment.nil? && @comment.length > 0 addr.join(' ') end def name phrase = @phrase.dup addr = @address.dup phrase = @comment.dup unless !phrase.nil? && phrase.length > 0 name = Address._extract_name(phrase) # first.last@domain address if (name == '') && (md = addr.match(/([^\%\.\@_]+([\._][^\%\.\@_]+)+)[\@\%]/)) then name = md[1] name.gsub!(/[\._]+/, ' ') name = Address._extract_name name end if (name == '' && addr.match(%r{/g=}i)) then # X400 style address f = addr.match(%r{g=([^/]*)}i) l = addr.match(%r{s=([^/]*)}i) name = Address._extract_name "#{f[1]} #{l[1]}" end name.length > 0 ? name : nil end def host addr = @address || ''; i = addr.rindex('@') i >= 0 ? addr[i + 1 .. -1] : nil end def user addr = @address || ''; i = addr.rindex('@') i >= 0 ? addr[0 ... i] : addr end private # given a comment, attempt to extract a person's name def self._extract_name(name) # This function can be called as method as well return '' if name.nil? || name == '' # Using encodings, too hard. See Mail::Message::Field::Full. return '' if name.match(/\=\?.*?\?\=/) # trim whitespace name.sub!(/^\s+/, '') name.sub!(/\s+$/, '') name.sub!(/\s+/, ' ') # Disregard numeric names (e.g. 123456.1234@compuserve.com) return "" if name.match(/^[\d ]+$/) name.sub!(/^\((.*)\)$/, '\1') # remove outermost parenthesis name.sub!(/^"(.*)"$/, '\1') # remove outer quotation marks name.gsub!(/\(.*?\)/, '') # remove minimal embedded comments name.gsub!(/\\/, '') # remove all escapes name.sub!(/^"(.*)"$/, '\1') # remove internal quotation marks name.sub!(/^([^\s]+) ?, ?(.*)$/, '\2 \1') # reverse "Last, First M." if applicable name.sub!(/,.*/, '') # Change casing only when the name contains only upper or only # lower cased characters. unless ( name.match(/[A-Z]/) && name.match(/[a-z]/) ) then # Set the case of the name to first char upper rest lower name.gsub!(/\b(\w+)/io) {|w| $1.capitalize } # Upcase first letter on name name.gsub!(/\bMc(\w)/io) { |w| "Mc#{$1.capitalize}" } # Scottish names such as 'McLeod' name.gsub!(/\bo'(\w)/io) { |w| "O'#{$1.capitalize}" } # Irish names such as 'O'Malley, O'Reilly' name.gsub!(/\b(x*(ix)?v*(iv)?i*)\b/io) { |w| $1.upcase } # Roman numerals, eg 'Level III Support' end # some cleanup name.gsub!(/\[[^\]]*\]/, '') name.gsub!(/(^[\s'"]+|[\s'"]+$)/, '') name.gsub!(/\s{2,}/, ' ') name end end end
require "yaml" require "set" require "manifests-vmc-plugin/loader" module VMCManifests MANIFEST_FILE = "manifest.yml" @@showed_manifest_usage = false def manifest return @manifest if @manifest if manifest_file && File.exists?(manifest_file) @manifest = load_manifest(manifest_file) end end def save_manifest(save_to = manifest_file) fail "No manifest to save!" unless @manifest File.open(save_to, "w") do |io| YAML.dump(@manifest, io) end end # find the manifest file to work with def manifest_file return @manifest_file if @manifest_file unless path = input[:manifest] where = Dir.pwd while true if File.exists?(File.join(where, MANIFEST_FILE)) path = File.join(where, MANIFEST_FILE) break elsif File.basename(where) == "/" path = nil break else where = File.expand_path("../", where) end end end return unless path @manifest_file = File.expand_path(path) end # load and resolve a given manifest file def load_manifest(file) Loader.new(file, self).manifest end # dynamic symbol resolution def resolve_symbol(sym) case sym when "target-url" client_target when "target-base" target_base when "random-word" sprintf("%04x", rand(0x0100000)) when /^ask (.+)/ ask($1) end end # find an app by its unique tag def app_by_tag(tag) manifest[:applications][tag] end # find apps by an identifier, which may be either a tag, a name, or a path def find_apps(identifier) return [] unless manifest if app = app_by_tag(identifier) return [app] end apps = apps_by(:name, identifier) if apps.empty? apps = apps_by(:path, from_manifest(identifier)) end apps end # call a block for each app in a manifest (in dependency order), setting # inputs for each app def each_app(&blk) return unless manifest ordered_by_deps(manifest[:applications]).each(&blk) end # return all the apps described by the manifest, in dependency order def all_apps apps = [] each_app do |app| apps << app end apps end # like each_app, but only acts on apps specified as paths instead of names # # returns the names that were not paths def specific_apps_or_all(input = nil, use_name = true, &blk) names_or_paths = if input.given?(:apps) # names may be given but be [], which will still cause # interaction, so use #given instead of #[] here input.given(:apps) elsif input.given?(:app) [input[:app]] else [] end input = input.without(:app, :apps) in_manifest = [] if names_or_paths.empty? apps = find_apps(Dir.pwd) if !apps.empty? in_manifest += apps else each_app(&blk) return [] end end external = [] names_or_paths.each do |x| if x.is_a?(String) path = File.expand_path(x) apps = find_apps(File.exists?(path) ? path : x) if !apps.empty? in_manifest += apps elsif app = client.app_by_name(x) external << app else fail("Unknown app '#{x}'") end else external << x end end in_manifest.each do |app| blk.call app end external end def create_manifest_for(app, path) meta = { "name" => app.name, "framework" => app.framework.name, "runtime" => app.runtime.name, "memory" => human_size(app.memory * 1024 * 1024, 0), "instances" => app.total_instances, "url" => app.url ? app.url.sub(target_base, '${target-base}') : "none", "path" => path } services = app.services unless services.empty? meta["services"] = {} services.each do |i| if v2? p = i.service_plan s = p.service meta["services"][i.name] = { "label" => s.label, "provider" => s.provider, "version" => s.version, "plan" => p.name } else meta["services"][i.name] = { "vendor" => i.vendor, "version" => i.version, "tier" => i.tier } end end end if cmd = app.command meta["command"] = cmd end meta end private def show_manifest_usage return if @@showed_manifest_usage path = Pathname.new(manifest_file).relative_path_from(Pathname.pwd) line "Using manifest file #{c(path, :name)}" line @@showed_manifest_usage = true end def no_apps fail "No applications or manifest to operate on." end def apps_by(attr, val) found = [] manifest[:applications].each do |tag, info| if info[attr] == val found << info end end found end # expand a path relative to the manifest file's directory def from_manifest(path) File.expand_path(path, File.dirname(manifest_file)) end # sort applications in dependency order # e.g. if A depends on B, B will be listed before A def ordered_by_deps(apps, processed = Set[]) ordered = [] apps.each do |tag, info| next if processed.include?(tag) if deps = Array(info[:"depends-on"]) dep_apps = {} deps.each do |dep| dep = dep.to_sym fail "Circular dependency detected." if processed.include? dep dep_apps[dep] = apps[dep] end processed.add(tag) ordered += ordered_by_deps(dep_apps, processed) ordered << info else ordered << info processed.add(tag) end end ordered end def ask_to_save(input, app) return if manifest_file if ask("Save configuration?", :default => false) with_progress("Saving to #{c("manifest.yml", :name)}") do File.open("manifest.yml", "w") do |io| YAML.dump( { "applications" => [meta] }, io) end end end end def env_hash(val) if val.is_a?(Hash) val else hash = {} val.each do |pair| name, val = pair.split("=", 2) hash[name] = val end hash end end def setup_env(app, info) return unless info[:env] app.env = env_hash(info[:env]) end def setup_services(app, info) return if !info[:services] || info[:services].empty? services = client.services to_bind = [] info[:services].each do |name, svc| name = name.to_s if instance = client.service_instance_by_name(name) to_bind << instance else service = services.find { |s| s.label == (svc[:label] || svc[:type] || svc[:vendor]) && (!svc[:version] || s.version == svc[:version]) && (s.provider == (svc[:provider] || "core")) } fail "Unknown service: #{svc.inspect}." unless service if v2? plan = service.service_plans.find { |p| p.name == (svc[:plan] || "D100") } fail "Unknown service plan: #{svc[:plan]}." unless plan end invoke :create_service, :name => name, :service => service, :plan => plan, :app => app end end to_bind.each do |i| # TODO: splat invoke :bind_service, :app => app, :instance => i end end def target_base client_target.sub(/^[^\.]+\./, "") end end fix asking to save after push Change-Id: Idfc865571cffbd947994175913de73872474be69 require "yaml" require "set" require "manifests-vmc-plugin/loader" module VMCManifests MANIFEST_FILE = "manifest.yml" @@showed_manifest_usage = false def manifest return @manifest if @manifest if manifest_file && File.exists?(manifest_file) @manifest = load_manifest(manifest_file) end end def save_manifest(save_to = manifest_file) fail "No manifest to save!" unless @manifest File.open(save_to, "w") do |io| YAML.dump(@manifest, io) end end # find the manifest file to work with def manifest_file return @manifest_file if @manifest_file unless path = input[:manifest] where = Dir.pwd while true if File.exists?(File.join(where, MANIFEST_FILE)) path = File.join(where, MANIFEST_FILE) break elsif File.basename(where) == "/" path = nil break else where = File.expand_path("../", where) end end end return unless path @manifest_file = File.expand_path(path) end # load and resolve a given manifest file def load_manifest(file) Loader.new(file, self).manifest end # dynamic symbol resolution def resolve_symbol(sym) case sym when "target-url" client_target when "target-base" target_base when "random-word" sprintf("%04x", rand(0x0100000)) when /^ask (.+)/ ask($1) end end # find an app by its unique tag def app_by_tag(tag) manifest[:applications][tag] end # find apps by an identifier, which may be either a tag, a name, or a path def find_apps(identifier) return [] unless manifest if app = app_by_tag(identifier) return [app] end apps = apps_by(:name, identifier) if apps.empty? apps = apps_by(:path, from_manifest(identifier)) end apps end # call a block for each app in a manifest (in dependency order), setting # inputs for each app def each_app(&blk) return unless manifest ordered_by_deps(manifest[:applications]).each(&blk) end # return all the apps described by the manifest, in dependency order def all_apps apps = [] each_app do |app| apps << app end apps end # like each_app, but only acts on apps specified as paths instead of names # # returns the names that were not paths def specific_apps_or_all(input = nil, use_name = true, &blk) names_or_paths = if input.given?(:apps) # names may be given but be [], which will still cause # interaction, so use #given instead of #[] here input.given(:apps) elsif input.given?(:app) [input[:app]] else [] end input = input.without(:app, :apps) in_manifest = [] if names_or_paths.empty? apps = find_apps(Dir.pwd) if !apps.empty? in_manifest += apps else each_app(&blk) return [] end end external = [] names_or_paths.each do |x| if x.is_a?(String) path = File.expand_path(x) apps = find_apps(File.exists?(path) ? path : x) if !apps.empty? in_manifest += apps elsif app = client.app_by_name(x) external << app else fail("Unknown app '#{x}'") end else external << x end end in_manifest.each do |app| blk.call app end external end def create_manifest_for(app, path) meta = { "name" => app.name, "framework" => app.framework.name, "runtime" => app.runtime.name, "memory" => human_size(app.memory * 1024 * 1024, 0), "instances" => app.total_instances, "url" => app.url ? app.url.sub(target_base, '${target-base}') : "none", "path" => path } services = app.services unless services.empty? meta["services"] = {} services.each do |i| if v2? p = i.service_plan s = p.service meta["services"][i.name] = { "label" => s.label, "provider" => s.provider, "version" => s.version, "plan" => p.name } else meta["services"][i.name] = { "vendor" => i.vendor, "version" => i.version, "tier" => i.tier } end end end if cmd = app.command meta["command"] = cmd end meta end private def show_manifest_usage return if @@showed_manifest_usage path = Pathname.new(manifest_file).relative_path_from(Pathname.pwd) line "Using manifest file #{c(path, :name)}" line @@showed_manifest_usage = true end def no_apps fail "No applications or manifest to operate on." end def apps_by(attr, val) found = [] manifest[:applications].each do |tag, info| if info[attr] == val found << info end end found end # expand a path relative to the manifest file's directory def from_manifest(path) File.expand_path(path, File.dirname(manifest_file)) end # sort applications in dependency order # e.g. if A depends on B, B will be listed before A def ordered_by_deps(apps, processed = Set[]) ordered = [] apps.each do |tag, info| next if processed.include?(tag) if deps = Array(info[:"depends-on"]) dep_apps = {} deps.each do |dep| dep = dep.to_sym fail "Circular dependency detected." if processed.include? dep dep_apps[dep] = apps[dep] end processed.add(tag) ordered += ordered_by_deps(dep_apps, processed) ordered << info else ordered << info processed.add(tag) end end ordered end def ask_to_save(input, app) return if manifest_file return unless ask("Save configuration?", :default => false) manifest = create_manifest_for(app, input[:path]) with_progress("Saving to #{c("manifest.yml", :name)}") do File.open("manifest.yml", "w") do |io| YAML.dump( { "applications" => [manifest] }, io) end end end def env_hash(val) if val.is_a?(Hash) val else hash = {} val.each do |pair| name, val = pair.split("=", 2) hash[name] = val end hash end end def setup_env(app, info) return unless info[:env] app.env = env_hash(info[:env]) end def setup_services(app, info) return if !info[:services] || info[:services].empty? services = client.services to_bind = [] info[:services].each do |name, svc| name = name.to_s if instance = client.service_instance_by_name(name) to_bind << instance else service = services.find { |s| s.label == (svc[:label] || svc[:type] || svc[:vendor]) && (!svc[:version] || s.version == svc[:version]) && (s.provider == (svc[:provider] || "core")) } fail "Unknown service: #{svc.inspect}." unless service if v2? plan = service.service_plans.find { |p| p.name == (svc[:plan] || "D100") } fail "Unknown service plan: #{svc[:plan]}." unless plan end invoke :create_service, :name => name, :service => service, :plan => plan, :app => app end end to_bind.each do |i| # TODO: splat invoke :bind_service, :app => app, :instance => i end end def target_base client_target.sub(/^[^\.]+\./, "") end end
class Memcached::Error < RuntimeError; end class Memcached::NotFound < Memcached::Error; end class Memcached::NotStored < Memcached::Error; end class Memcached::NotSupport < Memcached::Error; end remove unused file lib/memcached/exceptions.rb
module Merb class BootLoader # def self.subclasses # # :api: plugin cattr_accessor :subclasses, :after_load_callbacks, :before_load_callbacks, :finished, :before_worker_shutdown_callbacks, :before_master_shutdown_callbacks self.subclasses, self.after_load_callbacks, self.before_load_callbacks, self.finished, self.before_master_shutdown_callbacks, self.before_worker_shutdown_callbacks = [], [], [], [], [], [] class << self # Adds the inheriting class to the list of subclasses in a position # specified by the before and after methods. # # ==== Parameters # klass<Class>:: The class inheriting from Merb::BootLoader. # # ==== Returns # nil # # :api: plugin def inherited(klass) subclasses << klass.to_s super end # Execute this boot loader after the specified boot loader. # # ==== Parameters # klass<~to_s>:: # The boot loader class after which this boot loader should be run. # # ==== Returns # nil # # :api: plugin def after(klass) move_klass(klass, 1) nil end # Execute this boot loader before the specified boot loader. # # ==== Parameters # klass<~to_s>:: # The boot loader class before which this boot loader should be run. # # ==== Returns # nil # # :api: plugin def before(klass) move_klass(klass, 0) nil end # Move a class that is inside the bootloader to some place in the Array, # relative to another class. # # ==== Parameters # klass<~to_s>:: # The klass to move the bootloader relative to # where<Integer>:: # 0 means insert it before; 1 means insert it after # # ==== Returns # nil # # :api: private def move_klass(klass, where) index = Merb::BootLoader.subclasses.index(klass.to_s) if index Merb::BootLoader.subclasses.delete(self.to_s) Merb::BootLoader.subclasses.insert(index + where, self.to_s) end nil end # Runs all boot loader classes by calling their run methods. # # ==== Returns # nil # # :api: plugin def run Merb.started = true subklasses = subclasses.dup until subclasses.empty? time = Time.now.to_i bootloader = subclasses.shift if (ENV['DEBUG'] || $DEBUG || Merb::Config[:verbose]) && Merb.logger Merb.logger.debug!("Loading: #{bootloader}") end Object.full_const_get(bootloader).run if (ENV['DEBUG'] || $DEBUG || Merb::Config[:verbose]) && Merb.logger Merb.logger.debug!("It took: #{Time.now.to_i - time}") end self.finished << bootloader end self.subclasses = subklasses nil end # Determines whether or not a specific bootloader has finished yet. # # ==== Parameters # bootloader<String, Class>:: The name of the bootloader to check. # # ==== Returns # Boolean:: Whether or not the bootloader has finished. # # :api: private def finished?(bootloader) self.finished.include?(bootloader.to_s) end # Set up the default framework # # ==== Returns # nil # # :api: plugin # @overridable def default_framework %w[view model helper controller mailer part].each do |component| Merb.push_path(component.to_sym, Merb.root_path("app/#{component}s")) end Merb.push_path(:application, Merb.root_path("app" / "controllers" / "application.rb")) Merb.push_path(:config, Merb.root_path("config"), nil) Merb.push_path(:router, Merb.dir_for(:config), (Merb::Config[:router_file] || "router.rb")) Merb.push_path(:lib, Merb.root_path("lib"), nil) Merb.push_path(:merb_session, Merb.root_path("merb" / "session")) Merb.push_path(:log, Merb.log_path, nil) Merb.push_path(:public, Merb.root_path("public"), nil) Merb.push_path(:stylesheet, Merb.dir_for(:public) / "stylesheets", nil) Merb.push_path(:javascript, Merb.dir_for(:public) / "javascripts", nil) Merb.push_path(:image, Merb.dir_for(:public) / "images", nil) nil end # Execute a block of code after the app loads. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed after the # app loads. # # :api: public def after_app_loads(&block) after_load_callbacks << block end # Execute a block of code before the app loads but after dependencies load. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed before the # app loads. # # :api: public def before_app_loads(&block) before_load_callbacks << block end # Execute a block of code before master process is shut down. # Only makes sense on platforms where Merb server can use forking. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed # before master process is shut down. # # :api: public def before_master_shutdown(&block) before_master_shutdown_callbacks << block end # Execute a block of code before worker process is shut down. # Only makes sense on platforms where Merb server can use forking. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed # before worker process is shut down. # # :api: public def before_worker_shutdown(&block) before_worker_shutdown_callbacks << block end end end end # Set up the logger. # # Place the logger inside of the Merb log directory (set up in # Merb::BootLoader::BuildFramework) class Merb::BootLoader::Logger < Merb::BootLoader # Sets Merb.logger to a new logger created based on the config settings. # # ==== Returns # nil # # :api: plugin def self.run Merb::Config[:log_level] ||= begin if Merb.environment == "production" Merb::Logger::Levels[:warn] else Merb::Logger::Levels[:debug] end end Merb::Config[:log_stream] = Merb::Config[:original_log_stream] || Merb.log_stream print_warnings nil end # Print a warning if the installed version of rubygems is not supported # # ==== Returns # nil # # :api: private def self.print_warnings if Gem::Version.new(Gem::RubyGemsVersion) < Gem::Version.new("1.1") Merb.fatal! "Merb requires Rubygems 1.1 and later. " \ "Please upgrade RubyGems with gem update --system." end end end # Stores pid file. # # Only run if daemonization or clustering options specified on start. # Port is taken from Merb::Config and must be already set at this point. class Merb::BootLoader::DropPidFile < Merb::BootLoader class << self # Stores a PID file if Merb is running daemonized or clustered. # # ==== Returns # nil # # :api: plugin def run Merb::Server.store_pid("main") #if Merb::Config[:daemonize] || Merb::Config[:cluster] nil end end end # Setup some useful defaults class Merb::BootLoader::Defaults < Merb::BootLoader # Sets up the defaults # # ==== Returns # nil # # :api: plugin def self.run Merb::Request.http_method_overrides.concat([ proc { |c| c.params[:_method] }, proc { |c| c.env['HTTP_X_HTTP_METHOD_OVERRIDE'] } ]) nil end end # Build the framework paths. # # By default, the following paths will be used: # application:: Merb.root/app/controller/application.rb # config:: Merb.root/config # lib:: Merb.root/lib # log:: Merb.root/log # view:: Merb.root/app/views # model:: Merb.root/app/models # controller:: Merb.root/app/controllers # helper:: Merb.root/app/helpers # mailer:: Merb.root/app/mailers # part:: Merb.root/app/parts # # To override the default, set Merb::Config[:framework] in your initialization # file. Merb::Config[:framework] takes a Hash whose key is the name of the # path, and whose values can be passed into Merb.push_path (see Merb.push_path # for full details). # # ==== Notes # All paths will default to Merb.root, so you can get a flat-file structure by # doing Merb::Config[:framework] = {}. # # ==== Example # Merb::Config[:framework] = { # :view => Merb.root / "views", # :model => Merb.root / "models", # :lib => Merb.root / "lib", # :public => [Merb.root / "public", nil] # :router => [Merb.root / "config", "router.rb"] # } # # That will set up a flat directory structure with the config files and # controller files under Merb.root, but with models, views, and lib with their # own folders off of Merb.root. class Merb::BootLoader::BuildFramework < Merb::BootLoader class << self # Builds the framework directory structure. # # ==== Returns # nil # # :api: plugin def run $:.push Merb.root unless Merb.root == File.expand_path(Dir.pwd) build_framework nil end # Sets up merb paths to support the app's file layout. First, config/framework.rb is checked, # next we look for Merb.root/framework.rb, finally we use the default merb layout (Merb::BootLoader.default_framework) # # This method can be overriden to support other application layouts. # # ==== Returns # nil # # :api: plugin # @overridable def build_framework if File.exists?(Merb.root / "config" / "framework.rb") require Merb.root / "config" / "framework" elsif File.exists?(Merb.root / "framework.rb") require Merb.root / "framework" else Merb::BootLoader.default_framework end (Merb::Config[:framework] || {}).each do |name, path| path = Array(path) Merb.push_path(name, path.first, path.length == 2 ? path[1] : "**/*.rb") end nil end end end class Merb::BootLoader::Dependencies < Merb::BootLoader # ==== Returns # Array[Gem::Dependency]:: The dependencies regiestered in init.rb. # # :api: plugin cattr_accessor :dependencies self.dependencies = [] # Load the init_file specified in Merb::Config or if not specified, the # init.rb file from the Merb configuration directory, and any environment # files, which register the list of necessary dependencies and any # after_app_loads hooks. # # Dependencies can hook into the bootloader process itself by using # before or after insertion methods. Since these are loaded from this # bootloader (Dependencies), they can only adapt the bootloaders that # haven't been loaded up until this point. # # ==== Returns # nil # # :api: plugin def self.run set_encoding # this is crucial: load init file with all the preferences # then environment init file, then start enabling specific # components, load dependencies and update logger. unless Merb::disabled?(:initfile) load_initfile load_env_config end expand_ruby_path enable_json_gem unless Merb::disabled?(:json) load_dependencies update_logger nil end # Load each dependency that has been declared so far. # # ==== Returns # nil # # :api: private def self.load_dependencies dependencies.each { |dependency| Kernel.load_dependency(dependency, nil) } nil end # Loads json or json_pure and requires it. # # ==== Returns # nil # # :api: private def self.enable_json_gem gem "json" require "json/ext" rescue LoadError gem "json_pure" require "json/pure" end # Resets the logger and sets the log_stream to Merb::Config[:log_file] # if one is specified, falling back to STDOUT. # # ==== Returns # nil # # :api: private def self.update_logger Merb.reset_logger! # If log file is given, use it and not log stream we have. if Merb::Config[:log_file] raise "log file should be a string, got: #{Merb::Config[:log_file].inspect}" unless Merb::Config[:log_file].is_a?(String) STDOUT.puts "Logging to file at #{Merb::Config[:log_file]}" unless Merb.testing? Merb::Config[:log_stream] = File.open(Merb::Config[:log_file], "a") # but if it's not given, fallback to log stream or stdout else Merb::Config[:log_stream] ||= STDOUT end nil end # Default encoding to UTF8 if it has not already been set to something else. # # ==== Returns # nil # # :api: private def self.set_encoding unless Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("1.9") $KCODE = 'UTF8' if $KCODE == 'NONE' || $KCODE.blank? end nil end private # Determines the path for the environment configuration file # # ==== Returns # String:: The path to the config file for the environment # # :api: private def self.env_config Merb.dir_for(:config) / "environments" / (Merb.environment + ".rb") end # Checks to see whether or not an environment configuration exists # # ==== Returns # Boolean:: Whether or not the environment configuration file exists. # # :api: private def self.env_config? Merb.environment && File.exist?(env_config) end # Loads the environment configuration file, if it is present # # ==== Returns # nil # # :api: private def self.load_env_config if env_config? STDOUT.puts "Loading #{env_config}" unless Merb.testing? load(env_config) end nil end # Determines the init file to use, if any. # By default Merb uses init.rb from application config directory. # # ==== Returns # nil # # :api: private def self.initfile if Merb::Config[:init_file] Merb::Config[:init_file].chomp(".rb") + ".rb" else Merb.dir_for(:config) / "init.rb" end end # Loads the init file, should one exist # # ==== Returns # nil # # :api: private def self.load_initfile if File.exists?(initfile) STDOUT.puts "Loading init file from #{initfile}" unless Merb.testing? load(initfile) elsif !Merb.testing? Merb.fatal! "You are not in a Merb application, or you are in " \ "a flat application and have not specified the init file. If you " \ "are trying to create a new merb application, use merb-gen app." end nil end # Expands Ruby path with framework directories (for models, lib, etc). Only run once. # # ==== Returns # nil # # :api: private def self.expand_ruby_path # Add models, controllers, helpers and lib to the load path unless @ran Merb.logger.info "Expanding RUBY_PATH..." if Merb::Config[:verbose] $LOAD_PATH.unshift Merb.dir_for(:model) $LOAD_PATH.unshift Merb.dir_for(:controller) $LOAD_PATH.unshift Merb.dir_for(:lib) $LOAD_PATH.unshift Merb.dir_for(:helper) end @ran = true nil end end class Merb::BootLoader::MixinSession < Merb::BootLoader # Mixin the session functionality; this is done before BeforeAppLoads # so that SessionContainer and SessionStoreContainer can be subclassed by # plugin session stores for example - these need to be loaded in a # before_app_loads block or a BootLoader that runs after MixinSession. # # Note: access to Merb::Config is needed, so it needs to run after # Merb::BootLoader::Dependencies is done. # # ==== Returns # nil # # :api: plugin def self.run require 'merb-core/dispatch/session' Merb::Controller.send(:include, ::Merb::SessionMixin) Merb::Request.send(:include, ::Merb::SessionMixin::RequestMixin) end end class Merb::BootLoader::BeforeAppLoads < Merb::BootLoader # Call any before_app_loads hooks that were registered via before_app_loads # in any plugins. # # ==== Returns # nil # # :api: plugin def self.run Merb::BootLoader.before_load_callbacks.each { |x| x.call } nil end end # Load all classes inside the load paths. # # This is used in conjunction with Merb::BootLoader::ReloadClasses to track # files that need to be reloaded, and which constants need to be removed in # order to reload a file. # # This also adds the model, controller, and lib directories to the load path, # so they can be required in order to avoid load-order issues. class Merb::BootLoader::LoadClasses < Merb::BootLoader LOADED_CLASSES = {} MTIMES = {} FILES_LOADED = {} class << self # Load all classes from Merb's native load paths. # # If fork-based loading is used, every time classes are loaded this will return in a new spawner process # and boot loading will continue from this point in the boot loading process. # # If fork-based loading is not in use, this only returns once and does not fork a new # process. # # ==== Returns # Returns at least once: # nil # # :api: plugin def run # process name you see in ps output $0 = "merb#{" : " + Merb::Config[:name] if Merb::Config[:name]} : master" # Log the process configuration user defined signal 1 (SIGUSR1) is received. Merb.trap("USR1") do require "yaml" Merb.logger.fatal! "Configuration:\n#{Merb::Config.to_hash.merge(:pid => $$).to_yaml}\n\n" end if Merb::Config[:fork_for_class_load] && !Merb.testing? start_transaction else Merb.trap('INT') do Merb.logger.warn! "Reaping Workers" reap_workers end end # Load application file if it exists - for flat applications load_file Merb.dir_for(:application) if File.file?(Merb.dir_for(:application)) # Load classes and their requirements Merb.load_paths.each do |component, path| next if path.last.blank? || component == :application || component == :router load_classes(path.first / path.last) end Merb::Controller.send :include, Merb::GlobalHelpers nil end # Wait for any children to exit, remove the "main" PID, and # exit. # # ==== Returns # (Does not return.) # # :api: private def exit_gracefully # wait all workers to exit Process.waitall # remove master process pid Merb::Server.remove_pid("main") # terminate, workers remove their own pids # in on exit hook Merb::BootLoader.before_master_shutdown_callbacks.each do |cb| begin cb.call rescue Exception => e Merb.logger.fatal "before_master_shutdown callback crashed: #{e.message}" end end exit end # Set up the BEGIN point for fork-based loading and sets up # any signals in the parent and child. This is done by forking # the app. The child process continues on to run the app. The parent # process waits for the child process to finish and either forks again # # # ==== Returns # Parent Process: # (Does not return.) # Child Process returns at least once: # nil # # :api: private def start_transaction Merb.logger.warn! "Parent pid: #{Process.pid}" reader, writer = nil, nil if GC.respond_to?(:copy_on_write_friendly=) GC.copy_on_write_friendly = true end loop do # create two connected endpoints # we use them for master/workers communication reader, @writer = IO.pipe pid = Kernel.fork # pid means we're in the parent; only stay in the loop if that is case break unless pid # writer must be closed so reader can generate EOF condition @writer.close # master process stores pid to merb.main.pid Merb::Server.store_pid("main") if Merb::Config[:console_trap] Merb.trap("INT") {} else # send ABRT to worker on INT Merb.trap("INT") do Merb.logger.warn! "Reaping Workers" begin Process.kill(reap_workers_signal, pid) rescue SystemCallError end exit_gracefully end end Merb.trap("HUP") do Merb.logger.warn! "Doing a fast deploy\n" Process.kill("HUP", pid) end reader_ary = [reader] loop do # wait for worker to exit and capture exit status # # # WNOHANG specifies that wait2 exists without waiting # if no worker processes are ready to be noticed. if exit_status = Process.wait2(pid, Process::WNOHANG) # wait2 returns a 2-tuple of process id and exit # status. # # We do not care about specific pid here. exit_status[1] && exit_status[1].exitstatus == 128 ? break : exit end # wait for data to become available, timeout in 0.25 of a second if select(reader_ary, nil, nil, 0.25) begin # no open writers next if reader.eof? msg = reader.readline if msg =~ /128/ Process.detach(pid) break else exit_gracefully end rescue SystemCallError exit_gracefully end end end end reader.close # add traps to the worker if Merb::Config[:console_trap] Merb::Server.add_irb_trap at_exit { reap_workers } else Merb.trap('INT') do Merb::BootLoader.before_worker_shutdown_callbacks.each { |cb| cb.call } end Merb.trap('ABRT') { reap_workers } Merb.trap('HUP') { reap_workers(128, "ABRT") } end end def reap_workers_signal Merb::Config[:reap_workers_quickly] ? "KILL" : "ABRT" end # Reap any workers of the spawner process and # exit with an appropriate status code. # # Note that exiting the spawner process with a status code # of 128 when a master process exists will cause the # spawner process to be recreated, and the app code reloaded. # # ==== Parameters # status<Integer>:: The status code to exit with. Defaults to 0. # sig<String>:: The signal to send to workers # # ==== Returns # (Does not return.) # # :api: private def reap_workers(status = 0, sig = reap_workers_signal) Merb.logger.info "Executed all before worker shutdown callbacks..." Merb::BootLoader.before_worker_shutdown_callbacks.each do |cb| begin cb.call rescue Exception => e Merb.logger.fatal "before worker shutdown callback crashed: #{e.message}" end end Merb.exiting = true unless status == 128 begin @writer.puts(status.to_s) if @writer rescue SystemCallError end threads = [] ($WORKERS || []).each do |p| threads << Thread.new do begin Process.kill(sig, p) Process.wait2(p) rescue SystemCallError end end end threads.each {|t| t.join } exit(status) end # Loads a file, tracking its modified time and, if necessary, the classes it declared. # # ==== Parameters # file<String>:: The file to load. # # ==== Returns # nil # # :api: private def load_file(file, reload = false) puts "#{reload ? "re" : ""}loading #{file}" # If we're going to be reloading via constant remove, # keep track of what constants were loaded and what files # have been added, so that the constants can be removed # and the files can be removed from $LOADED_FEAUTRES if !Merb::Config[:fork_for_class_load] if FILES_LOADED[file] FILES_LOADED[file].each {|lf| $LOADED_FEATURES.delete(lf)} end klasses = ObjectSpace.classes.dup files_loaded = $LOADED_FEATURES.dup end # If we're in the midst of a reload, remove the file # itself from $LOADED_FEATURES so it will get reloaded if reload $LOADED_FEATURES.delete(file) if reload end # Ignore the file for syntax errors. The next time # the file is changed, it'll be reloaded again begin require file rescue SyntaxError => e Merb.logger.error "Cannot load #{file} because of syntax error: #{e.message}" ensure if Merb::Config[:reload_classes] MTIMES[file] = File.mtime(file) end end # If we're reloading via constant remove, store off the details # after the file has been loaded unless Merb::Config[:fork_for_class_load] LOADED_CLASSES[file] = ObjectSpace.classes - klasses FILES_LOADED[file] = $LOADED_FEATURES - files_loaded end nil end # Load classes from given paths - using path/glob pattern. # # ==== Parameters # *paths<Array>:: # Array of paths to load classes from - may contain glob pattern # # ==== Returns # nil # # :api: private def load_classes(*paths) orphaned_classes = [] paths.flatten.each do |path| Dir[path].each do |file| begin load_file file rescue NameError => ne orphaned_classes.unshift(file) end end end load_classes_with_requirements(orphaned_classes) end # Reloads the classes in the specified file. If fork-based loading is used, # this causes the current processes to be killed and and all classes to be # reloaded. If class-based loading is not in use, the classes declared in that file # are removed and the file is reloaded. # # ==== Parameters # file<String>:: The file to reload. # # ==== Returns # When fork-based loading is used: # (Does not return.) # When fork-based loading is not in use: # nil # # :api: private def reload(file) if Merb::Config[:fork_for_class_load] reap_workers(128) else remove_classes_in_file(file) { |f| load_file(f, true) } end end # Removes all classes declared in the specified file. Any hashes which use classes as keys # will be protected provided they have been added to Merb.klass_hashes. These hashes have their # keys substituted with placeholders before the file's classes are unloaded. If a block is provided, # it is called before the substituted keys are reconstituted. # # ==== Parameters # file<String>:: The file to remove classes for. # &block:: A block to call with the file that has been removed before klass_hashes are updated # to use the current values of the constants they used as keys. # # ==== Returns # nil # # :api: private def remove_classes_in_file(file, &block) Merb.klass_hashes.each { |x| x.protect_keys! } if klasses = LOADED_CLASSES.delete(file) klasses.each { |klass| remove_constant(klass) unless klass.to_s =~ /Router/ } end yield file if block_given? Merb.klass_hashes.each {|x| x.unprotect_keys!} nil end # Removes the specified class. # # Additionally, removes the specified class from the subclass list of every superclass that # tracks it's subclasses in an array returned by _subclasses_list. Classes that wish to use this # functionality are required to alias the reader for their list of subclasses # to _subclasses_list. Plugins for ORMs and other libraries should keep this in mind. # # ==== Parameters # const<Class>:: The class to remove. # # ==== Returns # nil # # :api: private def remove_constant(const) # This is to support superclasses (like AbstractController) that track # their subclasses in a class variable. superklass = const until (superklass = superklass.superclass).nil? if superklass.respond_to?(:_subclasses_list) superklass.send(:_subclasses_list).delete(klass) superklass.send(:_subclasses_list).delete(klass.to_s) end end parts = const.to_s.split("::") base = parts.size == 1 ? Object : Object.full_const_get(parts[0..-2].join("::")) object = parts[-1].to_s begin base.send(:remove_const, object) Merb.logger.debug("Removed constant #{object} from #{base}") rescue NameError Merb.logger.debug("Failed to remove constant #{object} from #{base}") end nil end private # "Better loading" of classes. If a file fails to load due to a NameError # it will be added to the failed_classes and load cycle will be repeated unless # no classes load. # # ==== Parameters # klasses<Array[Class]>:: Classes to load. # # ==== Returns # nil # # :api: private def load_classes_with_requirements(klasses) klasses.uniq! while klasses.size > 0 # Note size to make sure things are loading size_at_start = klasses.size # List of failed classes failed_classes = [] # Map classes to exceptions error_map = {} klasses.each do |klass| klasses.delete(klass) begin load_file klass rescue NameError => ne error_map[klass] = ne failed_classes.push(klass) end end # Keep list of classes unique failed_classes.each { |k| klasses.push(k) unless klasses.include?(k) } # Stop processing if nothing loads or if everything has loaded if klasses.size == size_at_start && klasses.size != 0 # Write all remaining failed classes and their exceptions to the log messages = error_map.only(*failed_classes).map do |klass, e| ["Could not load #{klass}:\n\n#{e.message} - (#{e.class})", "#{(e.backtrace || []).join("\n")}"] end messages.each { |msg, trace| Merb.logger.fatal!("#{msg}\n\n#{trace}") } Merb.fatal! "#{failed_classes.join(", ")} failed to load." end break if(klasses.size == size_at_start || klasses.size == 0) end nil end end end # Loads the router file. This needs to happen after everything else is loaded while merb is starting up to ensure # the router has everything it needs to run. class Merb::BootLoader::Router < Merb::BootLoader class << self # load the router file # # ==== Returns # nil # # :api: plugin def run Merb::BootLoader::LoadClasses.load_file(router_file) if router_file nil end # Tries to find the router file. # # ==== Returns # String:: The path to the router file if it exists, nil otherwise. # # :api: private def router_file @router_file ||= begin if File.file?(router = Merb.dir_for(:router) / Merb.glob_for(:router)) router end end end end end # Precompiles all non-partial templates. class Merb::BootLoader::Templates < Merb::BootLoader class << self # Loads all non-partial templates into the Merb::InlineTemplates module. # # ==== Returns # Array[String]:: The list of template files which were loaded. # # :api: plugin def run template_paths.each do |path| Merb::Template.inline_template(File.open(path)) end end # Finds a list of templates to load. # # ==== Returns # Array[String]:: All found template files whose basename does not begin with "_". # # :api: private def template_paths extension_glob = "{#{Merb::Template.template_extensions.join(',')}}" # This gets all templates set in the controllers template roots # We separate the two maps because most of controllers will have # the same _template_root, so it's silly to be globbing the same # path over and over. controller_view_paths = [] Merb::AbstractController._abstract_subclasses.each do |klass| next if (const = Object.full_const_get(klass))._template_root.blank? controller_view_paths += const._template_roots.map { |pair| pair.first } end template_paths = controller_view_paths.uniq.compact.map { |path| Dir["#{path}/**/*.#{extension_glob}"] } # This gets the templates that might be created outside controllers # template roots. eg app/views/shared/* template_paths << Dir["#{Merb.dir_for(:view)}/**/*.#{extension_glob}"] if Merb.dir_for(:view) # This ignores templates for partials, which need to be compiled at use time to generate # a preamble that assigns local variables template_paths.flatten.compact.uniq.grep(%r{^.*/[^_][^/]*$}) end end end # Register the default MIME types: # # By default, the mime-types include: # :all:: no transform, */* # :yaml:: to_yaml, application/x-yaml or text/yaml # :text:: to_text, text/plain # :html:: to_html, text/html or application/xhtml+xml or application/html # :xml:: to_xml, application/xml or text/xml or application/x-xml # :js:: to_json, text/javascript ot application/javascript or application/x-javascript # :json:: to_json, application/json or text/x-json class Merb::BootLoader::MimeTypes < Merb::BootLoader # Registers the default MIME types. # # ==== Returns # nil # # :api: plugin def self.run Merb.add_mime_type(:all, nil, %w[*/*]) Merb.add_mime_type(:yaml, :to_yaml, %w[application/x-yaml text/yaml], :charset => "utf-8") Merb.add_mime_type(:text, :to_text, %w[text/plain], :charset => "utf-8") Merb.add_mime_type(:html, :to_html, %w[text/html application/xhtml+xml application/html], :charset => "utf-8") Merb.add_mime_type(:xml, :to_xml, %w[application/xml text/xml application/x-xml], {:charset => "utf-8"}, 0.9998) Merb.add_mime_type(:js, :to_json, %w[text/javascript application/javascript application/x-javascript], :charset => "utf-8") Merb.add_mime_type(:json, :to_json, %w[application/json text/x-json], :charset => "utf-8") nil end end # Set up cookies support in Merb::Controller and Merb::Request class Merb::BootLoader::Cookies < Merb::BootLoader # Set up cookies support in Merb::Controller and Merb::Request # # ==== Returns # nil # # :api: plugin def self.run require 'merb-core/dispatch/cookies' Merb::Controller.send(:include, Merb::CookiesMixin) Merb::Request.send(:include, Merb::CookiesMixin::RequestMixin) nil end end class Merb::BootLoader::SetupSession < Merb::BootLoader # Enable the configured session container(s); any class that inherits from # SessionContainer will be considered by its session_store_type attribute. # # ==== Returns # nil # # :api: plugin def self.run # Require all standard session containers. Dir[Merb.framework_root / "merb-core" / "dispatch" / "session" / "*.rb"].each do |file| base_name = File.basename(file, ".rb") require file unless base_name == "container" || base_name == "store_container" end # Set some defaults. Merb::Config[:session_id_key] ||= "_session_id" # List of all session_stores from :session_stores and :session_store config options. config_stores = Merb::Config.session_stores # Register all configured session stores - any loaded session container class # (subclassed from Merb::SessionContainer) will be available for registration. Merb::SessionContainer.subclasses.each do |class_name| if(store = Object.full_const_get(class_name)) && config_stores.include?(store.session_store_type) Merb::Request.register_session_type(store.session_store_type, class_name) end end # Mixin the Merb::Session module to add app-level functionality to sessions overrides = (Merb::Session.instance_methods & Merb::SessionContainer.instance_methods) overrides.each do |m| Merb.logger.warn!("Warning: Merb::Session##{m} overrides existing " \ "Merb::SessionContainer##{m}") end Merb::SessionContainer.send(:include, Merb::Session) nil end end # In case someone's running a sparse app, the default exceptions require the # Exceptions class. This must run prior to the AfterAppLoads BootLoader # So that plugins may have ensured access in the after_app_loads block class Merb::BootLoader::SetupStubClasses < Merb::BootLoader # Declares empty Application and Exception controllers. # # ==== Returns # nil # # :api: plugin def self.run unless defined?(Exceptions) Object.class_eval <<-RUBY class Application < Merb::Controller abstract! end class Exceptions < Merb::Controller end RUBY end nil end end class Merb::BootLoader::AfterAppLoads < Merb::BootLoader # Call any after_app_loads hooks that were registered via after_app_loads in # init.rb. # # ==== Returns # nil # # :api: plugin def self.run Merb::BootLoader.after_load_callbacks.each {|x| x.call } nil end end class Merb::BootLoader::ChooseAdapter < Merb::BootLoader # Choose the Rack adapter/server to use and set Merb.adapter. # # ==== Returns # nil # # :api: plugin def self.run Merb.adapter = Merb::Rack::Adapter.get(Merb::Config[:adapter]) end end class Merb::BootLoader::RackUpApplication < Merb::BootLoader # Setup the Merb Rack App or read a rackup file located at # Merb::Config[:rackup] with the same syntax as the # rackup tool that comes with rack. Automatically evals the file in # the context of a Rack::Builder.new { } block. Allows for mounting # additional apps or middleware. # # ==== Returns # nil # # :api: plugin def self.run require 'rack' if File.exists?(Merb.dir_for(:config) / "rack.rb") Merb::Config[:rackup] ||= Merb.dir_for(:config) / "rack.rb" end if Merb::Config[:rackup] rackup_code = File.read(Merb::Config[:rackup]) Merb::Config[:app] = eval("::Rack::Builder.new {( #{rackup_code}\n )}.to_app", TOPLEVEL_BINDING, Merb::Config[:rackup]) else Merb::Config[:app] = ::Rack::Builder.new { if prefix = ::Merb::Config[:path_prefix] use Merb::Rack::PathPrefix, prefix end use Merb::Rack::Static, Merb.dir_for(:public) run Merb::Rack::Application.new }.to_app end nil end end class Merb::BootLoader::ReloadClasses < Merb::BootLoader class TimedExecutor # Executes the associated block every @seconds@ seconds in a separate thread. # # ==== Parameters # seconds<Integer>:: Number of seconds to sleep in between runs of &block. # &block:: The block to execute periodically. # # ==== Returns # Thread:: The thread executing the block periodically. # # :api: private def self.every(seconds, &block) Thread.new do loop do sleep( seconds ) yield end Thread.exit end end end # Set up the class reloader if class reloading is enabled. This checks periodically # for modifications to files loaded by the LoadClasses BootLoader and reloads them # when they are modified. # # ==== Returns # nil # # :api: plugin def self.run return unless Merb::Config[:reload_classes] paths = [] Merb.load_paths.each do |path_name, file_info| path, glob = file_info next unless glob paths << Dir[path / glob] end if Merb.dir_for(:application) && File.file?(Merb.dir_for(:application)) paths << Merb.dir_for(:application) end paths.flatten! TimedExecutor.every(Merb::Config[:reload_time] || 0.5) do GC.start reload(paths) end nil end # Reloads all files which have been modified since they were last loaded. # # ==== Returns # nil # # :api: private def self.reload(paths) paths.each do |file| next if LoadClasses::MTIMES[file] && LoadClasses::MTIMES[file] == File.mtime(file) LoadClasses.reload(file) end nil end end Make this debugging message only on in verbose mode module Merb class BootLoader # def self.subclasses # # :api: plugin cattr_accessor :subclasses, :after_load_callbacks, :before_load_callbacks, :finished, :before_worker_shutdown_callbacks, :before_master_shutdown_callbacks self.subclasses, self.after_load_callbacks, self.before_load_callbacks, self.finished, self.before_master_shutdown_callbacks, self.before_worker_shutdown_callbacks = [], [], [], [], [], [] class << self # Adds the inheriting class to the list of subclasses in a position # specified by the before and after methods. # # ==== Parameters # klass<Class>:: The class inheriting from Merb::BootLoader. # # ==== Returns # nil # # :api: plugin def inherited(klass) subclasses << klass.to_s super end # Execute this boot loader after the specified boot loader. # # ==== Parameters # klass<~to_s>:: # The boot loader class after which this boot loader should be run. # # ==== Returns # nil # # :api: plugin def after(klass) move_klass(klass, 1) nil end # Execute this boot loader before the specified boot loader. # # ==== Parameters # klass<~to_s>:: # The boot loader class before which this boot loader should be run. # # ==== Returns # nil # # :api: plugin def before(klass) move_klass(klass, 0) nil end # Move a class that is inside the bootloader to some place in the Array, # relative to another class. # # ==== Parameters # klass<~to_s>:: # The klass to move the bootloader relative to # where<Integer>:: # 0 means insert it before; 1 means insert it after # # ==== Returns # nil # # :api: private def move_klass(klass, where) index = Merb::BootLoader.subclasses.index(klass.to_s) if index Merb::BootLoader.subclasses.delete(self.to_s) Merb::BootLoader.subclasses.insert(index + where, self.to_s) end nil end # Runs all boot loader classes by calling their run methods. # # ==== Returns # nil # # :api: plugin def run Merb.started = true subklasses = subclasses.dup until subclasses.empty? time = Time.now.to_i bootloader = subclasses.shift if (ENV['DEBUG'] || $DEBUG || Merb::Config[:verbose]) && Merb.logger Merb.logger.debug!("Loading: #{bootloader}") end Object.full_const_get(bootloader).run if (ENV['DEBUG'] || $DEBUG || Merb::Config[:verbose]) && Merb.logger Merb.logger.debug!("It took: #{Time.now.to_i - time}") end self.finished << bootloader end self.subclasses = subklasses nil end # Determines whether or not a specific bootloader has finished yet. # # ==== Parameters # bootloader<String, Class>:: The name of the bootloader to check. # # ==== Returns # Boolean:: Whether or not the bootloader has finished. # # :api: private def finished?(bootloader) self.finished.include?(bootloader.to_s) end # Set up the default framework # # ==== Returns # nil # # :api: plugin # @overridable def default_framework %w[view model helper controller mailer part].each do |component| Merb.push_path(component.to_sym, Merb.root_path("app/#{component}s")) end Merb.push_path(:application, Merb.root_path("app" / "controllers" / "application.rb")) Merb.push_path(:config, Merb.root_path("config"), nil) Merb.push_path(:router, Merb.dir_for(:config), (Merb::Config[:router_file] || "router.rb")) Merb.push_path(:lib, Merb.root_path("lib"), nil) Merb.push_path(:merb_session, Merb.root_path("merb" / "session")) Merb.push_path(:log, Merb.log_path, nil) Merb.push_path(:public, Merb.root_path("public"), nil) Merb.push_path(:stylesheet, Merb.dir_for(:public) / "stylesheets", nil) Merb.push_path(:javascript, Merb.dir_for(:public) / "javascripts", nil) Merb.push_path(:image, Merb.dir_for(:public) / "images", nil) nil end # Execute a block of code after the app loads. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed after the # app loads. # # :api: public def after_app_loads(&block) after_load_callbacks << block end # Execute a block of code before the app loads but after dependencies load. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed before the # app loads. # # :api: public def before_app_loads(&block) before_load_callbacks << block end # Execute a block of code before master process is shut down. # Only makes sense on platforms where Merb server can use forking. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed # before master process is shut down. # # :api: public def before_master_shutdown(&block) before_master_shutdown_callbacks << block end # Execute a block of code before worker process is shut down. # Only makes sense on platforms where Merb server can use forking. # # ==== Parameters # &block:: # A block to be added to the callbacks that will be executed # before worker process is shut down. # # :api: public def before_worker_shutdown(&block) before_worker_shutdown_callbacks << block end end end end # Set up the logger. # # Place the logger inside of the Merb log directory (set up in # Merb::BootLoader::BuildFramework) class Merb::BootLoader::Logger < Merb::BootLoader # Sets Merb.logger to a new logger created based on the config settings. # # ==== Returns # nil # # :api: plugin def self.run Merb::Config[:log_level] ||= begin if Merb.environment == "production" Merb::Logger::Levels[:warn] else Merb::Logger::Levels[:debug] end end Merb::Config[:log_stream] = Merb::Config[:original_log_stream] || Merb.log_stream print_warnings nil end # Print a warning if the installed version of rubygems is not supported # # ==== Returns # nil # # :api: private def self.print_warnings if Gem::Version.new(Gem::RubyGemsVersion) < Gem::Version.new("1.1") Merb.fatal! "Merb requires Rubygems 1.1 and later. " \ "Please upgrade RubyGems with gem update --system." end end end # Stores pid file. # # Only run if daemonization or clustering options specified on start. # Port is taken from Merb::Config and must be already set at this point. class Merb::BootLoader::DropPidFile < Merb::BootLoader class << self # Stores a PID file if Merb is running daemonized or clustered. # # ==== Returns # nil # # :api: plugin def run Merb::Server.store_pid("main") #if Merb::Config[:daemonize] || Merb::Config[:cluster] nil end end end # Setup some useful defaults class Merb::BootLoader::Defaults < Merb::BootLoader # Sets up the defaults # # ==== Returns # nil # # :api: plugin def self.run Merb::Request.http_method_overrides.concat([ proc { |c| c.params[:_method] }, proc { |c| c.env['HTTP_X_HTTP_METHOD_OVERRIDE'] } ]) nil end end # Build the framework paths. # # By default, the following paths will be used: # application:: Merb.root/app/controller/application.rb # config:: Merb.root/config # lib:: Merb.root/lib # log:: Merb.root/log # view:: Merb.root/app/views # model:: Merb.root/app/models # controller:: Merb.root/app/controllers # helper:: Merb.root/app/helpers # mailer:: Merb.root/app/mailers # part:: Merb.root/app/parts # # To override the default, set Merb::Config[:framework] in your initialization # file. Merb::Config[:framework] takes a Hash whose key is the name of the # path, and whose values can be passed into Merb.push_path (see Merb.push_path # for full details). # # ==== Notes # All paths will default to Merb.root, so you can get a flat-file structure by # doing Merb::Config[:framework] = {}. # # ==== Example # Merb::Config[:framework] = { # :view => Merb.root / "views", # :model => Merb.root / "models", # :lib => Merb.root / "lib", # :public => [Merb.root / "public", nil] # :router => [Merb.root / "config", "router.rb"] # } # # That will set up a flat directory structure with the config files and # controller files under Merb.root, but with models, views, and lib with their # own folders off of Merb.root. class Merb::BootLoader::BuildFramework < Merb::BootLoader class << self # Builds the framework directory structure. # # ==== Returns # nil # # :api: plugin def run $:.push Merb.root unless Merb.root == File.expand_path(Dir.pwd) build_framework nil end # Sets up merb paths to support the app's file layout. First, config/framework.rb is checked, # next we look for Merb.root/framework.rb, finally we use the default merb layout (Merb::BootLoader.default_framework) # # This method can be overriden to support other application layouts. # # ==== Returns # nil # # :api: plugin # @overridable def build_framework if File.exists?(Merb.root / "config" / "framework.rb") require Merb.root / "config" / "framework" elsif File.exists?(Merb.root / "framework.rb") require Merb.root / "framework" else Merb::BootLoader.default_framework end (Merb::Config[:framework] || {}).each do |name, path| path = Array(path) Merb.push_path(name, path.first, path.length == 2 ? path[1] : "**/*.rb") end nil end end end class Merb::BootLoader::Dependencies < Merb::BootLoader # ==== Returns # Array[Gem::Dependency]:: The dependencies regiestered in init.rb. # # :api: plugin cattr_accessor :dependencies self.dependencies = [] # Load the init_file specified in Merb::Config or if not specified, the # init.rb file from the Merb configuration directory, and any environment # files, which register the list of necessary dependencies and any # after_app_loads hooks. # # Dependencies can hook into the bootloader process itself by using # before or after insertion methods. Since these are loaded from this # bootloader (Dependencies), they can only adapt the bootloaders that # haven't been loaded up until this point. # # ==== Returns # nil # # :api: plugin def self.run set_encoding # this is crucial: load init file with all the preferences # then environment init file, then start enabling specific # components, load dependencies and update logger. unless Merb::disabled?(:initfile) load_initfile load_env_config end expand_ruby_path enable_json_gem unless Merb::disabled?(:json) load_dependencies update_logger nil end # Load each dependency that has been declared so far. # # ==== Returns # nil # # :api: private def self.load_dependencies dependencies.each { |dependency| Kernel.load_dependency(dependency, nil) } nil end # Loads json or json_pure and requires it. # # ==== Returns # nil # # :api: private def self.enable_json_gem gem "json" require "json/ext" rescue LoadError gem "json_pure" require "json/pure" end # Resets the logger and sets the log_stream to Merb::Config[:log_file] # if one is specified, falling back to STDOUT. # # ==== Returns # nil # # :api: private def self.update_logger Merb.reset_logger! # If log file is given, use it and not log stream we have. if Merb::Config[:log_file] raise "log file should be a string, got: #{Merb::Config[:log_file].inspect}" unless Merb::Config[:log_file].is_a?(String) STDOUT.puts "Logging to file at #{Merb::Config[:log_file]}" unless Merb.testing? Merb::Config[:log_stream] = File.open(Merb::Config[:log_file], "a") # but if it's not given, fallback to log stream or stdout else Merb::Config[:log_stream] ||= STDOUT end nil end # Default encoding to UTF8 if it has not already been set to something else. # # ==== Returns # nil # # :api: private def self.set_encoding unless Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("1.9") $KCODE = 'UTF8' if $KCODE == 'NONE' || $KCODE.blank? end nil end private # Determines the path for the environment configuration file # # ==== Returns # String:: The path to the config file for the environment # # :api: private def self.env_config Merb.dir_for(:config) / "environments" / (Merb.environment + ".rb") end # Checks to see whether or not an environment configuration exists # # ==== Returns # Boolean:: Whether or not the environment configuration file exists. # # :api: private def self.env_config? Merb.environment && File.exist?(env_config) end # Loads the environment configuration file, if it is present # # ==== Returns # nil # # :api: private def self.load_env_config if env_config? STDOUT.puts "Loading #{env_config}" unless Merb.testing? load(env_config) end nil end # Determines the init file to use, if any. # By default Merb uses init.rb from application config directory. # # ==== Returns # nil # # :api: private def self.initfile if Merb::Config[:init_file] Merb::Config[:init_file].chomp(".rb") + ".rb" else Merb.dir_for(:config) / "init.rb" end end # Loads the init file, should one exist # # ==== Returns # nil # # :api: private def self.load_initfile if File.exists?(initfile) STDOUT.puts "Loading init file from #{initfile}" unless Merb.testing? load(initfile) elsif !Merb.testing? Merb.fatal! "You are not in a Merb application, or you are in " \ "a flat application and have not specified the init file. If you " \ "are trying to create a new merb application, use merb-gen app." end nil end # Expands Ruby path with framework directories (for models, lib, etc). Only run once. # # ==== Returns # nil # # :api: private def self.expand_ruby_path # Add models, controllers, helpers and lib to the load path unless @ran Merb.logger.info "Expanding RUBY_PATH..." if Merb::Config[:verbose] $LOAD_PATH.unshift Merb.dir_for(:model) $LOAD_PATH.unshift Merb.dir_for(:controller) $LOAD_PATH.unshift Merb.dir_for(:lib) $LOAD_PATH.unshift Merb.dir_for(:helper) end @ran = true nil end end class Merb::BootLoader::MixinSession < Merb::BootLoader # Mixin the session functionality; this is done before BeforeAppLoads # so that SessionContainer and SessionStoreContainer can be subclassed by # plugin session stores for example - these need to be loaded in a # before_app_loads block or a BootLoader that runs after MixinSession. # # Note: access to Merb::Config is needed, so it needs to run after # Merb::BootLoader::Dependencies is done. # # ==== Returns # nil # # :api: plugin def self.run require 'merb-core/dispatch/session' Merb::Controller.send(:include, ::Merb::SessionMixin) Merb::Request.send(:include, ::Merb::SessionMixin::RequestMixin) end end class Merb::BootLoader::BeforeAppLoads < Merb::BootLoader # Call any before_app_loads hooks that were registered via before_app_loads # in any plugins. # # ==== Returns # nil # # :api: plugin def self.run Merb::BootLoader.before_load_callbacks.each { |x| x.call } nil end end # Load all classes inside the load paths. # # This is used in conjunction with Merb::BootLoader::ReloadClasses to track # files that need to be reloaded, and which constants need to be removed in # order to reload a file. # # This also adds the model, controller, and lib directories to the load path, # so they can be required in order to avoid load-order issues. class Merb::BootLoader::LoadClasses < Merb::BootLoader LOADED_CLASSES = {} MTIMES = {} FILES_LOADED = {} class << self # Load all classes from Merb's native load paths. # # If fork-based loading is used, every time classes are loaded this will return in a new spawner process # and boot loading will continue from this point in the boot loading process. # # If fork-based loading is not in use, this only returns once and does not fork a new # process. # # ==== Returns # Returns at least once: # nil # # :api: plugin def run # process name you see in ps output $0 = "merb#{" : " + Merb::Config[:name] if Merb::Config[:name]} : master" # Log the process configuration user defined signal 1 (SIGUSR1) is received. Merb.trap("USR1") do require "yaml" Merb.logger.fatal! "Configuration:\n#{Merb::Config.to_hash.merge(:pid => $$).to_yaml}\n\n" end if Merb::Config[:fork_for_class_load] && !Merb.testing? start_transaction else Merb.trap('INT') do Merb.logger.warn! "Reaping Workers" reap_workers end end # Load application file if it exists - for flat applications load_file Merb.dir_for(:application) if File.file?(Merb.dir_for(:application)) # Load classes and their requirements Merb.load_paths.each do |component, path| next if path.last.blank? || component == :application || component == :router load_classes(path.first / path.last) end Merb::Controller.send :include, Merb::GlobalHelpers nil end # Wait for any children to exit, remove the "main" PID, and # exit. # # ==== Returns # (Does not return.) # # :api: private def exit_gracefully # wait all workers to exit Process.waitall # remove master process pid Merb::Server.remove_pid("main") # terminate, workers remove their own pids # in on exit hook Merb::BootLoader.before_master_shutdown_callbacks.each do |cb| begin cb.call rescue Exception => e Merb.logger.fatal "before_master_shutdown callback crashed: #{e.message}" end end exit end # Set up the BEGIN point for fork-based loading and sets up # any signals in the parent and child. This is done by forking # the app. The child process continues on to run the app. The parent # process waits for the child process to finish and either forks again # # # ==== Returns # Parent Process: # (Does not return.) # Child Process returns at least once: # nil # # :api: private def start_transaction Merb.logger.warn! "Parent pid: #{Process.pid}" reader, writer = nil, nil if GC.respond_to?(:copy_on_write_friendly=) GC.copy_on_write_friendly = true end loop do # create two connected endpoints # we use them for master/workers communication reader, @writer = IO.pipe pid = Kernel.fork # pid means we're in the parent; only stay in the loop if that is case break unless pid # writer must be closed so reader can generate EOF condition @writer.close # master process stores pid to merb.main.pid Merb::Server.store_pid("main") if Merb::Config[:console_trap] Merb.trap("INT") {} else # send ABRT to worker on INT Merb.trap("INT") do Merb.logger.warn! "Reaping Workers" begin Process.kill(reap_workers_signal, pid) rescue SystemCallError end exit_gracefully end end Merb.trap("HUP") do Merb.logger.warn! "Doing a fast deploy\n" Process.kill("HUP", pid) end reader_ary = [reader] loop do # wait for worker to exit and capture exit status # # # WNOHANG specifies that wait2 exists without waiting # if no worker processes are ready to be noticed. if exit_status = Process.wait2(pid, Process::WNOHANG) # wait2 returns a 2-tuple of process id and exit # status. # # We do not care about specific pid here. exit_status[1] && exit_status[1].exitstatus == 128 ? break : exit end # wait for data to become available, timeout in 0.25 of a second if select(reader_ary, nil, nil, 0.25) begin # no open writers next if reader.eof? msg = reader.readline if msg =~ /128/ Process.detach(pid) break else exit_gracefully end rescue SystemCallError exit_gracefully end end end end reader.close # add traps to the worker if Merb::Config[:console_trap] Merb::Server.add_irb_trap at_exit { reap_workers } else Merb.trap('INT') do Merb::BootLoader.before_worker_shutdown_callbacks.each { |cb| cb.call } end Merb.trap('ABRT') { reap_workers } Merb.trap('HUP') { reap_workers(128, "ABRT") } end end def reap_workers_signal Merb::Config[:reap_workers_quickly] ? "KILL" : "ABRT" end # Reap any workers of the spawner process and # exit with an appropriate status code. # # Note that exiting the spawner process with a status code # of 128 when a master process exists will cause the # spawner process to be recreated, and the app code reloaded. # # ==== Parameters # status<Integer>:: The status code to exit with. Defaults to 0. # sig<String>:: The signal to send to workers # # ==== Returns # (Does not return.) # # :api: private def reap_workers(status = 0, sig = reap_workers_signal) Merb.logger.info "Executed all before worker shutdown callbacks..." Merb::BootLoader.before_worker_shutdown_callbacks.each do |cb| begin cb.call rescue Exception => e Merb.logger.fatal "before worker shutdown callback crashed: #{e.message}" end end Merb.exiting = true unless status == 128 begin @writer.puts(status.to_s) if @writer rescue SystemCallError end threads = [] ($WORKERS || []).each do |p| threads << Thread.new do begin Process.kill(sig, p) Process.wait2(p) rescue SystemCallError end end end threads.each {|t| t.join } exit(status) end # Loads a file, tracking its modified time and, if necessary, the classes it declared. # # ==== Parameters # file<String>:: The file to load. # # ==== Returns # nil # # :api: private def load_file(file, reload = false) Merb.logger.verbose! "#{reload ? "re" : ""}loading #{file}" # If we're going to be reloading via constant remove, # keep track of what constants were loaded and what files # have been added, so that the constants can be removed # and the files can be removed from $LOADED_FEAUTRES if !Merb::Config[:fork_for_class_load] if FILES_LOADED[file] FILES_LOADED[file].each {|lf| $LOADED_FEATURES.delete(lf)} end klasses = ObjectSpace.classes.dup files_loaded = $LOADED_FEATURES.dup end # If we're in the midst of a reload, remove the file # itself from $LOADED_FEATURES so it will get reloaded if reload $LOADED_FEATURES.delete(file) if reload end # Ignore the file for syntax errors. The next time # the file is changed, it'll be reloaded again begin require file rescue SyntaxError => e Merb.logger.error "Cannot load #{file} because of syntax error: #{e.message}" ensure if Merb::Config[:reload_classes] MTIMES[file] = File.mtime(file) end end # If we're reloading via constant remove, store off the details # after the file has been loaded unless Merb::Config[:fork_for_class_load] LOADED_CLASSES[file] = ObjectSpace.classes - klasses FILES_LOADED[file] = $LOADED_FEATURES - files_loaded end nil end # Load classes from given paths - using path/glob pattern. # # ==== Parameters # *paths<Array>:: # Array of paths to load classes from - may contain glob pattern # # ==== Returns # nil # # :api: private def load_classes(*paths) orphaned_classes = [] paths.flatten.each do |path| Dir[path].each do |file| begin load_file file rescue NameError => ne orphaned_classes.unshift(file) end end end load_classes_with_requirements(orphaned_classes) end # Reloads the classes in the specified file. If fork-based loading is used, # this causes the current processes to be killed and and all classes to be # reloaded. If class-based loading is not in use, the classes declared in that file # are removed and the file is reloaded. # # ==== Parameters # file<String>:: The file to reload. # # ==== Returns # When fork-based loading is used: # (Does not return.) # When fork-based loading is not in use: # nil # # :api: private def reload(file) if Merb::Config[:fork_for_class_load] reap_workers(128) else remove_classes_in_file(file) { |f| load_file(f, true) } end end # Removes all classes declared in the specified file. Any hashes which use classes as keys # will be protected provided they have been added to Merb.klass_hashes. These hashes have their # keys substituted with placeholders before the file's classes are unloaded. If a block is provided, # it is called before the substituted keys are reconstituted. # # ==== Parameters # file<String>:: The file to remove classes for. # &block:: A block to call with the file that has been removed before klass_hashes are updated # to use the current values of the constants they used as keys. # # ==== Returns # nil # # :api: private def remove_classes_in_file(file, &block) Merb.klass_hashes.each { |x| x.protect_keys! } if klasses = LOADED_CLASSES.delete(file) klasses.each { |klass| remove_constant(klass) unless klass.to_s =~ /Router/ } end yield file if block_given? Merb.klass_hashes.each {|x| x.unprotect_keys!} nil end # Removes the specified class. # # Additionally, removes the specified class from the subclass list of every superclass that # tracks it's subclasses in an array returned by _subclasses_list. Classes that wish to use this # functionality are required to alias the reader for their list of subclasses # to _subclasses_list. Plugins for ORMs and other libraries should keep this in mind. # # ==== Parameters # const<Class>:: The class to remove. # # ==== Returns # nil # # :api: private def remove_constant(const) # This is to support superclasses (like AbstractController) that track # their subclasses in a class variable. superklass = const until (superklass = superklass.superclass).nil? if superklass.respond_to?(:_subclasses_list) superklass.send(:_subclasses_list).delete(klass) superklass.send(:_subclasses_list).delete(klass.to_s) end end parts = const.to_s.split("::") base = parts.size == 1 ? Object : Object.full_const_get(parts[0..-2].join("::")) object = parts[-1].to_s begin base.send(:remove_const, object) Merb.logger.debug("Removed constant #{object} from #{base}") rescue NameError Merb.logger.debug("Failed to remove constant #{object} from #{base}") end nil end private # "Better loading" of classes. If a file fails to load due to a NameError # it will be added to the failed_classes and load cycle will be repeated unless # no classes load. # # ==== Parameters # klasses<Array[Class]>:: Classes to load. # # ==== Returns # nil # # :api: private def load_classes_with_requirements(klasses) klasses.uniq! while klasses.size > 0 # Note size to make sure things are loading size_at_start = klasses.size # List of failed classes failed_classes = [] # Map classes to exceptions error_map = {} klasses.each do |klass| klasses.delete(klass) begin load_file klass rescue NameError => ne error_map[klass] = ne failed_classes.push(klass) end end # Keep list of classes unique failed_classes.each { |k| klasses.push(k) unless klasses.include?(k) } # Stop processing if nothing loads or if everything has loaded if klasses.size == size_at_start && klasses.size != 0 # Write all remaining failed classes and their exceptions to the log messages = error_map.only(*failed_classes).map do |klass, e| ["Could not load #{klass}:\n\n#{e.message} - (#{e.class})", "#{(e.backtrace || []).join("\n")}"] end messages.each { |msg, trace| Merb.logger.fatal!("#{msg}\n\n#{trace}") } Merb.fatal! "#{failed_classes.join(", ")} failed to load." end break if(klasses.size == size_at_start || klasses.size == 0) end nil end end end # Loads the router file. This needs to happen after everything else is loaded while merb is starting up to ensure # the router has everything it needs to run. class Merb::BootLoader::Router < Merb::BootLoader class << self # load the router file # # ==== Returns # nil # # :api: plugin def run Merb::BootLoader::LoadClasses.load_file(router_file) if router_file nil end # Tries to find the router file. # # ==== Returns # String:: The path to the router file if it exists, nil otherwise. # # :api: private def router_file @router_file ||= begin if File.file?(router = Merb.dir_for(:router) / Merb.glob_for(:router)) router end end end end end # Precompiles all non-partial templates. class Merb::BootLoader::Templates < Merb::BootLoader class << self # Loads all non-partial templates into the Merb::InlineTemplates module. # # ==== Returns # Array[String]:: The list of template files which were loaded. # # :api: plugin def run template_paths.each do |path| Merb::Template.inline_template(File.open(path)) end end # Finds a list of templates to load. # # ==== Returns # Array[String]:: All found template files whose basename does not begin with "_". # # :api: private def template_paths extension_glob = "{#{Merb::Template.template_extensions.join(',')}}" # This gets all templates set in the controllers template roots # We separate the two maps because most of controllers will have # the same _template_root, so it's silly to be globbing the same # path over and over. controller_view_paths = [] Merb::AbstractController._abstract_subclasses.each do |klass| next if (const = Object.full_const_get(klass))._template_root.blank? controller_view_paths += const._template_roots.map { |pair| pair.first } end template_paths = controller_view_paths.uniq.compact.map { |path| Dir["#{path}/**/*.#{extension_glob}"] } # This gets the templates that might be created outside controllers # template roots. eg app/views/shared/* template_paths << Dir["#{Merb.dir_for(:view)}/**/*.#{extension_glob}"] if Merb.dir_for(:view) # This ignores templates for partials, which need to be compiled at use time to generate # a preamble that assigns local variables template_paths.flatten.compact.uniq.grep(%r{^.*/[^_][^/]*$}) end end end # Register the default MIME types: # # By default, the mime-types include: # :all:: no transform, */* # :yaml:: to_yaml, application/x-yaml or text/yaml # :text:: to_text, text/plain # :html:: to_html, text/html or application/xhtml+xml or application/html # :xml:: to_xml, application/xml or text/xml or application/x-xml # :js:: to_json, text/javascript ot application/javascript or application/x-javascript # :json:: to_json, application/json or text/x-json class Merb::BootLoader::MimeTypes < Merb::BootLoader # Registers the default MIME types. # # ==== Returns # nil # # :api: plugin def self.run Merb.add_mime_type(:all, nil, %w[*/*]) Merb.add_mime_type(:yaml, :to_yaml, %w[application/x-yaml text/yaml], :charset => "utf-8") Merb.add_mime_type(:text, :to_text, %w[text/plain], :charset => "utf-8") Merb.add_mime_type(:html, :to_html, %w[text/html application/xhtml+xml application/html], :charset => "utf-8") Merb.add_mime_type(:xml, :to_xml, %w[application/xml text/xml application/x-xml], {:charset => "utf-8"}, 0.9998) Merb.add_mime_type(:js, :to_json, %w[text/javascript application/javascript application/x-javascript], :charset => "utf-8") Merb.add_mime_type(:json, :to_json, %w[application/json text/x-json], :charset => "utf-8") nil end end # Set up cookies support in Merb::Controller and Merb::Request class Merb::BootLoader::Cookies < Merb::BootLoader # Set up cookies support in Merb::Controller and Merb::Request # # ==== Returns # nil # # :api: plugin def self.run require 'merb-core/dispatch/cookies' Merb::Controller.send(:include, Merb::CookiesMixin) Merb::Request.send(:include, Merb::CookiesMixin::RequestMixin) nil end end class Merb::BootLoader::SetupSession < Merb::BootLoader # Enable the configured session container(s); any class that inherits from # SessionContainer will be considered by its session_store_type attribute. # # ==== Returns # nil # # :api: plugin def self.run # Require all standard session containers. Dir[Merb.framework_root / "merb-core" / "dispatch" / "session" / "*.rb"].each do |file| base_name = File.basename(file, ".rb") require file unless base_name == "container" || base_name == "store_container" end # Set some defaults. Merb::Config[:session_id_key] ||= "_session_id" # List of all session_stores from :session_stores and :session_store config options. config_stores = Merb::Config.session_stores # Register all configured session stores - any loaded session container class # (subclassed from Merb::SessionContainer) will be available for registration. Merb::SessionContainer.subclasses.each do |class_name| if(store = Object.full_const_get(class_name)) && config_stores.include?(store.session_store_type) Merb::Request.register_session_type(store.session_store_type, class_name) end end # Mixin the Merb::Session module to add app-level functionality to sessions overrides = (Merb::Session.instance_methods & Merb::SessionContainer.instance_methods) overrides.each do |m| Merb.logger.warn!("Warning: Merb::Session##{m} overrides existing " \ "Merb::SessionContainer##{m}") end Merb::SessionContainer.send(:include, Merb::Session) nil end end # In case someone's running a sparse app, the default exceptions require the # Exceptions class. This must run prior to the AfterAppLoads BootLoader # So that plugins may have ensured access in the after_app_loads block class Merb::BootLoader::SetupStubClasses < Merb::BootLoader # Declares empty Application and Exception controllers. # # ==== Returns # nil # # :api: plugin def self.run unless defined?(Exceptions) Object.class_eval <<-RUBY class Application < Merb::Controller abstract! end class Exceptions < Merb::Controller end RUBY end nil end end class Merb::BootLoader::AfterAppLoads < Merb::BootLoader # Call any after_app_loads hooks that were registered via after_app_loads in # init.rb. # # ==== Returns # nil # # :api: plugin def self.run Merb::BootLoader.after_load_callbacks.each {|x| x.call } nil end end class Merb::BootLoader::ChooseAdapter < Merb::BootLoader # Choose the Rack adapter/server to use and set Merb.adapter. # # ==== Returns # nil # # :api: plugin def self.run Merb.adapter = Merb::Rack::Adapter.get(Merb::Config[:adapter]) end end class Merb::BootLoader::RackUpApplication < Merb::BootLoader # Setup the Merb Rack App or read a rackup file located at # Merb::Config[:rackup] with the same syntax as the # rackup tool that comes with rack. Automatically evals the file in # the context of a Rack::Builder.new { } block. Allows for mounting # additional apps or middleware. # # ==== Returns # nil # # :api: plugin def self.run require 'rack' if File.exists?(Merb.dir_for(:config) / "rack.rb") Merb::Config[:rackup] ||= Merb.dir_for(:config) / "rack.rb" end if Merb::Config[:rackup] rackup_code = File.read(Merb::Config[:rackup]) Merb::Config[:app] = eval("::Rack::Builder.new {( #{rackup_code}\n )}.to_app", TOPLEVEL_BINDING, Merb::Config[:rackup]) else Merb::Config[:app] = ::Rack::Builder.new { if prefix = ::Merb::Config[:path_prefix] use Merb::Rack::PathPrefix, prefix end use Merb::Rack::Static, Merb.dir_for(:public) run Merb::Rack::Application.new }.to_app end nil end end class Merb::BootLoader::ReloadClasses < Merb::BootLoader class TimedExecutor # Executes the associated block every @seconds@ seconds in a separate thread. # # ==== Parameters # seconds<Integer>:: Number of seconds to sleep in between runs of &block. # &block:: The block to execute periodically. # # ==== Returns # Thread:: The thread executing the block periodically. # # :api: private def self.every(seconds, &block) Thread.new do loop do sleep( seconds ) yield end Thread.exit end end end # Set up the class reloader if class reloading is enabled. This checks periodically # for modifications to files loaded by the LoadClasses BootLoader and reloads them # when they are modified. # # ==== Returns # nil # # :api: plugin def self.run return unless Merb::Config[:reload_classes] paths = [] Merb.load_paths.each do |path_name, file_info| path, glob = file_info next unless glob paths << Dir[path / glob] end if Merb.dir_for(:application) && File.file?(Merb.dir_for(:application)) paths << Merb.dir_for(:application) end paths.flatten! TimedExecutor.every(Merb::Config[:reload_time] || 0.5) do GC.start reload(paths) end nil end # Reloads all files which have been modified since they were last loaded. # # ==== Returns # nil # # :api: private def self.reload(paths) paths.each do |file| next if LoadClasses::MTIMES[file] && LoadClasses::MTIMES[file] == File.mtime(file) LoadClasses.reload(file) end nil end end
module BeGateway VERSION = '0.19.0' end Up version 0.20.0 module BeGateway VERSION = '0.20.0' end
module BigKeeper VERSION = "0.6.0" end release 0.7.0 module BigKeeper VERSION = "0.7.0" end
# # bio/db/kegg/genome.rb - KEGG/GENOME database class # # Copyright (C) 2001, 2002 KATAYAMA Toshiaki <k@bioruby.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id: genome.rb,v 0.10 2002/03/04 08:13:25 katayama Exp $ # require 'bio/db' module Bio class KEGG class GENOME < KEGGDB DELIMITER = RS = "\n///\n" TAGSIZE = 12 def initialize(entry) super(entry, TAGSIZE) end # ENTRY def entry_id field_fetch('ENTRY') end # NAME def name field_fetch('NAME') end # DEFINITION def definition field_fetch('DEFINITION') end alias organism definition # TAXONOMY def taxonomy unless @data['TAXONOMY'] taxid, lineage = subtag2array(get('TAXONOMY')) @data['TAXONOMY'] = { 'taxid' => truncate(tag_cut(taxid)), 'lineage' => truncate(tag_cut(lineage)) } @data['TAXONOMY'].default = '' end @data['TAXONOMY'] end def taxid taxonomy['taxid'] end def lineage taxonomy['lineage'] end # COMMENT def comment field_fetch('COMMENT') end # REFERENCE def references unless @data['REFERENCE'] ary = [] toptag2array(get('REFERENCE')).each do |ref| hash = Hash.new('') subtag2array(ref).each do |field| case tag_get(field) when /AUTHORS/ authors = truncate(tag_cut(field)) authors = authors.split(', ') authors[-1] = authors[-1].split('\s+and\s+') authors = authors.flatten.map { |a| a.sub(',', ', ') } hash['authors'] = authors when /TITLE/ hash['title'] = truncate(tag_cut(field)) when /JOURNAL/ journal = truncate(tag_cut(field)) if journal =~ /(.*) (\d+):(\d+)-(\d+) \((\d+)\) \[UI:(\d+)\]$/ hash['journal'] = $1 hash['volume'] = $2 hash['pages'] = $3 hash['year'] = $5 hash['medline'] = $6 else hash['journal'] = journal end end end ary.push(Reference.new(hash)) end @data['REFERENCE'] = References.new(ary) end @data['REFERENCE'] end # CHROMOSOME def chromosomes unless @data['CHROMOSOME'] @data['CHROMOSOME'] = [] toptag2array(get('CHROMOSOME')).each do |chr| hash = Hash.new('') subtag2array(chr).each do |field| hash[tag_get(field)] = truncate(tag_cut(field)) end @data['CHROMOSOME'].push(hash) end end @data['CHROMOSOME'] end # PLASMID def plasmids unless @data['PLASMID'] @data['PLASMID'] = [] toptag2array(get('PLASMID')).each do |chr| hash = Hash.new('') subtag2array(chr).each do |field| hash[tag_get(field)] = truncate(tag_cut(field)) end @data['PLASMID'].push(hash) end end @data['PLASMID'] end # SCAFFOLD def scaffolds unless @data['SCAFFOLD'] @data['SCAFFOLD'] = [] toptag2array(get('SCAFFOLD')).each do |chr| hash = Hash.new('') subtag2array(chr).each do |field| hash[tag_get(field)] = truncate(tag_cut(field)) end @data['SCAFFOLD'].push(hash) end end @data['SCAFFOLD'] end # STATISTICS def statistics unless @data['STATISTICS'] hash = Hash.new(0.0) get('STATISTICS').each_line do |line| case line when /nucleotides.*(\d+)/ hash['nalen'] = $1.to_i when /protein genes.*(\d+)/ hash['num_gene'] = $1.to_i when /RNA genes.*(\d+)/ hash['num_rna'] = $1.to_i when /G\+C content.*(\d+.\d+)/ hash['gc'] = $1.to_f end end @data['STATISTICS'] = hash end @data['STATISTICS'] end def nalen statistics['nalen'] end alias length nalen def num_gene statistics['num_gene'] end def num_rna statistics['num_rna'] end def gc statistics['gc'] end # GENOMEMAP def genomemap field_fetch('GENOMEMAP') end end end end if __FILE__ == $0 begin require 'pp' def p(arg); pp(arg); end rescue LoadError end require 'bio/io/flatfile' ff = Bio::FlatFile.new(Bio::KEGG::GENOME, ARGF) ff.each do |genome| puts "### Tags" p genome.tags [ %w( ENTRY entry_id ), %w( NAME name ), %w( DEFINITION definition ), %w( TAXONOMY taxonomy taxid lineage ), %w( REFERENCE references ), %w( CHROMOSOME chromosomes ), %w( PLASMID plasmids ), %w( SCAFFOLD plasmids ), %w( STATISTICS statistics nalen num_gene num_rna gc ), %w( GENOMEMAP genomemap ), ].each do |x| puts "### " + x.shift x.each do |m| p genome.send(m) end end end end =begin = Bio::KEGG::GENOME === Initialize --- Bio::KEGG::GENOME.new(entry) === ENTRY --- Bio::KEGG::GENOME#entry_id -> String Returns contents of the ENTRY record as a String. === NAME --- Bio::KEGG::GENOME#name -> String Returns contents of the NAME record as a String. === DEFINITION --- Bio::KEGG::GENOME#definition -> String Returns contents of the DEFINITION record as a String. --- Bio::KEGG::GENOME#organism -> String Alias for the 'definition' method. === TAXONOMY --- Bio::KEGG::GENOME#taxonomy -> Hash Returns contents of the TAXONOMY record as a Hash. --- Bio::KEGG::GENOME#taxid -> String Returns NCBI taxonomy ID from the TAXONOMY record as a String. --- Bio::KEGG::GENOME#lineage -> String Returns contents of the TAXONOMY/LINEAGE record as a String. === COMMENT --- Bio::KEGG::GENOME#comment -> String Returns contents of the COMMENT record as a String. === REFERENCE --- Bio::GenBank#references -> Array Returns contents of the REFERENCE records as an Array of Bio::Reference objects. === CHROMOSOME --- Bio::KEGG::GENOME#chromosomes -> Array Returns contents of the CHROMOSOME records as an Array of Hash. === PLASMID --- Bio::KEGG::GENOME#plasmids -> Array Returns contents of the PLASMID records as an Array of Hash. === SCAFFOLD --- Bio::KEGG::GENOME#scaffolds -> Array Returns contents of the SCAFFOLD records as an Array of Hash. === STATISTICS --- Bio::KEGG::GENOME#statistics -> Hash Returns contents of the STATISTICS record as a Hash. --- Bio::KEGG::GENOME#nalen -> Fixnum Returns number of nucleotides from the STATISTICS record as a Fixnum. --- Bio::KEGG::GENOME#num_gene -> Fixnum Returns number of protein genes from the STATISTICS record as a Fixnum. --- Bio::KEGG::GENOME#num_rna -> Fixnum Returns number of rna from the STATISTICS record as a Fixnum. --- Bio::KEGG::GENOME#gc -> Float Returns G+C content from the STATISTICS record as a Float. === GENOMEMAP --- Bio::KEGG::GENOME#genomemap -> String Returns contents of the GENOMEMAP record as a String. == SEE ALSO ftp://ftp.genome.ad.jp/pub/kegg/genomes/genome =end * bugs in statistics field fixed by Shuichi Kawashima # # bio/db/kegg/genome.rb - KEGG/GENOME database class # # Copyright (C) 2001, 2002 KATAYAMA Toshiaki <k@bioruby.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # $Id: genome.rb,v 0.11 2003/09/20 08:17:36 k Exp $ # require 'bio/db' module Bio class KEGG class GENOME < KEGGDB DELIMITER = RS = "\n///\n" TAGSIZE = 12 def initialize(entry) super(entry, TAGSIZE) end # ENTRY def entry_id field_fetch('ENTRY') end # NAME def name field_fetch('NAME') end # DEFINITION def definition field_fetch('DEFINITION') end alias organism definition # TAXONOMY def taxonomy unless @data['TAXONOMY'] taxid, lineage = subtag2array(get('TAXONOMY')) taxid = taxid ? truncate(tag_cut(taxid)) : '' lineage = lineage ? truncate(tag_cut(lineage)) : '' @data['TAXONOMY'] = { 'taxid' => taxid, 'lineage' => lineage, } @data['TAXONOMY'].default = '' end @data['TAXONOMY'] end def taxid taxonomy['taxid'] end def lineage taxonomy['lineage'] end # COMMENT def comment field_fetch('COMMENT') end # REFERENCE def references unless @data['REFERENCE'] ary = [] toptag2array(get('REFERENCE')).each do |ref| hash = Hash.new('') subtag2array(ref).each do |field| case tag_get(field) when /AUTHORS/ authors = truncate(tag_cut(field)) authors = authors.split(', ') authors[-1] = authors[-1].split('\s+and\s+') authors = authors.flatten.map { |a| a.sub(',', ', ') } hash['authors'] = authors when /TITLE/ hash['title'] = truncate(tag_cut(field)) when /JOURNAL/ journal = truncate(tag_cut(field)) if journal =~ /(.*) (\d+):(\d+)-(\d+) \((\d+)\) \[UI:(\d+)\]$/ hash['journal'] = $1 hash['volume'] = $2 hash['pages'] = $3 hash['year'] = $5 hash['medline'] = $6 else hash['journal'] = journal end end end ary.push(Reference.new(hash)) end @data['REFERENCE'] = References.new(ary) end @data['REFERENCE'] end # CHROMOSOME def chromosomes unless @data['CHROMOSOME'] @data['CHROMOSOME'] = [] toptag2array(get('CHROMOSOME')).each do |chr| hash = Hash.new('') subtag2array(chr).each do |field| hash[tag_get(field)] = truncate(tag_cut(field)) end @data['CHROMOSOME'].push(hash) end end @data['CHROMOSOME'] end # PLASMID def plasmids unless @data['PLASMID'] @data['PLASMID'] = [] toptag2array(get('PLASMID')).each do |chr| hash = Hash.new('') subtag2array(chr).each do |field| hash[tag_get(field)] = truncate(tag_cut(field)) end @data['PLASMID'].push(hash) end end @data['PLASMID'] end # SCAFFOLD def scaffolds unless @data['SCAFFOLD'] @data['SCAFFOLD'] = [] toptag2array(get('SCAFFOLD')).each do |chr| hash = Hash.new('') subtag2array(chr).each do |field| hash[tag_get(field)] = truncate(tag_cut(field)) end @data['SCAFFOLD'].push(hash) end end @data['SCAFFOLD'] end # STATISTICS def statistics unless @data['STATISTICS'] hash = Hash.new(0.0) get('STATISTICS').each_line do |line| case line when /nucleotides:\s+(\d+)/ hash['nalen'] = $1.to_i when /protein genes:\s+(\d+)/ hash['num_gene'] = $1.to_i when /RNA genes:\s+(\d+)/ hash['num_rna'] = $1.to_i when /G\+C content:\s+(\d+.\d+)/ hash['gc'] = $1.to_f end end @data['STATISTICS'] = hash end @data['STATISTICS'] end def nalen statistics['nalen'] end alias length nalen def num_gene statistics['num_gene'] end def num_rna statistics['num_rna'] end def gc statistics['gc'] end # GENOMEMAP def genomemap field_fetch('GENOMEMAP') end end end end if __FILE__ == $0 begin require 'pp' def p(arg); pp(arg); end rescue LoadError end require 'bio/io/flatfile' ff = Bio::FlatFile.new(Bio::KEGG::GENOME, ARGF) ff.each do |genome| puts "### Tags" p genome.tags [ %w( ENTRY entry_id ), %w( NAME name ), %w( DEFINITION definition ), %w( TAXONOMY taxonomy taxid lineage ), %w( REFERENCE references ), %w( CHROMOSOME chromosomes ), %w( PLASMID plasmids ), %w( SCAFFOLD plasmids ), %w( STATISTICS statistics nalen num_gene num_rna gc ), %w( GENOMEMAP genomemap ), ].each do |x| puts "### " + x.shift x.each do |m| p genome.send(m) end end end end =begin = Bio::KEGG::GENOME === Initialize --- Bio::KEGG::GENOME.new(entry) === ENTRY --- Bio::KEGG::GENOME#entry_id -> String Returns contents of the ENTRY record as a String. === NAME --- Bio::KEGG::GENOME#name -> String Returns contents of the NAME record as a String. === DEFINITION --- Bio::KEGG::GENOME#definition -> String Returns contents of the DEFINITION record as a String. --- Bio::KEGG::GENOME#organism -> String Alias for the 'definition' method. === TAXONOMY --- Bio::KEGG::GENOME#taxonomy -> Hash Returns contents of the TAXONOMY record as a Hash. --- Bio::KEGG::GENOME#taxid -> String Returns NCBI taxonomy ID from the TAXONOMY record as a String. --- Bio::KEGG::GENOME#lineage -> String Returns contents of the TAXONOMY/LINEAGE record as a String. === COMMENT --- Bio::KEGG::GENOME#comment -> String Returns contents of the COMMENT record as a String. === REFERENCE --- Bio::GenBank#references -> Array Returns contents of the REFERENCE records as an Array of Bio::Reference objects. === CHROMOSOME --- Bio::KEGG::GENOME#chromosomes -> Array Returns contents of the CHROMOSOME records as an Array of Hash. === PLASMID --- Bio::KEGG::GENOME#plasmids -> Array Returns contents of the PLASMID records as an Array of Hash. === SCAFFOLD --- Bio::KEGG::GENOME#scaffolds -> Array Returns contents of the SCAFFOLD records as an Array of Hash. === STATISTICS --- Bio::KEGG::GENOME#statistics -> Hash Returns contents of the STATISTICS record as a Hash. --- Bio::KEGG::GENOME#nalen -> Fixnum Returns number of nucleotides from the STATISTICS record as a Fixnum. --- Bio::KEGG::GENOME#num_gene -> Fixnum Returns number of protein genes from the STATISTICS record as a Fixnum. --- Bio::KEGG::GENOME#num_rna -> Fixnum Returns number of rna from the STATISTICS record as a Fixnum. --- Bio::KEGG::GENOME#gc -> Float Returns G+C content from the STATISTICS record as a Float. === GENOMEMAP --- Bio::KEGG::GENOME#genomemap -> String Returns contents of the GENOMEMAP record as a String. == SEE ALSO ftp://ftp.genome.ad.jp/pub/kegg/genomes/genome =end
require "digest/md5" module Blazer class DataSource extend Forwardable attr_reader :id, :settings def_delegators :adapter_instance, :schema, :tables, :preview_statement, :reconnect, :cost, :explain, :cancel def initialize(id, settings) @id = id @settings = settings end def adapter settings["adapter"] || detect_adapter end def name settings["name"] || @id end def linked_columns settings["linked_columns"] || {} end def smart_columns settings["smart_columns"] || {} end def smart_variables settings["smart_variables"] || {} end def variable_defaults settings["variable_defaults"] || {} end def timeout settings["timeout"] end def cache @cache ||= begin if settings["cache"].is_a?(Hash) settings["cache"] elsif settings["cache"] { "mode" => "all", "expires_in" => settings["cache"] } else { "mode" => "off" } end end end def cache_mode cache["mode"] end def cache_expires_in (cache["expires_in"] || 60).to_f end def cache_slow_threshold (cache["slow_threshold"] || 15).to_f end def local_time_suffix @local_time_suffix ||= Array(settings["local_time_suffix"]) end def read_cache(cache_key) value = Blazer.cache.read(cache_key) if value Blazer::Result.new(self, *Marshal.load(value), nil) end end def run_results(run_id) read_cache(run_cache_key(run_id)) end def delete_results(run_id) Blazer.cache.delete(run_cache_key(run_id)) end def run_statement(statement, options = {}) async = options[:async] result = nil if cache_mode != "off" if options[:refresh_cache] clear_cache(statement) # for checks else result = read_cache(statement_cache_key(statement)) end end unless result comment = "blazer" if options[:user].respond_to?(:id) comment << ",user_id:#{options[:user].id}" end if options[:user].respond_to?(Blazer.user_name) # only include letters, numbers, and spaces to prevent injection comment << ",user_name:#{options[:user].send(Blazer.user_name).to_s.gsub(/[^a-zA-Z0-9 ]/, "")}" end if options[:query].respond_to?(:id) comment << ",query_id:#{options[:query].id}" end if options[:check] comment << ",check_id:#{options[:check].id},check_emails:#{options[:check].emails}" end if options[:run_id] comment << ",run_id:#{options[:run_id]}" end result = run_statement_helper(statement, comment, async ? options[:run_id] : nil) end result end def clear_cache(statement) Blazer.cache.delete(statement_cache_key(statement)) end def cache_key(key) (["blazer", "v4"] + key).join("/") end def statement_cache_key(statement) cache_key(["statement", id, Digest::MD5.hexdigest(statement.to_s.gsub("\r\n", "\n"))]) end def run_cache_key(run_id) cache_key(["run", run_id]) end protected def adapter_instance @adapter_instance ||= begin unless settings["url"] || Rails.env.development? || ["bigquery", "athena", "snowflake"].include?(settings["adapter"]) raise Blazer::Error, "Empty url for data source: #{id}" end unless Blazer.adapters[adapter] raise Blazer::Error, "Unknown adapter" end Blazer.adapters[adapter].new(self) end end def run_statement_helper(statement, comment, run_id) start_time = Time.now columns, rows, error = adapter_instance.run_statement(statement, comment) duration = Time.now - start_time cache_data = nil cache = !error && (cache_mode == "all" || (cache_mode == "slow" && duration >= cache_slow_threshold)) if cache || run_id cache_data = Marshal.dump([columns, rows, error, cache ? Time.now : nil]) rescue nil end if cache && cache_data && adapter_instance.cachable?(statement) Blazer.cache.write(statement_cache_key(statement), cache_data, expires_in: cache_expires_in.to_f * 60) end if run_id unless cache_data error = "Error storing the results of this query :(" cache_data = Marshal.dump([[], [], error, nil]) end Blazer.cache.write(run_cache_key(run_id), cache_data, expires_in: 30.seconds) end Blazer::Result.new(self, columns, rows, error, nil, cache && !cache_data.nil?) end def detect_adapter schema = settings["url"].to_s.split("://").first case schema when "mongodb", "presto", "cassandra" schema else "sql" end end end end Don't require url for Salesforce require "digest/md5" module Blazer class DataSource extend Forwardable attr_reader :id, :settings def_delegators :adapter_instance, :schema, :tables, :preview_statement, :reconnect, :cost, :explain, :cancel def initialize(id, settings) @id = id @settings = settings end def adapter settings["adapter"] || detect_adapter end def name settings["name"] || @id end def linked_columns settings["linked_columns"] || {} end def smart_columns settings["smart_columns"] || {} end def smart_variables settings["smart_variables"] || {} end def variable_defaults settings["variable_defaults"] || {} end def timeout settings["timeout"] end def cache @cache ||= begin if settings["cache"].is_a?(Hash) settings["cache"] elsif settings["cache"] { "mode" => "all", "expires_in" => settings["cache"] } else { "mode" => "off" } end end end def cache_mode cache["mode"] end def cache_expires_in (cache["expires_in"] || 60).to_f end def cache_slow_threshold (cache["slow_threshold"] || 15).to_f end def local_time_suffix @local_time_suffix ||= Array(settings["local_time_suffix"]) end def read_cache(cache_key) value = Blazer.cache.read(cache_key) if value Blazer::Result.new(self, *Marshal.load(value), nil) end end def run_results(run_id) read_cache(run_cache_key(run_id)) end def delete_results(run_id) Blazer.cache.delete(run_cache_key(run_id)) end def run_statement(statement, options = {}) async = options[:async] result = nil if cache_mode != "off" if options[:refresh_cache] clear_cache(statement) # for checks else result = read_cache(statement_cache_key(statement)) end end unless result comment = "blazer" if options[:user].respond_to?(:id) comment << ",user_id:#{options[:user].id}" end if options[:user].respond_to?(Blazer.user_name) # only include letters, numbers, and spaces to prevent injection comment << ",user_name:#{options[:user].send(Blazer.user_name).to_s.gsub(/[^a-zA-Z0-9 ]/, "")}" end if options[:query].respond_to?(:id) comment << ",query_id:#{options[:query].id}" end if options[:check] comment << ",check_id:#{options[:check].id},check_emails:#{options[:check].emails}" end if options[:run_id] comment << ",run_id:#{options[:run_id]}" end result = run_statement_helper(statement, comment, async ? options[:run_id] : nil) end result end def clear_cache(statement) Blazer.cache.delete(statement_cache_key(statement)) end def cache_key(key) (["blazer", "v4"] + key).join("/") end def statement_cache_key(statement) cache_key(["statement", id, Digest::MD5.hexdigest(statement.to_s.gsub("\r\n", "\n"))]) end def run_cache_key(run_id) cache_key(["run", run_id]) end protected def adapter_instance @adapter_instance ||= begin unless settings["url"] || Rails.env.development? || ["bigquery", "athena", "snowflake", "salesforce"].include?(settings["adapter"]) raise Blazer::Error, "Empty url for data source: #{id}" end unless Blazer.adapters[adapter] raise Blazer::Error, "Unknown adapter" end Blazer.adapters[adapter].new(self) end end def run_statement_helper(statement, comment, run_id) start_time = Time.now columns, rows, error = adapter_instance.run_statement(statement, comment) duration = Time.now - start_time cache_data = nil cache = !error && (cache_mode == "all" || (cache_mode == "slow" && duration >= cache_slow_threshold)) if cache || run_id cache_data = Marshal.dump([columns, rows, error, cache ? Time.now : nil]) rescue nil end if cache && cache_data && adapter_instance.cachable?(statement) Blazer.cache.write(statement_cache_key(statement), cache_data, expires_in: cache_expires_in.to_f * 60) end if run_id unless cache_data error = "Error storing the results of this query :(" cache_data = Marshal.dump([[], [], error, nil]) end Blazer.cache.write(run_cache_key(run_id), cache_data, expires_in: 30.seconds) end Blazer::Result.new(self, columns, rows, error, nil, cache && !cache_data.nil?) end def detect_adapter schema = settings["url"].to_s.split("://").first case schema when "mongodb", "presto", "cassandra" schema else "sql" end end end end
module Bootswatch VERSION = '4.1.1' end bump version v4.1.2 module Bootswatch VERSION = '4.1.2' end
module Brakecheck VERSION = "0.1.6" end v0.1.7 module Brakecheck VERSION = "0.1.7" end
# -*- encoding: utf-8 -*- module Brcobranca VERSION = "3.1.3" end bump up version to 3.2.0 # -*- encoding: utf-8 -*- module Brcobranca VERSION = "3.2.0" end
#!/bin/ruby require 'rubygems' require 'haml' require 'sinatra' require 'rss/parser' require 'rufus/scheduler' require_relative 'test_runner.rb' class MyApp < Sinatra::Base # config script_location = File.expand_path(File.dirname(__FILE__)) # set up web routes tests = TestRunner.new(script_location) get '/run' do tests.run_tests tests.create_output redirect '/' end get '/output' do send_file tests.output_file end get '/' do # Read the feed into rss_content rss_content = "" open(tests.output_file, "r") do |f| rss_content = f.read end # Parse the feed, dumping its contents to rss rss = RSS::Parser.parse(rss_content, false) title = "Is it up?" date = "Last updated: " + Time.parse(rss.channel.lastBuildDate.to_s).strftime("%H:%M:%S %d/%m/%Y") haml :index, :format => :html5, :locals => {:title => title, :date => date, :rss => rss} end get '/test' do puts "test3" end # set up scheduling - refactor to a different file? scheduler = Rufus::Scheduler.start_new scheduler.every '10m' do tests.run_tests tests.create_output tests.send_alerts end end change #!/bin/ruby require 'rubygems' require 'haml' require 'sinatra' require 'rss/parser' require 'rufus/scheduler' require_relative 'test_runner.rb' class MyApp < Sinatra::Base # config script_location = File.expand_path(File.dirname(__FILE__)) # set up web routes tests = TestRunner.new(script_location) get '/run' do tests.run_tests tests.create_output redirect '/' end get '/output' do send_file tests.output_file end get '/' do # Read the feed into rss_content rss_content = "" open(tests.output_file, "r") do |f| rss_content = f.read end # Parse the feed, dumping its contents to rss rss = RSS::Parser.parse(rss_content, false) title = "Is it up?" date = "Last updated: " + Time.parse(rss.channel.lastBuildDate.to_s).strftime("%H:%M:%S %d/%m/%Y") haml :index, :format => :html5, :locals => {:title => title, :date => date, :rss => rss} end get '/test' do "test3" end # set up scheduling - refactor to a different file? scheduler = Rufus::Scheduler.start_new scheduler.every '10m' do tests.run_tests tests.create_output tests.send_alerts end end
require 'bud/executor/elements' module Bud class PushGroup < PushStatefulElement def initialize(elem_name, bud_instance, collection_name, keys_in, aggpairs_in, schema_in, &blk) @groups = {} if keys_in.nil? @keys = [] else @keys = keys_in.map{|k| k[1]} end # ap[1] is nil for Count @aggpairs = aggpairs_in.map{|ap| ap[1].nil? ? [ap[0]] : [ap[0], ap[1][1]]} super(elem_name, bud_instance, collection_name, schema_in, &blk) end def insert(item, source) key = @keys.map{|k| item[k]} @aggpairs.each_with_index do |ap, agg_ix| agg_input = ap[1].nil? ? item : item[ap[1]] agg = (@groups[key].nil? or @groups[key][agg_ix].nil?) ? ap[0].send(:init, agg_input) : ap[0].send(:trans, @groups[key][agg_ix], agg_input)[0] @groups[key] ||= Array.new(@aggpairs.length) @groups[key][agg_ix] = agg push_out(nil) end end def invalidate_cache puts "Group #{qualified_tabname} invalidated" if $BUD_DEBUG @groups.clear end def flush @groups.each do |g, grps| grp = @keys == $EMPTY ? [[]] : [g] @aggpairs.each_with_index do |ap, agg_ix| grp << ap[0].send(:final, grps[agg_ix]) end outval = grp[0].flatten (1..grp.length-1).each {|i| outval << grp[i]} push_out(outval) end #@groups = {} end end class PushArgAgg < PushGroup def initialize(elem_name, bud_instance, collection_name, keys_in, aggpairs_in, schema_in, &blk) raise Bud::Error, "multiple aggpairs #{aggpairs_in.map{|a| a.class.name}} in ArgAgg; only one allowed" if aggpairs_in.length > 1 super(elem_name, bud_instance, collection_name, keys_in, aggpairs_in, schema_in, &blk) @agg = @aggpairs[0][0] @aggcol = @aggpairs[0][1] @winners = {} end public def invalidate_cache puts "#{self.class}/#{self.tabname} invalidated" if $BUD_DEBUG @groups.clear @winners.clear end def insert(item, source) key = @keys.map{|k| item[k]} @aggpairs.each_with_index do |ap, agg_ix| agg_input = item[ap[1]] if @groups[key].nil? agg = ap[0].send(:init, agg_input) @winners[key] = [item] else agg_result = ap[0].send(:trans, @groups[key][agg_ix], agg_input) agg = agg_result[0] case agg_result[1] when :ignore # do nothing when :replace @winners[key] = [item] when :keep @winners[key] << item when :delete agg_result[2..-1].each do |t| @winners[key].delete t unless @winners[key].empty? end else raise "strange result from argagg finalizer" end end @groups[key] ||= Array.new(@aggpairs.length) @groups[key][agg_ix] = agg #push_out(nil) end end def flush @groups.keys.each {|g| @winners[g].each{|t| push_out(t, false) } } #@groups = {} #@winners = {} end end end Code cleanup for grouping code. require 'bud/executor/elements' module Bud class PushGroup < PushStatefulElement def initialize(elem_name, bud_instance, collection_name, keys_in, aggpairs_in, schema_in, &blk) @groups = {} if keys_in.nil? @keys = [] else @keys = keys_in.map{|k| k[1]} end # ap[1] is nil for Count @aggpairs = aggpairs_in.map{|ap| ap[1].nil? ? [ap[0]] : [ap[0], ap[1][1]]} super(elem_name, bud_instance, collection_name, schema_in, &blk) end def insert(item, source) key = @keys.map{|k| item[k]} @aggpairs.each_with_index do |ap, agg_ix| agg_input = ap[1].nil? ? item : item[ap[1]] agg = (@groups[key].nil? or @groups[key][agg_ix].nil?) ? ap[0].send(:init, agg_input) : ap[0].send(:trans, @groups[key][agg_ix], agg_input)[0] @groups[key] ||= Array.new(@aggpairs.length) @groups[key][agg_ix] = agg end end def invalidate_cache puts "Group #{qualified_tabname} invalidated" if $BUD_DEBUG @groups.clear end def flush @groups.each do |g, grps| grp = @keys == $EMPTY ? [[]] : [g] @aggpairs.each_with_index do |ap, agg_ix| grp << ap[0].send(:final, grps[agg_ix]) end outval = grp[0].flatten (1..grp.length-1).each {|i| outval << grp[i]} push_out(outval) end end end class PushArgAgg < PushGroup def initialize(elem_name, bud_instance, collection_name, keys_in, aggpairs_in, schema_in, &blk) raise Bud::Error, "multiple aggpairs #{aggpairs_in.map{|a| a.class.name}} in ArgAgg; only one allowed" if aggpairs_in.length > 1 super(elem_name, bud_instance, collection_name, keys_in, aggpairs_in, schema_in, &blk) @agg = @aggpairs[0][0] @aggcol = @aggpairs[0][1] @winners = {} end public def invalidate_cache puts "#{self.class}/#{self.tabname} invalidated" if $BUD_DEBUG @groups.clear @winners.clear end def insert(item, source) key = @keys.map{|k| item[k]} @aggpairs.each_with_index do |ap, agg_ix| agg_input = item[ap[1]] if @groups[key].nil? agg = ap[0].send(:init, agg_input) @winners[key] = [item] else agg_result = ap[0].send(:trans, @groups[key][agg_ix], agg_input) agg = agg_result[0] case agg_result[1] when :ignore # do nothing when :replace @winners[key] = [item] when :keep @winners[key] << item when :delete agg_result[2..-1].each do |t| @winners[key].delete t unless @winners[key].empty? end else raise Bud::Error, "strange result from argagg finalizer" end end @groups[key] ||= Array.new(@aggpairs.length) @groups[key][agg_ix] = agg end end def flush @groups.each_key do |g| @winners[g].each do |t| push_out(t, false) end end end end end
# frozen_string_literal: true require "bundler/lockfile_parser" require "set" module Bundler class Definition include GemHelpers attr_reader( :dependencies, :locked_deps, :locked_gems, :platforms, :requires, :ruby_version, :lockfile, :gemfiles ) # Given a gemfile and lockfile creates a Bundler definition # # @param gemfile [Pathname] Path to Gemfile # @param lockfile [Pathname,nil] Path to Gemfile.lock # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @return [Bundler::Definition] def self.build(gemfile, lockfile, unlock) unlock ||= {} gemfile = Pathname.new(gemfile).expand_path raise GemfileNotFound, "#{gemfile} not found" unless gemfile.file? Dsl.evaluate(gemfile, lockfile, unlock) end # # How does the new system work? # # * Load information from Gemfile and Lockfile # * Invalidate stale locked specs # * All specs from stale source are stale # * All specs that are reachable only through a stale # dependency are stale. # * If all fresh dependencies are satisfied by the locked # specs, then we can try to resolve locally. # # @param lockfile [Pathname] Path to Gemfile.lock # @param dependencies [Array(Bundler::Dependency)] array of dependencies from Gemfile # @param sources [Bundler::SourceList] # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @param ruby_version [Bundler::RubyVersion, nil] Requested Ruby Version # @param optional_groups [Array(String)] A list of optional groups def initialize(lockfile, dependencies, sources, unlock, ruby_version = nil, optional_groups = [], gemfiles = []) if [true, false].include?(unlock) @unlocking_bundler = false @unlocking = unlock else unlock = unlock.dup @unlocking_bundler = unlock.delete(:bundler) unlock.delete_if {|_k, v| Array(v).empty? } @unlocking = !unlock.empty? end @dependencies = dependencies @sources = sources @unlock = unlock @optional_groups = optional_groups @remote = false @specs = nil @ruby_version = ruby_version @gemfiles = gemfiles @lockfile = lockfile @lockfile_contents = String.new @locked_bundler_version = nil @locked_ruby_version = nil @locked_specs_incomplete_for_platform = false if lockfile && File.exist?(lockfile) @lockfile_contents = Bundler.read_file(lockfile) @locked_gems = LockfileParser.new(@lockfile_contents) @locked_platforms = @locked_gems.platforms @platforms = @locked_platforms.dup @locked_bundler_version = @locked_gems.bundler_version @locked_ruby_version = @locked_gems.ruby_version if unlock != true @locked_deps = @locked_gems.dependencies @locked_specs = SpecSet.new(@locked_gems.specs) @locked_sources = @locked_gems.sources else @unlock = {} @locked_deps = {} @locked_specs = SpecSet.new([]) @locked_sources = [] end else @unlock = {} @platforms = [] @locked_gems = nil @locked_deps = {} @locked_specs = SpecSet.new([]) @locked_sources = [] @locked_platforms = [] end @unlock[:gems] ||= [] @unlock[:sources] ||= [] @unlock[:ruby] ||= if @ruby_version && locked_ruby_version_object @ruby_version.diff(locked_ruby_version_object) end @unlocking ||= @unlock[:ruby] ||= (!@locked_ruby_version ^ !@ruby_version) add_current_platform unless Bundler.frozen_bundle? converge_path_sources_to_gemspec_sources @path_changes = converge_paths @source_changes = converge_sources unless @unlock[:lock_shared_dependencies] eager_unlock = expand_dependencies(@unlock[:gems]) @unlock[:gems] = @locked_specs.for(eager_unlock).map(&:name) end @dependency_changes = converge_dependencies @local_changes = converge_locals @requires = compute_requires end def gem_version_promoter @gem_version_promoter ||= begin locked_specs = if unlocking? && @locked_specs.empty? && !@lockfile_contents.empty? # Definition uses an empty set of locked_specs to indicate all gems # are unlocked, but GemVersionPromoter needs the locked_specs # for conservative comparison. Bundler::SpecSet.new(@locked_gems.specs) else @locked_specs end GemVersionPromoter.new(locked_specs, @unlock[:gems]) end end def resolve_with_cache! raise "Specs already loaded" if @specs sources.cached! specs end def resolve_remotely! raise "Specs already loaded" if @specs @remote = true sources.remote! specs end # For given dependency list returns a SpecSet with Gemspec of all the required # dependencies. # 1. The method first resolves the dependencies specified in Gemfile # 2. After that it tries and fetches gemspec of resolved dependencies # # @return [Bundler::SpecSet] def specs @specs ||= begin begin specs = resolve.materialize(Bundler.settings[:cache_all_platforms] ? dependencies : requested_dependencies) rescue GemNotFound => e # Handle yanked gem gem_name, gem_version = extract_gem_info(e) locked_gem = @locked_specs[gem_name].last raise if locked_gem.nil? || locked_gem.version.to_s != gem_version || !@remote raise GemNotFound, "Your bundle is locked to #{locked_gem}, but that version could not " \ "be found in any of the sources listed in your Gemfile. If you haven't changed sources, " \ "that means the author of #{locked_gem} has removed it. You'll need to update your bundle " \ "to a different version of #{gem_name} that hasn't been removed in order to install." end unless specs["bundler"].any? bundler = sources.metadata_source.specs.search(Gem::Dependency.new("bundler", VERSION)).last specs["bundler"] = bundler end specs end end def new_specs specs - @locked_specs end def removed_specs @locked_specs - specs end def new_platform? @new_platform end def missing_specs missing = [] resolve.materialize(requested_dependencies, missing) missing end def missing_specs? missing = missing_specs return false if missing.empty? Bundler.ui.debug "The definition is missing #{missing.map(&:full_name)}" true rescue BundlerError => e @index = nil @resolve = nil @specs = nil @gem_version_promoter = nil Bundler.ui.debug "The definition is missing dependencies, failed to resolve & materialize locally (#{e})" true end def requested_specs @requested_specs ||= begin groups = requested_groups groups.map!(&:to_sym) specs_for(groups) end end def current_dependencies dependencies.select(&:should_include?) end def specs_for(groups) deps = dependencies.select {|d| (d.groups & groups).any? } deps.delete_if {|d| !d.should_include? } specs.for(expand_dependencies(deps)) end # Resolve all the dependencies specified in Gemfile. It ensures that # dependencies that have been already resolved via locked file and are fresh # are reused when resolving dependencies # # @return [SpecSet] resolved dependencies def resolve @resolve ||= begin last_resolve = converge_locked_specs if Bundler.frozen_bundle? Bundler.ui.debug "Frozen, using resolution from the lockfile" last_resolve elsif !unlocking? && nothing_changed? Bundler.ui.debug("Found no changes, using resolution from the lockfile") last_resolve else # Run a resolve against the locally available gems Bundler.ui.debug("Found changes from the lockfile, re-resolving dependencies because #{change_reason}") last_resolve.merge Resolver.resolve(expanded_dependencies, index, source_requirements, last_resolve, gem_version_promoter, additional_base_requirements_for_resolve, platforms) end end end def index @index ||= Index.build do |idx| dependency_names = @dependencies.map(&:name) sources.all_sources.each do |source| source.dependency_names = dependency_names - pinned_spec_names(source) idx.add_source source.specs dependency_names.concat(source.unmet_deps).uniq! end double_check_for_index(idx, dependency_names) end end # Suppose the gem Foo depends on the gem Bar. Foo exists in Source A. Bar has some versions that exist in both # sources A and B. At this point, the API request will have found all the versions of Bar in source A, # but will not have found any versions of Bar from source B, which is a problem if the requested version # of Foo specifically depends on a version of Bar that is only found in source B. This ensures that for # each spec we found, we add all possible versions from all sources to the index. def double_check_for_index(idx, dependency_names) pinned_names = pinned_spec_names loop do idxcount = idx.size names = :names # do this so we only have to traverse to get dependency_names from the index once unmet_dependency_names = lambda do return names unless names == :names new_names = sources.all_sources.map(&:dependency_names_to_double_check) return names = nil if new_names.compact! names = new_names.flatten(1).concat(dependency_names) names.uniq! names -= pinned_names names end sources.all_sources.each do |source| source.double_check_for(unmet_dependency_names) end break if idxcount == idx.size end end private :double_check_for_index def has_rubygems_remotes? sources.rubygems_sources.any? {|s| s.remotes.any? } end def has_local_dependencies? !sources.path_sources.empty? || !sources.git_sources.empty? end def spec_git_paths sources.git_sources.map {|s| s.path.to_s } end def groups dependencies.map(&:groups).flatten.uniq end def lock(file, preserve_unknown_sections = false) contents = to_lock # Convert to \r\n if the existing lock has them # i.e., Windows with `git config core.autocrlf=true` contents.gsub!(/\n/, "\r\n") if @lockfile_contents.match("\r\n") if @locked_bundler_version locked_major = @locked_bundler_version.segments.first current_major = Gem::Version.create(Bundler::VERSION).segments.first if updating_major = locked_major < current_major Bundler.ui.warn "Warning: the lockfile is being updated to Bundler #{current_major}, " \ "after which you will be unable to return to Bundler #{@locked_bundler_version.segments.first}." end end preserve_unknown_sections ||= !updating_major && (Bundler.frozen_bundle? || !(unlocking? || @unlocking_bundler)) return if lockfiles_equal?(@lockfile_contents, contents, preserve_unknown_sections) if Bundler.frozen_bundle? Bundler.ui.error "Cannot write a changed lockfile while frozen." return end SharedHelpers.filesystem_access(file) do |p| File.open(p, "wb") {|f| f.puts(contents) } end end def locked_bundler_version if @locked_bundler_version && @locked_bundler_version < Gem::Version.new(Bundler::VERSION) new_version = Bundler::VERSION end new_version || @locked_bundler_version || Bundler::VERSION end def locked_ruby_version return unless ruby_version if @unlock[:ruby] || !@locked_ruby_version Bundler::RubyVersion.system else @locked_ruby_version end end def locked_ruby_version_object return unless @locked_ruby_version @locked_ruby_version_object ||= begin unless version = RubyVersion.from_string(@locked_ruby_version) raise LockfileError, "The Ruby version #{@locked_ruby_version} from " \ "#{@lockfile} could not be parsed. " \ "Try running bundle update --ruby to resolve this." end version end end def to_lock require "bundler/lockfile_generator" LockfileGenerator.generate(self) end def ensure_equivalent_gemfile_and_lockfile(explicit_flag = false) msg = String.new msg << "You are trying to install in deployment mode after changing\n" \ "your Gemfile. Run `bundle install` elsewhere and add the\n" \ "updated #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} to version control." unless explicit_flag suggested_command = if Bundler.settings.locations("frozen")[:global] "bundle config --delete frozen" elsif Bundler.settings.locations("deployment").keys.&([:global, :local]).any? "bundle config --delete deployment" else "bundle install --no-deployment" end msg << "\n\nIf this is a development machine, remove the #{Bundler.default_gemfile} " \ "freeze \nby running `#{suggested_command}`." end added = [] deleted = [] changed = [] new_platforms = @platforms - @locked_platforms deleted_platforms = @locked_platforms - @platforms added.concat new_platforms.map {|p| "* platform: #{p}" } deleted.concat deleted_platforms.map {|p| "* platform: #{p}" } gemfile_sources = sources.lock_sources new_sources = gemfile_sources - @locked_sources deleted_sources = @locked_sources - gemfile_sources new_deps = @dependencies - @locked_deps.values deleted_deps = @locked_deps.values - @dependencies # Check if it is possible that the source is only changed thing if (new_deps.empty? && deleted_deps.empty?) && (!new_sources.empty? && !deleted_sources.empty?) new_sources.reject! {|source| (source.path? && source.path.exist?) || equivalent_rubygems_remotes?(source) } deleted_sources.reject! {|source| (source.path? && source.path.exist?) || equivalent_rubygems_remotes?(source) } end if @locked_sources != gemfile_sources if new_sources.any? added.concat new_sources.map {|source| "* source: #{source}" } end if deleted_sources.any? deleted.concat deleted_sources.map {|source| "* source: #{source}" } end end added.concat new_deps.map {|d| "* #{pretty_dep(d)}" } if new_deps.any? if deleted_deps.any? deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" } end both_sources = Hash.new {|h, k| h[k] = [] } @dependencies.each {|d| both_sources[d.name][0] = d } @locked_deps.each {|name, d| both_sources[name][1] = d.source } both_sources.each do |name, (dep, lock_source)| next unless (dep.nil? && !lock_source.nil?) || (!dep.nil? && !lock_source.nil? && !lock_source.can_lock?(dep)) gemfile_source_name = (dep && dep.source) || "no specified source" lockfile_source_name = lock_source || "no specified source" changed << "* #{name} from `#{gemfile_source_name}` to `#{lockfile_source_name}`" end reason = change_reason msg << "\n\n#{reason.split(", ").map(&:capitalize).join("\n")}" unless reason.strip.empty? msg << "\n\nYou have added to the Gemfile:\n" << added.join("\n") if added.any? msg << "\n\nYou have deleted from the Gemfile:\n" << deleted.join("\n") if deleted.any? msg << "\n\nYou have changed in the Gemfile:\n" << changed.join("\n") if changed.any? msg << "\n" raise ProductionError, msg if added.any? || deleted.any? || changed.any? || !nothing_changed? end def validate_runtime! validate_ruby! validate_platforms! end def validate_ruby! return unless ruby_version if diff = ruby_version.diff(Bundler::RubyVersion.system) problem, expected, actual = diff msg = case problem when :engine "Your Ruby engine is #{actual}, but your Gemfile specified #{expected}" when :version "Your Ruby version is #{actual}, but your Gemfile specified #{expected}" when :engine_version "Your #{Bundler::RubyVersion.system.engine} version is #{actual}, but your Gemfile specified #{ruby_version.engine} #{expected}" when :patchlevel if !expected.is_a?(String) "The Ruby patchlevel in your Gemfile must be a string" else "Your Ruby patchlevel is #{actual}, but your Gemfile specified #{expected}" end end raise RubyVersionMismatch, msg end end def validate_platforms! return if @platforms.any? do |bundle_platform| Bundler.rubygems.platforms.any? do |local_platform| MatchPlatform.platforms_match?(bundle_platform, local_platform) end end raise ProductionError, "Your bundle only supports platforms #{@platforms.map(&:to_s)} " \ "but your local platforms are #{Bundler.rubygems.platforms.map(&:to_s)}, and " \ "there's no compatible match between those two lists." end def add_platform(platform) @new_platform ||= !@platforms.include?(platform) @platforms |= [platform] end def remove_platform(platform) return if @platforms.delete(Gem::Platform.new(platform)) raise InvalidOption, "Unable to remove the platform `#{platform}` since the only platforms are #{@platforms.join ", "}" end def add_current_platform current_platform = Bundler.local_platform add_platform(current_platform) if Bundler.feature_flag.specific_platform? add_platform(generic(current_platform)) end def find_resolved_spec(current_spec) specs.find_by_name_and_platform(current_spec.name, current_spec.platform) end def find_indexed_specs(current_spec) index[current_spec.name].select {|spec| spec.match_platform(current_spec.platform) }.sort_by(&:version) end attr_reader :sources private :sources def nothing_changed? !@source_changes && !@dependency_changes && !@new_platform && !@path_changes && !@local_changes && !@locked_specs_incomplete_for_platform end def unlocking? @unlocking end private def change_reason if unlocking? unlock_reason = @unlock.reject {|_k, v| Array(v).empty? }.map do |k, v| if v == true k.to_s else v = Array(v) "#{k}: (#{v.join(", ")})" end end.join(", ") return "bundler is unlocking #{unlock_reason}" end [ [@source_changes, "the list of sources changed"], [@dependency_changes, "the dependencies in your gemfile changed"], [@new_platform, "you added a new platform to your gemfile"], [@path_changes, "the gemspecs for path gems changed"], [@local_changes, "the gemspecs for git local gems changed"], [@locked_specs_incomplete_for_platform, "the lockfile does not have all gems needed for the current platform"], ].select(&:first).map(&:last).join(", ") end def pretty_dep(dep, source = false) SharedHelpers.pretty_dependency(dep, source) end # Check if the specs of the given source changed # according to the locked source. def specs_changed?(source) locked = @locked_sources.find {|s| s == source } !locked || dependencies_for_source_changed?(source, locked) || specs_for_source_changed?(source) end def dependencies_for_source_changed?(source, locked_source = source) deps_for_source = @dependencies.select {|s| s.source == source } locked_deps_for_source = @locked_deps.values.select {|dep| dep.source == locked_source } Set.new(deps_for_source) != Set.new(locked_deps_for_source) end def specs_for_source_changed?(source) locked_index = Index.new locked_index.use(@locked_specs.select {|s| source.can_lock?(s) }) # order here matters, since Index#== is checking source.specs.include?(locked_index) locked_index != source.specs rescue PathError, GitError => e Bundler.ui.debug "Assuming that #{source} has not changed since fetching its specs errored (#{e})" false end # Get all locals and override their matching sources. # Return true if any of the locals changed (for example, # they point to a new revision) or depend on new specs. def converge_locals locals = [] Bundler.settings.local_overrides.map do |k, v| spec = @dependencies.find {|s| s.name == k } source = spec && spec.source if source && source.respond_to?(:local_override!) source.unlock! if @unlock[:gems].include?(spec.name) locals << [source, source.local_override!(v)] end end sources_with_changes = locals.select do |source, changed| changed || specs_changed?(source) end.map(&:first) !sources_with_changes.each {|source| @unlock[:sources] << source.name }.empty? end def converge_paths sources.path_sources.any? do |source| specs_changed?(source) end end def converge_path_source_to_gemspec_source(source) return source unless source.instance_of?(Source::Path) gemspec_source = sources.path_sources.find {|s| s.is_a?(Source::Gemspec) && s.as_path_source == source } gemspec_source || source end def converge_path_sources_to_gemspec_sources @locked_sources.map! do |source| converge_path_source_to_gemspec_source(source) end @locked_specs.each do |spec| spec.source &&= converge_path_source_to_gemspec_source(spec.source) end @locked_deps.each do |_, dep| dep.source &&= converge_path_source_to_gemspec_source(dep.source) end end def converge_rubygems_sources return false if Bundler.feature_flag.lockfile_uses_separate_rubygems_sources? changes = false # Get the RubyGems sources from the Gemfile.lock locked_gem_sources = @locked_sources.select {|s| s.is_a?(Source::Rubygems) } # Get the RubyGems remotes from the Gemfile actual_remotes = sources.rubygems_remotes # If there is a RubyGems source in both if !locked_gem_sources.empty? && !actual_remotes.empty? locked_gem_sources.each do |locked_gem| # Merge the remotes from the Gemfile into the Gemfile.lock changes |= locked_gem.replace_remotes(actual_remotes, Bundler.settings[:allow_deployment_source_credential_changes]) end end changes end def converge_sources changes = false changes |= converge_rubygems_sources # Replace the sources from the Gemfile with the sources from the Gemfile.lock, # if they exist in the Gemfile.lock and are `==`. If you can't find an equivalent # source in the Gemfile.lock, use the one from the Gemfile. changes |= sources.replace_sources!(@locked_sources) sources.all_sources.each do |source| # If the source is unlockable and the current command allows an unlock of # the source (for example, you are doing a `bundle update <foo>` of a git-pinned # gem), unlock it. For git sources, this means to unlock the revision, which # will cause the `ref` used to be the most recent for the branch (or master) if # an explicit `ref` is not used. if source.respond_to?(:unlock!) && @unlock[:sources].include?(source.name) source.unlock! changes = true end end changes end def converge_dependencies frozen = Bundler.frozen_bundle? (@dependencies + @locked_deps.values).each do |dep| locked_source = @locked_deps[dep.name] # This is to make sure that if bundler is installing in deployment mode and # after locked_source and sources don't match, we still use locked_source. if frozen && !locked_source.nil? && locked_source.respond_to?(:source) && locked_source.source.instance_of?(Source::Path) && locked_source.source.path.exist? dep.source = locked_source.source elsif dep.source dep.source = sources.get(dep.source) end if dep.source.is_a?(Source::Gemspec) dep.platforms.concat(@platforms.map {|p| Dependency::REVERSE_PLATFORM_MAP[p] }.flatten(1)).uniq! end end changes = false # We want to know if all match, but don't want to check all entries # This means we need to return false if any dependency doesn't match # the lock or doesn't exist in the lock. @dependencies.each do |dependency| unless locked_dep = @locked_deps[dependency.name] changes = true next end # Gem::Dependency#== matches Gem::Dependency#type. As the lockfile # doesn't carry a notion of the dependency type, if you use # add_development_dependency in a gemspec that's loaded with the gemspec # directive, the lockfile dependencies and resolved dependencies end up # with a mismatch on #type. Work around that by setting the type on the # dep from the lockfile. locked_dep.instance_variable_set(:@type, dependency.type) # We already know the name matches from the hash lookup # so we only need to check the requirement now changes ||= dependency.requirement != locked_dep.requirement end changes end # Remove elements from the locked specs that are expired. This will most # commonly happen if the Gemfile has changed since the lockfile was last # generated def converge_locked_specs deps = [] # Build a list of dependencies that are the same in the Gemfile # and Gemfile.lock. If the Gemfile modified a dependency, but # the gem in the Gemfile.lock still satisfies it, this is fine # too. @dependencies.each do |dep| locked_dep = @locked_deps[dep.name] # If the locked_dep doesn't match the dependency we're looking for then we ignore the locked_dep locked_dep = nil unless locked_dep == dep if in_locked_deps?(dep, locked_dep) || satisfies_locked_spec?(dep) deps << dep elsif dep.source.is_a?(Source::Path) && dep.current_platform? && (!locked_dep || dep.source != locked_dep.source) @locked_specs.each do |s| @unlock[:gems] << s.name if s.source == dep.source end dep.source.unlock! if dep.source.respond_to?(:unlock!) dep.source.specs.each {|s| @unlock[:gems] << s.name } end end unlock_source_unlocks_spec = Bundler.feature_flag.unlock_source_unlocks_spec? converged = [] @locked_specs.each do |s| # Replace the locked dependency's source with the equivalent source from the Gemfile dep = @dependencies.find {|d| s.satisfies?(d) } s.source = (dep && dep.source) || sources.get(s.source) # Don't add a spec to the list if its source is expired. For example, # if you change a Git gem to RubyGems. next if s.source.nil? next if @unlock[:sources].include?(s.source.name) # XXX This is a backwards-compatibility fix to preserve the ability to # unlock a single gem by passing its name via `--source`. See issue #3759 # TODO: delete in Bundler 2 next if unlock_source_unlocks_spec && @unlock[:sources].include?(s.name) # If the spec is from a path source and it doesn't exist anymore # then we unlock it. # Path sources have special logic if s.source.instance_of?(Source::Path) || s.source.instance_of?(Source::Gemspec) other_sources_specs = begin s.source.specs rescue PathError, GitError # if we won't need the source (according to the lockfile), # don't error if the path/git source isn't available next if @locked_specs. for(requested_dependencies, [], false, true, false). none? {|locked_spec| locked_spec.source == s.source } raise end other = other_sources_specs[s].first # If the spec is no longer in the path source, unlock it. This # commonly happens if the version changed in the gemspec next unless other deps2 = other.dependencies.select {|d| d.type != :development } runtime_dependencies = s.dependencies.select {|d| d.type != :development } # If the dependencies of the path source have changed, unlock it next unless runtime_dependencies.sort == deps2.sort end converged << s end resolve = SpecSet.new(converged) expanded_deps = expand_dependencies(deps, true) @locked_specs_incomplete_for_platform = !resolve.for(expanded_deps, @unlock[:gems], true, true) resolve = resolve.for(expanded_deps, @unlock[:gems], false, false, false) diff = nil # Now, we unlock any sources that do not have anymore gems pinned to it sources.all_sources.each do |source| next unless source.respond_to?(:unlock!) unless resolve.any? {|s| s.source == source } diff ||= @locked_specs.to_a - resolve.to_a source.unlock! if diff.any? {|s| s.source == source } end end resolve end def in_locked_deps?(dep, locked_dep) # Because the lockfile can't link a dep to a specific remote, we need to # treat sources as equivalent anytime the locked dep has all the remotes # that the Gemfile dep does. locked_dep && locked_dep.source && dep.source && locked_dep.source.include?(dep.source) end def satisfies_locked_spec?(dep) @locked_specs[dep].any? {|s| s.satisfies?(dep) && (!dep.source || s.source.include?(dep.source)) } end # This list of dependencies is only used in #resolve, so it's OK to add # the metadata dependencies here def expanded_dependencies @expanded_dependencies ||= begin expand_dependencies(dependencies + metadata_dependencies, @remote) end end def metadata_dependencies @metadata_dependencies ||= begin ruby_versions = concat_ruby_version_requirements(@ruby_version) if ruby_versions.empty? || !@ruby_version.exact? concat_ruby_version_requirements(RubyVersion.system) concat_ruby_version_requirements(locked_ruby_version_object) unless @unlock[:ruby] end [ Dependency.new("ruby\0", ruby_versions), Dependency.new("rubygems\0", Gem::VERSION), ] end end def concat_ruby_version_requirements(ruby_version, ruby_versions = []) return ruby_versions unless ruby_version if ruby_version.patchlevel ruby_versions << ruby_version.to_gem_version_with_patchlevel else ruby_versions.concat(ruby_version.versions.map do |version| requirement = Gem::Requirement.new(version) if requirement.exact? "~> #{version}.0" else requirement end end) end end def expand_dependencies(dependencies, remote = false) sorted_platforms = Resolver.sort_platforms(@platforms) deps = [] dependencies.each do |dep| dep = Dependency.new(dep, ">= 0") unless dep.respond_to?(:name) next if !remote && !dep.current_platform? platforms = dep.gem_platforms(sorted_platforms) if platforms.empty? mapped_platforms = dep.platforms.map {|p| Dependency::PLATFORM_MAP[p] } Bundler.ui.warn \ "The dependency #{dep} will be unused by any of the platforms Bundler is installing for. " \ "Bundler is installing for #{@platforms.join ", "} but the dependency " \ "is only for #{mapped_platforms.join ", "}. " \ "To add those platforms to the bundle, " \ "run `bundle lock --add-platform #{mapped_platforms.join " "}`." end platforms.each do |p| deps << DepProxy.new(dep, p) if remote || p == generic_local_platform end end deps end def requested_dependencies groups = requested_groups groups.map!(&:to_sym) dependencies.reject {|d| !d.should_include? || (d.groups & groups).empty? } end def source_requirements # Load all specs from remote sources index # Record the specs available in each gem's source, so that those # specs will be available later when the resolver knows where to # look for that gemspec (or its dependencies) default = sources.default_source source_requirements = { :default => default } default = nil unless Bundler.feature_flag.lockfile_uses_separate_rubygems_sources? dependencies.each do |dep| next unless source = dep.source || default source_requirements[dep.name] = source end metadata_dependencies.each do |dep| source_requirements[dep.name] = sources.metadata_source end source_requirements["bundler"] = sources.metadata_source # needs to come last to override source_requirements end def pinned_spec_names(skip = nil) pinned_names = [] default = Bundler.feature_flag.lockfile_uses_separate_rubygems_sources? && sources.default_source @dependencies.each do |dep| next unless dep_source = dep.source || default next if dep_source == skip pinned_names << dep.name end pinned_names end def requested_groups groups - Bundler.settings[:without] - @optional_groups + Bundler.settings[:with] end def lockfiles_equal?(current, proposed, preserve_unknown_sections) if preserve_unknown_sections sections_to_ignore = LockfileParser.sections_to_ignore(@locked_bundler_version) sections_to_ignore += LockfileParser.unknown_sections_in_lockfile(current) sections_to_ignore += LockfileParser::ENVIRONMENT_VERSION_SECTIONS pattern = /#{Regexp.union(sections_to_ignore)}\n(\s{2,}.*\n)+/ whitespace_cleanup = /\n{2,}/ current = current.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip proposed = proposed.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip end current == proposed end def extract_gem_info(error) # This method will extract the error message like "Could not find foo-1.2.3 in any of the sources" # to an array. The first element will be the gem name (e.g. foo), the second will be the version number. error.message.scan(/Could not find (\w+)-(\d+(?:\.\d+)+)/).flatten end def compute_requires dependencies.reduce({}) do |requires, dep| next requires unless dep.should_include? requires[dep.name] = Array(dep.autorequire || dep.name).map do |file| # Allow `require: true` as an alias for `require: <name>` file == true ? dep.name : file end requires end end def additional_base_requirements_for_resolve return [] unless @locked_gems && Bundler.feature_flag.only_update_to_newer_versions? dependencies_by_name = dependencies.group_by(&:name) @locked_gems.specs.reduce({}) do |requirements, locked_spec| name = locked_spec.name next requirements if @locked_deps[name] != dependencies_by_name[name] dep = Gem::Dependency.new(name, ">= #{locked_spec.version}") requirements[name] = DepProxy.new(dep, locked_spec.platform) requirements end.values end def equivalent_rubygems_remotes?(source) return false unless source.is_a?(Source::Rubygems) Bundler.settings[:allow_deployment_source_credential_changes] && source.equivalent_remotes?(sources.rubygems_remotes) end end end Further tweak yanked gem error message # frozen_string_literal: true require "bundler/lockfile_parser" require "set" module Bundler class Definition include GemHelpers attr_reader( :dependencies, :locked_deps, :locked_gems, :platforms, :requires, :ruby_version, :lockfile, :gemfiles ) # Given a gemfile and lockfile creates a Bundler definition # # @param gemfile [Pathname] Path to Gemfile # @param lockfile [Pathname,nil] Path to Gemfile.lock # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @return [Bundler::Definition] def self.build(gemfile, lockfile, unlock) unlock ||= {} gemfile = Pathname.new(gemfile).expand_path raise GemfileNotFound, "#{gemfile} not found" unless gemfile.file? Dsl.evaluate(gemfile, lockfile, unlock) end # # How does the new system work? # # * Load information from Gemfile and Lockfile # * Invalidate stale locked specs # * All specs from stale source are stale # * All specs that are reachable only through a stale # dependency are stale. # * If all fresh dependencies are satisfied by the locked # specs, then we can try to resolve locally. # # @param lockfile [Pathname] Path to Gemfile.lock # @param dependencies [Array(Bundler::Dependency)] array of dependencies from Gemfile # @param sources [Bundler::SourceList] # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @param ruby_version [Bundler::RubyVersion, nil] Requested Ruby Version # @param optional_groups [Array(String)] A list of optional groups def initialize(lockfile, dependencies, sources, unlock, ruby_version = nil, optional_groups = [], gemfiles = []) if [true, false].include?(unlock) @unlocking_bundler = false @unlocking = unlock else unlock = unlock.dup @unlocking_bundler = unlock.delete(:bundler) unlock.delete_if {|_k, v| Array(v).empty? } @unlocking = !unlock.empty? end @dependencies = dependencies @sources = sources @unlock = unlock @optional_groups = optional_groups @remote = false @specs = nil @ruby_version = ruby_version @gemfiles = gemfiles @lockfile = lockfile @lockfile_contents = String.new @locked_bundler_version = nil @locked_ruby_version = nil @locked_specs_incomplete_for_platform = false if lockfile && File.exist?(lockfile) @lockfile_contents = Bundler.read_file(lockfile) @locked_gems = LockfileParser.new(@lockfile_contents) @locked_platforms = @locked_gems.platforms @platforms = @locked_platforms.dup @locked_bundler_version = @locked_gems.bundler_version @locked_ruby_version = @locked_gems.ruby_version if unlock != true @locked_deps = @locked_gems.dependencies @locked_specs = SpecSet.new(@locked_gems.specs) @locked_sources = @locked_gems.sources else @unlock = {} @locked_deps = {} @locked_specs = SpecSet.new([]) @locked_sources = [] end else @unlock = {} @platforms = [] @locked_gems = nil @locked_deps = {} @locked_specs = SpecSet.new([]) @locked_sources = [] @locked_platforms = [] end @unlock[:gems] ||= [] @unlock[:sources] ||= [] @unlock[:ruby] ||= if @ruby_version && locked_ruby_version_object @ruby_version.diff(locked_ruby_version_object) end @unlocking ||= @unlock[:ruby] ||= (!@locked_ruby_version ^ !@ruby_version) add_current_platform unless Bundler.frozen_bundle? converge_path_sources_to_gemspec_sources @path_changes = converge_paths @source_changes = converge_sources unless @unlock[:lock_shared_dependencies] eager_unlock = expand_dependencies(@unlock[:gems]) @unlock[:gems] = @locked_specs.for(eager_unlock).map(&:name) end @dependency_changes = converge_dependencies @local_changes = converge_locals @requires = compute_requires end def gem_version_promoter @gem_version_promoter ||= begin locked_specs = if unlocking? && @locked_specs.empty? && !@lockfile_contents.empty? # Definition uses an empty set of locked_specs to indicate all gems # are unlocked, but GemVersionPromoter needs the locked_specs # for conservative comparison. Bundler::SpecSet.new(@locked_gems.specs) else @locked_specs end GemVersionPromoter.new(locked_specs, @unlock[:gems]) end end def resolve_with_cache! raise "Specs already loaded" if @specs sources.cached! specs end def resolve_remotely! raise "Specs already loaded" if @specs @remote = true sources.remote! specs end # For given dependency list returns a SpecSet with Gemspec of all the required # dependencies. # 1. The method first resolves the dependencies specified in Gemfile # 2. After that it tries and fetches gemspec of resolved dependencies # # @return [Bundler::SpecSet] def specs @specs ||= begin begin specs = resolve.materialize(Bundler.settings[:cache_all_platforms] ? dependencies : requested_dependencies) rescue GemNotFound => e # Handle yanked gem gem_name, gem_version = extract_gem_info(e) locked_gem = @locked_specs[gem_name].last raise if locked_gem.nil? || locked_gem.version.to_s != gem_version || !@remote raise GemNotFound, "Your bundle is locked to #{locked_gem}, but that version could not " \ "be found in any of the sources listed in your Gemfile. If you haven't changed sources, " \ "that means the author of #{locked_gem} has removed it. You'll need to update your bundle " \ "to a version other than #{locked_gem} that hasn't been removed in order to install." end unless specs["bundler"].any? bundler = sources.metadata_source.specs.search(Gem::Dependency.new("bundler", VERSION)).last specs["bundler"] = bundler end specs end end def new_specs specs - @locked_specs end def removed_specs @locked_specs - specs end def new_platform? @new_platform end def missing_specs missing = [] resolve.materialize(requested_dependencies, missing) missing end def missing_specs? missing = missing_specs return false if missing.empty? Bundler.ui.debug "The definition is missing #{missing.map(&:full_name)}" true rescue BundlerError => e @index = nil @resolve = nil @specs = nil @gem_version_promoter = nil Bundler.ui.debug "The definition is missing dependencies, failed to resolve & materialize locally (#{e})" true end def requested_specs @requested_specs ||= begin groups = requested_groups groups.map!(&:to_sym) specs_for(groups) end end def current_dependencies dependencies.select(&:should_include?) end def specs_for(groups) deps = dependencies.select {|d| (d.groups & groups).any? } deps.delete_if {|d| !d.should_include? } specs.for(expand_dependencies(deps)) end # Resolve all the dependencies specified in Gemfile. It ensures that # dependencies that have been already resolved via locked file and are fresh # are reused when resolving dependencies # # @return [SpecSet] resolved dependencies def resolve @resolve ||= begin last_resolve = converge_locked_specs if Bundler.frozen_bundle? Bundler.ui.debug "Frozen, using resolution from the lockfile" last_resolve elsif !unlocking? && nothing_changed? Bundler.ui.debug("Found no changes, using resolution from the lockfile") last_resolve else # Run a resolve against the locally available gems Bundler.ui.debug("Found changes from the lockfile, re-resolving dependencies because #{change_reason}") last_resolve.merge Resolver.resolve(expanded_dependencies, index, source_requirements, last_resolve, gem_version_promoter, additional_base_requirements_for_resolve, platforms) end end end def index @index ||= Index.build do |idx| dependency_names = @dependencies.map(&:name) sources.all_sources.each do |source| source.dependency_names = dependency_names - pinned_spec_names(source) idx.add_source source.specs dependency_names.concat(source.unmet_deps).uniq! end double_check_for_index(idx, dependency_names) end end # Suppose the gem Foo depends on the gem Bar. Foo exists in Source A. Bar has some versions that exist in both # sources A and B. At this point, the API request will have found all the versions of Bar in source A, # but will not have found any versions of Bar from source B, which is a problem if the requested version # of Foo specifically depends on a version of Bar that is only found in source B. This ensures that for # each spec we found, we add all possible versions from all sources to the index. def double_check_for_index(idx, dependency_names) pinned_names = pinned_spec_names loop do idxcount = idx.size names = :names # do this so we only have to traverse to get dependency_names from the index once unmet_dependency_names = lambda do return names unless names == :names new_names = sources.all_sources.map(&:dependency_names_to_double_check) return names = nil if new_names.compact! names = new_names.flatten(1).concat(dependency_names) names.uniq! names -= pinned_names names end sources.all_sources.each do |source| source.double_check_for(unmet_dependency_names) end break if idxcount == idx.size end end private :double_check_for_index def has_rubygems_remotes? sources.rubygems_sources.any? {|s| s.remotes.any? } end def has_local_dependencies? !sources.path_sources.empty? || !sources.git_sources.empty? end def spec_git_paths sources.git_sources.map {|s| s.path.to_s } end def groups dependencies.map(&:groups).flatten.uniq end def lock(file, preserve_unknown_sections = false) contents = to_lock # Convert to \r\n if the existing lock has them # i.e., Windows with `git config core.autocrlf=true` contents.gsub!(/\n/, "\r\n") if @lockfile_contents.match("\r\n") if @locked_bundler_version locked_major = @locked_bundler_version.segments.first current_major = Gem::Version.create(Bundler::VERSION).segments.first if updating_major = locked_major < current_major Bundler.ui.warn "Warning: the lockfile is being updated to Bundler #{current_major}, " \ "after which you will be unable to return to Bundler #{@locked_bundler_version.segments.first}." end end preserve_unknown_sections ||= !updating_major && (Bundler.frozen_bundle? || !(unlocking? || @unlocking_bundler)) return if lockfiles_equal?(@lockfile_contents, contents, preserve_unknown_sections) if Bundler.frozen_bundle? Bundler.ui.error "Cannot write a changed lockfile while frozen." return end SharedHelpers.filesystem_access(file) do |p| File.open(p, "wb") {|f| f.puts(contents) } end end def locked_bundler_version if @locked_bundler_version && @locked_bundler_version < Gem::Version.new(Bundler::VERSION) new_version = Bundler::VERSION end new_version || @locked_bundler_version || Bundler::VERSION end def locked_ruby_version return unless ruby_version if @unlock[:ruby] || !@locked_ruby_version Bundler::RubyVersion.system else @locked_ruby_version end end def locked_ruby_version_object return unless @locked_ruby_version @locked_ruby_version_object ||= begin unless version = RubyVersion.from_string(@locked_ruby_version) raise LockfileError, "The Ruby version #{@locked_ruby_version} from " \ "#{@lockfile} could not be parsed. " \ "Try running bundle update --ruby to resolve this." end version end end def to_lock require "bundler/lockfile_generator" LockfileGenerator.generate(self) end def ensure_equivalent_gemfile_and_lockfile(explicit_flag = false) msg = String.new msg << "You are trying to install in deployment mode after changing\n" \ "your Gemfile. Run `bundle install` elsewhere and add the\n" \ "updated #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} to version control." unless explicit_flag suggested_command = if Bundler.settings.locations("frozen")[:global] "bundle config --delete frozen" elsif Bundler.settings.locations("deployment").keys.&([:global, :local]).any? "bundle config --delete deployment" else "bundle install --no-deployment" end msg << "\n\nIf this is a development machine, remove the #{Bundler.default_gemfile} " \ "freeze \nby running `#{suggested_command}`." end added = [] deleted = [] changed = [] new_platforms = @platforms - @locked_platforms deleted_platforms = @locked_platforms - @platforms added.concat new_platforms.map {|p| "* platform: #{p}" } deleted.concat deleted_platforms.map {|p| "* platform: #{p}" } gemfile_sources = sources.lock_sources new_sources = gemfile_sources - @locked_sources deleted_sources = @locked_sources - gemfile_sources new_deps = @dependencies - @locked_deps.values deleted_deps = @locked_deps.values - @dependencies # Check if it is possible that the source is only changed thing if (new_deps.empty? && deleted_deps.empty?) && (!new_sources.empty? && !deleted_sources.empty?) new_sources.reject! {|source| (source.path? && source.path.exist?) || equivalent_rubygems_remotes?(source) } deleted_sources.reject! {|source| (source.path? && source.path.exist?) || equivalent_rubygems_remotes?(source) } end if @locked_sources != gemfile_sources if new_sources.any? added.concat new_sources.map {|source| "* source: #{source}" } end if deleted_sources.any? deleted.concat deleted_sources.map {|source| "* source: #{source}" } end end added.concat new_deps.map {|d| "* #{pretty_dep(d)}" } if new_deps.any? if deleted_deps.any? deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" } end both_sources = Hash.new {|h, k| h[k] = [] } @dependencies.each {|d| both_sources[d.name][0] = d } @locked_deps.each {|name, d| both_sources[name][1] = d.source } both_sources.each do |name, (dep, lock_source)| next unless (dep.nil? && !lock_source.nil?) || (!dep.nil? && !lock_source.nil? && !lock_source.can_lock?(dep)) gemfile_source_name = (dep && dep.source) || "no specified source" lockfile_source_name = lock_source || "no specified source" changed << "* #{name} from `#{gemfile_source_name}` to `#{lockfile_source_name}`" end reason = change_reason msg << "\n\n#{reason.split(", ").map(&:capitalize).join("\n")}" unless reason.strip.empty? msg << "\n\nYou have added to the Gemfile:\n" << added.join("\n") if added.any? msg << "\n\nYou have deleted from the Gemfile:\n" << deleted.join("\n") if deleted.any? msg << "\n\nYou have changed in the Gemfile:\n" << changed.join("\n") if changed.any? msg << "\n" raise ProductionError, msg if added.any? || deleted.any? || changed.any? || !nothing_changed? end def validate_runtime! validate_ruby! validate_platforms! end def validate_ruby! return unless ruby_version if diff = ruby_version.diff(Bundler::RubyVersion.system) problem, expected, actual = diff msg = case problem when :engine "Your Ruby engine is #{actual}, but your Gemfile specified #{expected}" when :version "Your Ruby version is #{actual}, but your Gemfile specified #{expected}" when :engine_version "Your #{Bundler::RubyVersion.system.engine} version is #{actual}, but your Gemfile specified #{ruby_version.engine} #{expected}" when :patchlevel if !expected.is_a?(String) "The Ruby patchlevel in your Gemfile must be a string" else "Your Ruby patchlevel is #{actual}, but your Gemfile specified #{expected}" end end raise RubyVersionMismatch, msg end end def validate_platforms! return if @platforms.any? do |bundle_platform| Bundler.rubygems.platforms.any? do |local_platform| MatchPlatform.platforms_match?(bundle_platform, local_platform) end end raise ProductionError, "Your bundle only supports platforms #{@platforms.map(&:to_s)} " \ "but your local platforms are #{Bundler.rubygems.platforms.map(&:to_s)}, and " \ "there's no compatible match between those two lists." end def add_platform(platform) @new_platform ||= !@platforms.include?(platform) @platforms |= [platform] end def remove_platform(platform) return if @platforms.delete(Gem::Platform.new(platform)) raise InvalidOption, "Unable to remove the platform `#{platform}` since the only platforms are #{@platforms.join ", "}" end def add_current_platform current_platform = Bundler.local_platform add_platform(current_platform) if Bundler.feature_flag.specific_platform? add_platform(generic(current_platform)) end def find_resolved_spec(current_spec) specs.find_by_name_and_platform(current_spec.name, current_spec.platform) end def find_indexed_specs(current_spec) index[current_spec.name].select {|spec| spec.match_platform(current_spec.platform) }.sort_by(&:version) end attr_reader :sources private :sources def nothing_changed? !@source_changes && !@dependency_changes && !@new_platform && !@path_changes && !@local_changes && !@locked_specs_incomplete_for_platform end def unlocking? @unlocking end private def change_reason if unlocking? unlock_reason = @unlock.reject {|_k, v| Array(v).empty? }.map do |k, v| if v == true k.to_s else v = Array(v) "#{k}: (#{v.join(", ")})" end end.join(", ") return "bundler is unlocking #{unlock_reason}" end [ [@source_changes, "the list of sources changed"], [@dependency_changes, "the dependencies in your gemfile changed"], [@new_platform, "you added a new platform to your gemfile"], [@path_changes, "the gemspecs for path gems changed"], [@local_changes, "the gemspecs for git local gems changed"], [@locked_specs_incomplete_for_platform, "the lockfile does not have all gems needed for the current platform"], ].select(&:first).map(&:last).join(", ") end def pretty_dep(dep, source = false) SharedHelpers.pretty_dependency(dep, source) end # Check if the specs of the given source changed # according to the locked source. def specs_changed?(source) locked = @locked_sources.find {|s| s == source } !locked || dependencies_for_source_changed?(source, locked) || specs_for_source_changed?(source) end def dependencies_for_source_changed?(source, locked_source = source) deps_for_source = @dependencies.select {|s| s.source == source } locked_deps_for_source = @locked_deps.values.select {|dep| dep.source == locked_source } Set.new(deps_for_source) != Set.new(locked_deps_for_source) end def specs_for_source_changed?(source) locked_index = Index.new locked_index.use(@locked_specs.select {|s| source.can_lock?(s) }) # order here matters, since Index#== is checking source.specs.include?(locked_index) locked_index != source.specs rescue PathError, GitError => e Bundler.ui.debug "Assuming that #{source} has not changed since fetching its specs errored (#{e})" false end # Get all locals and override their matching sources. # Return true if any of the locals changed (for example, # they point to a new revision) or depend on new specs. def converge_locals locals = [] Bundler.settings.local_overrides.map do |k, v| spec = @dependencies.find {|s| s.name == k } source = spec && spec.source if source && source.respond_to?(:local_override!) source.unlock! if @unlock[:gems].include?(spec.name) locals << [source, source.local_override!(v)] end end sources_with_changes = locals.select do |source, changed| changed || specs_changed?(source) end.map(&:first) !sources_with_changes.each {|source| @unlock[:sources] << source.name }.empty? end def converge_paths sources.path_sources.any? do |source| specs_changed?(source) end end def converge_path_source_to_gemspec_source(source) return source unless source.instance_of?(Source::Path) gemspec_source = sources.path_sources.find {|s| s.is_a?(Source::Gemspec) && s.as_path_source == source } gemspec_source || source end def converge_path_sources_to_gemspec_sources @locked_sources.map! do |source| converge_path_source_to_gemspec_source(source) end @locked_specs.each do |spec| spec.source &&= converge_path_source_to_gemspec_source(spec.source) end @locked_deps.each do |_, dep| dep.source &&= converge_path_source_to_gemspec_source(dep.source) end end def converge_rubygems_sources return false if Bundler.feature_flag.lockfile_uses_separate_rubygems_sources? changes = false # Get the RubyGems sources from the Gemfile.lock locked_gem_sources = @locked_sources.select {|s| s.is_a?(Source::Rubygems) } # Get the RubyGems remotes from the Gemfile actual_remotes = sources.rubygems_remotes # If there is a RubyGems source in both if !locked_gem_sources.empty? && !actual_remotes.empty? locked_gem_sources.each do |locked_gem| # Merge the remotes from the Gemfile into the Gemfile.lock changes |= locked_gem.replace_remotes(actual_remotes, Bundler.settings[:allow_deployment_source_credential_changes]) end end changes end def converge_sources changes = false changes |= converge_rubygems_sources # Replace the sources from the Gemfile with the sources from the Gemfile.lock, # if they exist in the Gemfile.lock and are `==`. If you can't find an equivalent # source in the Gemfile.lock, use the one from the Gemfile. changes |= sources.replace_sources!(@locked_sources) sources.all_sources.each do |source| # If the source is unlockable and the current command allows an unlock of # the source (for example, you are doing a `bundle update <foo>` of a git-pinned # gem), unlock it. For git sources, this means to unlock the revision, which # will cause the `ref` used to be the most recent for the branch (or master) if # an explicit `ref` is not used. if source.respond_to?(:unlock!) && @unlock[:sources].include?(source.name) source.unlock! changes = true end end changes end def converge_dependencies frozen = Bundler.frozen_bundle? (@dependencies + @locked_deps.values).each do |dep| locked_source = @locked_deps[dep.name] # This is to make sure that if bundler is installing in deployment mode and # after locked_source and sources don't match, we still use locked_source. if frozen && !locked_source.nil? && locked_source.respond_to?(:source) && locked_source.source.instance_of?(Source::Path) && locked_source.source.path.exist? dep.source = locked_source.source elsif dep.source dep.source = sources.get(dep.source) end if dep.source.is_a?(Source::Gemspec) dep.platforms.concat(@platforms.map {|p| Dependency::REVERSE_PLATFORM_MAP[p] }.flatten(1)).uniq! end end changes = false # We want to know if all match, but don't want to check all entries # This means we need to return false if any dependency doesn't match # the lock or doesn't exist in the lock. @dependencies.each do |dependency| unless locked_dep = @locked_deps[dependency.name] changes = true next end # Gem::Dependency#== matches Gem::Dependency#type. As the lockfile # doesn't carry a notion of the dependency type, if you use # add_development_dependency in a gemspec that's loaded with the gemspec # directive, the lockfile dependencies and resolved dependencies end up # with a mismatch on #type. Work around that by setting the type on the # dep from the lockfile. locked_dep.instance_variable_set(:@type, dependency.type) # We already know the name matches from the hash lookup # so we only need to check the requirement now changes ||= dependency.requirement != locked_dep.requirement end changes end # Remove elements from the locked specs that are expired. This will most # commonly happen if the Gemfile has changed since the lockfile was last # generated def converge_locked_specs deps = [] # Build a list of dependencies that are the same in the Gemfile # and Gemfile.lock. If the Gemfile modified a dependency, but # the gem in the Gemfile.lock still satisfies it, this is fine # too. @dependencies.each do |dep| locked_dep = @locked_deps[dep.name] # If the locked_dep doesn't match the dependency we're looking for then we ignore the locked_dep locked_dep = nil unless locked_dep == dep if in_locked_deps?(dep, locked_dep) || satisfies_locked_spec?(dep) deps << dep elsif dep.source.is_a?(Source::Path) && dep.current_platform? && (!locked_dep || dep.source != locked_dep.source) @locked_specs.each do |s| @unlock[:gems] << s.name if s.source == dep.source end dep.source.unlock! if dep.source.respond_to?(:unlock!) dep.source.specs.each {|s| @unlock[:gems] << s.name } end end unlock_source_unlocks_spec = Bundler.feature_flag.unlock_source_unlocks_spec? converged = [] @locked_specs.each do |s| # Replace the locked dependency's source with the equivalent source from the Gemfile dep = @dependencies.find {|d| s.satisfies?(d) } s.source = (dep && dep.source) || sources.get(s.source) # Don't add a spec to the list if its source is expired. For example, # if you change a Git gem to RubyGems. next if s.source.nil? next if @unlock[:sources].include?(s.source.name) # XXX This is a backwards-compatibility fix to preserve the ability to # unlock a single gem by passing its name via `--source`. See issue #3759 # TODO: delete in Bundler 2 next if unlock_source_unlocks_spec && @unlock[:sources].include?(s.name) # If the spec is from a path source and it doesn't exist anymore # then we unlock it. # Path sources have special logic if s.source.instance_of?(Source::Path) || s.source.instance_of?(Source::Gemspec) other_sources_specs = begin s.source.specs rescue PathError, GitError # if we won't need the source (according to the lockfile), # don't error if the path/git source isn't available next if @locked_specs. for(requested_dependencies, [], false, true, false). none? {|locked_spec| locked_spec.source == s.source } raise end other = other_sources_specs[s].first # If the spec is no longer in the path source, unlock it. This # commonly happens if the version changed in the gemspec next unless other deps2 = other.dependencies.select {|d| d.type != :development } runtime_dependencies = s.dependencies.select {|d| d.type != :development } # If the dependencies of the path source have changed, unlock it next unless runtime_dependencies.sort == deps2.sort end converged << s end resolve = SpecSet.new(converged) expanded_deps = expand_dependencies(deps, true) @locked_specs_incomplete_for_platform = !resolve.for(expanded_deps, @unlock[:gems], true, true) resolve = resolve.for(expanded_deps, @unlock[:gems], false, false, false) diff = nil # Now, we unlock any sources that do not have anymore gems pinned to it sources.all_sources.each do |source| next unless source.respond_to?(:unlock!) unless resolve.any? {|s| s.source == source } diff ||= @locked_specs.to_a - resolve.to_a source.unlock! if diff.any? {|s| s.source == source } end end resolve end def in_locked_deps?(dep, locked_dep) # Because the lockfile can't link a dep to a specific remote, we need to # treat sources as equivalent anytime the locked dep has all the remotes # that the Gemfile dep does. locked_dep && locked_dep.source && dep.source && locked_dep.source.include?(dep.source) end def satisfies_locked_spec?(dep) @locked_specs[dep].any? {|s| s.satisfies?(dep) && (!dep.source || s.source.include?(dep.source)) } end # This list of dependencies is only used in #resolve, so it's OK to add # the metadata dependencies here def expanded_dependencies @expanded_dependencies ||= begin expand_dependencies(dependencies + metadata_dependencies, @remote) end end def metadata_dependencies @metadata_dependencies ||= begin ruby_versions = concat_ruby_version_requirements(@ruby_version) if ruby_versions.empty? || !@ruby_version.exact? concat_ruby_version_requirements(RubyVersion.system) concat_ruby_version_requirements(locked_ruby_version_object) unless @unlock[:ruby] end [ Dependency.new("ruby\0", ruby_versions), Dependency.new("rubygems\0", Gem::VERSION), ] end end def concat_ruby_version_requirements(ruby_version, ruby_versions = []) return ruby_versions unless ruby_version if ruby_version.patchlevel ruby_versions << ruby_version.to_gem_version_with_patchlevel else ruby_versions.concat(ruby_version.versions.map do |version| requirement = Gem::Requirement.new(version) if requirement.exact? "~> #{version}.0" else requirement end end) end end def expand_dependencies(dependencies, remote = false) sorted_platforms = Resolver.sort_platforms(@platforms) deps = [] dependencies.each do |dep| dep = Dependency.new(dep, ">= 0") unless dep.respond_to?(:name) next if !remote && !dep.current_platform? platforms = dep.gem_platforms(sorted_platforms) if platforms.empty? mapped_platforms = dep.platforms.map {|p| Dependency::PLATFORM_MAP[p] } Bundler.ui.warn \ "The dependency #{dep} will be unused by any of the platforms Bundler is installing for. " \ "Bundler is installing for #{@platforms.join ", "} but the dependency " \ "is only for #{mapped_platforms.join ", "}. " \ "To add those platforms to the bundle, " \ "run `bundle lock --add-platform #{mapped_platforms.join " "}`." end platforms.each do |p| deps << DepProxy.new(dep, p) if remote || p == generic_local_platform end end deps end def requested_dependencies groups = requested_groups groups.map!(&:to_sym) dependencies.reject {|d| !d.should_include? || (d.groups & groups).empty? } end def source_requirements # Load all specs from remote sources index # Record the specs available in each gem's source, so that those # specs will be available later when the resolver knows where to # look for that gemspec (or its dependencies) default = sources.default_source source_requirements = { :default => default } default = nil unless Bundler.feature_flag.lockfile_uses_separate_rubygems_sources? dependencies.each do |dep| next unless source = dep.source || default source_requirements[dep.name] = source end metadata_dependencies.each do |dep| source_requirements[dep.name] = sources.metadata_source end source_requirements["bundler"] = sources.metadata_source # needs to come last to override source_requirements end def pinned_spec_names(skip = nil) pinned_names = [] default = Bundler.feature_flag.lockfile_uses_separate_rubygems_sources? && sources.default_source @dependencies.each do |dep| next unless dep_source = dep.source || default next if dep_source == skip pinned_names << dep.name end pinned_names end def requested_groups groups - Bundler.settings[:without] - @optional_groups + Bundler.settings[:with] end def lockfiles_equal?(current, proposed, preserve_unknown_sections) if preserve_unknown_sections sections_to_ignore = LockfileParser.sections_to_ignore(@locked_bundler_version) sections_to_ignore += LockfileParser.unknown_sections_in_lockfile(current) sections_to_ignore += LockfileParser::ENVIRONMENT_VERSION_SECTIONS pattern = /#{Regexp.union(sections_to_ignore)}\n(\s{2,}.*\n)+/ whitespace_cleanup = /\n{2,}/ current = current.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip proposed = proposed.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip end current == proposed end def extract_gem_info(error) # This method will extract the error message like "Could not find foo-1.2.3 in any of the sources" # to an array. The first element will be the gem name (e.g. foo), the second will be the version number. error.message.scan(/Could not find (\w+)-(\d+(?:\.\d+)+)/).flatten end def compute_requires dependencies.reduce({}) do |requires, dep| next requires unless dep.should_include? requires[dep.name] = Array(dep.autorequire || dep.name).map do |file| # Allow `require: true` as an alias for `require: <name>` file == true ? dep.name : file end requires end end def additional_base_requirements_for_resolve return [] unless @locked_gems && Bundler.feature_flag.only_update_to_newer_versions? dependencies_by_name = dependencies.group_by(&:name) @locked_gems.specs.reduce({}) do |requirements, locked_spec| name = locked_spec.name next requirements if @locked_deps[name] != dependencies_by_name[name] dep = Gem::Dependency.new(name, ">= #{locked_spec.version}") requirements[name] = DepProxy.new(dep, locked_spec.platform) requirements end.values end def equivalent_rubygems_remotes?(source) return false unless source.is_a?(Source::Rubygems) Bundler.settings[:allow_deployment_source_credential_changes] && source.equivalent_remotes?(sources.rubygems_remotes) end end end
# frozen_string_literal: true require "bundler/lockfile_parser" require "digest/sha1" require "set" module Bundler class Definition include GemHelpers attr_reader( :dependencies, :gem_version_promoter, :locked_deps, :locked_gems, :platforms, :requires, :ruby_version ) # Given a gemfile and lockfile creates a Bundler definition # # @param gemfile [Pathname] Path to Gemfile # @param lockfile [Pathname,nil] Path to Gemfile.lock # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @return [Bundler::Definition] def self.build(gemfile, lockfile, unlock) unlock ||= {} gemfile = Pathname.new(gemfile).expand_path raise GemfileNotFound, "#{gemfile} not found" unless gemfile.file? Dsl.evaluate(gemfile, lockfile, unlock) end # # How does the new system work? # # * Load information from Gemfile and Lockfile # * Invalidate stale locked specs # * All specs from stale source are stale # * All specs that are reachable only through a stale # dependency are stale. # * If all fresh dependencies are satisfied by the locked # specs, then we can try to resolve locally. # # @param lockfile [Pathname] Path to Gemfile.lock # @param dependencies [Array(Bundler::Dependency)] array of dependencies from Gemfile # @param sources [Bundler::SourceList] # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @param ruby_version [Bundler::RubyVersion, nil] Requested Ruby Version # @param optional_groups [Array(String)] A list of optional groups def initialize(lockfile, dependencies, sources, unlock, ruby_version = nil, optional_groups = []) @unlocking = unlock == true || !unlock.empty? @dependencies = dependencies @sources = sources @unlock = unlock @optional_groups = optional_groups @remote = false @specs = nil @ruby_version = ruby_version @lockfile = lockfile @lockfile_contents = String.new @locked_bundler_version = nil @locked_ruby_version = nil if lockfile && File.exist?(lockfile) @lockfile_contents = Bundler.read_file(lockfile) @locked_gems = LockfileParser.new(@lockfile_contents) @locked_platforms = @locked_gems.platforms @platforms = @locked_platforms.dup @locked_bundler_version = @locked_gems.bundler_version @locked_ruby_version = @locked_gems.ruby_version if unlock != true @locked_deps = @locked_gems.dependencies @locked_specs = SpecSet.new(@locked_gems.specs) @locked_sources = @locked_gems.sources else @unlock = {} @locked_deps = [] @locked_specs = SpecSet.new([]) @locked_sources = [] end else @unlock = {} @platforms = [] @locked_gems = nil @locked_deps = [] @locked_specs = SpecSet.new([]) @locked_sources = [] @locked_platforms = [] end @unlock[:gems] ||= [] @unlock[:sources] ||= [] @unlock[:ruby] ||= if @ruby_version && locked_ruby_version_object @ruby_version.diff(locked_ruby_version_object) end @unlocking ||= @unlock[:ruby] ||= (!@locked_ruby_version ^ !@ruby_version) add_current_platform unless Bundler.settings[:frozen] converge_path_sources_to_gemspec_sources @path_changes = converge_paths @source_changes = converge_sources unless @unlock[:lock_shared_dependencies] eager_unlock = expand_dependencies(@unlock[:gems]) @unlock[:gems] = @locked_specs.for(eager_unlock).map(&:name) end @gem_version_promoter = create_gem_version_promoter @dependency_changes = converge_dependencies @local_changes = converge_locals @requires = compute_requires fixup_dependency_types! end def fixup_dependency_types! # XXX This is a temporary workaround for a bug when using rubygems 1.8.15 # where Gem::Dependency#== matches Gem::Dependency#type. As the lockfile # doesn't carry a notion of the dependency type, if you use # add_development_dependency in a gemspec that's loaded with the gemspec # directive, the lockfile dependencies and resolved dependencies end up # with a mismatch on #type. # Test coverage to catch a regression on this is in gemspec_spec.rb @dependencies.each do |d| if ld = @locked_deps.find {|l| l.name == d.name } ld.instance_variable_set(:@type, d.type) end end end def create_gem_version_promoter locked_specs = if @unlocking && @locked_specs.empty? && !@lockfile_contents.empty? # Definition uses an empty set of locked_specs to indicate all gems # are unlocked, but GemVersionPromoter needs the locked_specs # for conservative comparison. Bundler::SpecSet.new(@locked_gems.specs) else @locked_specs end GemVersionPromoter.new(locked_specs, @unlock[:gems]) end def resolve_with_cache! raise "Specs already loaded" if @specs sources.cached! specs end def resolve_remotely! raise "Specs already loaded" if @specs @remote = true sources.remote! specs end # For given dependency list returns a SpecSet with Gemspec of all the required # dependencies. # 1. The method first resolves the dependencies specified in Gemfile # 2. After that it tries and fetches gemspec of resolved dependencies # # @return [Bundler::SpecSet] def specs @specs ||= begin begin specs = resolve.materialize(Bundler.settings[:cache_all_platforms] ? dependencies : requested_dependencies) rescue GemNotFound => e # Handle yanked gem gem_name, gem_version = extract_gem_info(e) locked_gem = @locked_specs[gem_name].last raise if locked_gem.nil? || locked_gem.version.to_s != gem_version || !@remote raise GemNotFound, "Your bundle is locked to #{locked_gem}, but that version could not " \ "be found in any of the sources listed in your Gemfile. If you haven't changed sources, " \ "that means the author of #{locked_gem} has removed it. You'll need to update your bundle " \ "to a different version of #{locked_gem} that hasn't been removed in order to install." end unless specs["bundler"].any? local = Bundler.settings[:frozen] ? rubygems_index : index bundler = local.search(Gem::Dependency.new("bundler", VERSION)).last specs["bundler"] = bundler if bundler end specs end end def new_specs specs - @locked_specs end def removed_specs @locked_specs - specs end def new_platform? @new_platform end def missing_specs missing = [] resolve.materialize(requested_dependencies, missing) missing end def missing_dependencies missing = [] resolve.materialize(current_dependencies, missing) missing end def requested_specs @requested_specs ||= begin groups = requested_groups groups.map!(&:to_sym) specs_for(groups) end end def current_dependencies dependencies.select(&:should_include?) end def specs_for(groups) deps = dependencies.select {|d| (d.groups & groups).any? } deps.delete_if {|d| !d.should_include? } specs.for(expand_dependencies(deps)) end # Resolve all the dependencies specified in Gemfile. It ensures that # dependencies that have been already resolved via locked file and are fresh # are reused when resolving dependencies # # @return [SpecSet] resolved dependencies def resolve @resolve ||= begin last_resolve = converge_locked_specs if Bundler.settings[:frozen] || (!@unlocking && nothing_changed?) Bundler.ui.debug("Found no changes, using resolution from the lockfile") last_resolve else # Run a resolve against the locally available gems Bundler.ui.debug("Found changes from the lockfile, re-resolving dependencies because #{change_reason}") last_resolve.merge Resolver.resolve(expanded_dependencies, index, source_requirements, last_resolve, gem_version_promoter, additional_base_requirements_for_resolve, platforms) end end end def index @index ||= Index.build do |idx| dependency_names = @dependencies.map(&:name) sources.all_sources.each do |source| source.dependency_names = dependency_names.dup idx.add_source source.specs dependency_names -= pinned_spec_names(source.specs) dependency_names.concat(source.unmet_deps).uniq! end idx << Gem::Specification.new("ruby\0", RubyVersion.system.to_gem_version_with_patchlevel) idx << Gem::Specification.new("rubygems\0", Gem::VERSION) end end # used when frozen is enabled so we can find the bundler # spec, even if (say) a git gem is not checked out. def rubygems_index @rubygems_index ||= Index.build do |idx| sources.rubygems_sources.each do |rubygems| idx.add_source rubygems.specs end end end def has_rubygems_remotes? sources.rubygems_sources.any? {|s| s.remotes.any? } end def has_local_dependencies? !sources.path_sources.empty? || !sources.git_sources.empty? end def spec_git_paths sources.git_sources.map {|s| s.path.to_s } end def groups dependencies.map(&:groups).flatten.uniq end def lock(file, preserve_unknown_sections = false) contents = to_lock # Convert to \r\n if the existing lock has them # i.e., Windows with `git config core.autocrlf=true` contents.gsub!(/\n/, "\r\n") if @lockfile_contents.match("\r\n") if @locked_bundler_version locked_major = @locked_bundler_version.segments.first current_major = Gem::Version.create(Bundler::VERSION).segments.first if updating_major = locked_major < current_major Bundler.ui.warn "Warning: the lockfile is being updated to Bundler #{current_major}, " \ "after which you will be unable to return to Bundler #{@locked_bundler_version.segments.first}." end end preserve_unknown_sections ||= !updating_major && (Bundler.settings[:frozen] || !@unlocking) return if lockfiles_equal?(@lockfile_contents, contents, preserve_unknown_sections) if Bundler.settings[:frozen] Bundler.ui.error "Cannot write a changed lockfile while frozen." return end SharedHelpers.filesystem_access(file) do |p| File.open(p, "wb") {|f| f.puts(contents) } end end def locked_bundler_version if @locked_bundler_version && @locked_bundler_version < Gem::Version.new(Bundler::VERSION) new_version = Bundler::VERSION end new_version || @locked_bundler_version || Bundler::VERSION end def locked_ruby_version return unless ruby_version if @unlock[:ruby] || !@locked_ruby_version Bundler::RubyVersion.system else @locked_ruby_version end end def locked_ruby_version_object return unless @locked_ruby_version @locked_ruby_version_object ||= begin unless version = RubyVersion.from_string(@locked_ruby_version) raise LockfileError, "The Ruby version #{@locked_ruby_version} from " \ "#{@lockfile} could not be parsed. " \ "Try running bundle update --ruby to resolve this." end version end end def to_lock out = String.new sources.lock_sources.each do |source| # Add the source header out << source.to_lock # Find all specs for this source resolve. select {|s| source.can_lock?(s) }. # This needs to be sorted by full name so that # gems with the same name, but different platform # are ordered consistently sort_by(&:full_name). each do |spec| next if spec.name == "bundler" out << spec.to_lock end out << "\n" end out << "PLATFORMS\n" platforms.map(&:to_s).sort.each do |p| out << " #{p}\n" end out << "\n" out << "DEPENDENCIES\n" handled = [] dependencies.sort_by(&:to_s).each do |dep| next if handled.include?(dep.name) out << dep.to_lock handled << dep.name end if locked_ruby_version out << "\nRUBY VERSION\n" out << " #{locked_ruby_version}\n" end # Record the version of Bundler that was used to create the lockfile out << "\nBUNDLED WITH\n" out << " #{locked_bundler_version}\n" out end def ensure_equivalent_gemfile_and_lockfile(explicit_flag = false) msg = String.new msg << "You are trying to install in deployment mode after changing\n" \ "your Gemfile. Run `bundle install` elsewhere and add the\n" \ "updated #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} to version control." unless explicit_flag msg << "\n\nIf this is a development machine, remove the #{Bundler.default_gemfile} " \ "freeze \nby running `bundle install --no-deployment`." end added = [] deleted = [] changed = [] new_platforms = @platforms - @locked_platforms deleted_platforms = @locked_platforms - @platforms added.concat new_platforms.map {|p| "* platform: #{p}" } deleted.concat deleted_platforms.map {|p| "* platform: #{p}" } gemfile_sources = sources.lock_sources new_sources = gemfile_sources - @locked_sources deleted_sources = @locked_sources - gemfile_sources new_deps = @dependencies - @locked_deps deleted_deps = @locked_deps - @dependencies # Check if it is possible that the source is only changed thing if (new_deps.empty? && deleted_deps.empty?) && (!new_sources.empty? && !deleted_sources.empty?) new_sources.reject! {|source| source.is_a_path? && source.path.exist? } deleted_sources.reject! {|source| source.is_a_path? && source.path.exist? } end if @locked_sources != gemfile_sources if new_sources.any? added.concat new_sources.map {|source| "* source: #{source}" } end if deleted_sources.any? deleted.concat deleted_sources.map {|source| "* source: #{source}" } end end added.concat new_deps.map {|d| "* #{pretty_dep(d)}" } if new_deps.any? if deleted_deps.any? deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" } end both_sources = Hash.new {|h, k| h[k] = [] } @dependencies.each {|d| both_sources[d.name][0] = d } @locked_deps.each {|d| both_sources[d.name][1] = d.source } both_sources.each do |name, (dep, lock_source)| next unless (dep.nil? && !lock_source.nil?) || (!dep.nil? && !lock_source.nil? && !lock_source.can_lock?(dep)) gemfile_source_name = (dep && dep.source) || "no specified source" lockfile_source_name = lock_source || "no specified source" changed << "* #{name} from `#{gemfile_source_name}` to `#{lockfile_source_name}`" end msg << "\n\n#{change_reason.split(", ").join("\n")}\n" msg << "\n\nYou have added to the Gemfile:\n" << added.join("\n") if added.any? msg << "\n\nYou have deleted from the Gemfile:\n" << deleted.join("\n") if deleted.any? msg << "\n\nYou have changed in the Gemfile:\n" << changed.join("\n") if changed.any? msg << "\n" raise ProductionError, msg if added.any? || deleted.any? || changed.any? || !nothing_changed? end def validate_runtime! validate_ruby! validate_platforms! end def validate_ruby! return unless ruby_version if diff = ruby_version.diff(Bundler::RubyVersion.system) problem, expected, actual = diff msg = case problem when :engine "Your Ruby engine is #{actual}, but your Gemfile specified #{expected}" when :version "Your Ruby version is #{actual}, but your Gemfile specified #{expected}" when :engine_version "Your #{Bundler::RubyVersion.system.engine} version is #{actual}, but your Gemfile specified #{ruby_version.engine} #{expected}" when :patchlevel if !expected.is_a?(String) "The Ruby patchlevel in your Gemfile must be a string" else "Your Ruby patchlevel is #{actual}, but your Gemfile specified #{expected}" end end raise RubyVersionMismatch, msg end end def validate_platforms! return if @platforms.any? do |bundle_platform| Bundler.rubygems.platforms.any? do |local_platform| MatchPlatform.platforms_match?(bundle_platform, local_platform) end end raise ProductionError, "Your bundle only supports platforms #{@platforms.map(&:to_s)} " \ "but your local platforms are #{Bundler.rubygems.platforms.map(&:to_s)}, and " \ "there's no compatible match between those two lists." end def add_platform(platform) @new_platform ||= !@platforms.include?(platform) @platforms |= [platform] end def remove_platform(platform) return if @platforms.delete(Gem::Platform.new(platform)) raise InvalidOption, "Unable to remove the platform `#{platform}` since the only platforms are #{@platforms.join ", "}" end def add_current_platform current_platform = Bundler.local_platform add_platform(current_platform) if Bundler.settings[:specific_platform] add_platform(generic(current_platform)) end def find_resolved_spec(current_spec) specs.find_by_name_and_platform(current_spec.name, current_spec.platform) end def find_indexed_specs(current_spec) index[current_spec.name].select {|spec| spec.match_platform(current_spec.platform) }.sort_by(&:version) end attr_reader :sources private :sources private def nothing_changed? !@source_changes && !@dependency_changes && !@new_platform && !@path_changes && !@local_changes end def change_reason if @unlocking unlock_reason = @unlock.reject {|_k, v| Array(v).empty? }.map do |k, v| if v == true k.to_s else v = Array(v) "#{k}: (#{v.join(", ")})" end end.join(", ") return "bundler is unlocking #{unlock_reason}" end [ [@source_changes, "the list of sources changed"], [@dependency_changes, "the dependencies in your gemfile changed"], [@new_platform, "you added a new platform to your gemfile"], [@path_changes, "the gemspecs for path gems changed"], [@local_changes, "the gemspecs for git local gems changed"], ].select(&:first).map(&:last).join(", ") end def pretty_dep(dep, source = false) msg = String.new(dep.name) msg << " (#{dep.requirement})" unless dep.requirement == Gem::Requirement.default msg << " from the `#{dep.source}` source" if source && dep.source msg end # Check if the specs of the given source changed # according to the locked source. def specs_changed?(source) locked = @locked_sources.find {|s| s == source } !locked || dependencies_for_source_changed?(source, locked) || specs_for_source_changed?(source) end def dependencies_for_source_changed?(source, locked_source = source) deps_for_source = @dependencies.select {|s| s.source == source } locked_deps_for_source = @locked_deps.select {|s| s.source == locked_source } Set.new(deps_for_source) != Set.new(locked_deps_for_source) end def specs_for_source_changed?(source) locked_index = Index.new locked_index.use(@locked_specs.select {|s| source.can_lock?(s) }) source.specs != locked_index end # Get all locals and override their matching sources. # Return true if any of the locals changed (for example, # they point to a new revision) or depend on new specs. def converge_locals locals = [] Bundler.settings.local_overrides.map do |k, v| spec = @dependencies.find {|s| s.name == k } source = spec && spec.source if source && source.respond_to?(:local_override!) source.unlock! if @unlock[:gems].include?(spec.name) locals << [source, source.local_override!(v)] end end sources_with_changes = locals.select do |source, changed| changed || specs_changed?(source) end.map(&:first) !sources_with_changes.each {|source| @unlock[:sources] << source.name }.empty? end def converge_paths sources.path_sources.any? do |source| specs_changed?(source) end end def converge_path_source_to_gemspec_source(source) return source unless source.instance_of?(Source::Path) gemspec_source = sources.path_sources.find {|s| s.is_a?(Source::Gemspec) && s.as_path_source == source } gemspec_source || source end def converge_path_sources_to_gemspec_sources @locked_sources.map! do |source| converge_path_source_to_gemspec_source(source) end @locked_specs.each do |spec| spec.source &&= converge_path_source_to_gemspec_source(spec.source) end @locked_deps.each do |dep| dep.source &&= converge_path_source_to_gemspec_source(dep.source) end end def converge_sources changes = false # Get the Rubygems sources from the Gemfile.lock locked_gem_sources = @locked_sources.select {|s| s.is_a?(Source::Rubygems) } # Get the Rubygems remotes from the Gemfile actual_remotes = sources.rubygems_remotes # If there is a Rubygems source in both if !locked_gem_sources.empty? && !actual_remotes.empty? locked_gem_sources.each do |locked_gem| # Merge the remotes from the Gemfile into the Gemfile.lock changes |= locked_gem.replace_remotes(actual_remotes) end end # Replace the sources from the Gemfile with the sources from the Gemfile.lock, # if they exist in the Gemfile.lock and are `==`. If you can't find an equivalent # source in the Gemfile.lock, use the one from the Gemfile. changes |= sources.replace_sources!(@locked_sources) sources.all_sources.each do |source| # If the source is unlockable and the current command allows an unlock of # the source (for example, you are doing a `bundle update <foo>` of a git-pinned # gem), unlock it. For git sources, this means to unlock the revision, which # will cause the `ref` used to be the most recent for the branch (or master) if # an explicit `ref` is not used. if source.respond_to?(:unlock!) && @unlock[:sources].include?(source.name) source.unlock! changes = true end end changes end def converge_dependencies (@dependencies + @locked_deps).each do |dep| locked_source = @locked_deps.select {|d| d.name == dep.name }.last # This is to make sure that if bundler is installing in deployment mode and # after locked_source and sources don't match, we still use locked_source. if Bundler.settings[:frozen] && !locked_source.nil? && locked_source.respond_to?(:source) && locked_source.source.instance_of?(Source::Path) && locked_source.source.path.exist? dep.source = locked_source.source elsif dep.source dep.source = sources.get(dep.source) end if dep.source.is_a?(Source::Gemspec) dep.platforms.concat(@platforms.map {|p| Dependency::REVERSE_PLATFORM_MAP[p] }.flatten(1)).uniq! end end dependency_without_type = proc {|d| Gem::Dependency.new(d.name, *d.requirement.as_list) } Set.new(@dependencies.map(&dependency_without_type)) != Set.new(@locked_deps.map(&dependency_without_type)) end # Remove elements from the locked specs that are expired. This will most # commonly happen if the Gemfile has changed since the lockfile was last # generated def converge_locked_specs deps = [] # Build a list of dependencies that are the same in the Gemfile # and Gemfile.lock. If the Gemfile modified a dependency, but # the gem in the Gemfile.lock still satisfies it, this is fine # too. locked_deps_hash = @locked_deps.inject({}) do |hsh, dep| hsh[dep] = dep hsh end @dependencies.each do |dep| locked_dep = locked_deps_hash[dep] if in_locked_deps?(dep, locked_dep) || satisfies_locked_spec?(dep) deps << dep elsif dep.source.is_a?(Source::Path) && dep.current_platform? && (!locked_dep || dep.source != locked_dep.source) @locked_specs.each do |s| @unlock[:gems] << s.name if s.source == dep.source end dep.source.unlock! if dep.source.respond_to?(:unlock!) dep.source.specs.each {|s| @unlock[:gems] << s.name } end end converged = [] @locked_specs.each do |s| # Replace the locked dependency's source with the equivalent source from the Gemfile dep = @dependencies.find {|d| s.satisfies?(d) } s.source = (dep && dep.source) || sources.get(s.source) # Don't add a spec to the list if its source is expired. For example, # if you change a Git gem to Rubygems. next if s.source.nil? || @unlock[:sources].include?(s.source.name) # XXX This is a backwards-compatibility fix to preserve the ability to # unlock a single gem by passing its name via `--source`. See issue #3759 next if s.source.nil? || @unlock[:sources].include?(s.name) # If the spec is from a path source and it doesn't exist anymore # then we unlock it. # Path sources have special logic if s.source.instance_of?(Source::Path) || s.source.instance_of?(Source::Gemspec) other = s.source.specs[s].first # If the spec is no longer in the path source, unlock it. This # commonly happens if the version changed in the gemspec next unless other deps2 = other.dependencies.select {|d| d.type != :development } # If the dependencies of the path source have changed, unlock it next unless s.dependencies.sort == deps2.sort end converged << s end resolve = SpecSet.new(converged) resolve = resolve.for(expand_dependencies(deps, true), @unlock[:gems]) diff = @locked_specs.to_a - resolve.to_a # Now, we unlock any sources that do not have anymore gems pinned to it sources.all_sources.each do |source| next unless source.respond_to?(:unlock!) unless resolve.any? {|s| s.source == source } source.unlock! if !diff.empty? && diff.any? {|s| s.source == source } end end resolve end def in_locked_deps?(dep, locked_dep) # Because the lockfile can't link a dep to a specific remote, we need to # treat sources as equivalent anytime the locked dep has all the remotes # that the Gemfile dep does. locked_dep && locked_dep.source && dep.source && locked_dep.source.include?(dep.source) end def satisfies_locked_spec?(dep) @locked_specs.any? {|s| s.satisfies?(dep) && (!dep.source || s.source.include?(dep.source)) } end # This list of dependencies is only used in #resolve, so it's OK to add # the metadata dependencies here def expanded_dependencies @expanded_dependencies ||= begin ruby_versions = concat_ruby_version_requirements(@ruby_version) if ruby_versions.empty? || !@ruby_version.exact? concat_ruby_version_requirements(RubyVersion.system) concat_ruby_version_requirements(locked_ruby_version_object) unless @unlock[:ruby] end metadata_dependencies = [ Dependency.new("ruby\0", ruby_versions), Dependency.new("rubygems\0", Gem::VERSION), ] expand_dependencies(dependencies + metadata_dependencies, @remote) end end def concat_ruby_version_requirements(ruby_version, ruby_versions = []) return ruby_versions unless ruby_version if ruby_version.patchlevel ruby_versions << ruby_version.to_gem_version_with_patchlevel else ruby_versions.concat(ruby_version.versions.map do |version| requirement = Gem::Requirement.new(version) if requirement.exact? "~> #{version}.0" else requirement end end) end end def expand_dependencies(dependencies, remote = false) deps = [] dependencies.each do |dep| dep = Dependency.new(dep, ">= 0") unless dep.respond_to?(:name) next if !remote && !dep.current_platform? platforms = dep.gem_platforms(@platforms) if platforms.empty? mapped_platforms = dep.platforms.map {|p| Dependency::PLATFORM_MAP[p] } Bundler.ui.warn \ "The dependency #{dep} will be unused by any of the platforms Bundler is installing for. " \ "Bundler is installing for #{@platforms.join ", "} but the dependency " \ "is only for #{mapped_platforms.join ", "}. " \ "To add those platforms to the bundle, " \ "run `bundle lock --add-platform #{mapped_platforms.join " "}`." end platforms.each do |p| deps << DepProxy.new(dep, p) if remote || p == generic_local_platform end end deps end def requested_dependencies groups = requested_groups groups.map!(&:to_sym) dependencies.reject {|d| !d.should_include? || (d.groups & groups).empty? } end def source_requirements # Load all specs from remote sources index # Record the specs available in each gem's source, so that those # specs will be available later when the resolver knows where to # look for that gemspec (or its dependencies) source_requirements = {} dependencies.each do |dep| next unless dep.source source_requirements[dep.name] = dep.source.specs end source_requirements end def pinned_spec_names(specs) names = [] specs.each do |s| # TODO: when two sources without blocks is an error, we can change # this check to !s.source.is_a?(Source::LocalRubygems). For now, # we need to ask every Rubygems for every gem name. if s.source.is_a?(Source::Git) || s.source.is_a?(Source::Path) names << s.name end end names.uniq! names end def requested_groups groups - Bundler.settings.without - @optional_groups + Bundler.settings.with end def lockfiles_equal?(current, proposed, preserve_unknown_sections) if preserve_unknown_sections sections_to_ignore = LockfileParser.sections_to_ignore(@locked_bundler_version) sections_to_ignore += LockfileParser.unknown_sections_in_lockfile(current) sections_to_ignore += LockfileParser::ENVIRONMENT_VERSION_SECTIONS pattern = /#{Regexp.union(sections_to_ignore)}\n(\s{2,}.*\n)+/ whitespace_cleanup = /\n{2,}/ current = current.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip proposed = proposed.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip end current == proposed end def extract_gem_info(error) # This method will extract the error message like "Could not find foo-1.2.3 in any of the sources" # to an array. The first element will be the gem name (e.g. foo), the second will be the version number. error.message.scan(/Could not find (\w+)-(\d+(?:\.\d+)+)/).flatten end def compute_requires dependencies.reduce({}) do |requires, dep| next requires unless dep.should_include? requires[dep.name] = Array(dep.autorequire || dep.name).map do |file| # Allow `require: true` as an alias for `require: <name>` file == true ? dep.name : file end requires end end def additional_base_requirements_for_resolve return [] unless @locked_gems && Bundler.feature_flag.only_update_to_newer_versions? @locked_gems.specs.reduce({}) do |requirements, locked_spec| dep = Gem::Dependency.new(locked_spec.name, ">= #{locked_spec.version}") requirements[locked_spec.name] = DepProxy.new(dep, locked_spec.platform) requirements end.values end end end [Definition] Only consider runtime deps in path source comparison # frozen_string_literal: true require "bundler/lockfile_parser" require "digest/sha1" require "set" module Bundler class Definition include GemHelpers attr_reader( :dependencies, :gem_version_promoter, :locked_deps, :locked_gems, :platforms, :requires, :ruby_version ) # Given a gemfile and lockfile creates a Bundler definition # # @param gemfile [Pathname] Path to Gemfile # @param lockfile [Pathname,nil] Path to Gemfile.lock # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @return [Bundler::Definition] def self.build(gemfile, lockfile, unlock) unlock ||= {} gemfile = Pathname.new(gemfile).expand_path raise GemfileNotFound, "#{gemfile} not found" unless gemfile.file? Dsl.evaluate(gemfile, lockfile, unlock) end # # How does the new system work? # # * Load information from Gemfile and Lockfile # * Invalidate stale locked specs # * All specs from stale source are stale # * All specs that are reachable only through a stale # dependency are stale. # * If all fresh dependencies are satisfied by the locked # specs, then we can try to resolve locally. # # @param lockfile [Pathname] Path to Gemfile.lock # @param dependencies [Array(Bundler::Dependency)] array of dependencies from Gemfile # @param sources [Bundler::SourceList] # @param unlock [Hash, Boolean, nil] Gems that have been requested # to be updated or true if all gems should be updated # @param ruby_version [Bundler::RubyVersion, nil] Requested Ruby Version # @param optional_groups [Array(String)] A list of optional groups def initialize(lockfile, dependencies, sources, unlock, ruby_version = nil, optional_groups = []) @unlocking = unlock == true || !unlock.empty? @dependencies = dependencies @sources = sources @unlock = unlock @optional_groups = optional_groups @remote = false @specs = nil @ruby_version = ruby_version @lockfile = lockfile @lockfile_contents = String.new @locked_bundler_version = nil @locked_ruby_version = nil if lockfile && File.exist?(lockfile) @lockfile_contents = Bundler.read_file(lockfile) @locked_gems = LockfileParser.new(@lockfile_contents) @locked_platforms = @locked_gems.platforms @platforms = @locked_platforms.dup @locked_bundler_version = @locked_gems.bundler_version @locked_ruby_version = @locked_gems.ruby_version if unlock != true @locked_deps = @locked_gems.dependencies @locked_specs = SpecSet.new(@locked_gems.specs) @locked_sources = @locked_gems.sources else @unlock = {} @locked_deps = [] @locked_specs = SpecSet.new([]) @locked_sources = [] end else @unlock = {} @platforms = [] @locked_gems = nil @locked_deps = [] @locked_specs = SpecSet.new([]) @locked_sources = [] @locked_platforms = [] end @unlock[:gems] ||= [] @unlock[:sources] ||= [] @unlock[:ruby] ||= if @ruby_version && locked_ruby_version_object @ruby_version.diff(locked_ruby_version_object) end @unlocking ||= @unlock[:ruby] ||= (!@locked_ruby_version ^ !@ruby_version) add_current_platform unless Bundler.settings[:frozen] converge_path_sources_to_gemspec_sources @path_changes = converge_paths @source_changes = converge_sources unless @unlock[:lock_shared_dependencies] eager_unlock = expand_dependencies(@unlock[:gems]) @unlock[:gems] = @locked_specs.for(eager_unlock).map(&:name) end @gem_version_promoter = create_gem_version_promoter @dependency_changes = converge_dependencies @local_changes = converge_locals @requires = compute_requires fixup_dependency_types! end def fixup_dependency_types! # XXX This is a temporary workaround for a bug when using rubygems 1.8.15 # where Gem::Dependency#== matches Gem::Dependency#type. As the lockfile # doesn't carry a notion of the dependency type, if you use # add_development_dependency in a gemspec that's loaded with the gemspec # directive, the lockfile dependencies and resolved dependencies end up # with a mismatch on #type. # Test coverage to catch a regression on this is in gemspec_spec.rb @dependencies.each do |d| if ld = @locked_deps.find {|l| l.name == d.name } ld.instance_variable_set(:@type, d.type) end end end def create_gem_version_promoter locked_specs = if @unlocking && @locked_specs.empty? && !@lockfile_contents.empty? # Definition uses an empty set of locked_specs to indicate all gems # are unlocked, but GemVersionPromoter needs the locked_specs # for conservative comparison. Bundler::SpecSet.new(@locked_gems.specs) else @locked_specs end GemVersionPromoter.new(locked_specs, @unlock[:gems]) end def resolve_with_cache! raise "Specs already loaded" if @specs sources.cached! specs end def resolve_remotely! raise "Specs already loaded" if @specs @remote = true sources.remote! specs end # For given dependency list returns a SpecSet with Gemspec of all the required # dependencies. # 1. The method first resolves the dependencies specified in Gemfile # 2. After that it tries and fetches gemspec of resolved dependencies # # @return [Bundler::SpecSet] def specs @specs ||= begin begin specs = resolve.materialize(Bundler.settings[:cache_all_platforms] ? dependencies : requested_dependencies) rescue GemNotFound => e # Handle yanked gem gem_name, gem_version = extract_gem_info(e) locked_gem = @locked_specs[gem_name].last raise if locked_gem.nil? || locked_gem.version.to_s != gem_version || !@remote raise GemNotFound, "Your bundle is locked to #{locked_gem}, but that version could not " \ "be found in any of the sources listed in your Gemfile. If you haven't changed sources, " \ "that means the author of #{locked_gem} has removed it. You'll need to update your bundle " \ "to a different version of #{locked_gem} that hasn't been removed in order to install." end unless specs["bundler"].any? local = Bundler.settings[:frozen] ? rubygems_index : index bundler = local.search(Gem::Dependency.new("bundler", VERSION)).last specs["bundler"] = bundler if bundler end specs end end def new_specs specs - @locked_specs end def removed_specs @locked_specs - specs end def new_platform? @new_platform end def missing_specs missing = [] resolve.materialize(requested_dependencies, missing) missing end def missing_dependencies missing = [] resolve.materialize(current_dependencies, missing) missing end def requested_specs @requested_specs ||= begin groups = requested_groups groups.map!(&:to_sym) specs_for(groups) end end def current_dependencies dependencies.select(&:should_include?) end def specs_for(groups) deps = dependencies.select {|d| (d.groups & groups).any? } deps.delete_if {|d| !d.should_include? } specs.for(expand_dependencies(deps)) end # Resolve all the dependencies specified in Gemfile. It ensures that # dependencies that have been already resolved via locked file and are fresh # are reused when resolving dependencies # # @return [SpecSet] resolved dependencies def resolve @resolve ||= begin last_resolve = converge_locked_specs if Bundler.settings[:frozen] || (!@unlocking && nothing_changed?) Bundler.ui.debug("Found no changes, using resolution from the lockfile") last_resolve else # Run a resolve against the locally available gems Bundler.ui.debug("Found changes from the lockfile, re-resolving dependencies because #{change_reason}") last_resolve.merge Resolver.resolve(expanded_dependencies, index, source_requirements, last_resolve, gem_version_promoter, additional_base_requirements_for_resolve, platforms) end end end def index @index ||= Index.build do |idx| dependency_names = @dependencies.map(&:name) sources.all_sources.each do |source| source.dependency_names = dependency_names.dup idx.add_source source.specs dependency_names -= pinned_spec_names(source.specs) dependency_names.concat(source.unmet_deps).uniq! end idx << Gem::Specification.new("ruby\0", RubyVersion.system.to_gem_version_with_patchlevel) idx << Gem::Specification.new("rubygems\0", Gem::VERSION) end end # used when frozen is enabled so we can find the bundler # spec, even if (say) a git gem is not checked out. def rubygems_index @rubygems_index ||= Index.build do |idx| sources.rubygems_sources.each do |rubygems| idx.add_source rubygems.specs end end end def has_rubygems_remotes? sources.rubygems_sources.any? {|s| s.remotes.any? } end def has_local_dependencies? !sources.path_sources.empty? || !sources.git_sources.empty? end def spec_git_paths sources.git_sources.map {|s| s.path.to_s } end def groups dependencies.map(&:groups).flatten.uniq end def lock(file, preserve_unknown_sections = false) contents = to_lock # Convert to \r\n if the existing lock has them # i.e., Windows with `git config core.autocrlf=true` contents.gsub!(/\n/, "\r\n") if @lockfile_contents.match("\r\n") if @locked_bundler_version locked_major = @locked_bundler_version.segments.first current_major = Gem::Version.create(Bundler::VERSION).segments.first if updating_major = locked_major < current_major Bundler.ui.warn "Warning: the lockfile is being updated to Bundler #{current_major}, " \ "after which you will be unable to return to Bundler #{@locked_bundler_version.segments.first}." end end preserve_unknown_sections ||= !updating_major && (Bundler.settings[:frozen] || !@unlocking) return if lockfiles_equal?(@lockfile_contents, contents, preserve_unknown_sections) if Bundler.settings[:frozen] Bundler.ui.error "Cannot write a changed lockfile while frozen." return end SharedHelpers.filesystem_access(file) do |p| File.open(p, "wb") {|f| f.puts(contents) } end end def locked_bundler_version if @locked_bundler_version && @locked_bundler_version < Gem::Version.new(Bundler::VERSION) new_version = Bundler::VERSION end new_version || @locked_bundler_version || Bundler::VERSION end def locked_ruby_version return unless ruby_version if @unlock[:ruby] || !@locked_ruby_version Bundler::RubyVersion.system else @locked_ruby_version end end def locked_ruby_version_object return unless @locked_ruby_version @locked_ruby_version_object ||= begin unless version = RubyVersion.from_string(@locked_ruby_version) raise LockfileError, "The Ruby version #{@locked_ruby_version} from " \ "#{@lockfile} could not be parsed. " \ "Try running bundle update --ruby to resolve this." end version end end def to_lock out = String.new sources.lock_sources.each do |source| # Add the source header out << source.to_lock # Find all specs for this source resolve. select {|s| source.can_lock?(s) }. # This needs to be sorted by full name so that # gems with the same name, but different platform # are ordered consistently sort_by(&:full_name). each do |spec| next if spec.name == "bundler" out << spec.to_lock end out << "\n" end out << "PLATFORMS\n" platforms.map(&:to_s).sort.each do |p| out << " #{p}\n" end out << "\n" out << "DEPENDENCIES\n" handled = [] dependencies.sort_by(&:to_s).each do |dep| next if handled.include?(dep.name) out << dep.to_lock handled << dep.name end if locked_ruby_version out << "\nRUBY VERSION\n" out << " #{locked_ruby_version}\n" end # Record the version of Bundler that was used to create the lockfile out << "\nBUNDLED WITH\n" out << " #{locked_bundler_version}\n" out end def ensure_equivalent_gemfile_and_lockfile(explicit_flag = false) msg = String.new msg << "You are trying to install in deployment mode after changing\n" \ "your Gemfile. Run `bundle install` elsewhere and add the\n" \ "updated #{Bundler.default_lockfile.relative_path_from(SharedHelpers.pwd)} to version control." unless explicit_flag msg << "\n\nIf this is a development machine, remove the #{Bundler.default_gemfile} " \ "freeze \nby running `bundle install --no-deployment`." end added = [] deleted = [] changed = [] new_platforms = @platforms - @locked_platforms deleted_platforms = @locked_platforms - @platforms added.concat new_platforms.map {|p| "* platform: #{p}" } deleted.concat deleted_platforms.map {|p| "* platform: #{p}" } gemfile_sources = sources.lock_sources new_sources = gemfile_sources - @locked_sources deleted_sources = @locked_sources - gemfile_sources new_deps = @dependencies - @locked_deps deleted_deps = @locked_deps - @dependencies # Check if it is possible that the source is only changed thing if (new_deps.empty? && deleted_deps.empty?) && (!new_sources.empty? && !deleted_sources.empty?) new_sources.reject! {|source| source.is_a_path? && source.path.exist? } deleted_sources.reject! {|source| source.is_a_path? && source.path.exist? } end if @locked_sources != gemfile_sources if new_sources.any? added.concat new_sources.map {|source| "* source: #{source}" } end if deleted_sources.any? deleted.concat deleted_sources.map {|source| "* source: #{source}" } end end added.concat new_deps.map {|d| "* #{pretty_dep(d)}" } if new_deps.any? if deleted_deps.any? deleted.concat deleted_deps.map {|d| "* #{pretty_dep(d)}" } end both_sources = Hash.new {|h, k| h[k] = [] } @dependencies.each {|d| both_sources[d.name][0] = d } @locked_deps.each {|d| both_sources[d.name][1] = d.source } both_sources.each do |name, (dep, lock_source)| next unless (dep.nil? && !lock_source.nil?) || (!dep.nil? && !lock_source.nil? && !lock_source.can_lock?(dep)) gemfile_source_name = (dep && dep.source) || "no specified source" lockfile_source_name = lock_source || "no specified source" changed << "* #{name} from `#{gemfile_source_name}` to `#{lockfile_source_name}`" end msg << "\n\n#{change_reason.split(", ").join("\n")}\n" msg << "\n\nYou have added to the Gemfile:\n" << added.join("\n") if added.any? msg << "\n\nYou have deleted from the Gemfile:\n" << deleted.join("\n") if deleted.any? msg << "\n\nYou have changed in the Gemfile:\n" << changed.join("\n") if changed.any? msg << "\n" raise ProductionError, msg if added.any? || deleted.any? || changed.any? || !nothing_changed? end def validate_runtime! validate_ruby! validate_platforms! end def validate_ruby! return unless ruby_version if diff = ruby_version.diff(Bundler::RubyVersion.system) problem, expected, actual = diff msg = case problem when :engine "Your Ruby engine is #{actual}, but your Gemfile specified #{expected}" when :version "Your Ruby version is #{actual}, but your Gemfile specified #{expected}" when :engine_version "Your #{Bundler::RubyVersion.system.engine} version is #{actual}, but your Gemfile specified #{ruby_version.engine} #{expected}" when :patchlevel if !expected.is_a?(String) "The Ruby patchlevel in your Gemfile must be a string" else "Your Ruby patchlevel is #{actual}, but your Gemfile specified #{expected}" end end raise RubyVersionMismatch, msg end end def validate_platforms! return if @platforms.any? do |bundle_platform| Bundler.rubygems.platforms.any? do |local_platform| MatchPlatform.platforms_match?(bundle_platform, local_platform) end end raise ProductionError, "Your bundle only supports platforms #{@platforms.map(&:to_s)} " \ "but your local platforms are #{Bundler.rubygems.platforms.map(&:to_s)}, and " \ "there's no compatible match between those two lists." end def add_platform(platform) @new_platform ||= !@platforms.include?(platform) @platforms |= [platform] end def remove_platform(platform) return if @platforms.delete(Gem::Platform.new(platform)) raise InvalidOption, "Unable to remove the platform `#{platform}` since the only platforms are #{@platforms.join ", "}" end def add_current_platform current_platform = Bundler.local_platform add_platform(current_platform) if Bundler.settings[:specific_platform] add_platform(generic(current_platform)) end def find_resolved_spec(current_spec) specs.find_by_name_and_platform(current_spec.name, current_spec.platform) end def find_indexed_specs(current_spec) index[current_spec.name].select {|spec| spec.match_platform(current_spec.platform) }.sort_by(&:version) end attr_reader :sources private :sources private def nothing_changed? !@source_changes && !@dependency_changes && !@new_platform && !@path_changes && !@local_changes end def change_reason if @unlocking unlock_reason = @unlock.reject {|_k, v| Array(v).empty? }.map do |k, v| if v == true k.to_s else v = Array(v) "#{k}: (#{v.join(", ")})" end end.join(", ") return "bundler is unlocking #{unlock_reason}" end [ [@source_changes, "the list of sources changed"], [@dependency_changes, "the dependencies in your gemfile changed"], [@new_platform, "you added a new platform to your gemfile"], [@path_changes, "the gemspecs for path gems changed"], [@local_changes, "the gemspecs for git local gems changed"], ].select(&:first).map(&:last).join(", ") end def pretty_dep(dep, source = false) msg = String.new(dep.name) msg << " (#{dep.requirement})" unless dep.requirement == Gem::Requirement.default msg << " from the `#{dep.source}` source" if source && dep.source msg end # Check if the specs of the given source changed # according to the locked source. def specs_changed?(source) locked = @locked_sources.find {|s| s == source } !locked || dependencies_for_source_changed?(source, locked) || specs_for_source_changed?(source) end def dependencies_for_source_changed?(source, locked_source = source) deps_for_source = @dependencies.select {|s| s.source == source } locked_deps_for_source = @locked_deps.select {|s| s.source == locked_source } Set.new(deps_for_source) != Set.new(locked_deps_for_source) end def specs_for_source_changed?(source) locked_index = Index.new locked_index.use(@locked_specs.select {|s| source.can_lock?(s) }) source.specs != locked_index end # Get all locals and override their matching sources. # Return true if any of the locals changed (for example, # they point to a new revision) or depend on new specs. def converge_locals locals = [] Bundler.settings.local_overrides.map do |k, v| spec = @dependencies.find {|s| s.name == k } source = spec && spec.source if source && source.respond_to?(:local_override!) source.unlock! if @unlock[:gems].include?(spec.name) locals << [source, source.local_override!(v)] end end sources_with_changes = locals.select do |source, changed| changed || specs_changed?(source) end.map(&:first) !sources_with_changes.each {|source| @unlock[:sources] << source.name }.empty? end def converge_paths sources.path_sources.any? do |source| specs_changed?(source) end end def converge_path_source_to_gemspec_source(source) return source unless source.instance_of?(Source::Path) gemspec_source = sources.path_sources.find {|s| s.is_a?(Source::Gemspec) && s.as_path_source == source } gemspec_source || source end def converge_path_sources_to_gemspec_sources @locked_sources.map! do |source| converge_path_source_to_gemspec_source(source) end @locked_specs.each do |spec| spec.source &&= converge_path_source_to_gemspec_source(spec.source) end @locked_deps.each do |dep| dep.source &&= converge_path_source_to_gemspec_source(dep.source) end end def converge_sources changes = false # Get the Rubygems sources from the Gemfile.lock locked_gem_sources = @locked_sources.select {|s| s.is_a?(Source::Rubygems) } # Get the Rubygems remotes from the Gemfile actual_remotes = sources.rubygems_remotes # If there is a Rubygems source in both if !locked_gem_sources.empty? && !actual_remotes.empty? locked_gem_sources.each do |locked_gem| # Merge the remotes from the Gemfile into the Gemfile.lock changes |= locked_gem.replace_remotes(actual_remotes) end end # Replace the sources from the Gemfile with the sources from the Gemfile.lock, # if they exist in the Gemfile.lock and are `==`. If you can't find an equivalent # source in the Gemfile.lock, use the one from the Gemfile. changes |= sources.replace_sources!(@locked_sources) sources.all_sources.each do |source| # If the source is unlockable and the current command allows an unlock of # the source (for example, you are doing a `bundle update <foo>` of a git-pinned # gem), unlock it. For git sources, this means to unlock the revision, which # will cause the `ref` used to be the most recent for the branch (or master) if # an explicit `ref` is not used. if source.respond_to?(:unlock!) && @unlock[:sources].include?(source.name) source.unlock! changes = true end end changes end def converge_dependencies (@dependencies + @locked_deps).each do |dep| locked_source = @locked_deps.select {|d| d.name == dep.name }.last # This is to make sure that if bundler is installing in deployment mode and # after locked_source and sources don't match, we still use locked_source. if Bundler.settings[:frozen] && !locked_source.nil? && locked_source.respond_to?(:source) && locked_source.source.instance_of?(Source::Path) && locked_source.source.path.exist? dep.source = locked_source.source elsif dep.source dep.source = sources.get(dep.source) end if dep.source.is_a?(Source::Gemspec) dep.platforms.concat(@platforms.map {|p| Dependency::REVERSE_PLATFORM_MAP[p] }.flatten(1)).uniq! end end dependency_without_type = proc {|d| Gem::Dependency.new(d.name, *d.requirement.as_list) } Set.new(@dependencies.map(&dependency_without_type)) != Set.new(@locked_deps.map(&dependency_without_type)) end # Remove elements from the locked specs that are expired. This will most # commonly happen if the Gemfile has changed since the lockfile was last # generated def converge_locked_specs deps = [] # Build a list of dependencies that are the same in the Gemfile # and Gemfile.lock. If the Gemfile modified a dependency, but # the gem in the Gemfile.lock still satisfies it, this is fine # too. locked_deps_hash = @locked_deps.inject({}) do |hsh, dep| hsh[dep] = dep hsh end @dependencies.each do |dep| locked_dep = locked_deps_hash[dep] if in_locked_deps?(dep, locked_dep) || satisfies_locked_spec?(dep) deps << dep elsif dep.source.is_a?(Source::Path) && dep.current_platform? && (!locked_dep || dep.source != locked_dep.source) @locked_specs.each do |s| @unlock[:gems] << s.name if s.source == dep.source end dep.source.unlock! if dep.source.respond_to?(:unlock!) dep.source.specs.each {|s| @unlock[:gems] << s.name } end end converged = [] @locked_specs.each do |s| # Replace the locked dependency's source with the equivalent source from the Gemfile dep = @dependencies.find {|d| s.satisfies?(d) } s.source = (dep && dep.source) || sources.get(s.source) # Don't add a spec to the list if its source is expired. For example, # if you change a Git gem to Rubygems. next if s.source.nil? || @unlock[:sources].include?(s.source.name) # XXX This is a backwards-compatibility fix to preserve the ability to # unlock a single gem by passing its name via `--source`. See issue #3759 next if s.source.nil? || @unlock[:sources].include?(s.name) # If the spec is from a path source and it doesn't exist anymore # then we unlock it. # Path sources have special logic if s.source.instance_of?(Source::Path) || s.source.instance_of?(Source::Gemspec) other = s.source.specs[s].first # If the spec is no longer in the path source, unlock it. This # commonly happens if the version changed in the gemspec next unless other deps2 = other.dependencies.select {|d| d.type != :development } runtime_dependencies = s.dependencies.select {|d| d.type != :development } # If the dependencies of the path source have changed, unlock it next unless runtime_dependencies.sort == deps2.sort end converged << s end resolve = SpecSet.new(converged) resolve = resolve.for(expand_dependencies(deps, true), @unlock[:gems]) diff = @locked_specs.to_a - resolve.to_a # Now, we unlock any sources that do not have anymore gems pinned to it sources.all_sources.each do |source| next unless source.respond_to?(:unlock!) unless resolve.any? {|s| s.source == source } source.unlock! if !diff.empty? && diff.any? {|s| s.source == source } end end resolve end def in_locked_deps?(dep, locked_dep) # Because the lockfile can't link a dep to a specific remote, we need to # treat sources as equivalent anytime the locked dep has all the remotes # that the Gemfile dep does. locked_dep && locked_dep.source && dep.source && locked_dep.source.include?(dep.source) end def satisfies_locked_spec?(dep) @locked_specs.any? {|s| s.satisfies?(dep) && (!dep.source || s.source.include?(dep.source)) } end # This list of dependencies is only used in #resolve, so it's OK to add # the metadata dependencies here def expanded_dependencies @expanded_dependencies ||= begin ruby_versions = concat_ruby_version_requirements(@ruby_version) if ruby_versions.empty? || !@ruby_version.exact? concat_ruby_version_requirements(RubyVersion.system) concat_ruby_version_requirements(locked_ruby_version_object) unless @unlock[:ruby] end metadata_dependencies = [ Dependency.new("ruby\0", ruby_versions), Dependency.new("rubygems\0", Gem::VERSION), ] expand_dependencies(dependencies + metadata_dependencies, @remote) end end def concat_ruby_version_requirements(ruby_version, ruby_versions = []) return ruby_versions unless ruby_version if ruby_version.patchlevel ruby_versions << ruby_version.to_gem_version_with_patchlevel else ruby_versions.concat(ruby_version.versions.map do |version| requirement = Gem::Requirement.new(version) if requirement.exact? "~> #{version}.0" else requirement end end) end end def expand_dependencies(dependencies, remote = false) deps = [] dependencies.each do |dep| dep = Dependency.new(dep, ">= 0") unless dep.respond_to?(:name) next if !remote && !dep.current_platform? platforms = dep.gem_platforms(@platforms) if platforms.empty? mapped_platforms = dep.platforms.map {|p| Dependency::PLATFORM_MAP[p] } Bundler.ui.warn \ "The dependency #{dep} will be unused by any of the platforms Bundler is installing for. " \ "Bundler is installing for #{@platforms.join ", "} but the dependency " \ "is only for #{mapped_platforms.join ", "}. " \ "To add those platforms to the bundle, " \ "run `bundle lock --add-platform #{mapped_platforms.join " "}`." end platforms.each do |p| deps << DepProxy.new(dep, p) if remote || p == generic_local_platform end end deps end def requested_dependencies groups = requested_groups groups.map!(&:to_sym) dependencies.reject {|d| !d.should_include? || (d.groups & groups).empty? } end def source_requirements # Load all specs from remote sources index # Record the specs available in each gem's source, so that those # specs will be available later when the resolver knows where to # look for that gemspec (or its dependencies) source_requirements = {} dependencies.each do |dep| next unless dep.source source_requirements[dep.name] = dep.source.specs end source_requirements end def pinned_spec_names(specs) names = [] specs.each do |s| # TODO: when two sources without blocks is an error, we can change # this check to !s.source.is_a?(Source::LocalRubygems). For now, # we need to ask every Rubygems for every gem name. if s.source.is_a?(Source::Git) || s.source.is_a?(Source::Path) names << s.name end end names.uniq! names end def requested_groups groups - Bundler.settings.without - @optional_groups + Bundler.settings.with end def lockfiles_equal?(current, proposed, preserve_unknown_sections) if preserve_unknown_sections sections_to_ignore = LockfileParser.sections_to_ignore(@locked_bundler_version) sections_to_ignore += LockfileParser.unknown_sections_in_lockfile(current) sections_to_ignore += LockfileParser::ENVIRONMENT_VERSION_SECTIONS pattern = /#{Regexp.union(sections_to_ignore)}\n(\s{2,}.*\n)+/ whitespace_cleanup = /\n{2,}/ current = current.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip proposed = proposed.gsub(pattern, "\n").gsub(whitespace_cleanup, "\n\n").strip end current == proposed end def extract_gem_info(error) # This method will extract the error message like "Could not find foo-1.2.3 in any of the sources" # to an array. The first element will be the gem name (e.g. foo), the second will be the version number. error.message.scan(/Could not find (\w+)-(\d+(?:\.\d+)+)/).flatten end def compute_requires dependencies.reduce({}) do |requires, dep| next requires unless dep.should_include? requires[dep.name] = Array(dep.autorequire || dep.name).map do |file| # Allow `require: true` as an alias for `require: <name>` file == true ? dep.name : file end requires end end def additional_base_requirements_for_resolve return [] unless @locked_gems && Bundler.feature_flag.only_update_to_newer_versions? @locked_gems.specs.reduce({}) do |requirements, locked_spec| dep = Gem::Dependency.new(locked_spec.name, ">= #{locked_spec.version}") requirements[locked_spec.name] = DepProxy.new(dep, locked_spec.platform) requirements end.values end end end
module CamperVan VERSION = "0.0.15" end Bump version to 0.0.16 module CamperVan VERSION = "0.0.16" end
require "capistrano-mailgun/version" require 'restclient' require 'erb' module Capistrano module Mailgun # Load the base configuration into the given Capistrano::Instance. # This is primarily used for testing and is executed automatically when requiring # the library in a Capistrano recipe. def self.load_into(config) config.load do Capistrano.plugin :mailgun, Capistrano::Mailgun set(:mailgun_subject) do [ "[Deployment]", fetch(:stage, '').to_s.capitalize, fetch(:application, '').capitalize, 'deploy completed'].join(' ').gsub(/\s+/, ' ') end set(:mailgun_api_key) { abort "Please set mailgun_api_key accordingly" } set(:mailgun_domain) { abort "Please set mailgun_domain accordingly" } set(:mailgun_from) { abort "Please set mailgun_from to your desired From field" } set(:mailgun_recipients) { abort "Please specify mailgun_recipients" } set(:mailgun_recipient_domain) { abort "Please set mailgun_recipient_domain accordingly" } # some internal variables that mailgun will use as the app runs set(:mailgun_deploy_servers) { find_servers_for_task( find_task('deploy:update_code') ) } # set these to nil to not use, or set to path to your custom template set :mailgun_text_template, :deploy_text set :mailgun_html_template, :deploy_html set :mailgun_include_servers, false set(:deployer_username) do if fetch(:scm, '').to_sym == :git `git config user.name`.chomp else `whoami`.chomp end end # default mailgun email tasks desc <<-DESC Send a mailgun deployment notification. This is here for convenience so you can force a notification to be sent from the commandline and also to simplify configuring after-deploy hooks and even after-mailgun-notify hooks. DESC task :mailgun_notify do mailgun.notify_of_deploy end end # config.load end # Simple wrapper for sending an email with a given template # Supports all options that the Mailgun API supports. In addition, it also accepts: # * +:text_template+ -- the path to the template for the text body. It will be processed and interpolated and set the +text+ field when doing the API call. # * +:html_template+ -- the path to the template for the html body. It will be processed and interpolated and set the +html+ field when doing the API call. # # If +mailgun_off+ is set, this function will do absolutely nothing. def send_email(options) return if exists?(:mailgun_off) options = process_send_email_options(options) RestClient.post build_mailgun_uri( mailgun_api_key, mailgun_domain ), options end # Sends the email via the Mailgun API using variables configured in Capistrano. # It depends on the following Capistrano vars in addition to the default: # * +mailgun_recipients+ # * +mailgun_from+ # * +mailgun_subject+ # Requires one or both of the following: # * +mailgun_text_template+ # * +mailgun_html_template+ # # See README for explanations of the above variables. def notify_of_deploy options = { :to => fetch(:mailgun_recipients), :from => fetch(:mailgun_from), :subject => fetch(:mailgun_subject) } options[:cc] = fetch(:mailgun_cc) if fetch(:mailgun_cc, nil) options[:bcc] = fetch(:mailgun_bcc) if fetch(:mailgun_bcc, nil) if fetch(:mailgun_text_template, nil).nil? && fetch(:mailgun_html_template, nil).nil? abort "You must specify one (or both) of mailgun_text_template and mailgun_html_template to use notify_of_deploy" end options[:text_template] = fetch(:mailgun_text_template, nil) options[:html_template] = fetch(:mailgun_html_template, nil) send_email options end # Given an array of +recipients+, it returns a comma-delimited, deduplicated string, suitable for populating the +to+, +cc+, and +bcc+ fields of a Mailgun API call. # Optionally, it will take a +default_domain+ which will automatically be appended to any unqualified recipients (eg: 'spike' => 'spike@example.com') def build_recipients(recipients, default_domain=nil) [*recipients].map do |r| if r.match /.+?@.+?$/ # the email contains an @ so it's fully-qualified. r else "#{ r }@#{ default_domain || fetch(:mailgun_recipient_domain) }" end end.uniq.sort.join(',') end # git log between +first_ref+ to +last_ref+ # memoizes the output so this function can be called multiple times without re-running # FIXME: memoization does not account for arguments # # returns an array of 2-element arrays in the form of # [ ref, log_text ] def log_output(first_ref, last_ref) return @log_output unless @log_output.nil? begin log_output = run_locally("git log --oneline #{ first_ref }..#{ last_ref }") @log_output = log_output = log_output.split("\n").map do |line| fields = line.split("\s", 2) [ fields[0], fields[1] ] end rescue [ [ 'n/a', 'Log output not available.' ] ] end end private def default_deploy_text_template_path default_template_path 'default.txt.erb' end def default_deploy_html_template_path default_template_path 'default.html.erb' end def default_template_path(name) File.join( File.dirname(__FILE__), 'templates', name) end def find_template(t) case t when :deploy_text then default_deploy_text_template_path when :deploy_html then default_deploy_html_template_path else abort "Unknown template symbol: #{ t }" if t.is_a?(Symbol) abort "Template not found: #{ t }" unless File.exists?(t) t end end # apply templates and all that jazz def process_send_email_options(options) text_template = options.delete(:text_template) html_template = options.delete(:html_template) options[:to] = build_recipients(options[:to]) unless options[:to].nil? options[:cc] = build_recipients(options[:cc]) unless options[:cc].nil? options[:bcc] = build_recipients(options[:bcc]) unless options[:bcc].nil? options[:text] = ERB.new( File.open( find_template(text_template) ).read ).result(self.binding) if text_template options[:html] = ERB.new( File.open( find_template(html_template) ).read ).result(self.binding) if html_template # clean up the text template a little if options[:text] options[:text].gsub! /^ +/, '' options[:text].gsub! /\n{3,}/, "\n\n" end options end # builds the Mailgun API URI from the given options. def build_mailgun_uri(mailgun_api_key, mailgun_domain) "https://api:#{ mailgun_api_key }@api.mailgun.net/v2/#{ mailgun_domain }/messages" end end end if Capistrano::Configuration.instance Capistrano::Mailgun.load_into(Capistrano::Configuration.instance) end use _cset when setting default cap vars require "capistrano-mailgun/version" require 'restclient' require 'erb' module Capistrano module Mailgun # Load the base configuration into the given Capistrano::Instance. # This is primarily used for testing and is executed automatically when requiring # the library in a Capistrano recipe. def self.load_into(config) config.load do Capistrano.plugin :mailgun, Capistrano::Mailgun def _cset(name, *args, &block) unless exists?(name) set(name, *args, &block) end end _cset(:mailgun_subject) do [ "[Deployment]", fetch(:stage, '').to_s.capitalize, fetch(:application, '').capitalize, 'deploy completed'].join(' ').gsub(/\s+/, ' ') end _cset(:mailgun_api_key) { abort "Please set mailgun_api_key accordingly" } _cset(:mailgun_domain) { abort "Please set mailgun_domain accordingly" } _cset(:mailgun_from) { abort "Please set mailgun_from to your desired From field" } _cset(:mailgun_recipients) { abort "Please specify mailgun_recipients" } _cset(:mailgun_recipient_domain) { abort "Please set mailgun_recipient_domain accordingly" } # some internal variables that mailgun will use as the app runs _cset(:mailgun_deploy_servers) { find_servers_for_task( find_task('deploy:update_code') ) } # set these to nil to not use, or set to path to your custom template _cset :mailgun_text_template, :deploy_text _cset :mailgun_html_template, :deploy_html _cset :mailgun_include_servers, false _cset(:deployer_username) do if fetch(:scm, '').to_sym == :git `git config user.name`.chomp else `whoami`.chomp end end # default mailgun email tasks desc <<-DESC Send a mailgun deployment notification. This is here for convenience so you can force a notification to be sent from the commandline and also to simplify configuring after-deploy hooks and even after-mailgun-notify hooks. DESC task :mailgun_notify do mailgun.notify_of_deploy end end # config.load end # Simple wrapper for sending an email with a given template # Supports all options that the Mailgun API supports. In addition, it also accepts: # * +:text_template+ -- the path to the template for the text body. It will be processed and interpolated and set the +text+ field when doing the API call. # * +:html_template+ -- the path to the template for the html body. It will be processed and interpolated and set the +html+ field when doing the API call. # # If +mailgun_off+ is set, this function will do absolutely nothing. def send_email(options) return if exists?(:mailgun_off) options = process_send_email_options(options) RestClient.post build_mailgun_uri( mailgun_api_key, mailgun_domain ), options end # Sends the email via the Mailgun API using variables configured in Capistrano. # It depends on the following Capistrano vars in addition to the default: # * +mailgun_recipients+ # * +mailgun_from+ # * +mailgun_subject+ # Requires one or both of the following: # * +mailgun_text_template+ # * +mailgun_html_template+ # # See README for explanations of the above variables. def notify_of_deploy options = { :to => fetch(:mailgun_recipients), :from => fetch(:mailgun_from), :subject => fetch(:mailgun_subject) } options[:cc] = fetch(:mailgun_cc) if fetch(:mailgun_cc, nil) options[:bcc] = fetch(:mailgun_bcc) if fetch(:mailgun_bcc, nil) if fetch(:mailgun_text_template, nil).nil? && fetch(:mailgun_html_template, nil).nil? abort "You must specify one (or both) of mailgun_text_template and mailgun_html_template to use notify_of_deploy" end options[:text_template] = fetch(:mailgun_text_template, nil) options[:html_template] = fetch(:mailgun_html_template, nil) send_email options end # Given an array of +recipients+, it returns a comma-delimited, deduplicated string, suitable for populating the +to+, +cc+, and +bcc+ fields of a Mailgun API call. # Optionally, it will take a +default_domain+ which will automatically be appended to any unqualified recipients (eg: 'spike' => 'spike@example.com') def build_recipients(recipients, default_domain=nil) [*recipients].map do |r| if r.match /.+?@.+?$/ # the email contains an @ so it's fully-qualified. r else "#{ r }@#{ default_domain || fetch(:mailgun_recipient_domain) }" end end.uniq.sort.join(',') end # git log between +first_ref+ to +last_ref+ # memoizes the output so this function can be called multiple times without re-running # FIXME: memoization does not account for arguments # # returns an array of 2-element arrays in the form of # [ ref, log_text ] def log_output(first_ref, last_ref) return @log_output unless @log_output.nil? begin log_output = run_locally("git log --oneline #{ first_ref }..#{ last_ref }") @log_output = log_output = log_output.split("\n").map do |line| fields = line.split("\s", 2) [ fields[0], fields[1] ] end rescue [ [ 'n/a', 'Log output not available.' ] ] end end private def default_deploy_text_template_path default_template_path 'default.txt.erb' end def default_deploy_html_template_path default_template_path 'default.html.erb' end def default_template_path(name) File.join( File.dirname(__FILE__), 'templates', name) end def find_template(t) case t when :deploy_text then default_deploy_text_template_path when :deploy_html then default_deploy_html_template_path else abort "Unknown template symbol: #{ t }" if t.is_a?(Symbol) abort "Template not found: #{ t }" unless File.exists?(t) t end end # apply templates and all that jazz def process_send_email_options(options) text_template = options.delete(:text_template) html_template = options.delete(:html_template) options[:to] = build_recipients(options[:to]) unless options[:to].nil? options[:cc] = build_recipients(options[:cc]) unless options[:cc].nil? options[:bcc] = build_recipients(options[:bcc]) unless options[:bcc].nil? options[:text] = ERB.new( File.open( find_template(text_template) ).read ).result(self.binding) if text_template options[:html] = ERB.new( File.open( find_template(html_template) ).read ).result(self.binding) if html_template # clean up the text template a little if options[:text] options[:text].gsub! /^ +/, '' options[:text].gsub! /\n{3,}/, "\n\n" end options end # builds the Mailgun API URI from the given options. def build_mailgun_uri(mailgun_api_key, mailgun_domain) "https://api:#{ mailgun_api_key }@api.mailgun.net/v2/#{ mailgun_domain }/messages" end end end if Capistrano::Configuration.instance Capistrano::Mailgun.load_into(Capistrano::Configuration.instance) end
class <%= controller_class_name %>Controller < ApplicationController def index @<%= table_name %> = <%= class_name %>.find(:all) end def show @<%= file_name %> = <%= class_name %>.find(params[:id]) end def new @<%= file_name %> = <%= class_name %>.new end def edit @<%= file_name %> = <%= class_name %>.find(params[:id]) end def create @<%= file_name %> = <%= class_name %>.new(params[:<%= file_name %>]) if @<%= file_name %>.save flash[:notice] = '<%= class_name %> was successfully created.' redirect_to(@<%= file_name %>) else render :action => "new" end end def update @<%= file_name %> = <%= class_name %>.find(params[:id]) if @<%= file_name %>.update_attributes(params[:<%= file_name %>]) flash[:notice] = '<%= class_name %> was successfully updated.' redirect_to(@<%= file_name %>) else render :action => "edit" end end def destroy @<%= file_name %> = <%= class_name %>.find(params[:id]) @<%= file_name %>.destroy redirect_to(<%= table_name %>_url) end end Moved duplicate controller finds into a filter class <%= controller_class_name %>Controller < ApplicationController before_filter :find_<%= table_name %>, :except => [:index, :new, :create] def index @<%= table_name %> = <%= class_name %>.find(:all) end def show end def new @<%= file_name %> = <%= class_name %>.new end def edit end def create if @<%= file_name %>.save flash[:notice] = '<%= class_name %> was successfully created.' redirect_to(@<%= file_name %>) else render :action => "new" end end def update if @<%= file_name %>.update_attributes(params[:<%= file_name %>]) flash[:notice] = '<%= class_name %> was successfully updated.' redirect_to(@<%= file_name %>) else render :action => "edit" end end def destroy @<%= file_name %>.destroy redirect_to(<%= table_name %>_url) end private def find_<%= table_name %> @<%= file_name %> = <%= class_name %>.find(params[:id]) end end
module Cardpay module Connection LIVE_URL = "https://api.globalgatewaye4.firstdata.com/transaction/v12" TEST_URL = "https://api.demo.globalgatewaye4.firstdata.com/transaction/v12" def post(txn_data) txn_data[:gateway_id] = @gateway_id txn_data[:password] = @password txn_data = JSON.generate(txn_data) authenticate(txn_data) uri = @test ? TEST_URL : LIVE_URL uri = URI.parse(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_timeout = 2 http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.request_uri) request.set_content_type 'application/json' request.add_field 'Accept', 'application/json' request.add_field 'X-GGe4-Content-SHA1', @content_digest request.add_field 'X-GGe4-Date', gge4_time request.add_field 'Authorization', 'GGE4_API ' + @key_id + ':' + @auth_hash response = http.request(request, txn_data) begin response = JSON.parse(response.body) rescue JSON::ParserError response.body end end end end Fixed bug in connection module Cardpay module Connection LIVE_URL = "https://api.globalgatewaye4.firstdata.com/transaction/v12" TEST_URL = "https://api.demo.globalgatewaye4.firstdata.com/transaction/v12" def post(txn_data) txn_data[:gateway_id] = @gateway_id txn_data[:password] = @password txn_data = JSON.generate(txn_data) authenticate(txn_data) uri = @test ? TEST_URL : LIVE_URL uri = URI.parse(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_timeout = 2 http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(uri.request_uri) request.set_content_type 'application/json' request.add_field 'Accept', 'application/json' request.add_field 'X-GGe4-Content-SHA1', @content_digest request.add_field 'X-GGe4-Date', @gge4_time request.add_field 'Authorization', 'GGE4_API ' + @key_id + ':' + @auth_hash response = http.request(request, txn_data) begin response = JSON.parse(response.body) rescue JSON::ParserError response.body end end end end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{cardboardfish} s.version = "0.0.6" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["David Rice"] s.date = %q{2010-12-02} s.description = %q{Ruby API for Cardboardfish SMS http://www.cardboardfish.com} s.email = %q{me@davidjrice.co.uk} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "cardboardfish.gemspec", "lib/cardboardfish.rb", "spec/cardboardfish_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/davidjrice/cardboardfish} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{Ruby API for Cardboardfish SMS http://www.cardboardfish.com} s.test_files = [ "spec/cardboardfish_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end Regenerated gemspec for version 0.0.7 # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{cardboardfish} s.version = "0.0.7" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["David Rice"] s.date = %q{2010-12-02} s.description = %q{Ruby API for Cardboardfish SMS http://www.cardboardfish.com} s.email = %q{me@davidjrice.co.uk} s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".gitignore", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "cardboardfish.gemspec", "lib/cardboardfish.rb", "spec/cardboardfish_spec.rb", "spec/spec.opts", "spec/spec_helper.rb" ] s.homepage = %q{http://github.com/davidjrice/cardboardfish} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.6} s.summary = %q{Ruby API for Cardboardfish SMS http://www.cardboardfish.com} s.test_files = [ "spec/cardboardfish_spec.rb", "spec/spec_helper.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) else s.add_dependency(%q<rspec>, [">= 1.2.9"]) end else s.add_dependency(%q<rspec>, [">= 1.2.9"]) end end
# LDAP extension for User ::User # # * Find or create user from omniauth.auth data # require 'chaltron/ldap/person' module Chaltron module LDAP class User class << self attr_reader :auth def find_or_create(auth, create) @auth = auth if uid.blank? || email.blank? || username.blank? raise_error('Account must provide a dn, uid and email address') end user = find_by_uid_and_provider entry = Chaltron::LDAP::Person.find_by_uid(username) if user.nil? and create # create user roles = Chaltron.default_roles roles = entry.ldap_groups.map do |e| Chaltron.ldap_role_mappings[e.dn] end.compact if !Chaltron.ldap_role_mappings.blank? user = entry.create_user(roles) end update_ldap_attributes(user, entry) unless user.nil? user end private def update_ldap_attributes(user, entry) user.update!( email: entry.email, department: entry.department ) end def find_by_uid_and_provider # LDAP distinguished name is case-insensitive user = ::User.where('provider = ? and lower(extern_uid) = ?', provider, uid.downcase).last if user.nil? # Look for user with same emails # # Possible cases: # * When user already has account and need to link their LDAP account. # * LDAP uid changed for user with same email and we need to update their uid # user = ::User.find_by(email: email) user.update!(extern_uid: uid, provider: provider) unless user.nil? end user end def uid auth.info.uid || auth.uid end def email auth.info.email.downcase unless auth.info.email.nil? end def name auth.info.name.to_s.force_encoding('utf-8') end def username auth.info.nickname.to_s.force_encoding('utf-8') end def provider 'ldap' end def raise_error(message) fail OmniAuth::Error, '(LDAP) ' + message end end end end end update roles from ldap at each login # LDAP extension for User ::User # # * Find or create user from omniauth.auth data # require 'chaltron/ldap/person' module Chaltron module LDAP class User class << self attr_reader :auth def find_or_create(auth, create) @auth = auth if uid.blank? || email.blank? || username.blank? raise_error('Account must provide a dn, uid and email address') end user = find_by_uid_and_provider entry = Chaltron::LDAP::Person.find_by_uid(username) if user.nil? && create # create user with default roles roles = Chaltron.default_roles user = entry.create_user(roles) end roles = if !Chaltron.ldap_role_mappings.blank? entry.ldap_groups.map do |e| Chaltron.ldap_role_mappings[e.dn] end.compact else Chaltron.default_roles end # update roles, email and department update_attributes_from_ldap(user, entry, roles) unless user.nil? user end private def update_attributes_from_ldap(user, entry, roles) user.email = entry.email user.department = entry.department user.roles = roles user.save end def find_by_uid_and_provider # LDAP distinguished name is case-insensitive user = ::User.where('provider = ? and lower(extern_uid) = ?', provider, uid.downcase).last if user.nil? # Look for user with same emails # # Possible cases: # * When user already has account and need to link their LDAP account. # * LDAP uid changed for user with same email and we need to update their uid # user = ::User.find_by(email: email) user.update!(extern_uid: uid, provider: provider) unless user.nil? end user end def uid auth.info.uid || auth.uid end def email auth.info.email.downcase unless auth.info.email.nil? end def name auth.info.name.to_s.force_encoding('utf-8') end def username auth.info.nickname.to_s.force_encoding('utf-8') end def provider 'ldap' end def raise_error(message) fail OmniAuth::Error, '(LDAP) ' + message end end end end end