CombinedText stringlengths 4 3.42M |
|---|
class ResponseObject
def initialize()
end
end
def returnJSON(text, option)
json = JSON.parse(
'{
"version": "1.0",
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + text + '"
},
"shouldEndSession": " ' + to_sb(option) + ' "
}
}')
end
def returnIntroduction()
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "true"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "Welcome to Jedi Archives. What would you like to know?"
},
"shouldEndSession": "false"
}
}')
end
def storeSessionAttribute(input, result, newSession, endSession)
puts "---RESULT---"
puts result
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "' + to_sb(newSession) + '"
},
"sessionAttributes": {
"input": "' + input + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Character",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "' + to_sb(endSession) + '"
}
}')
end
def storeSessionAttributeForMovie(input, result, newSession, endSession)
json = JSON.parse(
'{
"version": "1.0",
"sessionAttributes": {
"film": "' + input + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Movie",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "false"
}
}')
end
def storeSessionAttributeForPlanet(planet, result, newSession, endSession)
json = JSON.parse(
'{
"version": "1.0",
"sessionAttributes": {
"planet": "' + planet + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Planet",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "false"
}
}')
end
def storeSessionAttributeForStarship(starship, result, newSession, endSession)
json = JSON.parse(
'{
"version": "1.0",
"sessionAttributes": {
"starship": "' + starship + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Starship",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "false"
}
}')
end
def startSessionAttribute(result, newSession, endSession)
puts "---RESULT---"
puts result
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "' + to_sb(newSession) + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"shouldEndSession": "' + to_sb(endSession) + '"
}
}')
end
def returnError(input, result, newSession, endSession)
puts "---RESULT---"
puts result
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "' + to_sb(newSession) + '"
},
"sessionAttributes": {
"input": "' + input + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"shouldEndSession": "' + to_sb(endSession) + '"
}')
end
def to_sb(option)
if option == true
return 'true'
else
return 'false'
end
end
Fix session
class ResponseObject
def initialize()
end
end
def returnJSON(text, option)
json = JSON.parse(
'{
"version": "1.0",
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + text + '"
},
"shouldEndSession": " ' + to_sb(option) + ' "
}
}')
end
def returnIntroduction()
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "true"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "Welcome to Jedi Archives. What would you like to know?"
},
"shouldEndSession": "false"
}
}')
end
def storeSessionAttribute(input, result, newSession, endSession)
puts "---RESULT---"
puts result
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "' + to_sb(newSession) + '"
},
"sessionAttributes": {
"input": "' + input + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Character",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "' + to_sb(endSession) + '"
}
}')
end
def storeSessionAttributeForMovie(input, result, newSession, endSession)
json = JSON.parse(
'{
"version": "1.0",
"sessionAttributes": {
"film": "' + input + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Movie",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "false"
}
}')
end
def storeSessionAttributeForPlanet(planet, result, newSession, endSession)
json = JSON.parse(
'{
"version": "1.0",
"sessionAttributes": {
"planet": "' + planet + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Planet",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "false"
}
}')
end
def storeSessionAttributeForStarship(starship, result, newSession, endSession)
json = JSON.parse(
'{
"version": "1.0",
"sessionAttributes": {
"starship": "' + starship + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"card": {
"type": "Simple",
"title": "Star Wars Starship",
"content": "' + result + '"
},
"reprompt": {
"outputSpeech": {
"type": "PlainText",
"text": "Would you like to know anything else?"
}
},
"shouldEndSession": "false"
}
}')
end
def startSessionAttribute(result, newSession, endSession)
puts "---RESULT---"
puts result
json = JSON.parse(
'{
"version": "1.0",
"session": {
"new": "' + to_sb(newSession) + '"
},
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"shouldEndSession": "' + to_sb(endSession) + '"
}
}')
end
def returnError(result, newSession, endSession)
puts "---RESULT---"
puts result
json = JSON.parse(
'{
"version": "1.0",
"response": {
"outputSpeech": {
"type": "PlainText",
"text": "' + result + '"
},
"shouldEndSession": "' + to_sb(endSession) + '"
}')
end
def to_sb(option)
if option == true
return 'true'
else
return 'false'
end
end |
module ReportCard
class Grader
attr_reader :project, :config, :scores, :old_scores
def initialize(project, config)
@project = project
@config = config
end
def grade
return unless ready?
STDERR.puts ">> Building metrics for #{project.name}"
configure
generate
wrapup if success?
end
def wrapup
score
notify if score_changed?
end
def ready?
dir = Integrity::ProjectBuilder.new(project).send(:export_directory)
if File.exist?(dir)
Dir.chdir dir
else
STDERR.puts ">> Skipping, directory does not exist: #{dir}"
end
end
def configure
ENV['CC_BUILD_ARTIFACTS'] = self.output_path
MetricFu::Configuration.run do |config|
config.reset
config.data_directory = self.archive_path
config.template_class = AwesomeTemplate
config.metrics = config.graphs = [:flog, :flay, :rcov, :reek, :roodi]
config.rcov = { :test_files => ['test/**/*_test.rb', 'spec/**/*_spec.rb'],
:rcov_opts => ["--sort coverage",
"--no-html",
"--text-coverage",
"--no-color",
"--profile",
"--rails",
"--include test",
"--exclude /gems/,/usr/local/lib/site_ruby/1.8/,spec"]}
end
MetricFu.report.instance_variable_set(:@report_hash, {})
end
def generate
begin
MetricFu.metrics.each { |metric| MetricFu.report.add(metric) }
MetricFu.graphs.each { |graph| MetricFu.graph.add(graph) }
MetricFu.report.save_output(MetricFu.report.to_yaml, MetricFu.base_directory, 'report.yml')
MetricFu.report.save_output(MetricFu.report.to_yaml, MetricFu.data_directory, "#{Time.now.strftime("%Y%m%d")}.yml")
MetricFu.report.save_templatized_report
MetricFu.graph.generate
@success = true
rescue Exception => e
STDERR.puts "Problem generating the reports: #{e}"
@success = false
end
end
def score
report = YAML.load_file(File.join(MetricFu.base_directory, 'report.yml'))
@scores = {
:flay => report[:flay][:total_score].to_s,
:flog_total => report[:flog][:total].to_s,
:flog_average => report[:flog][:average].to_s,
:reek => report[:reek][:matches].inject(0) { |sum, match| sum + match[:code_smells].size }.to_s,
:roodi => report[:roodi][:problems].size.to_s
}
@scores[:rcov] = report[:rcov][:global_percent_run].to_s if report.has_key?(:rcov)
if File.exist?(self.scores_path)
@old_scores = YAML.load_file(self.scores_path)
else
FileUtils.mkdir_p(File.dirname(self.scores_path))
@old_scores = {}
end
File.open(self.scores_path, "w") do |f|
f.write @scores.to_yaml
end
end
def notify
return if @config['skip_notification']
STDERR.puts ">> Scores differ, notifying Campfire"
begin
config = @project.notifiers.first.config
room ||= begin
options = {}
options[:ssl] = true
campfire = Tinder::Campfire.new(config["account"], options)
campfire.login(config["user"], config["pass"])
campfire.find_room_by_name(config["room"])
end
room.speak self.message
room.paste self.scoreboard
room.leave
rescue Exception => e
STDERR.puts ">> Problem connecting to Campfire: #{e}"
end
end
def message
path = @project.public ? "" : "private"
"New metrics generated for #{@project.name}: #{File.join(@config['url'], path, @project.name, 'output')}"
end
def scoreboard
scores = ""
columns = "%15s%20s%20s\n"
scores << sprintf(columns, "", "This Run", "Last Run")
scores << sprintf(columns, "Flay Score", @scores[:flay], @old_scores[:flay])
scores << sprintf(columns, "Flog Total/Avg", "#{@scores[:flog_total]}/#{@scores[:flog_average]}", "#{@old_scores[:flog_total]}/#{@old_scores[:flog_average]}")
scores << sprintf(columns, "Reek Smells", @scores[:reek], @old_scores[:reek])
scores << sprintf(columns, "Roodi Problems", @scores[:roodi], @old_scores[:roodi])
end
def score_changed?
self.scores != self.old_scores
end
def success?
@success
end
def site_path(*dirs)
site_dir = @config['site'] || File.join(File.dirname(__FILE__), "..", "..")
File.expand_path(File.join(site_dir, *dirs))
end
def output_path
path = [@project.name]
path.unshift("private") unless @project.public
site_path(*path)
end
def scores_path
site_path("scores", @project.name)
end
def archive_path
site_path("archive", @project.name)
end
end
end
Moving the build message into #ready? so #grade is clean
module ReportCard
class Grader
attr_reader :project, :config, :scores, :old_scores
def initialize(project, config)
@project = project
@config = config
end
def grade
return unless ready?
configure
generate
wrapup if success?
end
def wrapup
score
notify if score_changed?
end
def ready?
dir = Integrity::ProjectBuilder.new(project).send(:export_directory)
if File.exist?(dir)
STDERR.puts ">> Building metrics for #{project.name}"
Dir.chdir dir
else
STDERR.puts ">> Skipping, directory does not exist: #{dir}"
end
end
def configure
ENV['CC_BUILD_ARTIFACTS'] = self.output_path
MetricFu::Configuration.run do |config|
config.reset
config.data_directory = self.archive_path
config.template_class = AwesomeTemplate
config.metrics = config.graphs = [:flog, :flay, :rcov, :reek, :roodi]
config.rcov = { :test_files => ['test/**/*_test.rb', 'spec/**/*_spec.rb'],
:rcov_opts => ["--sort coverage",
"--no-html",
"--text-coverage",
"--no-color",
"--profile",
"--rails",
"--include test",
"--exclude /gems/,/usr/local/lib/site_ruby/1.8/,spec"]}
end
MetricFu.report.instance_variable_set(:@report_hash, {})
end
def generate
begin
MetricFu.metrics.each { |metric| MetricFu.report.add(metric) }
MetricFu.graphs.each { |graph| MetricFu.graph.add(graph) }
MetricFu.report.save_output(MetricFu.report.to_yaml, MetricFu.base_directory, 'report.yml')
MetricFu.report.save_output(MetricFu.report.to_yaml, MetricFu.data_directory, "#{Time.now.strftime("%Y%m%d")}.yml")
MetricFu.report.save_templatized_report
MetricFu.graph.generate
@success = true
rescue Exception => e
STDERR.puts "Problem generating the reports: #{e}"
@success = false
end
end
def score
report = YAML.load_file(File.join(MetricFu.base_directory, 'report.yml'))
@scores = {
:flay => report[:flay][:total_score].to_s,
:flog_total => report[:flog][:total].to_s,
:flog_average => report[:flog][:average].to_s,
:reek => report[:reek][:matches].inject(0) { |sum, match| sum + match[:code_smells].size }.to_s,
:roodi => report[:roodi][:problems].size.to_s
}
@scores[:rcov] = report[:rcov][:global_percent_run].to_s if report.has_key?(:rcov)
if File.exist?(self.scores_path)
@old_scores = YAML.load_file(self.scores_path)
else
FileUtils.mkdir_p(File.dirname(self.scores_path))
@old_scores = {}
end
File.open(self.scores_path, "w") do |f|
f.write @scores.to_yaml
end
end
def notify
return if @config['skip_notification']
STDERR.puts ">> Scores differ, notifying Campfire"
begin
config = @project.notifiers.first.config
room ||= begin
options = {}
options[:ssl] = true
campfire = Tinder::Campfire.new(config["account"], options)
campfire.login(config["user"], config["pass"])
campfire.find_room_by_name(config["room"])
end
room.speak self.message
room.paste self.scoreboard
room.leave
rescue Exception => e
STDERR.puts ">> Problem connecting to Campfire: #{e}"
end
end
def message
path = @project.public ? "" : "private"
"New metrics generated for #{@project.name}: #{File.join(@config['url'], path, @project.name, 'output')}"
end
def scoreboard
scores = ""
columns = "%15s%20s%20s\n"
scores << sprintf(columns, "", "This Run", "Last Run")
scores << sprintf(columns, "Flay Score", @scores[:flay], @old_scores[:flay])
scores << sprintf(columns, "Flog Total/Avg", "#{@scores[:flog_total]}/#{@scores[:flog_average]}", "#{@old_scores[:flog_total]}/#{@old_scores[:flog_average]}")
scores << sprintf(columns, "Reek Smells", @scores[:reek], @old_scores[:reek])
scores << sprintf(columns, "Roodi Problems", @scores[:roodi], @old_scores[:roodi])
end
def score_changed?
self.scores != self.old_scores
end
def success?
@success
end
def site_path(*dirs)
site_dir = @config['site'] || File.join(File.dirname(__FILE__), "..", "..")
File.expand_path(File.join(site_dir, *dirs))
end
def output_path
path = [@project.name]
path.unshift("private") unless @project.public
site_path(*path)
end
def scores_path
site_path("scores", @project.name)
end
def archive_path
site_path("archive", @project.name)
end
end
end
|
require "active_support/core_ext/array"
require "active_support/core_ext/string"
require "builder"
require "representative/base"
require "representative/empty"
module Representative
# Easily generate XML while traversing an object-graph.
#
class Xml < Base
# Create an XML-generating Representative. The first argument should be an instance of
# Builder::XmlMarkup (or something that implements it's interface). The second argument
# if any, is the initial #subject of representation.
#
def initialize(xml_builder, subject = nil, options = {})
@xml = xml_builder
super(subject, options)
yield self if block_given?
end
# Generate an element.
#
# With two arguments, it generates an element with the specified text content.
#
# r.element :size, 42
# # => <size>42</size>
#
# More commonly, though, the second argument is omitted, in which case the
# element content is assumed to be the named property of the current #subject.
#
# r.representing my_shoe do
# r.element :size
# end
# # => <size>9</size>
#
# If a block is attached, nested elements can be generated. The element "value"
# (whether explicitly provided, or derived from the current subject) becomes the
# subject during evaluation of the block.
#
# r.element :book, book do
# r.title
# r.author
# end
# # => <book><title>Whatever</title><author>Whoever</author></book>
#
# Providing a final Hash argument specifies element attributes.
#
# r.element :size, :type => "integer"
# # => <size type="integer">9</size>
#
def element(name, *args, &block)
metadata = @inspector.get_metadata(current_subject, name)
attributes = args.extract_options!.merge(metadata)
subject_of_element = if args.empty?
lambda do |subject|
@inspector.get_value(current_subject, name)
end
else
args.shift
end
raise ArgumentError, "too many arguments" unless args.empty?
representing(subject_of_element) do
content_string = content_block = nil
unless current_subject.nil?
if block
unless block == Representative::EMPTY
content_block = Proc.new do
block.call(current_subject)
end
end
else
content_string = current_subject.to_s
end
end
resolved_attributes = resolve_attributes(attributes)
tag_args = [content_string, resolved_attributes].compact
@xml.tag!(name.to_s.dasherize, *tag_args, &content_block)
end
end
# Generate a list of elements from Enumerable data.
#
# r.list_of :books, my_books do
# r.element :title
# end
# # => <books type="array">
# # <book><title>Sailing for old dogs</title></book>
# # <book><title>On the horizon</title></book>
# # <book><title>The Little Blue Book of VHS Programming</title></book>
# # </books>
#
# Like #element, the value can be explicit, but is more commonly extracted
# by name from the current #subject.
#
def list_of(name, *args, &block)
options = args.extract_options!
list_subject = args.empty? ? name : args.shift
raise ArgumentError, "too many arguments" unless args.empty?
list_attributes = options[:list_attributes] || {}
item_name = options[:item_name] || name.to_s.singularize
item_attributes = options[:item_attributes] || {}
items = resolve_value(list_subject)
element(name, items, list_attributes.merge(:type => lambda{"array"})) do
items.each do |item|
element(item_name, item, item_attributes, &block)
end
end
end
# Return a magic value that, when passed to #element as a block, forces
# generation of an empty element.
#
# r.element(:link, :rel => "me", :href => "http://dogbiscuit.org", &r.empty)
# # => <link rel="parent" href="http://dogbiscuit.org"/>
#
def empty
Representative::EMPTY
end
# Generate a comment
def comment(text)
@xml.comment!(text)
end
end
end
Tweak to work with activesupport-3.0.0.
require "active_support/core_ext"
require "active_support/core_ext"
require "builder"
require "representative/base"
require "representative/empty"
module Representative
# Easily generate XML while traversing an object-graph.
#
class Xml < Base
# Create an XML-generating Representative. The first argument should be an instance of
# Builder::XmlMarkup (or something that implements it's interface). The second argument
# if any, is the initial #subject of representation.
#
def initialize(xml_builder, subject = nil, options = {})
@xml = xml_builder
super(subject, options)
yield self if block_given?
end
# Generate an element.
#
# With two arguments, it generates an element with the specified text content.
#
# r.element :size, 42
# # => <size>42</size>
#
# More commonly, though, the second argument is omitted, in which case the
# element content is assumed to be the named property of the current #subject.
#
# r.representing my_shoe do
# r.element :size
# end
# # => <size>9</size>
#
# If a block is attached, nested elements can be generated. The element "value"
# (whether explicitly provided, or derived from the current subject) becomes the
# subject during evaluation of the block.
#
# r.element :book, book do
# r.title
# r.author
# end
# # => <book><title>Whatever</title><author>Whoever</author></book>
#
# Providing a final Hash argument specifies element attributes.
#
# r.element :size, :type => "integer"
# # => <size type="integer">9</size>
#
def element(name, *args, &block)
metadata = @inspector.get_metadata(current_subject, name)
attributes = args.extract_options!.merge(metadata)
subject_of_element = if args.empty?
lambda do |subject|
@inspector.get_value(current_subject, name)
end
else
args.shift
end
raise ArgumentError, "too many arguments" unless args.empty?
representing(subject_of_element) do
content_string = content_block = nil
unless current_subject.nil?
if block
unless block == Representative::EMPTY
content_block = Proc.new do
block.call(current_subject)
end
end
else
content_string = current_subject.to_s
end
end
resolved_attributes = resolve_attributes(attributes)
tag_args = [content_string, resolved_attributes].compact
@xml.tag!(name.to_s.dasherize, *tag_args, &content_block)
end
end
# Generate a list of elements from Enumerable data.
#
# r.list_of :books, my_books do
# r.element :title
# end
# # => <books type="array">
# # <book><title>Sailing for old dogs</title></book>
# # <book><title>On the horizon</title></book>
# # <book><title>The Little Blue Book of VHS Programming</title></book>
# # </books>
#
# Like #element, the value can be explicit, but is more commonly extracted
# by name from the current #subject.
#
def list_of(name, *args, &block)
options = args.extract_options!
list_subject = args.empty? ? name : args.shift
raise ArgumentError, "too many arguments" unless args.empty?
list_attributes = options[:list_attributes] || {}
item_name = options[:item_name] || name.to_s.singularize
item_attributes = options[:item_attributes] || {}
items = resolve_value(list_subject)
element(name, items, list_attributes.merge(:type => lambda{"array"})) do
items.each do |item|
element(item_name, item, item_attributes, &block)
end
end
end
# Return a magic value that, when passed to #element as a block, forces
# generation of an empty element.
#
# r.element(:link, :rel => "me", :href => "http://dogbiscuit.org", &r.empty)
# # => <link rel="parent" href="http://dogbiscuit.org"/>
#
def empty
Representative::EMPTY
end
# Generate a comment
def comment(text)
@xml.comment!(text)
end
end
end
|
module ResourceFull
class ResourceNotFound < Exception; end
class Base < ActionController::Base
unless Rails.version == "2.3.2"
session :off, :if => lambda { |request| request.format.xml? || request.format.json? }
end
def model_name; self.class.model_name; end
def model_class; self.class.model_class; end
class << self
# Returns the list of all resources handled by ResourceFull.
def all_resources
ActionController::Routing.possible_controllers.map do |possible_controller|
controller_for(possible_controller)
end.select do |controller_class|
controller_class.ancestors.include?(self)
end
end
# Returns the controller for the given resource.
def controller_for(resource)
return resource if resource.is_a?(Class) && resource.ancestors.include?(ActionController::Base)
"#{resource.to_s.underscore}_controller".classify.constantize
rescue NameError
raise ResourceFull::ResourceNotFound, "not found: #{resource}"
end
private
def inherited(controller)
super(controller)
controller.send :extend, ClassMethods
controller.send :include,
ResourceFull::Retrieve,
ResourceFull::Query,
ResourceFull::Dispatch,
ResourceFull::Render
controller.send :alias_retrieval_methods!
end
end
end
module ClassMethods
attr_accessor_with_default :paginatable, true
attr_accessor_with_default :resource_identifier, :id
# Returns true if this resource is paginatable, which is to say, it recognizes and honors
# the :limit and :offset parameters if present in a query. True by default.
def paginatable?; paginatable; end
# The name of the model exposed by this resource. Derived from the name of the controller
# by default. See +exposes+.
def model_name
@model_class ? @model_class.simple_name.underscore : self.controller_name.singularize
end
# Indicates that this resource is identified by a database column other than the default
# :id.
# TODO This should honor the model's primary key column but needn't be bound by it.
# TODO Refactor this.
# TODO Improve the documentation.
def identified_by(*args, &block)
opts = args.extract_options!
column = args.first
if !block.nil?
self.resource_identifier = block
elsif !column.nil?
if !opts.empty? && ( opts.has_key?(:if) || opts.has_key?(:unless) )
if opts[:unless] == :id_numeric
opts[:unless] = lambda { |id| id =~ /^[0-9]+$/ }
end
# Negate the condition to generate an :if from an :unless.
condition = opts[:if] || lambda { |id| not opts[:unless].call(id) }
self.resource_identifier = lambda do |id|
if condition.call(id)
column
else :id end
end
else
self.resource_identifier = column
end
else
raise ArgumentError, "identified_by expects either a block or a column name and some options"
end
end
# The class of the model exposed by this resource. Derived from the model name. See +exposes+.
def model_class
@model_class ||= model_name.camelize.constantize
end
# Indicates that the CRUD methods should be called on the given class. Accepts
# either a class object or the name of the desired model.
def exposes(model_class)
remove_retrieval_methods!
@model_class = model_class.to_s.singularize.camelize.constantize
alias_retrieval_methods!
end
# Renders the resource as XML.
def to_xml(opts={})
{ :name => self.controller_name,
:parameters => self.queryable_params,
:identifier => self.xml_identifier
}.to_xml(opts.merge(:root => "resource"))
end
protected
def xml_identifier
(self.resource_identifier.is_a?(Proc) ? self.resource_identifier.call(nil) : self.resource_identifier).to_s
end
private
def alias_retrieval_methods!
define_method("new_#{model_name}") { new_model_object }
define_method("find_#{model_name}") { find_model_object }
define_method("create_#{model_name}") { create_model_object }
define_method("update_#{model_name}") { update_model_object }
define_method("destroy_#{model_name}") { destroy_model_object }
define_method("find_all_#{model_name.pluralize}") { find_all_model_objects }
define_method("count_all_#{model_name.pluralize}") { count_all_model_objects }
end
def remove_retrieval_methods!
remove_method "new_#{model_name}"
remove_method "find_#{model_name}"
remove_method "create_#{model_name}"
remove_method "update_#{model_name}"
remove_method "destroy_#{model_name}"
remove_method "find_all_#{model_name.pluralize}"
remove_method "count_all_#{model_name.pluralize}"
end
end
end
Vijay: Added checks to safely try and remove the stubbed methods - so that it does not fail if the methods have not yet been defined.
module ResourceFull
class ResourceNotFound < Exception; end
class Base < ActionController::Base
unless Rails.version == "2.3.2"
session :off, :if => lambda { |request| request.format.xml? || request.format.json? }
end
def model_name; self.class.model_name; end
def model_class; self.class.model_class; end
class << self
# Returns the list of all resources handled by ResourceFull.
def all_resources
ActionController::Routing.possible_controllers.map do |possible_controller|
controller_for(possible_controller)
end.select do |controller_class|
controller_class.ancestors.include?(self)
end
end
# Returns the controller for the given resource.
def controller_for(resource)
return resource if resource.is_a?(Class) && resource.ancestors.include?(ActionController::Base)
"#{resource.to_s.underscore}_controller".classify.constantize
rescue NameError
raise ResourceFull::ResourceNotFound, "not found: #{resource}"
end
private
def inherited(controller)
super(controller)
controller.send :extend, ClassMethods
controller.send :include,
ResourceFull::Retrieve,
ResourceFull::Query,
ResourceFull::Dispatch,
ResourceFull::Render
controller.send :alias_retrieval_methods!
end
end
end
module ClassMethods
attr_accessor_with_default :paginatable, true
attr_accessor_with_default :resource_identifier, :id
# Returns true if this resource is paginatable, which is to say, it recognizes and honors
# the :limit and :offset parameters if present in a query. True by default.
def paginatable?; paginatable; end
# The name of the model exposed by this resource. Derived from the name of the controller
# by default. See +exposes+.
def model_name
@model_class ? @model_class.simple_name.underscore : self.controller_name.singularize
end
# Indicates that this resource is identified by a database column other than the default
# :id.
# TODO This should honor the model's primary key column but needn't be bound by it.
# TODO Refactor this.
# TODO Improve the documentation.
def identified_by(*args, &block)
opts = args.extract_options!
column = args.first
if !block.nil?
self.resource_identifier = block
elsif !column.nil?
if !opts.empty? && ( opts.has_key?(:if) || opts.has_key?(:unless) )
if opts[:unless] == :id_numeric
opts[:unless] = lambda { |id| id =~ /^[0-9]+$/ }
end
# Negate the condition to generate an :if from an :unless.
condition = opts[:if] || lambda { |id| not opts[:unless].call(id) }
self.resource_identifier = lambda do |id|
if condition.call(id)
column
else :id end
end
else
self.resource_identifier = column
end
else
raise ArgumentError, "identified_by expects either a block or a column name and some options"
end
end
# The class of the model exposed by this resource. Derived from the model name. See +exposes+.
def model_class
@model_class ||= model_name.camelize.constantize
end
# Indicates that the CRUD methods should be called on the given class. Accepts
# either a class object or the name of the desired model.
def exposes(model_class)
remove_retrieval_methods!
@model_class = model_class.to_s.singularize.camelize.constantize
alias_retrieval_methods!
end
# Renders the resource as XML.
def to_xml(opts={})
{ :name => self.controller_name,
:parameters => self.queryable_params,
:identifier => self.xml_identifier
}.to_xml(opts.merge(:root => "resource"))
end
protected
def xml_identifier
(self.resource_identifier.is_a?(Proc) ? self.resource_identifier.call(nil) : self.resource_identifier).to_s
end
private
def alias_retrieval_methods!
define_method("new_#{model_name}") { new_model_object }
define_method("find_#{model_name}") { find_model_object }
define_method("create_#{model_name}") { create_model_object }
define_method("update_#{model_name}") { update_model_object }
define_method("destroy_#{model_name}") { destroy_model_object }
define_method("find_all_#{model_name.pluralize}") { find_all_model_objects }
define_method("count_all_#{model_name.pluralize}") { count_all_model_objects }
end
def remove_retrieval_methods!
remove_method "new_#{model_name}" if method_defined? "new_#{model_name}"
remove_method "find_#{model_name}" if method_defined? "find_#{model_name}"
remove_method "create_#{model_name}" if method_defined? "create_#{model_name}"
remove_method "update_#{model_name}" if method_defined? "update_#{model_name}"
remove_method "destroy_#{model_name}" if method_defined? "destroy_#{model_name}"
remove_method "find_all_#{model_name.pluralize}" if method_defined? "find_all_#{model_name.pluralize}"
remove_method "count_all_#{model_name.pluralize}" if method_defined? "count_all_#{model_name.pluralize}"
end
end
end
|
# encoding: utf-8
#
# Copyright (c) 2002-2007 Minero Aoki
# 2008-2014 Minero Aoki, Kenshi Muto, Masayoshi Takahashi,
# KADO Masanori
#
# This program is free software.
# You can distribute or modify this program under the terms of
# the GNU LGPL, Lesser General Public License version 2.1.
#
require 'review/builder'
require 'review/htmlutils'
require 'review/htmllayout'
require 'review/textutils'
require 'review/sec_counter'
module ReVIEW
class HTMLBuilder < Builder
include TextUtils
include HTMLUtils
[:ref].each {|e| Compiler.definline(e) }
Compiler.defblock(:memo, 0..1)
Compiler.defblock(:tip, 0..1)
Compiler.defblock(:info, 0..1)
Compiler.defblock(:planning, 0..1)
Compiler.defblock(:best, 0..1)
Compiler.defblock(:important, 0..1)
Compiler.defblock(:security, 0..1)
Compiler.defblock(:caution, 0..1)
Compiler.defblock(:notice, 0..1)
Compiler.defblock(:point, 0..1)
Compiler.defblock(:shoot, 0..1)
def pre_paragraph
'<p>'
end
def post_paragraph
'</p>'
end
def extname
".#{ReVIEW.book.param["htmlext"]}"
end
def builder_init(no_error = false)
@no_error = no_error
@column = 0
@noindent = nil
@ol_num = nil
end
private :builder_init
def builder_init_file
@warns = []
@errors = []
@chapter.book.image_types = %w( .png .jpg .jpeg .gif .svg )
@sec_counter = SecCounter.new(5, @chapter)
end
private :builder_init_file
def result
layout_file = File.join(@book.basedir, "layouts", "layout.erb")
if File.exist?(layout_file)
title = convert_outencoding(strip_html(compile_inline(@chapter.title)), ReVIEW.book.param["outencoding"])
messages() +
HTMLLayout.new(@output.string, title, layout_file).result
else
# default XHTML header/footer
header = <<EOT
<?xml version="1.0" encoding="#{ReVIEW.book.param["outencoding"] || :UTF-8}"?>
EOT
if ReVIEW.book.param["htmlversion"].to_i == 5
header += <<EOT
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:#{xmlns_ops_prefix}="http://www.idpf.org/2007/ops" xml:lang="#{ReVIEW.book.param["language"]}">
<head>
<meta charset="#{ReVIEW.book.param["outencoding"] || :UTF-8}" />
EOT
else
header += <<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ops="http://www.idpf.org/2007/ops" xml:lang="#{ReVIEW.book.param["language"]}">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=#{ReVIEW.book.param["outencoding"] || :UTF-8}" />
<meta http-equiv="Content-Style-Type" content="text/css" />
EOT
end
unless ReVIEW.book.param["stylesheet"].nil?
ReVIEW.book.param["stylesheet"].each do |style|
header += <<EOT
<link rel="stylesheet" type="text/css" href="#{style}" />
EOT
end
end
header += <<EOT
<meta name="generator" content="Re:VIEW" />
<title>#{convert_outencoding(strip_html(compile_inline(@chapter.title)), ReVIEW.book.param["outencoding"])}</title>
</head>
<body>
EOT
footer = <<EOT
</body>
</html>
EOT
header + messages() + convert_outencoding(@output.string, ReVIEW.book.param["outencoding"]) + footer
end
end
def xmlns_ops_prefix
if ReVIEW.book.param["epubversion"].to_i == 3
"epub"
else
"ops"
end
end
def warn(msg)
if @no_error
@warns.push [@location.filename, @location.lineno, msg]
puts "----WARNING: #{escape_html(msg)}----"
else
$stderr.puts "#{@location}: warning: #{msg}"
end
end
def error(msg)
if @no_error
@errors.push [@location.filename, @location.lineno, msg]
puts "----ERROR: #{escape_html(msg)}----"
else
$stderr.puts "#{@location}: error: #{msg}"
end
end
def messages
error_messages() + warning_messages()
end
def error_messages
return '' if @errors.empty?
"<h2>Syntax Errors</h2>\n" +
"<ul>\n" +
@errors.map {|file, line, msg|
"<li>#{escape_html(file)}:#{line}: #{escape_html(msg.to_s)}</li>\n"
}.join('') +
"</ul>\n"
end
def warning_messages
return '' if @warns.empty?
"<h2>Warnings</h2>\n" +
"<ul>\n" +
@warns.map {|file, line, msg|
"<li>#{escape_html(file)}:#{line}: #{escape_html(msg)}</li>\n"
}.join('') +
"</ul>\n"
end
def headline_prefix(level)
@sec_counter.inc(level)
anchor = @sec_counter.anchor(level)
prefix = @sec_counter.prefix(level, ReVIEW.book.param["secnolevel"])
[prefix, anchor]
end
private :headline_prefix
def headline(level, label, caption)
prefix, anchor = headline_prefix(level)
puts '' if level > 1
a_id = ""
unless anchor.nil?
a_id = %Q[<a id="h#{anchor}"></a>]
end
if caption.empty?
puts a_id unless label.nil?
else
if label.nil?
puts %Q[<h#{level}>#{a_id}#{prefix}#{compile_inline(caption)}</h#{level}>]
else
puts %Q[<h#{level} id="#{label}">#{a_id}#{prefix}#{compile_inline(caption)}</h#{level}>]
end
end
end
def nonum_begin(level, label, caption)
puts '' if level > 1
unless caption.empty?
if label.nil?
puts %Q[<h#{level}>#{compile_inline(caption)}</h#{level}>]
else
puts %Q[<h#{level} id="#{label}">#{compile_inline(caption)}</h#{level}>]
end
end
end
def nonum_end(level)
end
def column_begin(level, label, caption)
puts %Q[<div class="column">]
@column += 1
puts '' if level > 1
a_id = %Q[<a id="column-#{@column}"></a>]
if caption.empty?
puts a_id unless label.nil?
else
if label.nil?
puts %Q[<h#{level}>#{a_id}#{compile_inline(caption)}</h#{level}>]
else
puts %Q[<h#{level} id="#{label}">#{a_id}#{compile_inline(caption)}</h#{level}>]
end
end
# headline(level, label, caption)
end
def column_end(level)
puts '</div>'
end
def xcolumn_begin(level, label, caption)
puts %Q[<div class="xcolumn">]
headline(level, label, caption)
end
def xcolumn_end(level)
puts '</div>'
end
def ref_begin(level, label, caption)
print %Q[<div class="reference">]
headline(level, label, caption)
end
def ref_end(level)
puts '</div>'
end
def sup_begin(level, label, caption)
print %Q[<div class="supplement">]
headline(level, label, caption)
end
def sup_end(level)
puts '</div>'
end
def tsize(str)
# null
end
def captionblock(type, lines, caption)
puts %Q[<div class="#{type}">]
unless caption.nil?
puts %Q[<p class="caption">#{compile_inline(caption)}</p>]
end
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts blocked_lines.join("\n")
else
lines.each {|l| puts "<p>#{l}</p>" }
end
puts '</div>'
end
def memo(lines, caption = nil)
captionblock("memo", lines, caption)
end
def tip(lines, caption = nil)
captionblock("tip", lines, caption)
end
def info(lines, caption = nil)
captionblock("info", lines, caption)
end
def planning(lines, caption = nil)
captionblock("planning", lines, caption)
end
def best(lines, caption = nil)
captionblock("best", lines, caption)
end
def important(lines, caption = nil)
captionblock("important", lines, caption)
end
def security(lines, caption = nil)
captionblock("security", lines, caption)
end
def caution(lines, caption = nil)
captionblock("caution", lines, caption)
end
def notice(lines, caption = nil)
captionblock("notice", lines, caption)
end
def point(lines, caption = nil)
captionblock("point", lines, caption)
end
def shoot(lines, caption = nil)
captionblock("shoot", lines, caption)
end
def box(lines, caption = nil)
puts %Q[<div class="syntax">]
puts %Q[<p class="caption">#{compile_inline(caption)}</p>] unless caption.nil?
print %Q[<pre class="syntax">]
lines.each {|line| puts detab(line) }
puts '</pre>'
puts '</div>'
end
def note(lines, caption = nil)
captionblock("note", lines, caption)
end
def ul_begin
puts '<ul>'
end
def ul_item(lines)
puts "<li>#{lines.join}</li>"
end
def ul_item_begin(lines)
print "<li>#{lines.join}"
end
def ul_item_end
puts "</li>"
end
def ul_end
puts '</ul>'
end
def ol_begin
if @ol_num
puts "<ol start=\"#{@ol_num}\">" ## it's OK in HTML5, but not OK in XHTML1.1
@ol_num = nil
else
puts '<ol>'
end
end
def ol_item(lines, num)
puts "<li>#{lines.join}</li>"
end
def ol_end
puts '</ol>'
end
def dl_begin
puts '<dl>'
end
def dt(line)
puts "<dt>#{line}</dt>"
end
def dd(lines)
puts "<dd>#{lines.join}</dd>"
end
def dl_end
puts '</dl>'
end
def paragraph(lines)
if @noindent.nil?
puts "<p>#{lines.join}</p>"
else
puts %Q[<p class="noindent">#{lines.join}</p>]
@noindent = nil
end
end
def parasep()
puts '<br />'
end
def read(lines)
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts %Q[<div class="lead">\n#{blocked_lines.join("\n")}\n</div>]
else
puts %Q[<p class="lead">\n#{lines.join("\n")}\n</p>]
end
end
alias :lead read
def list(lines, id, caption)
puts %Q[<div class="caption-code">]
begin
list_header id, caption
rescue KeyError
error "no such list: #{id}"
end
list_body id, lines
puts '</div>'
end
def list_header(id, caption)
if get_chap.nil?
puts %Q[<p class="caption">#{I18n.t("list")}#{I18n.t("format_number_header_without_chapter", [@chapter.list(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
else
puts %Q[<p class="caption">#{I18n.t("list")}#{I18n.t("format_number_header", [get_chap, @chapter.list(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
end
end
def list_body(id, lines)
id ||= ''
print %Q[<pre class="list">]
body = lines.inject(''){|i, j| i + detab(j) + "\n"}
lexer = File.extname(id).gsub(/\./, '')
puts highlight(:body => body, :lexer => lexer, :format => 'html')
puts '</pre>'
end
def source(lines, caption = nil)
puts %Q[<div class="source-code">]
source_header caption
source_body caption, lines
puts '</div>'
end
def source_header(caption)
if caption.present?
puts %Q[<p class="caption">#{compile_inline(caption)}</p>]
end
end
def source_body(id, lines)
id ||= ''
print %Q[<pre class="source">]
body = lines.inject(''){|i, j| i + detab(j) + "\n"}
lexer = File.extname(id).gsub(/\./, '')
puts highlight(:body => body, :lexer => lexer, :format => 'html')
puts '</pre>'
end
def listnum(lines, id, caption)
puts %Q[<div class="code">]
begin
list_header id, caption
rescue KeyError
error "no such list: #{id}"
end
listnum_body lines
puts '</div>'
end
def listnum_body(lines)
print %Q[<pre class="list">]
lines.each_with_index do |line, i|
puts detab((i+1).to_s.rjust(2) + ": " + line)
end
puts '</pre>'
end
def emlist(lines, caption = nil)
puts %Q[<div class="emlist-code">]
puts %Q(<p class="caption">#{caption}</p>) unless caption.nil?
print %Q[<pre class="emlist">]
lines.each do |line|
puts detab(line)
end
puts '</pre>'
puts '</div>'
end
def emlistnum(lines, caption = nil)
puts %Q[<div class="emlistnum-code">]
puts %Q(<p class="caption">#{caption}</p>) unless caption.nil?
print %Q[<pre class="emlist">]
lines.each_with_index do |line, i|
puts detab((i+1).to_s.rjust(2) + ": " + line)
end
puts '</pre>'
puts '</div>'
end
def cmd(lines, caption = nil)
puts %Q[<div class="cmd-code">]
puts %Q(<p class="caption">#{caption}</p>) unless caption.nil?
print %Q[<pre class="cmd">]
lines.each do |line|
puts detab(line)
end
puts '</pre>'
puts '</div>'
end
def quotedlist(lines, css_class)
print %Q[<blockquote><pre class="#{css_class}">]
lines.each do |line|
puts detab(line)
end
puts '</pre></blockquote>'
end
private :quotedlist
def quote(lines)
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts "<blockquote>#{blocked_lines.join("\n")}</blockquote>"
else
puts "<blockquote><pre>#{lines.join("\n")}</pre></blockquote>"
end
end
def doorquote(lines, ref)
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts %Q[<blockquote style="text-align:right;">]
puts "#{blocked_lines.join("\n")}"
puts %Q[<p>#{ref}より</p>]
puts %Q[</blockquote>]
else
puts <<-QUOTE
<blockquote style="text-align:right;">
<pre>#{lines.join("\n")}
#{ref}より</pre>
</blockquote>
QUOTE
end
end
def talk(lines)
puts %Q[<div class="talk">]
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts "#{blocked_lines.join("\n")}"
else
print '<pre>'
puts "#{lines.join("\n")}"
puts '</pre>'
end
puts '</div>'
end
def texequation(lines)
puts %Q[<div class="equation">]
if ReVIEW.book.param["mathml"]
p = MathML::LaTeX::Parser.new(:symbol=>MathML::Symbol::CharacterReference)
puts p.parse(unescape_html(lines.join("\n")), true)
else
print '<pre>'
puts "#{lines.join("\n")}"
puts '</pre>'
end
puts '</div>'
end
def handle_metric(str)
if str =~ /\Ascale=([\d.]+)\Z/
return "width=\"#{($1.to_f * 100).round}%\""
else
k, v = str.split('=', 2)
return %Q|#{k}=\"#{v.sub(/\A["']/, '').sub(/["']\Z/, '')}\"|
end
end
def result_metric(array)
" #{array.join(' ')}"
end
def image_image(id, caption, metric)
metrics = parse_metric("html", metric)
puts %Q[<div class="image">]
puts %Q[<img src="#{@chapter.image(id).path.sub(/\A\.\//, "")}" alt="#{escape_html(compile_inline(caption))}"#{metrics} />]
image_header id, caption
puts %Q[</div>]
end
def image_dummy(id, caption, lines)
puts %Q[<div class="image">]
puts %Q[<pre class="dummyimage">]
lines.each do |line|
puts detab(line)
end
puts %Q[</pre>]
image_header id, caption
puts %Q[</div>]
end
def image_header(id, caption)
puts %Q[<p class="caption">]
if get_chap.nil?
puts %Q[#{I18n.t("image")}#{I18n.t("format_number_header_without_chapter", [@chapter.image(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}]
else
puts %Q[#{I18n.t("image")}#{I18n.t("format_number_header", [get_chap, @chapter.image(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}]
end
puts %Q[</p>]
end
def table(lines, id = nil, caption = nil)
rows = []
sepidx = nil
lines.each_with_index do |line, idx|
if /\A[\=\-]{12}/ =~ line
# just ignore
#error "too many table separator" if sepidx
sepidx ||= idx
next
end
rows.push line.strip.split(/\t+/).map {|s| s.sub(/\A\./, '') }
end
rows = adjust_n_cols(rows)
puts %Q[<div class="table">]
begin
table_header id, caption unless caption.nil?
rescue KeyError
error "no such table: #{id}"
end
table_begin rows.first.size
return if rows.empty?
if sepidx
sepidx.times do
tr rows.shift.map {|s| th(s) }
end
rows.each do |cols|
tr cols.map {|s| td(s) }
end
else
rows.each do |cols|
h, *cs = *cols
tr [th(h)] + cs.map {|s| td(s) }
end
end
table_end
puts %Q[</div>]
end
def table_header(id, caption)
if get_chap.nil?
puts %Q[<p class="caption">#{I18n.t("table")}#{I18n.t("format_number_header_without_chapter", [@chapter.table(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
else
puts %Q[<p class="caption">#{I18n.t("table")}#{I18n.t("format_number_header", [get_chap, @chapter.table(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
end
end
def table_begin(ncols)
puts '<table>'
end
def tr(rows)
puts "<tr>#{rows.join}</tr>"
end
def th(str)
"<th>#{str}</th>"
end
def td(str)
"<td>#{str}</td>"
end
def table_end
puts '</table>'
end
def comment(lines, comment = nil)
lines ||= []
lines.unshift comment unless comment.blank?
if ReVIEW.book.param["draft"]
str = lines.map{|line| escape_html(line) }.join("<br />")
puts %Q(<div class="draft-comment">#{str}</div>)
else
str = lines.join("\n")
puts %Q(<!-- #{escape_html(str)} -->)
end
end
def footnote(id, str)
if ReVIEW.book.param["epubversion"].to_i == 3
puts %Q(<div class="footnote" epub:type="footnote" id="fn-#{id}"><p class="footnote">[*#{@chapter.footnote(id).number}] #{compile_inline(str)}</p></div>)
else
puts %Q(<div class="footnote"><p class="footnote">[<a id="fn-#{id}">*#{@chapter.footnote(id).number}</a>] #{compile_inline(str)}</p></div>)
end
end
def indepimage(id, caption="", metric=nil)
metrics = parse_metric("html", metric)
caption = "" if caption.nil?
puts %Q[<div class="image">]
begin
puts %Q[<img src="#{@chapter.image(id).path.sub(/\A\.\//, "")}" alt="#{escape_html(compile_inline(caption))}"#{metrics} />]
rescue
puts %Q[<pre>missing image: #{id}</pre>]
end
unless caption.empty?
puts %Q[<p class="caption">]
puts %Q[#{I18n.t("numberless_image")}#{I18n.t("caption_prefix")}#{compile_inline(caption)}]
puts %Q[</p>]
end
puts %Q[</div>]
end
alias :numberlessimage indepimage
def hr
puts "<hr />"
end
def label(id)
puts %Q(<a id="#{id}"></a>)
end
def linebreak
puts "<br />"
end
def pagebreak
puts %Q(<br class="pagebreak" />)
end
def bpo(lines)
puts "<bpo>"
lines.each do |line|
puts detab(line)
end
puts "</bpo>"
end
def noindent
@noindent = true
end
def inline_labelref(idref)
%Q[<a target='#{escape_html(idref)}'>「●● #{escape_html(idref)}」</a>]
end
alias inline_ref inline_labelref
def inline_chapref(id)
title = super
if ReVIEW.book.param["chapterlink"]
%Q(<a href="./#{id}.html">#{title}</a>)
else
title
end
rescue KeyError
error "unknown chapter: #{id}"
nofunc_text("[UnknownChapter:#{id}]")
end
def inline_chap(id)
if ReVIEW.book.param["chapterlink"]
%Q(<a href="./#{id}.html">#{@chapter.env.chapter_index.number(id)}</a>)
else
@chapter.env.chapter_index.number(id)
end
rescue KeyError
error "unknown chapter: #{id}"
nofunc_text("[UnknownChapter:#{id}]")
end
def inline_title(id)
if ReVIEW.book.param["chapterlink"]
%Q(<a href="./#{id}.html">#{compile_inline(@chapter.env.chapter_index.title(id))}</a>)
else
@chapter.env.chapter_index.title(id)
end
rescue KeyError
error "unknown chapter: #{id}"
nofunc_text("[UnknownChapter:#{id}]")
end
def inline_fn(id)
if ReVIEW.book.param["epubversion"].to_i == 3
%Q(<a href="#fn-#{id}" class="noteref" epub:type="noteref">*#{@chapter.footnote(id).number}</a>)
else
%Q(<a href="#fn-#{id}" class="noteref">*#{@chapter.footnote(id).number}</a>)
end
end
def compile_ruby(base, ruby)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q[<ruby>#{escape_html(base)}<rp>#{I18n.t("ruby_prefix")}</rp><rt>#{escape_html(ruby)}</rt><rp>#{I18n.t("ruby_postfix")}</rp></ruby>]
else
%Q[<ruby><rb>#{escape_html(base)}</rb><rp>#{I18n.t("ruby_prefix")}</rp><rt>#{ruby}</rt><rp>#{I18n.t("ruby_postfix")}</rp></ruby>]
end
end
def compile_kw(word, alt)
%Q[<b class="kw">] +
if alt
then escape_html(word + " (#{alt.strip})")
else escape_html(word)
end +
"</b><!-- IDX:#{escape_html(word)} -->"
end
def inline_i(str)
%Q(<i>#{escape_html(str)}</i>)
end
def inline_b(str)
%Q(<b>#{escape_html(str)}</b>)
end
def inline_ami(str)
%Q(<span class="ami">#{escape_html(str)}</span>)
end
def inline_bou(str)
%Q(<span class="bou">#{escape_html(str)}</span>)
end
def inline_tti(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="tt"><i>#{escape_html(str)}</i></code>)
else
%Q(<tt><i>#{escape_html(str)}</i></tt>)
end
end
def inline_ttb(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="tt"><b>#{escape_html(str)}</b></code>)
else
%Q(<tt><b>#{escape_html(str)}</b></tt>)
end
end
def inline_dtp(str)
"<?dtp #{str} ?>"
end
def inline_code(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="inline-code tt">#{escape_html(str)}</code>)
else
%Q(<tt class="inline-code">#{escape_html(str)}</tt>)
end
end
def inline_idx(str)
%Q(#{escape_html(str)}<!-- IDX:#{escape_html(str)} -->)
end
def inline_hidx(str)
%Q(<!-- IDX:#{escape_html(str)} -->)
end
def inline_br(str)
%Q(<br />)
end
def inline_m(str)
if ReVIEW.book.param["mathml"]
p = MathML::LaTeX::Parser.new(:symbol=>MathML::Symbol::CharacterReference)
%Q[<span class="equation">#{p.parse(str, nil)}</span>]
else
%Q[<span class="equation">#{escape_html(str)}</span>]
end
end
def text(str)
str
end
def bibpaper(lines, id, caption)
puts %Q[<div class="bibpaper">]
bibpaper_header id, caption
unless lines.empty?
bibpaper_bibpaper id, caption, lines
end
puts "</div>"
end
def bibpaper_header(id, caption)
print %Q(<a id="bib-#{id}">)
print "[#{@chapter.bibpaper(id).number}]"
print %Q(</a>)
puts " #{compile_inline(caption)}"
end
def bibpaper_bibpaper(id, caption, lines)
print split_paragraph(lines).join("")
end
def inline_bib(id)
%Q(<a href=".#{@book.bib_file.gsub(/re\Z/, "html")}#bib-#{id}">[#{@chapter.bibpaper(id).number}]</a>)
end
def inline_hd_chap(chap, id)
n = chap.headline_index.number(id)
if chap.number and ReVIEW.book.param["secnolevel"] >= n.split('.').size
str = "「#{n} #{compile_inline(chap.headline(id).caption)}」"
else
str = "「#{compile_inline(chap.headline(id).caption)}」"
end
if ReVIEW.book.param["chapterlink"]
anchor = "h"+n.gsub(/\./, "-")
%Q(<a href="#{chap.id}.html\##{anchor}">#{str}</a>)
else
str
end
end
def inline_column(id)
if ReVIEW.book.param["chapterlink"]
%Q(<a href="\##{id}" class="columnref">#{@chapter.column(id).caption}</a>)
else
@chapter.column(id).caption
end
rescue KeyError
error "unknown column: #{id}"
nofunc_text("[UnknownColumn:#{id}]")
end
def inline_list(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
"#{I18n.t("list")}#{I18n.t("format_number_without_header", [chapter.list(id).number])}"
else
"#{I18n.t("list")}#{I18n.t("format_number", [get_chap(chapter), chapter.list(id).number])}"
end
rescue KeyError
error "unknown list: #{id}"
nofunc_text("[UnknownList:#{id}]")
end
def inline_table(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
"#{I18n.t("table")}#{I18n.t("format_number_without_chapter", [chapter.table(id).number])}"
else
"#{I18n.t("table")}#{I18n.t("format_number", [get_chap(chapter), chapter.table(id).number])}"
end
rescue KeyError
error "unknown table: #{id}"
nofunc_text("[UnknownTable:#{id}]")
end
def inline_img(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
"#{I18n.t("image")}#{I18n.t("format_number_without_chapter", [chapter.image(id).number])}"
else
"#{I18n.t("image")}#{I18n.t("format_number", [get_chap(chapter), chapter.image(id).number])}"
end
rescue KeyError
error "unknown image: #{id}"
nofunc_text("[UnknownImage:#{id}]")
end
def inline_asis(str, tag)
%Q(<#{tag}>#{escape_html(str)}</#{tag}>)
end
def inline_abbr(str)
inline_asis(str, "abbr")
end
def inline_acronym(str)
inline_asis(str, "acronym")
end
def inline_cite(str)
inline_asis(str, "cite")
end
def inline_dfn(str)
inline_asis(str, "dfn")
end
def inline_em(str)
inline_asis(str, "em")
end
def inline_kbd(str)
inline_asis(str, "kbd")
end
def inline_samp(str)
inline_asis(str, "samp")
end
def inline_strong(str)
inline_asis(str, "strong")
end
def inline_var(str)
inline_asis(str, "var")
end
def inline_big(str)
inline_asis(str, "big")
end
def inline_small(str)
inline_asis(str, "small")
end
def inline_sub(str)
inline_asis(str, "sub")
end
def inline_sup(str)
inline_asis(str, "sup")
end
def inline_tt(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="tt">#{escape_html(str)}</code>)
else
%Q(<tt>#{escape_html(str)}</tt>)
end
end
def inline_del(str)
inline_asis(str, "del")
end
def inline_ins(str)
inline_asis(str, "ins")
end
def inline_u(str)
%Q(<u>#{escape_html(str)}</u>)
end
def inline_recipe(str)
%Q(<span class="recipe">「#{escape_html(str)}」</span>)
end
def inline_icon(id)
begin
%Q[<img src="#{@chapter.image(id).path.sub(/\A\.\//, "")}" alt="[#{id}]" />]
rescue
%Q[<pre>missing image: #{id}</pre>]
end
end
def inline_uchar(str)
%Q(&#x#{str};)
end
def inline_comment(str)
if ReVIEW.book.param["draft"]
%Q(<span class="draft-comment">#{escape_html(str)}</span>)
else
%Q(<!-- #{escape_html(str)} -->)
end
end
def inline_raw(str)
super(str)
end
def nofunc_text(str)
escape_html(str)
end
def compile_href(url, label)
%Q(<a href="#{escape_html(url)}" class="link">#{label.nil? ? escape_html(url) : escape_html(label)}</a>)
end
def flushright(lines)
if ReVIEW.book.param["deprecated-blocklines"].nil?
puts split_paragraph(lines).join("\n").gsub("<p>", "<p class=\"flushright\">")
else
puts %Q[<div style="text-align:right;">]
print %Q[<pre class="flushright">]
lines.each {|line| puts detab(line) }
puts '</pre>'
puts '</div>'
end
end
def centering(lines)
puts split_paragraph(lines).join("\n").gsub("<p>", "<p class=\"center\">")
end
def image_ext
"png"
end
def olnum(num)
@ol_num = num.to_i
end
end
end # module ReVIEW
fix column label
# encoding: utf-8
#
# Copyright (c) 2002-2007 Minero Aoki
# 2008-2014 Minero Aoki, Kenshi Muto, Masayoshi Takahashi,
# KADO Masanori
#
# This program is free software.
# You can distribute or modify this program under the terms of
# the GNU LGPL, Lesser General Public License version 2.1.
#
require 'review/builder'
require 'review/htmlutils'
require 'review/htmllayout'
require 'review/textutils'
require 'review/sec_counter'
module ReVIEW
class HTMLBuilder < Builder
include TextUtils
include HTMLUtils
[:ref].each {|e| Compiler.definline(e) }
Compiler.defblock(:memo, 0..1)
Compiler.defblock(:tip, 0..1)
Compiler.defblock(:info, 0..1)
Compiler.defblock(:planning, 0..1)
Compiler.defblock(:best, 0..1)
Compiler.defblock(:important, 0..1)
Compiler.defblock(:security, 0..1)
Compiler.defblock(:caution, 0..1)
Compiler.defblock(:notice, 0..1)
Compiler.defblock(:point, 0..1)
Compiler.defblock(:shoot, 0..1)
def pre_paragraph
'<p>'
end
def post_paragraph
'</p>'
end
def extname
".#{ReVIEW.book.param["htmlext"]}"
end
def builder_init(no_error = false)
@no_error = no_error
@column = 0
@noindent = nil
@ol_num = nil
end
private :builder_init
def builder_init_file
@warns = []
@errors = []
@chapter.book.image_types = %w( .png .jpg .jpeg .gif .svg )
@sec_counter = SecCounter.new(5, @chapter)
end
private :builder_init_file
def result
layout_file = File.join(@book.basedir, "layouts", "layout.erb")
if File.exist?(layout_file)
title = convert_outencoding(strip_html(compile_inline(@chapter.title)), ReVIEW.book.param["outencoding"])
messages() +
HTMLLayout.new(@output.string, title, layout_file).result
else
# default XHTML header/footer
header = <<EOT
<?xml version="1.0" encoding="#{ReVIEW.book.param["outencoding"] || :UTF-8}"?>
EOT
if ReVIEW.book.param["htmlversion"].to_i == 5
header += <<EOT
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:#{xmlns_ops_prefix}="http://www.idpf.org/2007/ops" xml:lang="#{ReVIEW.book.param["language"]}">
<head>
<meta charset="#{ReVIEW.book.param["outencoding"] || :UTF-8}" />
EOT
else
header += <<EOT
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ops="http://www.idpf.org/2007/ops" xml:lang="#{ReVIEW.book.param["language"]}">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=#{ReVIEW.book.param["outencoding"] || :UTF-8}" />
<meta http-equiv="Content-Style-Type" content="text/css" />
EOT
end
unless ReVIEW.book.param["stylesheet"].nil?
ReVIEW.book.param["stylesheet"].each do |style|
header += <<EOT
<link rel="stylesheet" type="text/css" href="#{style}" />
EOT
end
end
header += <<EOT
<meta name="generator" content="Re:VIEW" />
<title>#{convert_outencoding(strip_html(compile_inline(@chapter.title)), ReVIEW.book.param["outencoding"])}</title>
</head>
<body>
EOT
footer = <<EOT
</body>
</html>
EOT
header + messages() + convert_outencoding(@output.string, ReVIEW.book.param["outencoding"]) + footer
end
end
def xmlns_ops_prefix
if ReVIEW.book.param["epubversion"].to_i == 3
"epub"
else
"ops"
end
end
def warn(msg)
if @no_error
@warns.push [@location.filename, @location.lineno, msg]
puts "----WARNING: #{escape_html(msg)}----"
else
$stderr.puts "#{@location}: warning: #{msg}"
end
end
def error(msg)
if @no_error
@errors.push [@location.filename, @location.lineno, msg]
puts "----ERROR: #{escape_html(msg)}----"
else
$stderr.puts "#{@location}: error: #{msg}"
end
end
def messages
error_messages() + warning_messages()
end
def error_messages
return '' if @errors.empty?
"<h2>Syntax Errors</h2>\n" +
"<ul>\n" +
@errors.map {|file, line, msg|
"<li>#{escape_html(file)}:#{line}: #{escape_html(msg.to_s)}</li>\n"
}.join('') +
"</ul>\n"
end
def warning_messages
return '' if @warns.empty?
"<h2>Warnings</h2>\n" +
"<ul>\n" +
@warns.map {|file, line, msg|
"<li>#{escape_html(file)}:#{line}: #{escape_html(msg)}</li>\n"
}.join('') +
"</ul>\n"
end
def headline_prefix(level)
@sec_counter.inc(level)
anchor = @sec_counter.anchor(level)
prefix = @sec_counter.prefix(level, ReVIEW.book.param["secnolevel"])
[prefix, anchor]
end
private :headline_prefix
def headline(level, label, caption)
prefix, anchor = headline_prefix(level)
puts '' if level > 1
a_id = ""
unless anchor.nil?
a_id = %Q[<a id="h#{anchor}"></a>]
end
if caption.empty?
puts a_id unless label.nil?
else
if label.nil?
puts %Q[<h#{level}>#{a_id}#{prefix}#{compile_inline(caption)}</h#{level}>]
else
puts %Q[<h#{level} id="#{label}">#{a_id}#{prefix}#{compile_inline(caption)}</h#{level}>]
end
end
end
def nonum_begin(level, label, caption)
puts '' if level > 1
unless caption.empty?
if label.nil?
puts %Q[<h#{level}>#{compile_inline(caption)}</h#{level}>]
else
puts %Q[<h#{level} id="#{label}">#{compile_inline(caption)}</h#{level}>]
end
end
end
def nonum_end(level)
end
def column_begin(level, label, caption)
puts %Q[<div class="column">]
@column += 1
puts '' if level > 1
a_id = %Q[<a id="column-#{@column}"></a>]
if caption.empty?
puts a_id unless label.nil?
else
if label.nil?
puts %Q[<h#{level}>#{a_id}#{compile_inline(caption)}</h#{level}>]
else
puts %Q[<h#{level} id="#{label}">#{a_id}#{compile_inline(caption)}</h#{level}>]
end
end
# headline(level, label, caption)
end
def column_end(level)
puts '</div>'
end
def xcolumn_begin(level, label, caption)
puts %Q[<div class="xcolumn">]
headline(level, label, caption)
end
def xcolumn_end(level)
puts '</div>'
end
def ref_begin(level, label, caption)
print %Q[<div class="reference">]
headline(level, label, caption)
end
def ref_end(level)
puts '</div>'
end
def sup_begin(level, label, caption)
print %Q[<div class="supplement">]
headline(level, label, caption)
end
def sup_end(level)
puts '</div>'
end
def tsize(str)
# null
end
def captionblock(type, lines, caption)
puts %Q[<div class="#{type}">]
unless caption.nil?
puts %Q[<p class="caption">#{compile_inline(caption)}</p>]
end
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts blocked_lines.join("\n")
else
lines.each {|l| puts "<p>#{l}</p>" }
end
puts '</div>'
end
def memo(lines, caption = nil)
captionblock("memo", lines, caption)
end
def tip(lines, caption = nil)
captionblock("tip", lines, caption)
end
def info(lines, caption = nil)
captionblock("info", lines, caption)
end
def planning(lines, caption = nil)
captionblock("planning", lines, caption)
end
def best(lines, caption = nil)
captionblock("best", lines, caption)
end
def important(lines, caption = nil)
captionblock("important", lines, caption)
end
def security(lines, caption = nil)
captionblock("security", lines, caption)
end
def caution(lines, caption = nil)
captionblock("caution", lines, caption)
end
def notice(lines, caption = nil)
captionblock("notice", lines, caption)
end
def point(lines, caption = nil)
captionblock("point", lines, caption)
end
def shoot(lines, caption = nil)
captionblock("shoot", lines, caption)
end
def box(lines, caption = nil)
puts %Q[<div class="syntax">]
puts %Q[<p class="caption">#{compile_inline(caption)}</p>] unless caption.nil?
print %Q[<pre class="syntax">]
lines.each {|line| puts detab(line) }
puts '</pre>'
puts '</div>'
end
def note(lines, caption = nil)
captionblock("note", lines, caption)
end
def ul_begin
puts '<ul>'
end
def ul_item(lines)
puts "<li>#{lines.join}</li>"
end
def ul_item_begin(lines)
print "<li>#{lines.join}"
end
def ul_item_end
puts "</li>"
end
def ul_end
puts '</ul>'
end
def ol_begin
if @ol_num
puts "<ol start=\"#{@ol_num}\">" ## it's OK in HTML5, but not OK in XHTML1.1
@ol_num = nil
else
puts '<ol>'
end
end
def ol_item(lines, num)
puts "<li>#{lines.join}</li>"
end
def ol_end
puts '</ol>'
end
def dl_begin
puts '<dl>'
end
def dt(line)
puts "<dt>#{line}</dt>"
end
def dd(lines)
puts "<dd>#{lines.join}</dd>"
end
def dl_end
puts '</dl>'
end
def paragraph(lines)
if @noindent.nil?
puts "<p>#{lines.join}</p>"
else
puts %Q[<p class="noindent">#{lines.join}</p>]
@noindent = nil
end
end
def parasep()
puts '<br />'
end
def read(lines)
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts %Q[<div class="lead">\n#{blocked_lines.join("\n")}\n</div>]
else
puts %Q[<p class="lead">\n#{lines.join("\n")}\n</p>]
end
end
alias :lead read
def list(lines, id, caption)
puts %Q[<div class="caption-code">]
begin
list_header id, caption
rescue KeyError
error "no such list: #{id}"
end
list_body id, lines
puts '</div>'
end
def list_header(id, caption)
if get_chap.nil?
puts %Q[<p class="caption">#{I18n.t("list")}#{I18n.t("format_number_header_without_chapter", [@chapter.list(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
else
puts %Q[<p class="caption">#{I18n.t("list")}#{I18n.t("format_number_header", [get_chap, @chapter.list(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
end
end
def list_body(id, lines)
id ||= ''
print %Q[<pre class="list">]
body = lines.inject(''){|i, j| i + detab(j) + "\n"}
lexer = File.extname(id).gsub(/\./, '')
puts highlight(:body => body, :lexer => lexer, :format => 'html')
puts '</pre>'
end
def source(lines, caption = nil)
puts %Q[<div class="source-code">]
source_header caption
source_body caption, lines
puts '</div>'
end
def source_header(caption)
if caption.present?
puts %Q[<p class="caption">#{compile_inline(caption)}</p>]
end
end
def source_body(id, lines)
id ||= ''
print %Q[<pre class="source">]
body = lines.inject(''){|i, j| i + detab(j) + "\n"}
lexer = File.extname(id).gsub(/\./, '')
puts highlight(:body => body, :lexer => lexer, :format => 'html')
puts '</pre>'
end
def listnum(lines, id, caption)
puts %Q[<div class="code">]
begin
list_header id, caption
rescue KeyError
error "no such list: #{id}"
end
listnum_body lines
puts '</div>'
end
def listnum_body(lines)
print %Q[<pre class="list">]
lines.each_with_index do |line, i|
puts detab((i+1).to_s.rjust(2) + ": " + line)
end
puts '</pre>'
end
def emlist(lines, caption = nil)
puts %Q[<div class="emlist-code">]
puts %Q(<p class="caption">#{caption}</p>) unless caption.nil?
print %Q[<pre class="emlist">]
lines.each do |line|
puts detab(line)
end
puts '</pre>'
puts '</div>'
end
def emlistnum(lines, caption = nil)
puts %Q[<div class="emlistnum-code">]
puts %Q(<p class="caption">#{caption}</p>) unless caption.nil?
print %Q[<pre class="emlist">]
lines.each_with_index do |line, i|
puts detab((i+1).to_s.rjust(2) + ": " + line)
end
puts '</pre>'
puts '</div>'
end
def cmd(lines, caption = nil)
puts %Q[<div class="cmd-code">]
puts %Q(<p class="caption">#{caption}</p>) unless caption.nil?
print %Q[<pre class="cmd">]
lines.each do |line|
puts detab(line)
end
puts '</pre>'
puts '</div>'
end
def quotedlist(lines, css_class)
print %Q[<blockquote><pre class="#{css_class}">]
lines.each do |line|
puts detab(line)
end
puts '</pre></blockquote>'
end
private :quotedlist
def quote(lines)
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts "<blockquote>#{blocked_lines.join("\n")}</blockquote>"
else
puts "<blockquote><pre>#{lines.join("\n")}</pre></blockquote>"
end
end
def doorquote(lines, ref)
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts %Q[<blockquote style="text-align:right;">]
puts "#{blocked_lines.join("\n")}"
puts %Q[<p>#{ref}より</p>]
puts %Q[</blockquote>]
else
puts <<-QUOTE
<blockquote style="text-align:right;">
<pre>#{lines.join("\n")}
#{ref}より</pre>
</blockquote>
QUOTE
end
end
def talk(lines)
puts %Q[<div class="talk">]
if ReVIEW.book.param["deprecated-blocklines"].nil?
blocked_lines = split_paragraph(lines)
puts "#{blocked_lines.join("\n")}"
else
print '<pre>'
puts "#{lines.join("\n")}"
puts '</pre>'
end
puts '</div>'
end
def texequation(lines)
puts %Q[<div class="equation">]
if ReVIEW.book.param["mathml"]
p = MathML::LaTeX::Parser.new(:symbol=>MathML::Symbol::CharacterReference)
puts p.parse(unescape_html(lines.join("\n")), true)
else
print '<pre>'
puts "#{lines.join("\n")}"
puts '</pre>'
end
puts '</div>'
end
def handle_metric(str)
if str =~ /\Ascale=([\d.]+)\Z/
return "width=\"#{($1.to_f * 100).round}%\""
else
k, v = str.split('=', 2)
return %Q|#{k}=\"#{v.sub(/\A["']/, '').sub(/["']\Z/, '')}\"|
end
end
def result_metric(array)
" #{array.join(' ')}"
end
def image_image(id, caption, metric)
metrics = parse_metric("html", metric)
puts %Q[<div class="image">]
puts %Q[<img src="#{@chapter.image(id).path.sub(/\A\.\//, "")}" alt="#{escape_html(compile_inline(caption))}"#{metrics} />]
image_header id, caption
puts %Q[</div>]
end
def image_dummy(id, caption, lines)
puts %Q[<div class="image">]
puts %Q[<pre class="dummyimage">]
lines.each do |line|
puts detab(line)
end
puts %Q[</pre>]
image_header id, caption
puts %Q[</div>]
end
def image_header(id, caption)
puts %Q[<p class="caption">]
if get_chap.nil?
puts %Q[#{I18n.t("image")}#{I18n.t("format_number_header_without_chapter", [@chapter.image(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}]
else
puts %Q[#{I18n.t("image")}#{I18n.t("format_number_header", [get_chap, @chapter.image(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}]
end
puts %Q[</p>]
end
def table(lines, id = nil, caption = nil)
rows = []
sepidx = nil
lines.each_with_index do |line, idx|
if /\A[\=\-]{12}/ =~ line
# just ignore
#error "too many table separator" if sepidx
sepidx ||= idx
next
end
rows.push line.strip.split(/\t+/).map {|s| s.sub(/\A\./, '') }
end
rows = adjust_n_cols(rows)
puts %Q[<div class="table">]
begin
table_header id, caption unless caption.nil?
rescue KeyError
error "no such table: #{id}"
end
table_begin rows.first.size
return if rows.empty?
if sepidx
sepidx.times do
tr rows.shift.map {|s| th(s) }
end
rows.each do |cols|
tr cols.map {|s| td(s) }
end
else
rows.each do |cols|
h, *cs = *cols
tr [th(h)] + cs.map {|s| td(s) }
end
end
table_end
puts %Q[</div>]
end
def table_header(id, caption)
if get_chap.nil?
puts %Q[<p class="caption">#{I18n.t("table")}#{I18n.t("format_number_header_without_chapter", [@chapter.table(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
else
puts %Q[<p class="caption">#{I18n.t("table")}#{I18n.t("format_number_header", [get_chap, @chapter.table(id).number])}#{I18n.t("caption_prefix")}#{compile_inline(caption)}</p>]
end
end
def table_begin(ncols)
puts '<table>'
end
def tr(rows)
puts "<tr>#{rows.join}</tr>"
end
def th(str)
"<th>#{str}</th>"
end
def td(str)
"<td>#{str}</td>"
end
def table_end
puts '</table>'
end
def comment(lines, comment = nil)
lines ||= []
lines.unshift comment unless comment.blank?
if ReVIEW.book.param["draft"]
str = lines.map{|line| escape_html(line) }.join("<br />")
puts %Q(<div class="draft-comment">#{str}</div>)
else
str = lines.join("\n")
puts %Q(<!-- #{escape_html(str)} -->)
end
end
def footnote(id, str)
if ReVIEW.book.param["epubversion"].to_i == 3
puts %Q(<div class="footnote" epub:type="footnote" id="fn-#{id}"><p class="footnote">[*#{@chapter.footnote(id).number}] #{compile_inline(str)}</p></div>)
else
puts %Q(<div class="footnote"><p class="footnote">[<a id="fn-#{id}">*#{@chapter.footnote(id).number}</a>] #{compile_inline(str)}</p></div>)
end
end
def indepimage(id, caption="", metric=nil)
metrics = parse_metric("html", metric)
caption = "" if caption.nil?
puts %Q[<div class="image">]
begin
puts %Q[<img src="#{@chapter.image(id).path.sub(/\A\.\//, "")}" alt="#{escape_html(compile_inline(caption))}"#{metrics} />]
rescue
puts %Q[<pre>missing image: #{id}</pre>]
end
unless caption.empty?
puts %Q[<p class="caption">]
puts %Q[#{I18n.t("numberless_image")}#{I18n.t("caption_prefix")}#{compile_inline(caption)}]
puts %Q[</p>]
end
puts %Q[</div>]
end
alias :numberlessimage indepimage
def hr
puts "<hr />"
end
def label(id)
puts %Q(<a id="#{id}"></a>)
end
def linebreak
puts "<br />"
end
def pagebreak
puts %Q(<br class="pagebreak" />)
end
def bpo(lines)
puts "<bpo>"
lines.each do |line|
puts detab(line)
end
puts "</bpo>"
end
def noindent
@noindent = true
end
def inline_labelref(idref)
%Q[<a target='#{escape_html(idref)}'>「●● #{escape_html(idref)}」</a>]
end
alias inline_ref inline_labelref
def inline_chapref(id)
title = super
if ReVIEW.book.param["chapterlink"]
%Q(<a href="./#{id}.html">#{title}</a>)
else
title
end
rescue KeyError
error "unknown chapter: #{id}"
nofunc_text("[UnknownChapter:#{id}]")
end
def inline_chap(id)
if ReVIEW.book.param["chapterlink"]
%Q(<a href="./#{id}.html">#{@chapter.env.chapter_index.number(id)}</a>)
else
@chapter.env.chapter_index.number(id)
end
rescue KeyError
error "unknown chapter: #{id}"
nofunc_text("[UnknownChapter:#{id}]")
end
def inline_title(id)
if ReVIEW.book.param["chapterlink"]
%Q(<a href="./#{id}.html">#{compile_inline(@chapter.env.chapter_index.title(id))}</a>)
else
@chapter.env.chapter_index.title(id)
end
rescue KeyError
error "unknown chapter: #{id}"
nofunc_text("[UnknownChapter:#{id}]")
end
def inline_fn(id)
if ReVIEW.book.param["epubversion"].to_i == 3
%Q(<a href="#fn-#{id}" class="noteref" epub:type="noteref">*#{@chapter.footnote(id).number}</a>)
else
%Q(<a href="#fn-#{id}" class="noteref">*#{@chapter.footnote(id).number}</a>)
end
end
def compile_ruby(base, ruby)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q[<ruby>#{escape_html(base)}<rp>#{I18n.t("ruby_prefix")}</rp><rt>#{escape_html(ruby)}</rt><rp>#{I18n.t("ruby_postfix")}</rp></ruby>]
else
%Q[<ruby><rb>#{escape_html(base)}</rb><rp>#{I18n.t("ruby_prefix")}</rp><rt>#{ruby}</rt><rp>#{I18n.t("ruby_postfix")}</rp></ruby>]
end
end
def compile_kw(word, alt)
%Q[<b class="kw">] +
if alt
then escape_html(word + " (#{alt.strip})")
else escape_html(word)
end +
"</b><!-- IDX:#{escape_html(word)} -->"
end
def inline_i(str)
%Q(<i>#{escape_html(str)}</i>)
end
def inline_b(str)
%Q(<b>#{escape_html(str)}</b>)
end
def inline_ami(str)
%Q(<span class="ami">#{escape_html(str)}</span>)
end
def inline_bou(str)
%Q(<span class="bou">#{escape_html(str)}</span>)
end
def inline_tti(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="tt"><i>#{escape_html(str)}</i></code>)
else
%Q(<tt><i>#{escape_html(str)}</i></tt>)
end
end
def inline_ttb(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="tt"><b>#{escape_html(str)}</b></code>)
else
%Q(<tt><b>#{escape_html(str)}</b></tt>)
end
end
def inline_dtp(str)
"<?dtp #{str} ?>"
end
def inline_code(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="inline-code tt">#{escape_html(str)}</code>)
else
%Q(<tt class="inline-code">#{escape_html(str)}</tt>)
end
end
def inline_idx(str)
%Q(#{escape_html(str)}<!-- IDX:#{escape_html(str)} -->)
end
def inline_hidx(str)
%Q(<!-- IDX:#{escape_html(str)} -->)
end
def inline_br(str)
%Q(<br />)
end
def inline_m(str)
if ReVIEW.book.param["mathml"]
p = MathML::LaTeX::Parser.new(:symbol=>MathML::Symbol::CharacterReference)
%Q[<span class="equation">#{p.parse(str, nil)}</span>]
else
%Q[<span class="equation">#{escape_html(str)}</span>]
end
end
def text(str)
str
end
def bibpaper(lines, id, caption)
puts %Q[<div class="bibpaper">]
bibpaper_header id, caption
unless lines.empty?
bibpaper_bibpaper id, caption, lines
end
puts "</div>"
end
def bibpaper_header(id, caption)
print %Q(<a id="bib-#{id}">)
print "[#{@chapter.bibpaper(id).number}]"
print %Q(</a>)
puts " #{compile_inline(caption)}"
end
def bibpaper_bibpaper(id, caption, lines)
print split_paragraph(lines).join("")
end
def inline_bib(id)
%Q(<a href=".#{@book.bib_file.gsub(/re\Z/, "html")}#bib-#{id}">[#{@chapter.bibpaper(id).number}]</a>)
end
def inline_hd_chap(chap, id)
n = chap.headline_index.number(id)
if chap.number and ReVIEW.book.param["secnolevel"] >= n.split('.').size
str = "「#{n} #{compile_inline(chap.headline(id).caption)}」"
else
str = "「#{compile_inline(chap.headline(id).caption)}」"
end
if ReVIEW.book.param["chapterlink"]
anchor = "h"+n.gsub(/\./, "-")
%Q(<a href="#{chap.id}.html\##{anchor}">#{str}</a>)
else
str
end
end
def column_label(id)
num = @chapter.column(id).number
"column-#{num}"
end
private :column_label
def inline_column(id)
if ReVIEW.book.param["chapterlink"]
%Q(<a href="\##{column_label(id)}" class="columnref">#{@chapter.column(id).caption}</a>)
else
@chapter.column(id).caption
end
rescue KeyError
error "unknown column: #{id}"
nofunc_text("[UnknownColumn:#{id}]")
end
def inline_list(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
"#{I18n.t("list")}#{I18n.t("format_number_without_header", [chapter.list(id).number])}"
else
"#{I18n.t("list")}#{I18n.t("format_number", [get_chap(chapter), chapter.list(id).number])}"
end
rescue KeyError
error "unknown list: #{id}"
nofunc_text("[UnknownList:#{id}]")
end
def inline_table(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
"#{I18n.t("table")}#{I18n.t("format_number_without_chapter", [chapter.table(id).number])}"
else
"#{I18n.t("table")}#{I18n.t("format_number", [get_chap(chapter), chapter.table(id).number])}"
end
rescue KeyError
error "unknown table: #{id}"
nofunc_text("[UnknownTable:#{id}]")
end
def inline_img(id)
chapter, id = extract_chapter_id(id)
if get_chap(chapter).nil?
"#{I18n.t("image")}#{I18n.t("format_number_without_chapter", [chapter.image(id).number])}"
else
"#{I18n.t("image")}#{I18n.t("format_number", [get_chap(chapter), chapter.image(id).number])}"
end
rescue KeyError
error "unknown image: #{id}"
nofunc_text("[UnknownImage:#{id}]")
end
def inline_asis(str, tag)
%Q(<#{tag}>#{escape_html(str)}</#{tag}>)
end
def inline_abbr(str)
inline_asis(str, "abbr")
end
def inline_acronym(str)
inline_asis(str, "acronym")
end
def inline_cite(str)
inline_asis(str, "cite")
end
def inline_dfn(str)
inline_asis(str, "dfn")
end
def inline_em(str)
inline_asis(str, "em")
end
def inline_kbd(str)
inline_asis(str, "kbd")
end
def inline_samp(str)
inline_asis(str, "samp")
end
def inline_strong(str)
inline_asis(str, "strong")
end
def inline_var(str)
inline_asis(str, "var")
end
def inline_big(str)
inline_asis(str, "big")
end
def inline_small(str)
inline_asis(str, "small")
end
def inline_sub(str)
inline_asis(str, "sub")
end
def inline_sup(str)
inline_asis(str, "sup")
end
def inline_tt(str)
if ReVIEW.book.param["htmlversion"].to_i == 5
%Q(<code class="tt">#{escape_html(str)}</code>)
else
%Q(<tt>#{escape_html(str)}</tt>)
end
end
def inline_del(str)
inline_asis(str, "del")
end
def inline_ins(str)
inline_asis(str, "ins")
end
def inline_u(str)
%Q(<u>#{escape_html(str)}</u>)
end
def inline_recipe(str)
%Q(<span class="recipe">「#{escape_html(str)}」</span>)
end
def inline_icon(id)
begin
%Q[<img src="#{@chapter.image(id).path.sub(/\A\.\//, "")}" alt="[#{id}]" />]
rescue
%Q[<pre>missing image: #{id}</pre>]
end
end
def inline_uchar(str)
%Q(&#x#{str};)
end
def inline_comment(str)
if ReVIEW.book.param["draft"]
%Q(<span class="draft-comment">#{escape_html(str)}</span>)
else
%Q(<!-- #{escape_html(str)} -->)
end
end
def inline_raw(str)
super(str)
end
def nofunc_text(str)
escape_html(str)
end
def compile_href(url, label)
%Q(<a href="#{escape_html(url)}" class="link">#{label.nil? ? escape_html(url) : escape_html(label)}</a>)
end
def flushright(lines)
if ReVIEW.book.param["deprecated-blocklines"].nil?
puts split_paragraph(lines).join("\n").gsub("<p>", "<p class=\"flushright\">")
else
puts %Q[<div style="text-align:right;">]
print %Q[<pre class="flushright">]
lines.each {|line| puts detab(line) }
puts '</pre>'
puts '</div>'
end
end
def centering(lines)
puts split_paragraph(lines).join("\n").gsub("<p>", "<p class=\"center\">")
end
def image_ext
"png"
end
def olnum(num)
@ol_num = num.to_i
end
end
end # module ReVIEW
|
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'proc_index/version'
Gem::Specification.new do |gem|
gem.name = "proc_index"
gem.version = ProcIndex::VERSION
gem.summary = "Process table ORM"
gem.description = "Map and search all your processes."
gem.license = "MIT"
gem.authors = ["Alex Manelis"]
gem.email = "amanelis@gmail.com"
gem.homepage = "https://rubygems.org/gems/proc_index"
gem.files = `git ls-files`.split($/)
`git submodule --quiet foreach --recursive pwd`.split($/).each do |submodule|
submodule.sub!("#{Dir.pwd}/",'')
Dir.chdir(submodule) do
`git ls-files`.split($/).map do |subpath|
gem.files << File.join(submodule,subpath)
end
end
end
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 'awesome_print', '1.6.1'
gem.add_dependency 'fuzzy_match', '2.1.0'
gem.add_runtime_dependency 'hashie', '~> 2.1.1'
gem.add_development_dependency 'pry', '~> 0.10.3'
gem.add_development_dependency 'bundler', '~> 1.10'
gem.add_development_dependency 'rake', '~> 10.0'
gem.add_development_dependency 'rdoc', '~> 4.0'
gem.add_development_dependency 'rspec', '~> 3.0'
gem.add_development_dependency 'rubygems-tasks', '~> 0.2'
end
Symantic errors :)
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'proc_index/version'
Gem::Specification.new do |gem|
gem.name = "proc_index"
gem.version = ProcIndex::VERSION
gem.summary = "Process table ORM"
gem.description = "Map and search all your processes."
gem.license = "MIT"
gem.authors = ["Alex Manelis"]
gem.email = "amanelis@gmail.com"
gem.homepage = "https://rubygems.org/gems/proc_index"
gem.files = `git ls-files`.split($/)
`git submodule --quiet foreach --recursive pwd`.split($/).each do |submodule|
submodule.sub!("#{Dir.pwd}/",'')
Dir.chdir(submodule) do
`git ls-files`.split($/).map do |subpath|
gem.files << File.join(submodule,subpath)
end
end
end
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 'awesome_print', '1.6.1'
gem.add_dependency 'fuzzy_match', '2.1.0'
gem.add_runtime_dependency 'hashie', '~> 2.1', '>= 2.1.1'
gem.add_development_dependency 'pry', '~> 0.10.3'
gem.add_development_dependency 'bundler', '~> 1.10'
gem.add_development_dependency 'rake', '~> 10.0'
gem.add_development_dependency 'rdoc', '~> 4.0'
gem.add_development_dependency 'rspec', '~> 3.0'
gem.add_development_dependency 'rubygems-tasks', '~> 0.2'
end
|
# coding: utf-8
$:.unshift "."
require 'spec_helper'
require 'rdf/spec/writer'
describe JSON::LD::API do
describe ".fromRDF" do
context "simple tests" do
it "One subject IRI object" do
input = %(<http://a/b> <http://a/c> <http://a/d> .)
serialize(input).should produce([
{
'@id' => "http://a/b",
"http://a/c" => [{"@id" => "http://a/d"}]
}, {
'@id' => 'http://a/d'
}
], @debug)
end
it "should generate object list" do
input = %(@prefix : <http://example.com/> . :b :c :d, :e .)
serialize(input).
should produce([{
'@id' => "http://example.com/b",
"http://example.com/c" => [
{"@id" => "http://example.com/d"},
{"@id" => "http://example.com/e"}
]
},
{"@id" => "http://example.com/d"},
{"@id" => "http://example.com/e"}
], @debug)
end
it "should generate property list" do
input = %(@prefix : <http://example.com/> . :b :c :d; :e :f .)
serialize(input).
should produce([{
'@id' => "http://example.com/b",
"http://example.com/c" => [{"@id" => "http://example.com/d"}],
"http://example.com/e" => [{"@id" => "http://example.com/f"}]
},
{"@id" => "http://example.com/d"},
{"@id" => "http://example.com/f"}
], @debug)
end
it "serializes multiple subjects" do
input = %q(
@prefix : <http://www.w3.org/2006/03/test-description#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
<test-cases/0001> a :TestCase .
<test-cases/0002> a :TestCase .
)
serialize(input).
should produce([
{'@id' => "http://www.w3.org/2006/03/test-description#TestCase"},
{'@id' => "test-cases/0001", '@type' => ["http://www.w3.org/2006/03/test-description#TestCase"]},
{'@id' => "test-cases/0002", '@type' => ["http://www.w3.org/2006/03/test-description#TestCase"]},
], @debug)
end
end
context "literals" do
context "coercion" do
it "typed literal" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b "foo"^^ex:d .)
serialize(input).should produce([
{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "foo", "@type" => "http://example.com/d"}]
}
], @debug)
end
it "integer" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1 .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => 1}]
}], @debug)
end
it "integer (non-native)" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1 .)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "1","@type" => "http://www.w3.org/2001/XMLSchema#integer"}]
}], @debug)
end
it "boolean" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b true .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => true}]
}], @debug)
end
it "boolean (non-native)" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b true .)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "true","@type" => "http://www.w3.org/2001/XMLSchema#boolean"}]
}], @debug)
end
it "decmal" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1.0 .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "1.0", "@type" => "http://www.w3.org/2001/XMLSchema#decimal"}]
}], @debug)
end
it "double" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1.0e0 .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => 1.0E0}]
}], @debug)
end
it "double (non-native)" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1.0e0 .)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "1.0E0","@type" => "http://www.w3.org/2001/XMLSchema#double"}]
}], @debug)
end
end
context "datatyped (non-native)" do
{
:integer => 1,
:unsignedInteger => 1,
:nonNegativeInteger => 1,
:float => 1,
:nonPositiveInteger => -1,
:negativeInteger => -1,
}.each do |t, v|
it "#{t}" do
input = %(
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix ex: <http://example.com/> .
ex:a ex:b "#{v}"^^xsd:#{t} .
)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "#{v}","@type" => "http://www.w3.org/2001/XMLSchema##{t}"}]
}], @debug)
end
end
end
it "encodes language literal" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b "foo"@en-us .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "foo", "@language" => "en-us"}]
}], @debug)
end
end
context "anons" do
it "should generate bare anon" do
input = %(@prefix : <http://example.com/> . _:a :a :b .)
serialize(input).should produce([
{
"@id" => "_:a",
"http://example.com/a" => [{"@id" => "http://example.com/b"}]
},
{"@id" => "http://example.com/b"}
], @debug)
end
it "should generate anon as object" do
input = %(@prefix : <http://example.com/> . :a :b _:a . _:a :c :d .)
serialize(input).should produce([
{
"@id" => "_:a",
"http://example.com/c" => [{"@id" => "http://example.com/d"}]
},
{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@id" => "_:a"}]
},
{"@id" => "http://example.com/d"},
], @debug)
end
end
context "lists" do
it "should generate literal list" do
input = %(
@prefix : <http://example.com/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
:a :b ("apple" "banana") .
)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [
{"@value" => "apple"},
{"@value" => "banana"}
]
}]
}], @debug)
end
it "should generate iri list" do
input = %(@prefix : <http://example.com/> . :a :b (:c) .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [
{"@id" => "http://example.com/c"}
]
}]
}, {"@id" => "http://example.com/c"}], @debug)
end
it "should generate empty list" do
input = %(@prefix : <http://example.com/> . :a :b () .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@list" => []}]
}], @debug)
end
it "should generate single element list" do
input = %(@prefix : <http://example.com/> . :a :b ( "apple" ) .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@list" => [{"@value" => "apple"}]}]
}], @debug)
end
it "should generate single element list without @type" do
input = %(
@prefix : <http://example.com/> . :a :b ( _:a ) . _:a :b "foo" .)
serialize(input).should produce([
{
'@id' => "_:a",
"http://example.com/b" => [{"@value" => "foo"}]
},
{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@list" => [{"@id" => "_:a"}]}]
},
], @debug)
end
end
context "quads" do
{
"simple named graph" => {
:input => %(
<http://example.com/a> <http://example.com/b> <http://example.com/c> <http://example.com/U> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@id" => "http://example.com/c"}]
}, {"@id" => "http://example.com/c"}]
},
]
},
"with properties" => {
:input => %(
<http://example.com/a> <http://example.com/b> <http://example.com/c> <http://example.com/U> .
<http://example.com/U> <http://example.com/d> <http://example.com/e> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@id" => "http://example.com/c"}]
}, {"@id" => "http://example.com/c"}],
"http://example.com/d" => [{"@id" => "http://example.com/e"}]
},
{"@id" => "http://example.com/e"}
]
},
"with lists" => {
:input => %(
<http://example.com/a> <http://example.com/b> _:a <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/c> <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> <http://example.com/U> .
<http://example.com/U> <http://example.com/d> _:b .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/e> .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@list" => [{"@id" => "http://example.com/c"}]}]
}, {"@id" => "http://example.com/c"}],
"http://example.com/d" => [{"@list" => [{"@id" => "http://example.com/e"}]}]
},
{"@id" => "http://example.com/e"}
]
},
"Two Graphs with same subject and lists" => {
:input => %(
<http://example.com/a> <http://example.com/b> _:a <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/c> <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> <http://example.com/U> .
<http://example.com/a> <http://example.com/b> _:b <http://example.com/V> .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/e> <http://example.com/V> .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> <http://example.com/V> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [
{
"@id" => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [{"@id" => "http://example.com/c"}]
}]
},
{"@id" => "http://example.com/c"}
]
},
{
"@id" => "http://example.com/V",
"@graph" => [
{
"@id" => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [{"@id" => "http://example.com/e"}]
}]
},
{"@id" => "http://example.com/e"}
]
}
]
},
}.each_pair do |name, properties|
it name do
r = serialize(properties[:input], :reader => RDF::NQuads::Reader)
r.should produce(properties[:output], @debug)
end
end
end
context "useRdfType option" do
it "uses @type if set to false" do
input = %(@prefix ex: <http://example.com/> . ex:a a ex:b .)
serialize(input, :useRdfType => false).should produce([{
'@id' => "http://example.com/a",
"@type" => ["http://example.com/b"]
}, {'@id' => "http://example.com/b"}], @debug)
end
it "does not use @type if set to true" do
input = %(@prefix ex: <http://example.com/> . ex:a a ex:b .)
serialize(input, :useRdfType => true).should produce([{
'@id' => "http://example.com/a",
'@type' => ["http://example.com/b"]
}, {"@id" => "http://example.com/b"}], @debug)
end
end
context "problems" do
{
"xsd:boolean as value" => [
%(
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<http://data.wikia.com/terms#playable> rdfs:range xsd:boolean .
),
[{
"@id" => "http://data.wikia.com/terms#playable",
"http://www.w3.org/2000/01/rdf-schema#range" => [
{ "@id" => "http://www.w3.org/2001/XMLSchema#boolean" }
]
}, { "@id" => "http://www.w3.org/2001/XMLSchema#boolean" }]
],
}.each do |t, (input, output)|
it "#{t}" do
serialize(input).should produce(output, @debug)
end
end
end
end
def parse(input, options = {})
reader = options[:reader] || RDF::Turtle::Reader
RDF::Repository.new << reader.new(input, options)
end
# Serialize ntstr to a string and compare against regexps
def serialize(ntstr, options = {})
@debug = []
@debug << ntstr if ntstr.is_a?(String)
g = ntstr.is_a?(String) ? parse(ntstr, options) : ntstr
@debug << g.dump(:trig)
statements = g.each_statement.to_a
JSON::LD::API.fromRDF(statements, options.merge(:debug => @debug))
end
end
More fromRdf test updates.
# coding: utf-8
$:.unshift "."
require 'spec_helper'
require 'rdf/spec/writer'
describe JSON::LD::API do
describe ".fromRDF" do
context "simple tests" do
it "One subject IRI object" do
input = %(<http://a/b> <http://a/c> <http://a/d> .)
serialize(input).should produce([
{
'@id' => "http://a/b",
"http://a/c" => [{"@id" => "http://a/d"}]
}
], @debug)
end
it "should generate object list" do
input = %(@prefix : <http://example.com/> . :b :c :d, :e .)
serialize(input).
should produce([{
'@id' => "http://example.com/b",
"http://example.com/c" => [
{"@id" => "http://example.com/d"},
{"@id" => "http://example.com/e"}
]
}
], @debug)
end
it "should generate property list" do
input = %(@prefix : <http://example.com/> . :b :c :d; :e :f .)
serialize(input).
should produce([{
'@id' => "http://example.com/b",
"http://example.com/c" => [{"@id" => "http://example.com/d"}],
"http://example.com/e" => [{"@id" => "http://example.com/f"}]
}
], @debug)
end
it "serializes multiple subjects" do
input = %q(
@prefix : <http://www.w3.org/2006/03/test-description#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
<test-cases/0001> a :TestCase .
<test-cases/0002> a :TestCase .
)
serialize(input).
should produce([
{'@id' => "test-cases/0001", '@type' => ["http://www.w3.org/2006/03/test-description#TestCase"]},
{'@id' => "test-cases/0002", '@type' => ["http://www.w3.org/2006/03/test-description#TestCase"]},
], @debug)
end
end
context "literals" do
context "coercion" do
it "typed literal" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b "foo"^^ex:d .)
serialize(input).should produce([
{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "foo", "@type" => "http://example.com/d"}]
}
], @debug)
end
it "integer" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1 .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => 1}]
}], @debug)
end
it "integer (non-native)" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1 .)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "1","@type" => "http://www.w3.org/2001/XMLSchema#integer"}]
}], @debug)
end
it "boolean" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b true .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => true}]
}], @debug)
end
it "boolean (non-native)" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b true .)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "true","@type" => "http://www.w3.org/2001/XMLSchema#boolean"}]
}], @debug)
end
it "decmal" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1.0 .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "1.0", "@type" => "http://www.w3.org/2001/XMLSchema#decimal"}]
}], @debug)
end
it "double" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1.0e0 .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => 1.0E0}]
}], @debug)
end
it "double (non-native)" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b 1.0e0 .)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "1.0E0","@type" => "http://www.w3.org/2001/XMLSchema#double"}]
}], @debug)
end
end
context "datatyped (non-native)" do
{
:integer => 1,
:unsignedInteger => 1,
:nonNegativeInteger => 1,
:float => 1,
:nonPositiveInteger => -1,
:negativeInteger => -1,
}.each do |t, v|
it "#{t}" do
input = %(
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix ex: <http://example.com/> .
ex:a ex:b "#{v}"^^xsd:#{t} .
)
serialize(input, :useNativeTypes => false).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "#{v}","@type" => "http://www.w3.org/2001/XMLSchema##{t}"}]
}], @debug)
end
end
end
it "encodes language literal" do
input = %(@prefix ex: <http://example.com/> . ex:a ex:b "foo"@en-us .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@value" => "foo", "@language" => "en-us"}]
}], @debug)
end
end
context "anons" do
it "should generate bare anon" do
input = %(@prefix : <http://example.com/> . _:a :a :b .)
serialize(input).should produce([
{
"@id" => "_:a",
"http://example.com/a" => [{"@id" => "http://example.com/b"}]
}
], @debug)
end
it "should generate anon as object" do
input = %(@prefix : <http://example.com/> . :a :b _:a . _:a :c :d .)
serialize(input).should produce([
{
"@id" => "_:a",
"http://example.com/c" => [{"@id" => "http://example.com/d"}]
},
{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@id" => "_:a"}]
}
], @debug)
end
end
context "lists" do
it "should generate literal list" do
input = %(
@prefix : <http://example.com/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
:a :b ("apple" "banana") .
)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [
{"@value" => "apple"},
{"@value" => "banana"}
]
}]
}], @debug)
end
it "should generate iri list" do
input = %(@prefix : <http://example.com/> . :a :b (:c) .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [
{"@id" => "http://example.com/c"}
]
}]
}], @debug)
end
it "should generate empty list" do
input = %(@prefix : <http://example.com/> . :a :b () .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@list" => []}]
}], @debug)
end
it "should generate single element list" do
input = %(@prefix : <http://example.com/> . :a :b ( "apple" ) .)
serialize(input).should produce([{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@list" => [{"@value" => "apple"}]}]
}], @debug)
end
it "should generate single element list without @type" do
input = %(
@prefix : <http://example.com/> . :a :b ( _:a ) . _:a :b "foo" .)
serialize(input).should produce([
{
'@id' => "_:a",
"http://example.com/b" => [{"@value" => "foo"}]
},
{
'@id' => "http://example.com/a",
"http://example.com/b" => [{"@list" => [{"@id" => "_:a"}]}]
},
], @debug)
end
end
context "quads" do
{
"simple named graph" => {
:input => %(
<http://example.com/a> <http://example.com/b> <http://example.com/c> <http://example.com/U> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@id" => "http://example.com/c"}]
}]
},
]
},
"with properties" => {
:input => %(
<http://example.com/a> <http://example.com/b> <http://example.com/c> <http://example.com/U> .
<http://example.com/U> <http://example.com/d> <http://example.com/e> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@id" => "http://example.com/c"}]
}],
"http://example.com/d" => [{"@id" => "http://example.com/e"}]
}
]
},
"with lists" => {
:input => %(
<http://example.com/a> <http://example.com/b> _:a <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/c> <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> <http://example.com/U> .
<http://example.com/U> <http://example.com/d> _:b .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/e> .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [{
"@id" => "http://example.com/a",
"http://example.com/b" => [{"@list" => [{"@id" => "http://example.com/c"}]}]
}],
"http://example.com/d" => [{"@list" => [{"@id" => "http://example.com/e"}]}]
}
]
},
"Two Graphs with same subject and lists" => {
:input => %(
<http://example.com/a> <http://example.com/b> _:a <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/c> <http://example.com/U> .
_:a <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> <http://example.com/U> .
<http://example.com/a> <http://example.com/b> _:b <http://example.com/V> .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#first> <http://example.com/e> <http://example.com/V> .
_:b <http://www.w3.org/1999/02/22-rdf-syntax-ns#rest> <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil> <http://example.com/V> .
),
:output => [
{
"@id" => "http://example.com/U",
"@graph" => [
{
"@id" => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [{"@id" => "http://example.com/c"}]
}]
}
]
},
{
"@id" => "http://example.com/V",
"@graph" => [
{
"@id" => "http://example.com/a",
"http://example.com/b" => [{
"@list" => [{"@id" => "http://example.com/e"}]
}]
}
]
}
]
},
}.each_pair do |name, properties|
it name do
r = serialize(properties[:input], :reader => RDF::NQuads::Reader)
r.should produce(properties[:output], @debug)
end
end
end
context "useRdfType option" do
it "uses @type if set to false" do
input = %(@prefix ex: <http://example.com/> . ex:a a ex:b .)
serialize(input, :useRdfType => false).should produce([{
'@id' => "http://example.com/a",
"@type" => ["http://example.com/b"]
}], @debug)
end
it "does not use @type if set to true" do
input = %(@prefix ex: <http://example.com/> . ex:a a ex:b .)
serialize(input, :useRdfType => true).should produce([{
'@id' => "http://example.com/a",
'@type' => ["http://example.com/b"]
}], @debug)
end
end
context "problems" do
{
"xsd:boolean as value" => [
%(
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
<http://data.wikia.com/terms#playable> rdfs:range xsd:boolean .
),
[{
"@id" => "http://data.wikia.com/terms#playable",
"http://www.w3.org/2000/01/rdf-schema#range" => [
{ "@id" => "http://www.w3.org/2001/XMLSchema#boolean" }
]
}]
],
}.each do |t, (input, output)|
it "#{t}" do
serialize(input).should produce(output, @debug)
end
end
end
end
def parse(input, options = {})
reader = options[:reader] || RDF::Turtle::Reader
RDF::Repository.new << reader.new(input, options)
end
# Serialize ntstr to a string and compare against regexps
def serialize(ntstr, options = {})
@debug = []
@debug << ntstr if ntstr.is_a?(String)
g = ntstr.is_a?(String) ? parse(ntstr, options) : ntstr
@debug << g.dump(:trig)
statements = g.each_statement.to_a
JSON::LD::API.fromRDF(statements, options.merge(:debug => @debug))
end
end
|
require 'spec_helper'
describe JSON::JWE do
let(:private_key_path) { der_file_path 'rsa/private_key' }
describe '#content_type' do
let(:jwe) { JSON::JWE.new 'hello' }
it do
jwe.content_type.should == 'application/jose'
end
end
describe 'encrypt!' do
shared_examples_for :unexpected_algorithm_for_encryption do
it do
expect do
jwe.encrypt!(key).to_s # NOTE: encrypt! won't raise, but to_s does. might need to fix.
end.to raise_error JSON::JWE::UnexpectedAlgorithm
end
end
shared_examples_for :unsupported_algorithm_for_encryption do
it do
expect do
jwe.encrypt!(key).to_s # NOTE: encrypt! won't raise, but to_s does. might need to fix.
end.to raise_error NotImplementedError
end
end
context 'when plaintext given' do
let(:plain_text) { 'Hello World' }
let(:jwe) { JSON::JWE.new plain_text }
context 'when alg=dir' do
it :TODO
end
context 'when alg=A128KW' do
it :TODO
end
context 'when alg=A256KW' do
it :TODO
end
context 'when unknonw/unsupported algorithm given' do
let(:key) { public_key }
let(:alg) { :RSA1_5 }
let(:enc) { :'A128CBC-HS256' }
before { jwe.alg, jwe.enc = alg, enc }
context 'when alg=unknown' do
let(:alg) { :unknown }
it_behaves_like :unexpected_algorithm_for_encryption
end
context 'when enc=unknown' do
let(:enc) { :unknown }
it_behaves_like :unexpected_algorithm_for_encryption
end
[:'ECDH-ES', :'ECDH-ES+A128KW', :'ECDH-ES+A256KW'].each do |alg|
context "when alg=#{alg}" do
let(:alg) { alg }
it_behaves_like :unsupported_algorithm_for_encryption
end
end
end
end
end
describe 'decrypt!' do
let(:plain_text) { 'Hello World' }
let(:jwe_string) do
_jwe_ = JSON::JWE.new plain_text
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_.encrypt! key
_jwe_.to_s
end
let(:jwe) do
_jwe_ = JSON::JWE.decode jwe_string, :skip_decryption
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_
end
shared_examples_for :decryptable do
it do
jwe.decrypt! key
jwe.plain_text.should == plain_text
end
end
shared_examples_for :verify_cbc_authentication_tag do
let(:jwe_string) do
_jwe_ = JSON::JWE.new plain_text
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_.encrypt! key
_jwe_.to_s + 'tampered'
end
it do
expect do
jwe.decrypt! key
end.to raise_error JSON::JWE::DecryptionFailed
end
end
shared_examples_for :verify_gcm_authentication_tag do
let(:jwe_string) do
_jwe_ = JSON::JWE.new plain_text
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_.encrypt! key
header, key, iv, cipher_text, auth_tag = _jwe_.to_s.split('.')
truncated_auth_tag = Base64.urlsafe_decode64(auth_tag).slice(0..-2)
truncated_auth_tag = Base64.urlsafe_encode64(truncated_auth_tag, padding: false)
[header, key, iv, cipher_text, truncated_auth_tag].join('.')
end
it do
expect do
jwe.decrypt! key
end.to raise_error JSON::JWE::DecryptionFailed
end
end
shared_examples_for :unexpected_algorithm_for_decryption do
it do
expect do
jwe.decrypt! key
end.to raise_error JSON::JWE::UnexpectedAlgorithm
end
end
shared_examples_for :unsupported_algorithm_for_decryption do
it do
expect do
jwe.decrypt! key
end.to raise_error NotImplementedError
end
end
context 'when alg=RSA1_5' do
let(:alg) { :RSA1_5 }
let(:key) { private_key }
context 'when enc=A128GCM' do
let(:enc) { :A128GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A256GCM' do
let(:enc) { :A256GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A128CBC-HS256' do
let(:enc) { :'A128CBC-HS256' }
it_behaves_like :decryptable
end
context 'when enc=A256CBC-HS512' do
let(:enc) { :'A256CBC-HS512' }
it_behaves_like :decryptable
end
end
context 'when alg=RSA-OAEP' do
let(:alg) { :'RSA-OAEP' }
let(:key) { private_key }
context 'when enc=A128GCM' do
let(:enc) { :A128GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A256GCM' do
let(:enc) { :A256GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A128CBC-HS256' do
let(:enc) { :'A128CBC-HS256' }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
context 'when enc=A256CBC-HS512' do
let(:enc) { :'A256CBC-HS512' }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
end
context 'when alg=dir' do
let(:alg) { :dir }
let(:key) { SecureRandom.random_bytes key_size }
context 'when enc=A128GCM' do
let(:enc) { :A128GCM }
let(:key_size) { 16 }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A256GCM' do
let(:enc) { :A256GCM }
let(:key_size) { 32 }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A128CBC-HS256' do
let(:enc) { :'A128CBC-HS256' }
let(:key_size) { 32 }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
context 'when enc=A256CBC-HS512' do
let(:enc) { :'A256CBC-HS512' }
let(:key_size) { 64 }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
end
context 'when alg=A128KW' do
it :TODO
end
context 'when alg=A256KW' do
it :TODO
end
context 'when unknonw/unsupported algorithm given' do
let(:input) { 'header.key.iv.cipher_text.auth_tag' }
let(:key) { public_key }
let(:alg) { :RSA1_5 }
let(:enc) { :'A128CBC-HS256' }
context 'when alg=unknown' do
let(:alg) { :unknown }
it_behaves_like :unexpected_algorithm_for_decryption
end
context 'when enc=unknown' do
let(:enc) { :unknown }
it_behaves_like :unexpected_algorithm_for_decryption
end
[:'ECDH-ES', :'ECDH-ES+A128KW', :'ECDH-ES+A256KW'].each do |alg|
context "when alg=#{alg}" do
let(:alg) { alg }
it_behaves_like :unsupported_algorithm_for_decryption
end
end
end
end
end
Test for CVE-2019-18848
require 'spec_helper'
describe JSON::JWE do
let(:private_key_path) { der_file_path 'rsa/private_key' }
describe '#content_type' do
let(:jwe) { JSON::JWE.new 'hello' }
it do
jwe.content_type.should == 'application/jose'
end
end
describe 'encrypt!' do
shared_examples_for :unexpected_algorithm_for_encryption do
it do
expect do
jwe.encrypt!(key).to_s # NOTE: encrypt! won't raise, but to_s does. might need to fix.
end.to raise_error JSON::JWE::UnexpectedAlgorithm
end
end
shared_examples_for :unsupported_algorithm_for_encryption do
it do
expect do
jwe.encrypt!(key).to_s # NOTE: encrypt! won't raise, but to_s does. might need to fix.
end.to raise_error NotImplementedError
end
end
context 'when plaintext given' do
let(:plain_text) { 'Hello World' }
let(:jwe) { JSON::JWE.new plain_text }
context 'when alg=dir' do
it :TODO
end
context 'when alg=A128KW' do
it :TODO
end
context 'when alg=A256KW' do
it :TODO
end
context 'when unknonw/unsupported algorithm given' do
let(:key) { public_key }
let(:alg) { :RSA1_5 }
let(:enc) { :'A128CBC-HS256' }
before { jwe.alg, jwe.enc = alg, enc }
context 'when alg=unknown' do
let(:alg) { :unknown }
it_behaves_like :unexpected_algorithm_for_encryption
end
context 'when enc=unknown' do
let(:enc) { :unknown }
it_behaves_like :unexpected_algorithm_for_encryption
end
[:'ECDH-ES', :'ECDH-ES+A128KW', :'ECDH-ES+A256KW'].each do |alg|
context "when alg=#{alg}" do
let(:alg) { alg }
it_behaves_like :unsupported_algorithm_for_encryption
end
end
end
end
end
describe 'decrypt!' do
let(:plain_text) { 'Hello World' }
let(:jwe_string) do
_jwe_ = JSON::JWE.new plain_text
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_.encrypt! key
_jwe_.to_s
end
let(:jwe) do
_jwe_ = JSON::JWE.decode jwe_string, :skip_decryption
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_
end
shared_examples_for :decryptable do
it do
jwe.decrypt! key
jwe.plain_text.should == plain_text
end
end
shared_examples_for :verify_cbc_authentication_tag do
let(:jwe_string) do
_jwe_ = JSON::JWE.new plain_text
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_.encrypt! key
hdr, extra, iv, cipher_text, _ = _jwe_.to_s.split '.'
[hdr, extra, iv, cipher_text, ''].join '.'
end
it do
# fetching those variables outside of exception block to make sure
# we intercept exception in decrypt! and not in other place
j = jwe
k = key
expect do
j.decrypt! k
end.to raise_error JSON::JWE::DecryptionFailed
end
end
shared_examples_for :verify_gcm_authentication_tag do
let(:jwe_string) do
_jwe_ = JSON::JWE.new plain_text
_jwe_.alg, _jwe_.enc = alg, enc
_jwe_.encrypt! key
header, key, iv, cipher_text, auth_tag = _jwe_.to_s.split('.')
truncated_auth_tag = Base64.urlsafe_decode64(auth_tag).slice(0..-2)
truncated_auth_tag = Base64.urlsafe_encode64(truncated_auth_tag, padding: false)
[header, key, iv, cipher_text, truncated_auth_tag].join('.')
end
it do
expect do
jwe.decrypt! key
end.to raise_error JSON::JWE::DecryptionFailed
end
end
shared_examples_for :unexpected_algorithm_for_decryption do
it do
expect do
jwe.decrypt! key
end.to raise_error JSON::JWE::UnexpectedAlgorithm
end
end
shared_examples_for :unsupported_algorithm_for_decryption do
it do
expect do
jwe.decrypt! key
end.to raise_error NotImplementedError
end
end
context 'when alg=RSA1_5' do
let(:alg) { :RSA1_5 }
let(:key) { private_key }
context 'when enc=A128GCM' do
let(:enc) { :A128GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A256GCM' do
let(:enc) { :A256GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A128CBC-HS256' do
let(:enc) { :'A128CBC-HS256' }
it_behaves_like :decryptable
end
context 'when enc=A256CBC-HS512' do
let(:enc) { :'A256CBC-HS512' }
it_behaves_like :decryptable
end
end
context 'when alg=RSA-OAEP' do
let(:alg) { :'RSA-OAEP' }
let(:key) { private_key }
context 'when enc=A128GCM' do
let(:enc) { :A128GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A256GCM' do
let(:enc) { :A256GCM }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A128CBC-HS256' do
let(:enc) { :'A128CBC-HS256' }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
context 'when enc=A256CBC-HS512' do
let(:enc) { :'A256CBC-HS512' }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
end
context 'when alg=dir' do
let(:alg) { :dir }
let(:key) { SecureRandom.random_bytes key_size }
context 'when enc=A128GCM' do
let(:enc) { :A128GCM }
let(:key_size) { 16 }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A256GCM' do
let(:enc) { :A256GCM }
let(:key_size) { 32 }
it_behaves_like :decryptable
it_behaves_like :verify_gcm_authentication_tag
end
context 'when enc=A128CBC-HS256' do
let(:enc) { :'A128CBC-HS256' }
let(:key_size) { 32 }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
context 'when enc=A256CBC-HS512' do
let(:enc) { :'A256CBC-HS512' }
let(:key_size) { 64 }
it_behaves_like :decryptable
it_behaves_like :verify_cbc_authentication_tag
end
end
context 'when alg=A128KW' do
it :TODO
end
context 'when alg=A256KW' do
it :TODO
end
context 'when unknonw/unsupported algorithm given' do
let(:input) { 'header.key.iv.cipher_text.auth_tag' }
let(:key) { public_key }
let(:alg) { :RSA1_5 }
let(:enc) { :'A128CBC-HS256' }
context 'when alg=unknown' do
let(:alg) { :unknown }
it_behaves_like :unexpected_algorithm_for_decryption
end
context 'when enc=unknown' do
let(:enc) { :unknown }
it_behaves_like :unexpected_algorithm_for_decryption
end
[:'ECDH-ES', :'ECDH-ES+A128KW', :'ECDH-ES+A256KW'].each do |alg|
context "when alg=#{alg}" do
let(:alg) { alg }
it_behaves_like :unsupported_algorithm_for_decryption
end
end
end
end
end
|
require 'spec_helper'
require './lib/ael_tracker/bill'
describe AelTracker::Bill do
it "must include httparty methods" do
expect( AelTracker::Bill ).to include HTTParty
end
it "must have the base url set to the Dribble API endpoint" do
expect( AelTracker::Bill.base_uri ).to eq 'http://www.aeltracker.org/api'
end
describe "GET bill" do
let(:bill) { AelTracker::Bill.new("1") }
before(:all) do
VCR.insert_cassette 'bill', :record => :new_episodes
end
after(:all) do
VCR.eject_cassette
end
it "must have an profile method" do
expect( bill ).to respond_to :profile
end
it "must parse the api response from JSON to HASH" do
expect( bill.profile ).to be_an_instance_of( Hash )
end
it "records the fixture" do
expect( bill.profile["bill_id"] ).to eq "1"
end
end
end
Personalize
require 'spec_helper'
require './lib/ael_tracker/bill'
describe AelTracker::Bill do
it "must include httparty methods" do
expect( AelTracker::Bill ).to include HTTParty
end
it "must have the base url set to the AelTracker API endpoint" do
expect( AelTracker::Bill.base_uri ).to eq 'http://www.aeltracker.org/api'
end
describe "GET bill" do
let(:bill) { AelTracker::Bill.new("1") }
before(:all) do
VCR.insert_cassette 'bill', :record => :new_episodes
end
after(:all) do
VCR.eject_cassette
end
it "must have an profile method" do
expect( bill ).to respond_to :profile
end
it "must parse the api response from JSON to HASH" do
expect( bill.profile ).to be_an_instance_of( Hash )
end
it "records the fixture" do
expect( bill.profile["bill_id"] ).to eq "1"
end
end
end
|
require "spec_helper"
require "dice"
RSpec.describe Dice do
describe "#new" do
describe "dice" do
subject {Dice.new.dice}
it {is_expected.to be_an_instance_of Array}
end
subject {Dice.new}
it {is_expected.to be_an_instance_of Dice}
end
end
Update dice_spec.rb
require "spec_helper"
require "dice"
RSpec.describe Dice do
describe "#new" do
subject {Dice.new}
it {is_expected.to be_an_instance_of Dice}
describe "dice" do
subject {Dice.new.dice}
it {is_expected.to be_an_instance_of Array}
end
end
end
|
require 'rubygems'
require 'sinatra'
require 'mixpanel-ruby'
require 'open-uri'
require 'nokogiri'
require 'rss'
require 'pry'
require 'awesome_print'
require 'uuid'
require 'atom'
before do
content_type :xml
# Mixpanel token is set via 'heroku config:set MIXPANEL_TOKEN=whateverthetokenis'
@mixpanel = Mixpanel::Tracker.new(ENV['MIXPANEL_TOKEN'])
end
class AttributeFilter
# Since Nokogiri (by way of libxml) only supports XPath 1.0, we're missing
# a lot of the more helpful functions. No worries, however!
def contains_text node_set, text
node_set.find_all { |node| node.to_s =~ /#{ text }/i }
end
end
get '/bids/procurement.xml' do
# TODO: Set unique user IDs for Mixpanel tracking.
@mixpanel.track('1', 'Added Procurement feed')
generate_xml('483')
end
get '/bids/watershed.xml' do
@mixpanel.track('1', 'Added Watershed feed')
generate_xml('486')
end
get '/bids/public-works.xml' do
@mixpanel.track('1', 'Added Public Works feed')
generate_xml('484')
end
get '/bids/general-funds.xml' do
@mixpanel.track('1', 'Added General Funds feed')
generate_xml('482')
end
def generate_xml(category)
# XPaths yanked from WebKit. w00t.
xpaths = {
# Watershed RFPs
'486' => { xpath: %{//*[@id="ctl00_content_Screen"]/table/tbody/tr[1]/td[1]/table[contains_text(., 'Award')]},
name: 'Watershed RFPs' },
'484' => { xpath: %{//*[@id="ctl00_content_Screen"]/table[2]/tbody/tr/td[1]/table[contains_text(., 'Award')]},
name: 'Public Works RFPs'},
'482' => { xpath: %{//*[@id="ctl00_content_Screen"]/table[contains_text(., 'Award')]},
name: 'General Funds RFPs' },
'483' => { xpath: %{//*[@id="ctl00_content_Screen"]/table[contains_text(., 'Award')]},
name: 'Procurement RFPs'}
}
return unless category
doc = Nokogiri::HTML(open("http://www.atlantaga.gov/index.aspx?page=#{ category }")).remove_namespaces!
bid_table = doc.xpath(xpaths[category][:xpath], AttributeFilter.new)
@bid_opportunities = []
bid_table.each do |bid|
_bid = {}
# Try a few things to get the project number.
_bid[:project_id] = bid.xpath(".//tr[contains_text(., 'Project number')]/td[2]", AttributeFilter.new)[0].content
# Project name
# For 483, there is no project number set out separately.
project_name = bid.xpath(".//tr[contains_text(., 'Project name')]/td[2]", AttributeFilter.new)[0]
if project_name != nil
_bid[:name] = project_name.content
end
# Set up enclosures...!
_enclosures = bid.xpath(".//a")
@enclosures = []
_enclosures.each do |enclosure|
_enclosure = {}
_enclosure[:name] = enclosure.content
if enclosure["href"] && enclosure["href"].to_s.include?("mailto:")
_enclosure[:href] = enclosure["href"][7, enclosure["href"].length]
elsif enclosure["href"]
_enclosure[:href] = "http://atlantaga.gov/#{ enclosure["href"] }"
end
@enclosures << _enclosure
end
_last = @enclosures.last
if _last[:href].include?("@atlantaga.gov")
_bid[:contracting_officer] = @enclosures.pop
end
_bid[:enclosures] = @enclosures
@bid_opportunities << _bid
end
atom = Atom::Feed.new do |feed|
feed.id = "urn:uuid:#{ UUID.new.generate }"
feed.title = "City of Atlanta - #{ xpaths[category][:name] }"
feed.updated = Time.now.strftime("%Y-%m-%dT%H:%M:%SZ")
feed.authors << Atom::Person.new(name: "Department of Procurement", email: "tiffani+DOP@codeforamerica.org")
feed.generator = Atom::Generator.new(name: "Supply", version: "1.0", uri: "http://atlantaga.gov/procurement")
feed.categories << Atom::Category.new(label: "#{ xpaths[category][:name] }", term: "#{ xpaths[category][:name] }")
feed.rights = "Unless otherwise noted, the content, data, and documents offered through this ATOM feed are public domain and made available with a Creative Commons CC0 1.0 Universal dedication. https://creativecommons.org/publicdomain/zero/1.0/"
@bid_opportunities.each do |bid_opp|
if bid_opp[:contracting_officer]
# Clean up names
name = bid_opp[:contracting_officer][:name].gsub(/(Mr|Mrs|Ms)\.*/i, "").gsub(/,\s+(Contracting Officer|Contract Administrator)/i, "").strip
contracting_officer = Atom::Person.new(name: name, email: bid_opp[:contracting_officer][:href], uri: "http://atlantaga.gov/index.aspx?page=#{ category }")
end
feed.entries << Atom::Entry.new do |entry|
entry.id = "urn:uuid:#{ UUID.new.generate }"
entry.title = "#{ bid_opp[:project_id] } - #{ bid_opp[:name].to_s }"
bid_opp[:enclosures].each do |enclosure|
_enclosure = Atom::Link.new(title: enclosure[:name], href: enclosure[:href], rel: "enclosure", type: "application/pdf")
entry.links << _enclosure
end
entry.authors << contracting_officer
# TODO: Don't tie this date to when someone pulls the feed.
entry.updated = Time.now.strftime("%Y-%m-%dT%H:%M:%SZ")
# TODO: Beef up this summary.
entry.summary = "A bid announcement for #{ bid_opp[:name] }."
end
end
end
#File.open("/Users/tiffani/Desktop/rss-procurement.xml", "w") { |f| f.write(atom.to_xml)}
atom.to_xml
end
Link to bid documents from something other than just enclosures...
require 'rubygems'
require 'sinatra'
require 'mixpanel-ruby'
require 'open-uri'
require 'nokogiri'
require 'rss'
require 'pry'
require 'awesome_print'
require 'uuid'
require 'atom'
before do
content_type :xml
# Mixpanel token is set via 'heroku config:set MIXPANEL_TOKEN=whateverthetokenis'
@mixpanel = Mixpanel::Tracker.new(ENV['MIXPANEL_TOKEN'])
end
class AttributeFilter
# Since Nokogiri (by way of libxml) only supports XPath 1.0, we're missing
# a lot of the more helpful functions. No worries, however!
def contains_text node_set, text
node_set.find_all { |node| node.to_s =~ /#{ text }/i }
end
end
get '/bids/procurement.xml' do
# TODO: Set unique user IDs for Mixpanel tracking.
@mixpanel.track('1', 'Added Procurement feed')
generate_xml('483')
end
get '/bids/watershed.xml' do
@mixpanel.track('1', 'Added Watershed feed')
generate_xml('486')
end
get '/bids/public-works.xml' do
@mixpanel.track('1', 'Added Public Works feed')
generate_xml('484')
end
get '/bids/general-funds.xml' do
@mixpanel.track('1', 'Added General Funds feed')
generate_xml('482')
end
def generate_xml(category)
# XPaths yanked from WebKit. w00t.
xpaths = {
# Watershed RFPs
'486' => { xpath: %{//*[@id="ctl00_content_Screen"]/table/tbody/tr[1]/td[1]/table[contains_text(., 'Award')]},
name: 'Watershed RFPs' },
'484' => { xpath: %{//*[@id="ctl00_content_Screen"]/table[2]/tbody/tr/td[1]/table[contains_text(., 'Award')]},
name: 'Public Works RFPs'},
'482' => { xpath: %{//*[@id="ctl00_content_Screen"]/table[contains_text(., 'Award')]},
name: 'General Funds RFPs' },
'483' => { xpath: %{//*[@id="ctl00_content_Screen"]/table[contains_text(., 'Award')]},
name: 'Procurement RFPs'}
}
return unless category
doc = Nokogiri::HTML(open("http://www.atlantaga.gov/index.aspx?page=#{ category }")).remove_namespaces!
bid_table = doc.xpath(xpaths[category][:xpath], AttributeFilter.new)
@bid_opportunities = []
bid_table.each do |bid|
_bid = {}
# Try a few things to get the project number.
_bid[:project_id] = bid.xpath(".//tr[contains_text(., 'Project number')]/td[2]", AttributeFilter.new)[0].content
# Project name
# For 483, there is no project number set out separately.
project_name = bid.xpath(".//tr[contains_text(., 'Project name')]/td[2]", AttributeFilter.new)[0]
if project_name != nil
_bid[:name] = project_name.content
end
# Set up enclosures...!
_enclosures = bid.xpath(".//a")
@enclosures = []
_enclosures.each do |enclosure|
_enclosure = {}
_enclosure[:name] = enclosure.content
if enclosure["href"] && enclosure["href"].to_s.include?("mailto:")
_enclosure[:href] = enclosure["href"][7, enclosure["href"].length]
elsif enclosure["href"]
_enclosure[:href] = "http://atlantaga.gov/#{ enclosure["href"] }"
end
@enclosures << _enclosure
end
_last = @enclosures.last
if _last[:href].include?("@atlantaga.gov")
_bid[:contracting_officer] = @enclosures.pop
end
_bid[:enclosures] = @enclosures
@bid_opportunities << _bid
end
atom = Atom::Feed.new do |feed|
feed.id = "urn:uuid:#{ UUID.new.generate }"
feed.title = "City of Atlanta - #{ xpaths[category][:name] }"
feed.updated = Time.now.strftime("%Y-%m-%dT%H:%M:%SZ")
feed.authors << Atom::Person.new(name: "Department of Procurement", email: "tiffani+DOP@codeforamerica.org")
feed.generator = Atom::Generator.new(name: "Supply", version: "1.0", uri: "http://atlantaga.gov/procurement")
feed.categories << Atom::Category.new(label: "#{ xpaths[category][:name] }", term: "#{ xpaths[category][:name] }")
feed.rights = "Unless otherwise noted, the content, data, and documents offered through this ATOM feed are public domain and made available with a Creative Commons CC0 1.0 Universal dedication. https://creativecommons.org/publicdomain/zero/1.0/"
@bid_opportunities.each do |bid_opp|
if bid_opp[:contracting_officer]
# Clean up names
name = bid_opp[:contracting_officer][:name].gsub(/(Mr|Mrs|Ms)\.*/i, "").gsub(/,\s+(Contracting Officer|Contract Administrator)/i, "").strip
contracting_officer = Atom::Person.new(name: name, email: bid_opp[:contracting_officer][:href], uri: "http://atlantaga.gov/index.aspx?page=#{ category }")
end
feed.entries << Atom::Entry.new do |entry|
entry.id = "urn:uuid:#{ UUID.new.generate }"
entry.title = "#{ bid_opp[:project_id] } - #{ bid_opp[:name].to_s }"
entry_content = %Q{
<p>
A bid announcement for #{ bid_opp[:name] }.
</p>
<p>
Included files:
<ol>
#{ bid_opp[:enclosures].collect { |enclosure| %{<li><a href="#{ enclosure[:href] }">#{ enclosure[:name] }</a></li>} }.join }
</ol>
</p>
}
entry.content = Atom::Content::Html.new(entry_content)
bid_opp[:enclosures].each do |enclosure|
_enclosure = Atom::Link.new(title: enclosure[:name], href: enclosure[:href], rel: "enclosure", type: "application/pdf")
entry.links << _enclosure
end
entry.authors << contracting_officer
# TODO: Don't tie this date to when someone pulls the feed.
entry.updated = Time.now.strftime("%Y-%m-%dT%H:%M:%SZ")
# TODO: Beef up this summary.
entry.summary = "A bid announcement for #{ bid_opp[:name] }."
end
end
end
#File.open("/Users/tiffani/Desktop/rss-procurement.xml", "w") { |f| f.write(atom.to_xml)}
atom.to_xml
end
|
require "base64"
require "openssl"
require "vagrant/util/retryable"
module Vagrant
module Util
class Keypair
extend Retryable
# Creates an SSH keypair and returns it.
#
# @param [String] password Password for the key, or nil for no password.
# @return [Array<String, String, String>] PEM-encoded public and private key,
# respectively. The final element is the OpenSSH encoded public
# key.
def self.create(password=nil)
# This sometimes fails with RSAError. It is inconsistent and strangely
# sleeps seem to fix it. We just retry this a few times. See GH-5056
rsa_key = nil
retryable(on: OpenSSL::PKey::RSAError, sleep: 2, tries: 5) do
rsa_key = OpenSSL::PKey::RSA.new(2048)
end
public_key = rsa_key.public_key
private_key = rsa_key.to_pem
if password
cipher = OpenSSL::Cipher::Cipher.new('des3')
private_key = rsa_key.to_pem(cipher, password)
end
# Generate the binary necessary for the OpenSSH public key.
binary = [7].pack("N")
binary += "ssh-rsa"
["e", "n"].each do |m|
val = public_key.send(m)
data = val.to_s(2)
first_byte = data[0,1].unpack("c").first
if val < 0
data[0] = [0x80 & first_byte].pack("c")
elsif first_byte < 0
data = 0.chr + data
end
binary += [data.length].pack("N") + data
end
openssh_key = "ssh-rsa #{Base64.encode64(binary).gsub("\n", "")} vagrant"
public_key = public_key.to_pem
return [public_key, private_key, openssh_key]
end
end
end
end
Do not use deprecated API.
require "base64"
require "openssl"
require "vagrant/util/retryable"
module Vagrant
module Util
class Keypair
extend Retryable
# Creates an SSH keypair and returns it.
#
# @param [String] password Password for the key, or nil for no password.
# @return [Array<String, String, String>] PEM-encoded public and private key,
# respectively. The final element is the OpenSSH encoded public
# key.
def self.create(password=nil)
# This sometimes fails with RSAError. It is inconsistent and strangely
# sleeps seem to fix it. We just retry this a few times. See GH-5056
rsa_key = nil
retryable(on: OpenSSL::PKey::RSAError, sleep: 2, tries: 5) do
rsa_key = OpenSSL::PKey::RSA.new(2048)
end
public_key = rsa_key.public_key
private_key = rsa_key.to_pem
if password
cipher = OpenSSL::Cipher.new('des3')
private_key = rsa_key.to_pem(cipher, password)
end
# Generate the binary necessary for the OpenSSH public key.
binary = [7].pack("N")
binary += "ssh-rsa"
["e", "n"].each do |m|
val = public_key.send(m)
data = val.to_s(2)
first_byte = data[0,1].unpack("c").first
if val < 0
data[0] = [0x80 & first_byte].pack("c")
elsif first_byte < 0
data = 0.chr + data
end
binary += [data.length].pack("N") + data
end
openssh_key = "ssh-rsa #{Base64.encode64(binary).gsub("\n", "")} vagrant"
public_key = public_key.to_pem
return [public_key, private_key, openssh_key]
end
end
end
end
|
module Vmdb
module ConsoleMethods
def enable_console_sql_logging
ActiveRecord::Base.logger.level = 0
end
def disable_console_sql_logging
ActiveRecord::Base.logger.level = 1
end
def toggle_console_sql_logging
ActiveRecord::Base.logger.level == 0 ? disable_console_sql_logging : enable_console_sql_logging
end
def backtrace(include_external = false)
caller.select { |path| include_external || path.start_with?(Rails.root.to_s) }
end
# Development helper method for Rails console for simulating queue workers.
def simulate_queue_worker(break_on_complete = false)
raise NotImplementedError, "not implemented in production mode" if Rails.env.production?
Rails.logger.level = :DEBUG
loop do
q = MiqQueue.where(MiqQueue.arel_table[:queue_name].not_eq("miq_server")).order(:id).first
if q
status, message, result = q.deliver
q.delivered(status, message, result) unless status == MiqQueue::STATUS_RETRY
else
break_on_complete ? break : sleep(1.second)
end
end
end
end
end
Fixed Bug in simulate_queue_worker introduced by #8085
module Vmdb
module ConsoleMethods
def enable_console_sql_logging
ActiveRecord::Base.logger.level = 0
end
def disable_console_sql_logging
ActiveRecord::Base.logger.level = 1
end
def toggle_console_sql_logging
ActiveRecord::Base.logger.level == 0 ? disable_console_sql_logging : enable_console_sql_logging
end
def backtrace(include_external = false)
caller.select { |path| include_external || path.start_with?(Rails.root.to_s) }
end
# Development helper method for Rails console for simulating queue workers.
def simulate_queue_worker(break_on_complete = false)
raise NotImplementedError, "not implemented in production mode" if Rails.env.production?
Rails.logger.level = Logger::DEBUG
loop do
q = MiqQueue.where(MiqQueue.arel_table[:queue_name].not_eq("miq_server")).order(:id).first
if q
status, message, result = q.deliver
q.delivered(status, message, result) unless status == MiqQueue::STATUS_RETRY
else
break_on_complete ? break : sleep(1.second)
end
end
end
end
end
|
require 'ostruct'
module Wakame
# System wide configuration parameters
class Configuration < OpenStruct
PARAMS = {
#:config_template_root => nil,
#:config_tmp_root => nil,
#:config_root => nil,
:load_paths => [],
:ssh_private_key => nil,
:drb_command_server_uri => 'druby://localhost:12345',
:vm_environment => nil,
:amqp_server_uri => nil,
:unused_vm_live_period => 60 * 10,
:eventmachine_use_epoll => true
}
def initialize(env=WAKAME_ENV)
super(PARAMS)
if root_path.nil?
root_path = Object.const_defined?(:WAKAME_ROOT) ? WAKAME_ROOT : '../'
end
@root_path = root_path
#default_set.process(self)
end
def environment
::WAKAME_ENV.to_sym
end
def root_path
::WAKAME_ROOT
end
def ssh_known_hosts
File.join(self.config_root, "ssh", "known_hosts")
end
def config_tmp_root
File.join(self.config_root, "tmp")
end
def framework_root_path
defined?(::WAKAME_FRAMEWORK_ROOT) ? ::WAKAME_FRAMEWORK_ROOT : "#{root_path}/vendor/wakame"
end
def framework_paths
paths = %w(lib)
paths.map{|dir| File.join(framework_root_path, dir) }.select{|path| File.directory?(path) }
end
#
class DefaultSet
def process(config)
end
end
class EC2 < DefaultSet
def process(config)
super(config)
config.config_template_root = File.join(config.root, "config", "template")
config.config_root = '/home/wakame/config'
config.vm_environment = :EC2
config.ssh_private_key = '/home/wakame/config/root.id_rsa'
config.aws_access_key = ''
config.aws_secret_key = ''
end
end
class StandAlone < DefaultSet
def process(config)
super(config)
config.config_template_root = File.join(config.root, "config", "template")
config.config_root = File.join('home', 'wakame', 'config')
config.vm_environment = :StandAlone
config.amqp_server_uri = 'amqp://localhost/'
end
end
end
end
Modified configuration variables.
require 'ostruct'
module Wakame
# System wide configuration parameters
class Configuration < OpenStruct
PARAMS = {
#:config_template_root => nil,
#:config_tmp_root => nil,
:config_root => nil,
:cluster_class => 'WebCluster',
:load_paths => [],
:ssh_private_key => nil,
:drb_command_server_uri => 'druby://localhost:12345',
:amqp_server_uri => nil,
:unused_vm_live_period => 60 * 10,
:eventmachine_use_epoll => true
}
def initialize(env=WAKAME_ENV)
super(PARAMS)
if root_path.nil?
root_path = Object.const_defined?(:WAKAME_ROOT) ? WAKAME_ROOT : '../'
end
@root_path = root_path
self.class.const_get(env).new.process(self)
end
def environment
::WAKAME_ENV.to_sym
end
alias :vm_environment :environment
def root_path
::WAKAME_ROOT
end
def tmp_path
File.join(root_path, 'tmp')
end
def ssh_known_hosts
File.join(self.config_root, "ssh", "known_hosts")
end
def config_tmp_root
File.join(self.config_root, "tmp")
end
def framework_root_path
defined?(::WAKAME_FRAMEWORK_ROOT) ? ::WAKAME_FRAMEWORK_ROOT : "#{root_path}/vendor/wakame"
end
def framework_paths
paths = %w(lib)
paths.map{|dir| File.join(framework_root_path, dir) }.select{|path| File.directory?(path) }
end
#
class DefaultSet
def process(config)
end
end
class EC2 < DefaultSet
def process(config)
super(config)
config.config_root = File.join(config.root_path, 'tmp', 'config')
config.ssh_private_key = '/home/wakame/config/root.id_rsa'
config.aws_access_key = ''
config.aws_secret_key = ''
end
end
class StandAlone < DefaultSet
def process(config)
super(config)
config.config_root = File.join(config.root_path, 'tmp', 'config')
config.amqp_server_uri = 'amqp://localhost/'
end
end
end
end
|
require 'open-uri'
require 'mechanize'
require 'nokogiri'
module Waterworks
class Extractor
def initialize(url, store = '~/Downloads')
@agent = agent(url)
@store = File.expand_path(store)
end
def save
mkdir(save_to)
resources.each do |resource|
display_resource_info(resource)
system("wget -O '#{save_to}#{resource.destination}' '#{resource.source}'")
end
end
protected
def agent(url)
Nokogiri::HTML(open(url))
end
def save_to
"#{@store}/#{series}/#{season}"
end
# return the series name
def series; end
# return the season name
def season; end
# return the title
def title; end
# return the download file path list
def resources; end
def http_response_headers(uri, redirect_limit = 5)
raise ArgumentError, 'HTTP redirect too deep' if redirect_limit == 0
uri = URI.parse(uri)
headers = {}
Net::HTTP.start(uri.host) do |http|
headers = http.head(uri.path)
end
case headers
when Net::HTTPOK
headers
when Net::HTTPFound
uri = headers['Location']
http_response_headers(uri, redirect_limit - 1)
end
headers
end
private
def mkdir(path)
Dir.mkdir(path) unless File.directory?(path)
end
def display_resource_info(resource)
puts "Save to: #{save_to}#{resource.destination}"
puts " Source: #{resource.source}"
puts " Size: #{resource.size_mb} MB"
end
end
end
autoload extractors
require 'open-uri'
require 'mechanize'
require 'nokogiri'
module Waterworks
class Extractor
class << self
def matches(uri)
Dir.glob(extractor_file_paths).each do |file|
require file
klass = eval(filename_classify(File.basename(file, '.rb'))).new
next unless klass.match?(uri)
yield klass
end
end
def filename_classify(filename)
filename.split('_').map(&:capitalize).join
end
def extractor_file_paths
[
File.expand_path("#{ENV['HOME']}/.waterworks/extractors/*.rb"),
File.expand_path('./lib/waterworks/extractors/*.rb')
]
end
end
def initialize(store = '~/Downloads')
@store = File.expand_path(store)
end
def match?(uri)
uri =~ /#{domain}/
end
def save(uri)
@agent = agent(uri)
mkdir(save_to)
resources.each do |resource|
display_resource_info(resource)
system("wget -O '#{save_to}#{resource.destination}' '#{resource.source}'")
end
end
protected
def agent(url)
Nokogiri::HTML(open(url))
rescue Exception => e
abort e.to_s
end
def save_to
"#{@store}/#{series}/#{season}"
end
# return the domain
def domain; end
# return the series name
def series; end
# return the season name
def season; end
# return the title
def title; end
# return the download file path list
def resources; end
def http_response_headers(uri, redirect_limit = 5)
raise ArgumentError, 'HTTP redirect too deep' if redirect_limit == 0
uri = URI.parse(uri)
headers = {}
http_request.start(uri.host) do |http|
headers = http.head(uri.path)
end
case headers
when Net::HTTPOK
headers
when Net::HTTPFound
uri = headers['Location']
http_response_headers(uri, redirect_limit - 1)
end
headers
end
def http_request
proxy_uri = ENV['https_proxy'] || ENV['http_proxy'] || false
return Net::HTTP unless proxy_uri
proxy = URI.parse(proxy_uri)
Net::HTTP::Proxy(proxy.host, proxy.port)
end
private
def mkdir(path)
Dir.mkdir(path) unless File.directory?(path)
end
def display_resource_info(resource)
puts "Save to: #{save_to}#{resource.destination}"
puts " Source: #{resource.source}"
puts " Size: #{resource.size_mb} MB"
end
end
end
|
module WavesUtilities
class Task
def initialize(key)
@key = key.to_sym
end
def ==(other)
@key == other.to_sym
end
def description
Task.all_task_types.find { |t| t[1] == @key }[0]
end
def declarations_required_on_create?
[
:new_registration, :provisional, :re_registration, :renewal
].include?(@key)
end
def declarations_required_on_add_owner?
return true if declarations_required_on_create?
[:change_owner].include?(@key)
end
def electronic_delivery_available?
[:current_transcript, :historic_transcript].include?(@key)
end
def ownership_can_be_changed?
[
:new_registration, :provisional, :change_owner, :renewal,
:re_registration, :manual_override
].include?(@key)
end
def address_can_be_changed?
ownership_can_be_changed? || @key == :change_address
end
def vessel_can_be_edited?
[
:new_registration, :provisional, :change_vessel, :renewal,
:re_registration, :manual_override
].include?(@key)
end
def payment_required?
![
:change_address, :closure, :enquiry, :termination_notice,
:registrar_closure, :registrar_restores_closure, :issue_csr,
:manual_override].include?(@key)
end
def print_job_templates
if prints_certificate?
[:registration_certificate, :cover_letter]
elsif prints_provisional_certificate?
[:provisional_certificate, :cover_letter]
elsif prints_current_transcript?
[:current_transcript]
elsif prints_historic_transcript?
[:historic_transcript]
elsif @key == :issue_csr
[:csr_form]
elsif @key == :termination_notice
[:termination_notice]
end
end
def prints_certificate?
[
:new_registration, :change_owner, :change_vessel, :renewal,
:duplicate_certificate, :re_registration
].include?(@key)
end
def prints_provisional_certificate?
[:provisional].include?(@key)
end
def prints_current_transcript?
[:closure, :current_transcript].include?(@key)
end
def prints_historic_transcript?
[:historic_transcript].include?(@key)
end
def duplicates_certificate?
[:duplicate_certificate].include?(@key)
end
def renews_certificate?
[:change_owner, :change_vessel, :renewal, :re_registration]
.include?(@key)
end
def builds_registry?
[
:change_owner, :change_vessel, :change_address,
:re_registration, :new_registration, :provisional, :renewal,
:manual_override, :mortgage].include?(@key)
end
def builds_registration?
[
:change_owner, :change_vessel, :provisional,
:re_registration, :new_registration, :renewal].include?(@key)
end
def emails_application_approval?
[
:new_registration, :renewal, :re_registration, :provisional,
:change_owner, :change_vessel, :change_address,
:closure, :current_transcript, :historic_transcript,
:mortgage].include?(@key)
end
def emails_application_receipt?
[
:new_registration, :renewal, :re_registration, :provisional,
:change_owner, :change_vessel, :change_address,
:closure, :current_transcript, :historic_transcript,
:duplicate_certificate, :enquiry, :mortgage].include?(@key)
end
def referrable?
![:manual_override].include?(@key)
end
def issues_csr?
[:issue_csr].include?(@key)
end
class << self
def finance_task_types
all_task_types.delete_if do |t|
[:change_address, :closure, :enquiry].include?(t[1])
end
end
def default_task_types
all_task_types.delete_if { |t| t[1] == :unknown }
end
def govuk_task_types
[
:new_registration, :renewal, :change_owner,
:change_vessel, :change_address, :duplicate_certificate,
:current_transcript, :historic_transcript, :closure
]
end
def validation_helper_task_type_list
default_task_types.map { |t| t[1].to_s }
end
# rubocop:disable Metrics/MethodLength
def all_task_types
[
["New Registration", :new_registration],
["Provisional Registration", :provisional],
["Renewal of Registration", :renewal],
["Re-Registration", :re_registration],
["Change of Ownership", :change_owner],
["Change of Vessel details", :change_vessel],
["Change of Address", :change_address],
["Registration Closure", :closure],
["Current Transcript of Registry", :current_transcript],
["Historic Transcript of Registry", :historic_transcript],
["Duplicate Certificate", :duplicate_certificate],
["General Enquiry", :enquiry],
["Registration Closure: Owner Request", :registrar_closure],
["Registration Closure: Notice of Termination", :termination_notice],
["Registrar Restores Closure", :registrar_restores_closure],
["Mortgage(s)", :mortgage],
["Issue CSR", :issue_csr],
["Manual Override", :manual_override],
["Unknown", :unknown]]
end
end
end
end
Ensure registrar tools tasks are not in the default_task_types list
module WavesUtilities
class Task
def initialize(key)
@key = key.to_sym
end
def ==(other)
@key == other.to_sym
end
def description
Task.all_task_types.find { |t| t[1] == @key }[0]
end
def declarations_required_on_create?
[
:new_registration, :provisional, :re_registration, :renewal
].include?(@key)
end
def declarations_required_on_add_owner?
return true if declarations_required_on_create?
[:change_owner].include?(@key)
end
def electronic_delivery_available?
[:current_transcript, :historic_transcript].include?(@key)
end
def ownership_can_be_changed?
[
:new_registration, :provisional, :change_owner, :renewal,
:re_registration, :manual_override
].include?(@key)
end
def address_can_be_changed?
ownership_can_be_changed? || @key == :change_address
end
def vessel_can_be_edited?
[
:new_registration, :provisional, :change_vessel, :renewal,
:re_registration, :manual_override
].include?(@key)
end
def payment_required?
![
:change_address, :closure, :enquiry, :termination_notice,
:registrar_closure, :registrar_restores_closure, :issue_csr,
:manual_override].include?(@key)
end
def print_job_templates
if prints_certificate?
[:registration_certificate, :cover_letter]
elsif prints_provisional_certificate?
[:provisional_certificate, :cover_letter]
elsif prints_current_transcript?
[:current_transcript]
elsif prints_historic_transcript?
[:historic_transcript]
elsif @key == :issue_csr
[:csr_form]
elsif @key == :termination_notice
[:termination_notice]
end
end
def prints_certificate?
[
:new_registration, :change_owner, :change_vessel, :renewal,
:duplicate_certificate, :re_registration
].include?(@key)
end
def prints_provisional_certificate?
[:provisional].include?(@key)
end
def prints_current_transcript?
[:closure, :current_transcript].include?(@key)
end
def prints_historic_transcript?
[:historic_transcript].include?(@key)
end
def duplicates_certificate?
[:duplicate_certificate].include?(@key)
end
def renews_certificate?
[:change_owner, :change_vessel, :renewal, :re_registration]
.include?(@key)
end
def builds_registry?
[
:change_owner, :change_vessel, :change_address,
:re_registration, :new_registration, :provisional, :renewal,
:manual_override, :mortgage].include?(@key)
end
def builds_registration?
[
:change_owner, :change_vessel, :provisional,
:re_registration, :new_registration, :renewal].include?(@key)
end
def emails_application_approval?
[
:new_registration, :renewal, :re_registration, :provisional,
:change_owner, :change_vessel, :change_address,
:closure, :current_transcript, :historic_transcript,
:mortgage].include?(@key)
end
def emails_application_receipt?
[
:new_registration, :renewal, :re_registration, :provisional,
:change_owner, :change_vessel, :change_address,
:closure, :current_transcript, :historic_transcript,
:duplicate_certificate, :enquiry, :mortgage].include?(@key)
end
def referrable?
![:manual_override].include?(@key)
end
def issues_csr?
[:issue_csr].include?(@key)
end
class << self
def finance_task_types
all_task_types.delete_if do |t|
[:change_address, :closure, :enquiry].include?(t[1])
end
end
def default_task_types
all_task_types.delete_if do |t|
[
:registrar_closure, :termination_notice,
:registrar_restores_closure, :unknown
].include?(t[1])
end
end
def govuk_task_types
[
:new_registration, :renewal, :change_owner,
:change_vessel, :change_address, :duplicate_certificate,
:current_transcript, :historic_transcript, :closure
]
end
def validation_helper_task_type_list
all_task_types.map { |t| t[1].to_s }
end
# rubocop:disable Metrics/MethodLength
def all_task_types
[
["New Registration", :new_registration],
["Provisional Registration", :provisional],
["Renewal of Registration", :renewal],
["Re-Registration", :re_registration],
["Change of Ownership", :change_owner],
["Change of Vessel details", :change_vessel],
["Change of Address", :change_address],
["Registration Closure", :closure],
["Current Transcript of Registry", :current_transcript],
["Historic Transcript of Registry", :historic_transcript],
["Duplicate Certificate", :duplicate_certificate],
["General Enquiry", :enquiry],
["Registration Closure: Owner Request", :registrar_closure],
["Registration Closure: Notice of Termination", :termination_notice],
["Registrar Restores Closure", :registrar_restores_closure],
["Mortgage(s)", :mortgage],
["Issue CSR", :issue_csr],
["Manual Override", :manual_override],
["Unknown", :unknown]]
end
end
end
end
|
require 'spec_helper'
require 'tmpdir'
module Vim
module Flavor
describe LockFile do
around :each do |example|
Dir.mktmpdir do |tmp_path|
@tmp_path = tmp_path
example.run
end
end
def flavor(repo_name, locked_version)
f = Flavor.new()
f.repo_name = repo_name
f.locked_version = v(locked_version)
f
end
def v(s)
Version.create(s)
end
it 'has flavors sorted by repo_name' do
l = LockFile.new(@tmp_path.to_lockfile_path)
foo = flavor('foo', '1.2.3')
bar = flavor('bar', '2.3.4')
baz = flavor('baz', '3.4.5')
[foo, bar, baz].each do |f|
l.flavor_table[f.repo_name] = f
end
expect(l.flavors).to be == [bar, baz, foo]
end
describe '::serialize_lock_status' do
it 'converts a flavor into an array of lines' do
expect(
LockFile.serialize_lock_status(flavor('foo', '1.2.3'))
).to be == ['foo (1.2.3)']
end
end
describe '#load' do
it 'loads locked information from a lockfile' do
File.open(@tmp_path.to_lockfile_path, 'w') do |io|
io.write(<<-'END')
foo (1.2.3)
bar (2.3.4)
baz (3.4.5)
END
end
l = LockFile.new(@tmp_path.to_lockfile_path)
expect(l.flavor_table).to be_empty
l.load()
expect(l.flavor_table['foo'].repo_name).to be == 'foo'
expect(l.flavor_table['foo'].locked_version).to be == v('1.2.3')
expect(l.flavor_table['bar'].repo_name).to be == 'bar'
expect(l.flavor_table['bar'].locked_version).to be == v('2.3.4')
expect(l.flavor_table['baz'].repo_name).to be == 'baz'
expect(l.flavor_table['baz'].locked_version).to be == v('3.4.5')
end
end
describe '::load_or_new' do
it 'creates a new instance then loads a lockfile' do
File.open(@tmp_path.to_lockfile_path, 'w') do |io|
io.write(<<-'END')
foo (1.2.3)
END
end
l = LockFile.load_or_new(@tmp_path.to_lockfile_path)
expect(l.flavor_table['foo'].repo_name).to be == 'foo'
expect(l.flavor_table['foo'].locked_version).to be == v('1.2.3')
end
it 'only creates a new instance if a given path does not exist' do
l = LockFile.load_or_new(@tmp_path.to_lockfile_path)
expect(l.flavor_table).to be_empty
end
end
end
end
end
Refine a spec on LockFile#flavors
require 'spec_helper'
require 'tmpdir'
module Vim
module Flavor
describe LockFile do
around :each do |example|
Dir.mktmpdir do |tmp_path|
@tmp_path = tmp_path
example.run
end
end
def flavor(repo_name, locked_version)
f = Flavor.new()
f.repo_name = repo_name
f.locked_version = v(locked_version)
f
end
def v(s)
Version.create(s)
end
describe '#flavors' do
it 'is sorted by repo_name' do
l = LockFile.new(@tmp_path.to_lockfile_path)
foo = flavor('foo', '1.2.3')
bar = flavor('bar', '2.3.4')
baz = flavor('baz', '3.4.5')
[foo, bar, baz].each do |f|
l.flavor_table[f.repo_name] = f
end
expect(l.flavors).to be == [bar, baz, foo]
end
end
describe '::serialize_lock_status' do
it 'converts a flavor into an array of lines' do
expect(
LockFile.serialize_lock_status(flavor('foo', '1.2.3'))
).to be == ['foo (1.2.3)']
end
end
describe '#load' do
it 'loads locked information from a lockfile' do
File.open(@tmp_path.to_lockfile_path, 'w') do |io|
io.write(<<-'END')
foo (1.2.3)
bar (2.3.4)
baz (3.4.5)
END
end
l = LockFile.new(@tmp_path.to_lockfile_path)
expect(l.flavor_table).to be_empty
l.load()
expect(l.flavor_table['foo'].repo_name).to be == 'foo'
expect(l.flavor_table['foo'].locked_version).to be == v('1.2.3')
expect(l.flavor_table['bar'].repo_name).to be == 'bar'
expect(l.flavor_table['bar'].locked_version).to be == v('2.3.4')
expect(l.flavor_table['baz'].repo_name).to be == 'baz'
expect(l.flavor_table['baz'].locked_version).to be == v('3.4.5')
end
end
describe '::load_or_new' do
it 'creates a new instance then loads a lockfile' do
File.open(@tmp_path.to_lockfile_path, 'w') do |io|
io.write(<<-'END')
foo (1.2.3)
END
end
l = LockFile.load_or_new(@tmp_path.to_lockfile_path)
expect(l.flavor_table['foo'].repo_name).to be == 'foo'
expect(l.flavor_table['foo'].locked_version).to be == v('1.2.3')
end
it 'only creates a new instance if a given path does not exist' do
l = LockFile.load_or_new(@tmp_path.to_lockfile_path)
expect(l.flavor_table).to be_empty
end
end
end
end
end
|
Regenerate gemspec for version 0.0.1
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "typecollection"
s.version = "0.0.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["James Petty"]
s.date = "2012-01-10"
s.description = "Easily map subtypes into their parent type for later retrieval"
s.email = "jp@jibe.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/typecollection.rb",
"lib/typecollection/class+inferred_type.rb",
"lib/typecollection/class_methods.rb",
"test/helper.rb",
"test/test_typecollection.rb"
]
s.homepage = "http://github.com/pettyjamesm/TypeCollection"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.10"
s.summary = "TypeCollection maintains a record of sub-types for a given class based on a common suffix."
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_development_dependency(%q<rcov>, [">= 0"])
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
end
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<bundler>, ["~> 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
end
end
|
RSpec.describe Messages do
let(:messagable) { Class.new { include Messages }.new }
let(:outputting_message) { -> { message } }
describe '#inform_creation_of_social_media_links' do
let(:message) { messagable.inform_creation_of_social_media_links }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
describe '#inform_creation_of_employment_history' do
let(:message) { messagable.inform_creation_of_employment_history }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
describe '#inform_creation_of_education_history' do
let(:message) { messagable.inform_creation_of_education_history }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
end
Bring code coverage back up
RSpec.describe Messages do
let(:messagable) { Class.new { include Messages }.new }
let(:outputting_message) { -> { message } }
describe '#inform_creation_of_social_media_links' do
let(:message) { messagable.inform_creation_of_social_media_links }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
describe '#inform_creation_of_technical_skills' do
let(:message) { messagable.inform_creation_of_technical_skills }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
describe '#inform_creation_of_employment_history' do
let(:message) { messagable.inform_creation_of_employment_history }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
describe '#inform_creation_of_education_history' do
let(:message) { messagable.inform_creation_of_education_history }
it 'outputs a message to stdout' do
expect(outputting_message).to output.to_stdout
end
end
end
|
added organise controller, authorise method.
added ISO country codes and UN/LOCODEs.
{
:en => {
:hello => "Hello, world!",
:name => "Name",
:aliases => "Aliases",
:about_me => "About me",
:gender => "Gender",
:date_of_birth => "Date of Birth",
:country => "Country"
}
}
|
#
# Ruby Benchmark driver
#
require 'net/http'
require 'tempfile'
RAW_URL = 'https://raw.githubusercontent.com/ruby-bench/ruby-bench-suite/master/ruby/benchmarks/bm_'
first = true
begin
require 'optparse'
rescue LoadError
if first
first = false
$:.unshift File.join(File.dirname(__FILE__), '../lib')
retry
else
raise
end
end
require 'benchmark'
require 'pp'
class BenchmarkDriver
def self.benchmark(opt)
driver = self.new(opt[:execs], opt[:dir], opt)
begin
driver.run
ensure
driver.show_results
end
end
def output *args
puts(*args)
@output and @output.puts(*args)
end
def message *args
output(*args) if @verbose
end
def message_print *args
if @verbose
print(*args)
STDOUT.flush
@output and @output.print(*args)
end
end
def progress_message *args
unless STDOUT.tty?
STDERR.print(*args)
STDERR.flush
end
end
def initialize execs, dir, opt = {}
@execs = execs.map{|e|
e.strip!
next if e.empty?
if /(.+)::(.+)/ =~ e
# ex) ruby-a::/path/to/ruby-a
label = $1.strip
path = $2
version = `#{path} -v`.chomp
else
path = e
version = label = `#{path} -v`.chomp
end
[path, label, version]
}.compact
@dir = dir
@repeat = opt[:repeat] || 1
@repeat = 1 if @repeat < 1
@patterns = opt[:pattern] || []
@excludes = opt[:exclude] || []
@verbose = opt[:quiet] ? false : (opt[:verbose] || false)
@output = opt[:output] ? open(opt[:output], 'w') : nil
@rawdata_output = opt[:rawdata_output] ? open(opt[:rawdata_output], 'w') : nil
@loop_wl1 = @loop_wl2 = nil
@ruby_arg = opt[:ruby_arg] || nil
@opt = opt
# [[name, [[r-1-1, r-1-2, ...], [r-2-1, r-2-2, ...]]], ...]
@results = []
@memory_results = {}
if @verbose
@start_time = Time.now
message @start_time
@execs.each_with_index{|(path, label, version), i|
message "target #{i}: " + (label == version ? "#{label}" : "#{label} (#{version})") + " at \"#{path}\""
}
end
end
def adjusted_results name, results
results.first.map(&:to_f).min
end
def show_results
output
if @verbose
message '-----------------------------------------------------------'
message 'raw data:'
message
message PP.pp(@results, "", 79)
message
message "Elapsed time: #{Time.now - @start_time} (sec)"
end
if @rawdata_output
h = {}
h[:cpuinfo] = File.read('/proc/cpuinfo') if File.exist?('/proc/cpuinfo')
h[:executables] = @execs
h[:results] = @results
@rawdata_output.puts h.inspect
end
output '-----------------------------------------------------------'
output 'benchmark results:'
if @verbose and @repeat > 1
output "minimum results in each #{@repeat} measurements."
end
output "Execution time (sec)"
output "name\t#{@execs.map{|(_, v)| v}.join("\t")}"
@results.each{|v, result|
rets = adjusted_results(v, result)
http = Net::HTTP.new(ENV["API_URL"] || 'rubybench.org')
request = Net::HTTP::Post.new('/benchmark_runs')
request.basic_auth(ENV["API_NAME"], ENV["API_PASSWORD"])
initiator_hash = {}
if(ENV['RUBY_COMMIT_HASH'])
initiator_hash['commit_hash'] = ENV['RUBY_COMMIT_HASH']
elsif(ENV['RUBY_VERSION'])
initiator_hash['version'] = ENV['RUBY_VERSION']
end
request.set_form_data({
'benchmark_type[category]' => "#{v}_memory",
'benchmark_type[unit]' => 'kilobytes',
'benchmark_type[script_url]' => "#{RAW_URL}#{v}.rb",
"benchmark_run[result][rss_kb]" => rets,
'benchmark_run[environment]' => @execs.map { |(_,v)| v }.first,
'repo' => 'ruby',
'organization' => 'ruby'
}.merge(initiator_hash))
http.request(request)
output "Posting memory results to Web UI...."
}
if @opt[:output]
output
output "Log file: #{@opt[:output]}"
end
end
def files
flag = {}
@files = Dir.glob(File.join(@dir, 'bm*.rb')).map{|file|
next if !@patterns.empty? && /#{@patterns.join('|')}/ !~ File.basename(file)
next if !@excludes.empty? && /#{@excludes.join('|')}/ =~ File.basename(file)
case file
when /bm_(vm[12])_/, /bm_loop_(whileloop2?).rb/
flag[$1] = true
end
file
}.compact
if flag['vm1'] && !flag['whileloop']
@files << File.join(@dir, 'bm_loop_whileloop.rb')
elsif flag['vm2'] && !flag['whileloop2']
@files << File.join(@dir, 'bm_loop_whileloop2.rb')
end
@files.sort!
progress_message "total: #{@files.size * @repeat} trial(s) (#{@repeat} trial(s) for #{@files.size} benchmark(s))\n"
@files
end
def run
files.each_with_index{|file, i|
@i = i
r = measure_file(file)
if /bm_loop_whileloop.rb/ =~ file
@loop_wl1 = r[1].map{|e| e.min}
elsif /bm_loop_whileloop2.rb/ =~ file
@loop_wl2 = r[1].map{|e| e.min}
end
}
end
def measure_file file
name = File.basename(file, '.rb').sub(/^bm_/, '')
prepare_file = File.join(File.dirname(file), "prepare_#{name}.rb")
load prepare_file if FileTest.exist?(prepare_file)
result = [name]
result << @execs.map{|(e, v)|
(0...@repeat).map{
message_print "#{v}\t"
m = measure(e, file)
output "#{name}: rss_kb=#{m}"
m
}
}
@results << result
result
end
unless defined?(File::NULL)
if File.exist?('/dev/null')
File::NULL = '/dev/null'
end
end
def measure executable, file
cmd = "#{executable} #{@ruby_arg} #{file}"
begin
if !(file.match(/so_nsieve_bits/))
File.copy_stream(file, "#{file}.temp")
temp_file_read = File.open("#{file}.temp", 'r').read
if temp_file_read.match(/__END__/)
begin
temp = Tempfile.new("extract")
File.open(file, 'r').each do |line|
if line.match(/__END__/)
temp << "mem = `ps -o rss= -p \#\{$$\}`.to_i\nputs \"mem_result:\#\{mem\}\"\n__END__\n"
else
temp << line
end
end
ensure
temp.close
end
File.copy_stream(temp, file)
else
File.open(file, 'a') do |f|
f << "mem = `ps -o rss= -p \#\{$$\}`.to_i\n"
f << "puts \"mem_result:\#\{mem\}\""
end
end
end
memory = `#{cmd}`
ensure
if !(file.match(/so_nsieve_bits/))
File.copy_stream("#{file}.temp", file)
File.delete("#{file}.temp")
end
end
if $? != 0
output "\`#{cmd}\' exited with abnormal status (#{$?})"
0
else
memory.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') =~ /mem_result:(.+)\Z/
$1.to_f
end
end
end
if __FILE__ == $0
opt = {
:execs => [],
:dir => File.dirname(__FILE__),
:repeat => 1,
:output => "bmlog-#{Time.now.strftime('%Y%m%d-%H%M%S')}.#{$$}",
:raw_output => nil
}
parser = OptionParser.new{|o|
o.on('-e', '--executables [EXECS]',
"Specify benchmark one or more targets (e1::path1; e2::path2; e3::path3;...)"){|e|
e.split(/;/).each{|path|
opt[:execs] << path
}
}
o.on('-d', '--directory [DIRECTORY]', "Benchmark suites directory"){|d|
opt[:dir] = d
}
o.on('-p', '--pattern <PATTERN1,PATTERN2,PATTERN3>', "Benchmark name pattern"){|p|
opt[:pattern] = p.split(',')
}
o.on('-x', '--exclude <PATTERN1,PATTERN2,PATTERN3>', "Benchmark exclude pattern"){|e|
opt[:exclude] = e.split(',')
}
o.on('-r', '--repeat-count [NUM]', "Repeat count"){|n|
opt[:repeat] = n.to_i
}
o.on('-o', '--output-file [FILE]', "Output file"){|f|
opt[:output] = f
}
o.on('--ruby-arg [ARG]', "Optional argument for ruby"){|a|
opt[:ruby_arg] = a
}
o.on('--rawdata-output [FILE]', 'output rawdata'){|r|
opt[:rawdata_output] = r
}
o.on('-v', '--verbose'){|v|
opt[:verbose] = v
}
o.on('-q', '--quiet', "Run without notify information except result table."){|q|
opt[:quiet] = q
opt[:verbose] = false
}
}
parser.parse!(ARGV)
BenchmarkDriver.benchmark(opt)
end
Copy file before closing it.
Fixes: https://github.com/ruby-bench/ruby-bench-suite/issues/14.
#
# Ruby Benchmark driver
#
require 'net/http'
require 'tempfile'
RAW_URL = 'https://raw.githubusercontent.com/ruby-bench/ruby-bench-suite/master/ruby/benchmarks/bm_'
first = true
begin
require 'optparse'
rescue LoadError
if first
first = false
$:.unshift File.join(File.dirname(__FILE__), '../lib')
retry
else
raise
end
end
require 'benchmark'
require 'pp'
class BenchmarkDriver
def self.benchmark(opt)
driver = self.new(opt[:execs], opt[:dir], opt)
begin
driver.run
ensure
driver.show_results
end
end
def output *args
puts(*args)
@output and @output.puts(*args)
end
def message *args
output(*args) if @verbose
end
def message_print *args
if @verbose
print(*args)
STDOUT.flush
@output and @output.print(*args)
end
end
def progress_message *args
unless STDOUT.tty?
STDERR.print(*args)
STDERR.flush
end
end
def initialize execs, dir, opt = {}
@execs = execs.map{|e|
e.strip!
next if e.empty?
if /(.+)::(.+)/ =~ e
# ex) ruby-a::/path/to/ruby-a
label = $1.strip
path = $2
version = `#{path} -v`.chomp
else
path = e
version = label = `#{path} -v`.chomp
end
[path, label, version]
}.compact
@dir = dir
@repeat = opt[:repeat] || 1
@repeat = 1 if @repeat < 1
@patterns = opt[:pattern] || []
@excludes = opt[:exclude] || []
@verbose = opt[:quiet] ? false : (opt[:verbose] || false)
@output = opt[:output] ? open(opt[:output], 'w') : nil
@rawdata_output = opt[:rawdata_output] ? open(opt[:rawdata_output], 'w') : nil
@loop_wl1 = @loop_wl2 = nil
@ruby_arg = opt[:ruby_arg] || nil
@opt = opt
# [[name, [[r-1-1, r-1-2, ...], [r-2-1, r-2-2, ...]]], ...]
@results = []
@memory_results = {}
if @verbose
@start_time = Time.now
message @start_time
@execs.each_with_index{|(path, label, version), i|
message "target #{i}: " + (label == version ? "#{label}" : "#{label} (#{version})") + " at \"#{path}\""
}
end
end
def adjusted_results name, results
results.first.map(&:to_f).min
end
def show_results
output
if @verbose
message '-----------------------------------------------------------'
message 'raw data:'
message
message PP.pp(@results, "", 79)
message
message "Elapsed time: #{Time.now - @start_time} (sec)"
end
if @rawdata_output
h = {}
h[:cpuinfo] = File.read('/proc/cpuinfo') if File.exist?('/proc/cpuinfo')
h[:executables] = @execs
h[:results] = @results
@rawdata_output.puts h.inspect
end
output '-----------------------------------------------------------'
output 'benchmark results:'
if @verbose and @repeat > 1
output "minimum results in each #{@repeat} measurements."
end
output "Execution time (sec)"
output "name\t#{@execs.map{|(_, v)| v}.join("\t")}"
@results.each{|v, result|
rets = adjusted_results(v, result)
http = Net::HTTP.new(ENV["API_URL"] || 'rubybench.org')
request = Net::HTTP::Post.new('/benchmark_runs')
request.basic_auth(ENV["API_NAME"], ENV["API_PASSWORD"])
initiator_hash = {}
if(ENV['RUBY_COMMIT_HASH'])
initiator_hash['commit_hash'] = ENV['RUBY_COMMIT_HASH']
elsif(ENV['RUBY_VERSION'])
initiator_hash['version'] = ENV['RUBY_VERSION']
end
request.set_form_data({
'benchmark_type[category]' => "#{v}_memory",
'benchmark_type[unit]' => 'kilobytes',
'benchmark_type[script_url]' => "#{RAW_URL}#{v}.rb",
"benchmark_run[result][rss_kb]" => rets,
'benchmark_run[environment]' => @execs.map { |(_,v)| v }.first,
'repo' => 'ruby',
'organization' => 'ruby'
}.merge(initiator_hash))
http.request(request)
output "Posting memory results to Web UI...."
}
if @opt[:output]
output
output "Log file: #{@opt[:output]}"
end
end
def files
flag = {}
@files = Dir.glob(File.join(@dir, 'bm*.rb')).map{|file|
next if !@patterns.empty? && /#{@patterns.join('|')}/ !~ File.basename(file)
next if !@excludes.empty? && /#{@excludes.join('|')}/ =~ File.basename(file)
case file
when /bm_(vm[12])_/, /bm_loop_(whileloop2?).rb/
flag[$1] = true
end
file
}.compact
if flag['vm1'] && !flag['whileloop']
@files << File.join(@dir, 'bm_loop_whileloop.rb')
elsif flag['vm2'] && !flag['whileloop2']
@files << File.join(@dir, 'bm_loop_whileloop2.rb')
end
@files.sort!
progress_message "total: #{@files.size * @repeat} trial(s) (#{@repeat} trial(s) for #{@files.size} benchmark(s))\n"
@files
end
def run
files.each_with_index{|file, i|
@i = i
r = measure_file(file)
if /bm_loop_whileloop.rb/ =~ file
@loop_wl1 = r[1].map{|e| e.min}
elsif /bm_loop_whileloop2.rb/ =~ file
@loop_wl2 = r[1].map{|e| e.min}
end
}
end
def measure_file file
name = File.basename(file, '.rb').sub(/^bm_/, '')
prepare_file = File.join(File.dirname(file), "prepare_#{name}.rb")
load prepare_file if FileTest.exist?(prepare_file)
result = [name]
result << @execs.map{|(e, v)|
(0...@repeat).map{
message_print "#{v}\t"
m = measure(e, file)
output "#{name}: rss_kb=#{m}"
m
}
}
@results << result
result
end
unless defined?(File::NULL)
if File.exist?('/dev/null')
File::NULL = '/dev/null'
end
end
def measure executable, file
cmd = "#{executable} #{@ruby_arg} #{file}"
begin
if !(file.match(/so_nsieve_bits/))
File.copy_stream(file, "#{file}.temp")
temp_file_read = File.open("#{file}.temp", 'r').read
if temp_file_read.match(/__END__/)
begin
temp = Tempfile.new("extract")
File.open(file, 'r').each do |line|
if line.match(/__END__/)
temp << "mem = `ps -o rss= -p \#\{$$\}`.to_i\nputs \"mem_result:\#\{mem\}\"\n__END__\n"
else
temp << line
end
end
File.copy_stream(temp, file)
ensure
temp.close
end
else
File.open(file, 'a') do |f|
f << "mem = `ps -o rss= -p \#\{$$\}`.to_i\n"
f << "puts \"mem_result:\#\{mem\}\""
end
end
end
memory = `#{cmd}`
ensure
if !(file.match(/so_nsieve_bits/))
File.copy_stream("#{file}.temp", file)
File.delete("#{file}.temp")
end
end
if $? != 0
output "\`#{cmd}\' exited with abnormal status (#{$?})"
0
else
memory.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '') =~ /mem_result:(.+)\Z/
$1.to_f
end
end
end
if __FILE__ == $0
opt = {
:execs => [],
:dir => File.dirname(__FILE__),
:repeat => 1,
:output => "bmlog-#{Time.now.strftime('%Y%m%d-%H%M%S')}.#{$$}",
:raw_output => nil
}
parser = OptionParser.new{|o|
o.on('-e', '--executables [EXECS]',
"Specify benchmark one or more targets (e1::path1; e2::path2; e3::path3;...)"){|e|
e.split(/;/).each{|path|
opt[:execs] << path
}
}
o.on('-d', '--directory [DIRECTORY]', "Benchmark suites directory"){|d|
opt[:dir] = d
}
o.on('-p', '--pattern <PATTERN1,PATTERN2,PATTERN3>', "Benchmark name pattern"){|p|
opt[:pattern] = p.split(',')
}
o.on('-x', '--exclude <PATTERN1,PATTERN2,PATTERN3>', "Benchmark exclude pattern"){|e|
opt[:exclude] = e.split(',')
}
o.on('-r', '--repeat-count [NUM]', "Repeat count"){|n|
opt[:repeat] = n.to_i
}
o.on('-o', '--output-file [FILE]', "Output file"){|f|
opt[:output] = f
}
o.on('--ruby-arg [ARG]', "Optional argument for ruby"){|a|
opt[:ruby_arg] = a
}
o.on('--rawdata-output [FILE]', 'output rawdata'){|r|
opt[:rawdata_output] = r
}
o.on('-v', '--verbose'){|v|
opt[:verbose] = v
}
o.on('-q', '--quiet', "Run without notify information except result table."){|q|
opt[:quiet] = q
opt[:verbose] = false
}
}
parser.parse!(ARGV)
BenchmarkDriver.benchmark(opt)
end
|
# Improves on v3 by catching unnecessary concat in the case of very negative current state.
# Still always building the Add and Subtract
class Centipad
def initialize(min=1, max=9, equal=100, print=false)
@equal = equal
@print = print
@current_state = (min..max).to_a
@current_location = 1
@solutions = 0
@last_add = true
end
def solve()
beginning_time = Time.now
loop()
end_time = Time.now
puts @solutions.to_s
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
end
def loop()
if @current_location >= @current_state.size
# Evaluate and print
solution = @current_state.join()
if eval(solution) == @equal
puts solution if @print
@solutions += 1
end
return
else
concat = true
# If no + yet or the most recent is addition, current term should be no more than 100 larger than rest of remaining numbers (maybe ensure length before eval'ing?)
if @current_location > 1 && @current_location + 1 < @current_state.size
current_value = eval(@current_state[0,@current_location].join())
if @last_add == true && current_value > @current_state[@current_location+1, @current_state.size-1].join().to_i + @equal
concat = false
end
if @last_add == false && current_value < -(@current_state[@current_location+1, @current_state.size-1].join().to_i + @equal)
concat = false
end
end
# Concat Operation
if concat
@current_location += 1
loop()
@current_location -= 1
end
# Add Operation
@current_state.insert(@current_location, '+')
@current_location += 2
@last_add = true
loop()
@current_location -= 2
@current_state.delete_at(@current_location)
# Subtract Operation
@current_state.insert(@current_location, '-')
@current_location += 2
@last_add = false
loop()
@current_location -= 2
@current_state.delete_at(@current_location)
end
end
end
v5. Limit unnecessary Add and Subtract operations.
# Features:
# + Global object memory optimization (v2)
# + Concat limiting (v3, v4)
# + Add limiting (v5)
# + Subtract limiting (v5)
#
# Potential Improvements:
# - current_value not always available or may be evaluated too often
# - ditch eval() for faster expression evaluator (build one?)
# - change arguments to a params hash
class Centipad
def initialize(min=1, max=9, equal=100, print=false)
@equal = equal
@print = print
@current_state = (min..max).to_a
@current_location = 1
@solutions = 0
@last_add = true
end
def solve()
beginning_time = Time.now
loop()
end_time = Time.now
puts @solutions.to_s
puts "Time elapsed #{(end_time - beginning_time)*1000} milliseconds"
end
def loop()
if @current_location >= @current_state.size
# Evaluate and print
solution = @current_state.join()
if eval(solution) == @equal
puts solution if @print
@solutions += 1
end
return
else
# Concat limiting logic
concat = true
current_value = nil
# TODO: Revisit this if statement. Not sure about @current_state.size/2 being the optimal case.
if @current_location > @current_state.size/2 && @current_location + 1 < @current_state.size
current_value = eval(@current_state[0,@current_location].join())
# If no + yet or the most recent is addition, current term should be no more than 100 larger than rest of remaining numbers
if @last_add == true && current_value > @current_state[@current_location+1, @current_state.size-1].join().to_i + @equal
concat = false
end
if @last_add == false && current_value < -(@current_state[@current_location+1, @current_state.size-1].join().to_i + @equal)
concat = false
end
end
# Concat Operation
if concat
@current_location += 1
loop()
@current_location -= 1
end
# Add Operation
if current_value.nil? || current_value >= -(@current_state[@current_location, @current_state.size-1].join().to_i + @equal)
@current_state.insert(@current_location, '+')
@current_location += 2
@last_add = true
loop()
@current_location -= 2
@current_state.delete_at(@current_location)
end
# Subtract Operation
if current_value.nil? || current_value <= @current_state[@current_location, @current_state.size-1].join().to_i + @equal
@current_state.insert(@current_location, '-')
@current_location += 2
@last_add = false
loop()
@current_location -= 2
@current_state.delete_at(@current_location)
end
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ruby_svg_image_generator/version'
Gem::Specification.new do |spec|
spec.name = "ruby_svg_image_generator"
spec.version = RubySvgImageGenerator::VERSION
spec.authors = ["santiriera626" , "camumino", "franx0"]
spec.email = ["santiriera626@gmail.com", "camumino@gmail.com", "francisco.moya.martinez@gmail.com"]
spec.summary = %q{TODO: Write a short summary, because Rubygems requires one.}
spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency 'rspec', "~> 3.4.0"
spec.add_dependency "ruby_matrix_to_svg", "~> 0.0.1"
end
fix gemspec error to build travis
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ruby_svg_image_generator/version'
Gem::Specification.new do |spec|
spec.name = "ruby_svg_image_generator"
spec.version = RubySvgImageGenerator::VERSION
spec.authors = ["santiriera626" , "camumino", "franx0"]
spec.email = ["santiriera626@gmail.com", "camumino@gmail.com", "francisco.moya.martinez@gmail.com"]
spec.summary = "%q{TODO: Write a short summary, because Rubygems requires one.}"
spec.description = "%q{TODO: Write a longer description or delete this line"
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency 'rspec', "~> 3.4.0"
spec.add_dependency "ruby_matrix_to_svg", "~> 0.0.1"
end
|
require 'capistrano'
require 'capistrano_colors'
require 'bundler/capistrano'
require 'airbrake/capistrano'
module RPCapistrano
module Base
def self.load_into(configuration)
configuration.load do
after 'deploy:restart', 'deploy:cleanup'
before 'deploy:setup', 'rvm:create_gemset'
# User details
_cset :user, 'capi'
_cset(:group) { user }
_cset :sudo_user, 'www'
# Application details
_cset(:app_name) { abort "Please specify the short name of your application, set :app_name, 'foo'" }
set(:application) { app_name }
_cset :use_sudo, false
_cset(:passenger_user) { sudo_user }
_cset(:passenger_group) { sudo_user }
# SCM settings
set :deploy_to, "/var/www/#{app_name}"
_cset :scm, 'git'
set(:repository) { "git@nas01:#{app_name}" }
_cset :branch, $1 if `git branch` =~ /\* (\S+)\s/m
_cset :deploy_via, :remote_cache
set :ssh_options, { :forward_agent => true }
_cset :bundle_flags, "--deployment"
# Git settings for Capistrano
default_run_options[:pty] = true # needed for git password prompts
namespace :deploy do
task :start do ; end
task :stop do ; end
task :restart, :roles => :app, :except => { :no_release => true } do
run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
end
desc "Make sure local git is in sync with remote."
task :check_revision, roles: :web do
unless `git rev-parse HEAD` == `git rev-parse origin/#{branch}`
puts "WARNING: HEAD is not the same as origin/#{branch}"
puts "Run `git push` to sync changes."
exit
end
end
before "deploy", "deploy:check_revision"
end
end
end
end
end
if Capistrano::Configuration.instance
RPCapistrano::Base.load_into(Capistrano::Configuration.instance)
end
Fix remote caching issue to speed up deploys
require 'capistrano'
require 'capistrano_colors'
require 'bundler/capistrano'
require 'airbrake/capistrano'
module RPCapistrano
module Base
def self.load_into(configuration)
configuration.load do
after 'deploy:restart', 'deploy:cleanup'
before 'deploy:setup', 'rvm:create_gemset'
# User details
_cset :user, 'capi'
_cset(:group) { user }
_cset :sudo_user, 'www'
# Application details
_cset(:app_name) { abort "Please specify the short name of your application, set :app_name, 'foo'" }
set(:application) { app_name }
_cset :use_sudo, false
_cset(:passenger_user) { sudo_user }
_cset(:passenger_group) { sudo_user }
# SCM settings
set :deploy_to, "/var/www/#{app_name}"
set :scm, 'git'
set(:repository) { "git@nas01:#{app_name}" }
_cset :branch, $1 if `git branch` =~ /\* (\S+)\s/m
set :deploy_via, :remote_cache
set :ssh_options, { :forward_agent => true }
_cset :bundle_flags, "--deployment"
# Git settings for Capistrano
default_run_options[:pty] = true # needed for git password prompts
namespace :deploy do
task :start do ; end
task :stop do ; end
task :restart, :roles => :app, :except => { :no_release => true } do
run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
end
desc "Make sure local git is in sync with remote."
task :check_revision, roles: :web do
unless `git rev-parse HEAD` == `git rev-parse origin/#{branch}`
puts "WARNING: HEAD is not the same as origin/#{branch}"
puts "Run `git push` to sync changes."
exit
end
end
before "deploy", "deploy:check_revision"
end
end
end
end
end
if Capistrano::Configuration.instance
RPCapistrano::Base.load_into(Capistrano::Configuration.instance)
end
|
require File.join(File.dirname(__FILE__), 'selenium')
require File.join(File.dirname(__FILE__), 'exceptions')
# NOTE: Function names beginning with these words are forbidden:
#
# - check
# - ensure
# - reject
# - note
# - show
# - start
#
# This is because the above words are keywords in Slim script tables; if
# the first cell of a script table begins with any of these words, Slim tries
# to apply special handling to them, which usually doesn't do what you want.
module Rsel
class SeleniumTest
# Start up a test, connecting to the given Selenium server and opening
# a browser.
#
# @param [String] url
# Full URL, including http://, of the system under test
# @param [String] server
# IP address or hostname where selenium-server is running
# @param [String] port
# Port number of selenium-server
# @param [String] browser
# Which browser to test with
#
# @example
# | script | selenium test | http://site.to.test/ |
# | script | selenium test | http://site.to.test/ | 192.168.0.3 | 4445 |
#
def initialize(url, server='localhost', port='4444', browser='*firefox')
@selenium = Selenium::SeleniumDriver.new(server, port, browser, url)
end
# Start the Selenium session.
#
# @example
# | Open browser |
#
def open_browser
begin
@selenium.start
rescue
raise SeleniumNotRunning, "Could not start Selenium."
else
return true
end
end
# Close the browser window
#
# @example
# | Close browser |
#
def close_browser
@selenium.stop
return true
end
# ----------------------------------------
# Navigation
# ----------------------------------------
# Load an absolute URL or a relative path in the browser.
#
# @param [String] path_or_url
# Relative path or absolute URL to load
#
# @example
# | Visit | http://www.automation-excellence.com |
# | Visit | /software |
#
def visit(path_or_url)
@selenium.open(path_or_url)
return true
end
# Click the Back button to navigate to the previous page.
#
# @example
# | Click back |
#
def click_back
@selenium.go_back
return true
end
# Reload the current page.
#
# @example
# | refresh page |
#
def refresh_page
@selenium.refresh
return true
end
# ----------------------------------------
# Verification
# ----------------------------------------
# Ensure that the given text appears on the current page.
#
# @param [String] text
# Plain text that should be visible on the current page
#
# @example
# | Should see | Welcome, Marcus |
#
def should_see(text)
return @selenium.is_text_present(text)
end
# Ensure that the current page has the given title text.
#
# @param [String] title
# Text of the page title that you expect to see
#
# @example
# | Should see title | Our Homepage |
# | Should see | Our Homepage | title |
#
def should_see_title(title)
if @selenium.get_title == title then
return true
else
return false
end
end
# ----------------------------------------
# Entering text
# ----------------------------------------
# Type a value into the given field
#
# @param [String] text
# What to type into the field
# @param [String] locator
# Locator string for the field you want to type into
#
# @example
# | Type | Dale | into field | First name |
# | Type | Dale | into | First name | field |
#
def type_into_field(text, locator)
@selenium.type(get_locator(locator, textFieldLocators), text)
return true
end
# ----------------------------------------
# Clicking things
# ----------------------------------------
# Click on a link.
#
# @param [String] locator
# Link text, or the id, name, or href of the anchor element
#
# @example
# | Click | Logout | link |
# | Click link | Logout |
#
def click_link(locator)
begin
@selenium.click(get_locator(locator, linkLocators))
rescue
@selenium.click("Link=#{locator}")
end
end
# Press a button.
#
# @param [String] locator
# Button text, or the id or name of the button/submit element
#
# @example
# | Click | Login | button |
# | Click button | Login |
#
def click_button(locator)
@selenium.click(get_locator(locator, buttonLocators))
end
# Check or uncheck a checkbox.
#
# @param [String] locator
# Label, id, or name of the checkbox to click
#
# @example
# | Click | Send me spam | checkbox |
# | Click checkbox | Send me spam |
#
def click_checkbox(locator)
@selenium.click(get_locator(locator, checkboxLocators))
end
# Click on an image.
#
# @param [String] locator
# The id, src, title, or href of the image to click on
#
# @example
# | Click | colorado.png | image |
# | Click image | colorado.png |
#
def click_image(locator)
@selenium.click(get_locator(locator, imageLocators))
end
# Click on a radiobutton.
#
# @param [String] locator
# Label, id, or name of the radiobutton to click
#
# @example
# | Click | female | radio |
# | Click radio | female |
def click_radio(locator)
@selenium.click(get_locator(locator, radioLocators))
end
# ----------------------------------------
# Waiting
# ----------------------------------------
# Pause for a certain number of seconds.
#
# @param [String, Int] seconds
# How many seconds to pause
#
# @example
# | Pause | 5 | seconds |
#
def pause_seconds(seconds)
sleep seconds.to_i
return true
end
# ----------------------------------------
# Form stuff
# ----------------------------------------
# Select a value from a dropdown/combo box.
#
# @param [String] value
# The value to choose from the dropdown
# @param [String] locator
# Dropdown locator
#
# @example
# | select | Tall | from | Height | dropdown |
# | select | Tall | from dropdown | Height |
#
def select_from_dropdown(value, locator)
# TODO: Provide xpaths for locator
@selenium.select(locator, value)
end
# Submit the form with the given name.
#
# @param [String] locator
# Form id, name or action
#
# @example
# | submit form | place_order |
# | submit | place_order | form |
#
def submit_form(locator)
@selenium.submit(get_locator(locator, formLocators))
end
# ----------------------------------------
# Miscellaneous
# ----------------------------------------
# Maximize the browser window. May not work in some browsers.
#
# @example
# | maximize window |
#
def maximize_window
@selenium.window_maximize
end
# Wait some number of seconds for the current page request to finish.
#
# @example
# | page reloads in less than | 10 | seconds |
#
def page_reloads_in_less_than_seconds(seconds)
return @selenium.wait_for_page_to_load(seconds + "000")
end
# ----------------------------------------
# Helper functions
# ----------------------------------------
def capitalizeEachWord(str)
return str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
end
def get_locator(caption, possibleFormats)
possibleCaptions = getPossibleCaptions(caption)
possibleCaptions.each do |possibleCaption|
possibleFormats.each do |possibleFormat|
locator = possibleFormat.sub('{0}', possibleCaption)
puts "possible locator: " + locator
if @selenium.is_element_present(locator)
return locator
end
end
end
raise LocatorNotFound, "Could not find locator '#{caption}'"
end
# possible variations on the caption to look for
def getPossibleCaptions(caption)
possibleCaptions = Array.new
possibleCaptions[0] = caption
possibleCaptions[1] = ' ' + caption
possibleCaptions[2] = caption + ' '
possibleCaptions[3] = capitalizeEachWord(caption)
possibleCaptions[4] = ' ' + capitalizeEachWord(caption)
possibleCaptions[5] = capitalizeEachWord(caption) + ' '
return possibleCaptions
end
def textFieldLocators
[
"xpath=//input[@type='text' and @name='{0}']",
"xpath=//input[@type='text' and @title='{0}']",
"xpath=//input[@type='password' and @name='{0}']",
"xpath=//textarea[@name='{0}']",
"xpath=//input[@type='text' and @id='{0}']",
"xpath=//input[@type='password' and @id='{0}']",
"xpath=//textarea[@id='{0}']",
]
end
def buttonLocators
[
"xpath=//input[@type='submit' and @name='{0}']",
"xpath=//input[@type='button' and @name='{0}']",
"xpath=//input[@type='submit' and @value='{0}']",
"xpath=//input[@type='button' and @value='{0}']",
"xpath=//input[@type='submit' and @id='{0}']",
"xpath=//input[@type='button' and @id='{0}']",
]
end
def checkboxLocators
[
"xpath=//input[@type='checkbox' and @name='{0}']",
"xpath=//span[@id='{0}']/span/button",
"xpath=//span[@type='checkbox' and @id='{0}']/span/button",
"xpath=//input[@type='checkbox' and @label[text()='{0}']]",
"xpath=//input[@type='checkbox' and @id=(//label[text()='{0}']/@for)]",
]
end
#added 7/1/08 -Dale; bug fix 7/7
def radioLocators
[
"xpath=//input[@type='radio' and @name='{0}']",
"xpath=//input[@type='radio' and @id='{0}']",
"xpath=//input[@type='radio' and @label[text()='{0}']]",
"xpath=//input[@type='radio' and @id=(//label[text()=' {0}']/@for)]",
"xpath=//input[@type='radio' and @id=(//label[text()='{0} ']/@for)]",
"xpath=//input[@type='radio' and @id=(//label[text()='{0}']/@for)]",
]
end
# added 2nd and 3rd xpaths because leading or trailing space may exist for the text of links
# added title and class 7/9 -Dale
def linkLocators
[
"xpath=//a[text()='{0}']",
"xpath=//a[text()=' {0}']",
"xpath=//a[text()='{0} ']",
"xpath=//a[@href='{0}']",
"xpath=//a[@title='{0}']",
"xpath=//a[@class='{0}']",
]
end
# added to verify image elements -Dale
def imageLocators
[
"xpath=//img[@alt='{0}']",
"xpath=//img[@title='{0}']",
"xpath=//img[@id='{0}']",
"xpath=//img[@href='{0}']",
"xpath=//img[@src='{0}']",
"xpath=//input[@type='image' and @src='{0}']",
"xpath=//input[@type='image' and @id='{0}']",
"xpath=//input[@type='image' and @alt='{0}']",
]
end
#added 7/8 -Dale
def formLocators
[
"xpath=//form[@action='{0}']",
"xpath=//form[@class='{0}']",
"xpath=//form[@name='{0}']",
"xpath=//form[@legend[text()='{0}']]",
]
end
# added 7/8 -Dale
def dragdropLocators
[
"xpath=//div[@id='{0}']",
"xpath=//img[@alt='{0}']",
"xpath=//img[@src='{0}']",
]
end
#added 7/8 -Dale (use locator and offset e.g., "+70, -300"
# Sample Call-> |UserDrags|slider name|AndDrops|-10, 0|
def UserDragsAndDrops(selenium,params)
selenium.drag_and_drop(get_locator(selenium,params[0],dragdropLocators), params[1])
end
# Sample Call-> |VerifyText|my image|
def VerifyImage(selenium,params)
if selenium.is_element_present(get_locator(selenium,params[0],imageLocators)) then
return "right"
else
return "wrong"
end
end
# Sample Call-> |WaitUpTo|30|SecondsToVerifyImage|my image|
def WaitUpToSecondsToVerifyImage(selenium,params)
count=0
retval = "wrong"
while (count<params[0].to_i)
if selenium.is_element_present(get_locator(selenium,params[1],imageLocators)) then
retval = "right"
break
end
sleep 1
count=count+1
end
return retval
end
#added return value for text found or not - 6/26/08
# Sample Call-> |WaitUpTo|30|SecondsToVerifyText|my text|
def WaitUpToSecondsToVerifyText(selenium,params)
count=0
retval = "wrong"
while (count<params[0].to_i)
if selenium.is_text_present(params[1]) then
retval = "right"
break
end
sleep 1
count=count+1
end
return retval
end
####################################################
#DEBUG - all functions after this point are in a debug state - Dale
####################################################
def ChooseOKNextConfirmation(selenium,params)
selenium.choose_ok_on_next_confirmation
end
def ChooseCancelNextConfirmation(selenium,params)
selenium.choose_cancel_on_next_confirmation
end
#-need to add functionality to select window before closing
def CloseWindow(selenium,params)
selenium.close
end
def SelectWindow(selenium,params)
windowIDs=selenium.get_all_window_ids()
windowIDs.each{|id| puts "id="+id}
windowNames=selenium.get_all_window_names()
windowNames.each{|name| puts "name="+name}
windowTitles=selenium.get_all_window_titles()
windowTitles.each{|title| puts "title="+title}
selenium.select_window(params[0])
end
def FocusWindow(selenium,params)
selenium.window_focus()
end
def OpenURLOnWindow(selenium,params)
selenium.open_window(params[0],params[1])
end
#def GetAllLinks(selenium,params)
# return selenium.get_all_links
#end
#def GetTitle(selenium,params)
# return selenium.get_title
# #return get_string_array("getAllLinks", [])
#end
end
end
Use more XPath, exception handling
require File.join(File.dirname(__FILE__), 'selenium')
require File.join(File.dirname(__FILE__), 'exceptions')
require 'xpath'
# NOTE: Function names beginning with these words are forbidden:
#
# - check
# - ensure
# - reject
# - note
# - show
# - start
#
# This is because the above words are keywords in Slim script tables; if
# the first cell of a script table begins with any of these words, Slim tries
# to apply special handling to them, which usually doesn't do what you want.
module Rsel
class SeleniumTest
# Start up a test, connecting to the given Selenium server and opening
# a browser.
#
# @param [String] url
# Full URL, including http://, of the system under test
# @param [String] server
# IP address or hostname where selenium-server is running
# @param [String] port
# Port number of selenium-server
# @param [String] browser
# Which browser to test with
#
# @example
# | script | selenium test | http://site.to.test/ |
# | script | selenium test | http://site.to.test/ | 192.168.0.3 | 4445 |
#
def initialize(url, server='localhost', port='4444', browser='*firefox')
@selenium = Selenium::SeleniumDriver.new(server, port, browser, url)
end
# Start the Selenium session.
#
# @example
# | Open browser |
#
def open_browser
begin
@selenium.start
rescue
raise SeleniumNotRunning, "Could not start Selenium."
else
return true
end
end
# Close the browser window
#
# @example
# | Close browser |
#
def close_browser
@selenium.stop
return true
end
# ----------------------------------------
# Navigation
# ----------------------------------------
# Load an absolute URL or a relative path in the browser.
#
# @param [String] path_or_url
# Relative path or absolute URL to load
#
# @example
# | Visit | http://www.automation-excellence.com |
# | Visit | /software |
#
def visit(path_or_url)
@selenium.open(path_or_url)
return true
end
# Click the Back button to navigate to the previous page.
#
# @example
# | Click back |
#
def click_back
@selenium.go_back
return true
end
# Reload the current page.
#
# @example
# | refresh page |
#
def refresh_page
@selenium.refresh
return true
end
# ----------------------------------------
# Verification
# ----------------------------------------
# Ensure that the given text appears on the current page.
#
# @param [String] text
# Plain text that should be visible on the current page
#
# @example
# | Should see | Welcome, Marcus |
#
def should_see(text)
return @selenium.is_text_present(text)
end
# Ensure that the current page has the given title text.
#
# @param [String] title
# Text of the page title that you expect to see
#
# @example
# | Should see title | Our Homepage |
# | Should see | Our Homepage | title |
#
def should_see_title(title)
if @selenium.get_title == title then
return true
else
return false
end
end
# ----------------------------------------
# Entering text
# ----------------------------------------
# Type a value into the given field
#
# @param [String] text
# What to type into the field
# @param [String] locator
# Locator string for the field you want to type into
#
# @example
# | Type | Dale | into field | First name |
# | Type | Dale | into | First name | field |
#
def type_into_field(text, locator)
field_xpath = XPath::HTML.field(locator)
begin
@selenium.type("xpath=#{field_xpath}", text)
rescue
raise LocatorNotFound, "Could not find field with locator '#{locator}'"
else
return true
end
end
# ----------------------------------------
# Clicking things
# ----------------------------------------
# Click on a link.
#
# @param [String] locator
# Link text, or the id, name, or href of the anchor element
#
# @example
# | Click | Logout | link |
# | Click link | Logout |
#
def click_link(locator)
link_xpath = XPath::HTML.link(locator).to_s
begin
@selenium.click("xpath=#{link_xpath}")
rescue
raise LocatorNotFound, "Could not find link with locator '#{locator}'"
else
return true
end
end
# Press a button.
#
# @param [String] locator
# Button text, or the id or name of the button/submit element
#
# @example
# | Click | Login | button |
# | Click button | Login |
#
def click_button(locator)
button_xpath = XPath::HTML.button(locator).to_s
begin
@selenium.click("xpath=#{button_xpath}")
rescue
raise LocatorNotFound, "Could not find button with locator '#{locator}'"
else
return true
end
end
# Enable (check) a checkbox.
#
# @param [String] locator
# Label, id, or name of the checkbox to check
#
# @example
# | Enable | Send me spam | checkbox |
# | Enable checkbox | Send me spam |
#
def enable_checkbox(locator)
checkbox_xpath = XPath::HTML.checkbox(locator)
begin
@selenium.check("xpath=#{checkbox_xpath}")
rescue
raise LocatorNotFound, "Could not find checkbox with locator '#{locator}'"
else
return true
end
end
# Disable (uncheck) a checkbox.
#
# @param [String] locator
# Label, id, or name of the checkbox to uncheck
#
# @example
# | Disable | Send me spam | checkbox |
# | Disable checkbox | Send me spam |
#
def disable_checkbox(locator)
checkbox_xpath = XPath::HTML.checkbox(locator)
begin
@selenium.uncheck("xpath=#{checkbox_xpath}")
rescue
raise LocatorNotFound, "Could not find checkbox with locator '#{locator}'"
else
return true
end
end
# Click on an image.
#
# @param [String] locator
# The id, src, title, or href of the image to click on
#
# @example
# | Click | colorado.png | image |
# | Click image | colorado.png |
#
def click_image(locator)
@selenium.click(get_locator(locator, imageLocators))
end
# Click on a radiobutton.
#
# @param [String] locator
# Label, id, or name of the radiobutton to click
#
# @example
# | Click | female | radio |
# | Click radio | female |
def click_radio(locator)
@selenium.click(get_locator(locator, radioLocators))
end
# ----------------------------------------
# Waiting
# ----------------------------------------
# Pause for a certain number of seconds.
#
# @param [String, Int] seconds
# How many seconds to pause
#
# @example
# | Pause | 5 | seconds |
#
def pause_seconds(seconds)
sleep seconds.to_i
return true
end
# ----------------------------------------
# Form stuff
# ----------------------------------------
# Select a value from a dropdown/combo box.
#
# @param [String] value
# The value to choose from the dropdown
# @param [String] locator
# Dropdown locator
#
# @example
# | select | Tall | from | Height | dropdown |
# | select | Tall | from dropdown | Height |
#
def select_from_dropdown(value, locator)
# TODO: Provide xpaths for locator
@selenium.select(locator, value)
end
# Submit the form with the given name.
#
# @param [String] locator
# Form id, name or action
#
# @example
# | submit form | place_order |
# | submit | place_order | form |
#
def submit_form(locator)
@selenium.submit(get_locator(locator, formLocators))
end
# ----------------------------------------
# Miscellaneous
# ----------------------------------------
# Maximize the browser window. May not work in some browsers.
#
# @example
# | maximize window |
#
def maximize_window
@selenium.window_maximize
end
# Wait some number of seconds for the current page request to finish.
#
# @example
# | page reloads in less than | 10 | seconds |
#
def page_reloads_in_less_than_seconds(seconds)
return @selenium.wait_for_page_to_load(seconds + "000")
end
# ----------------------------------------
# Helper functions
# ----------------------------------------
def capitalizeEachWord(str)
return str.gsub(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
end
def get_locator(caption, possibleFormats)
possibleCaptions = getPossibleCaptions(caption)
possibleCaptions.each do |possibleCaption|
possibleFormats.each do |possibleFormat|
locator = possibleFormat.sub('{0}', possibleCaption)
puts "possible locator: " + locator
if @selenium.is_element_present(locator)
return locator
end
end
end
raise LocatorNotFound, "Could not find locator '#{caption}'"
end
# possible variations on the caption to look for
def getPossibleCaptions(caption)
possibleCaptions = Array.new
possibleCaptions[0] = caption
possibleCaptions[1] = ' ' + caption
possibleCaptions[2] = caption + ' '
possibleCaptions[3] = capitalizeEachWord(caption)
possibleCaptions[4] = ' ' + capitalizeEachWord(caption)
possibleCaptions[5] = capitalizeEachWord(caption) + ' '
return possibleCaptions
end
def textFieldLocators
[
"xpath=//input[@type='text' and @name='{0}']",
"xpath=//input[@type='text' and @title='{0}']",
"xpath=//input[@type='password' and @name='{0}']",
"xpath=//textarea[@name='{0}']",
"xpath=//input[@type='text' and @id='{0}']",
"xpath=//input[@type='password' and @id='{0}']",
"xpath=//textarea[@id='{0}']",
]
end
def buttonLocators
[
"xpath=//input[@type='submit' and @name='{0}']",
"xpath=//input[@type='button' and @name='{0}']",
"xpath=//input[@type='submit' and @value='{0}']",
"xpath=//input[@type='button' and @value='{0}']",
"xpath=//input[@type='submit' and @id='{0}']",
"xpath=//input[@type='button' and @id='{0}']",
]
end
def checkboxLocators
[
"xpath=//input[@type='checkbox' and @name='{0}']",
"xpath=//span[@id='{0}']/span/button",
"xpath=//span[@type='checkbox' and @id='{0}']/span/button",
"xpath=//input[@type='checkbox' and @label[text()='{0}']]",
"xpath=//input[@type='checkbox' and @id=(//label[text()='{0}']/@for)]",
]
end
#added 7/1/08 -Dale; bug fix 7/7
def radioLocators
[
"xpath=//input[@type='radio' and @name='{0}']",
"xpath=//input[@type='radio' and @id='{0}']",
"xpath=//input[@type='radio' and @label[text()='{0}']]",
"xpath=//input[@type='radio' and @id=(//label[text()=' {0}']/@for)]",
"xpath=//input[@type='radio' and @id=(//label[text()='{0} ']/@for)]",
"xpath=//input[@type='radio' and @id=(//label[text()='{0}']/@for)]",
]
end
# added 2nd and 3rd xpaths because leading or trailing space may exist for the text of links
# added title and class 7/9 -Dale
def linkLocators
[
"xpath=//a[text()='{0}']",
"xpath=//a[text()=' {0}']",
"xpath=//a[text()='{0} ']",
"xpath=//a[@href='{0}']",
"xpath=//a[@title='{0}']",
"xpath=//a[@class='{0}']",
]
end
# added to verify image elements -Dale
def imageLocators
[
"xpath=//img[@alt='{0}']",
"xpath=//img[@title='{0}']",
"xpath=//img[@id='{0}']",
"xpath=//img[@href='{0}']",
"xpath=//img[@src='{0}']",
"xpath=//input[@type='image' and @src='{0}']",
"xpath=//input[@type='image' and @id='{0}']",
"xpath=//input[@type='image' and @alt='{0}']",
]
end
#added 7/8 -Dale
def formLocators
[
"xpath=//form[@action='{0}']",
"xpath=//form[@class='{0}']",
"xpath=//form[@name='{0}']",
"xpath=//form[@legend[text()='{0}']]",
]
end
# added 7/8 -Dale
def dragdropLocators
[
"xpath=//div[@id='{0}']",
"xpath=//img[@alt='{0}']",
"xpath=//img[@src='{0}']",
]
end
#added 7/8 -Dale (use locator and offset e.g., "+70, -300"
# Sample Call-> |UserDrags|slider name|AndDrops|-10, 0|
def UserDragsAndDrops(selenium,params)
selenium.drag_and_drop(get_locator(selenium,params[0],dragdropLocators), params[1])
end
# Sample Call-> |VerifyText|my image|
def VerifyImage(selenium,params)
if selenium.is_element_present(get_locator(selenium,params[0],imageLocators)) then
return "right"
else
return "wrong"
end
end
# Sample Call-> |WaitUpTo|30|SecondsToVerifyImage|my image|
def WaitUpToSecondsToVerifyImage(selenium,params)
count=0
retval = "wrong"
while (count<params[0].to_i)
if selenium.is_element_present(get_locator(selenium,params[1],imageLocators)) then
retval = "right"
break
end
sleep 1
count=count+1
end
return retval
end
#added return value for text found or not - 6/26/08
# Sample Call-> |WaitUpTo|30|SecondsToVerifyText|my text|
def WaitUpToSecondsToVerifyText(selenium,params)
count=0
retval = "wrong"
while (count<params[0].to_i)
if selenium.is_text_present(params[1]) then
retval = "right"
break
end
sleep 1
count=count+1
end
return retval
end
####################################################
#DEBUG - all functions after this point are in a debug state - Dale
####################################################
def ChooseOKNextConfirmation(selenium,params)
selenium.choose_ok_on_next_confirmation
end
def ChooseCancelNextConfirmation(selenium,params)
selenium.choose_cancel_on_next_confirmation
end
#-need to add functionality to select window before closing
def CloseWindow(selenium,params)
selenium.close
end
def SelectWindow(selenium,params)
windowIDs=selenium.get_all_window_ids()
windowIDs.each{|id| puts "id="+id}
windowNames=selenium.get_all_window_names()
windowNames.each{|name| puts "name="+name}
windowTitles=selenium.get_all_window_titles()
windowTitles.each{|title| puts "title="+title}
selenium.select_window(params[0])
end
def FocusWindow(selenium,params)
selenium.window_focus()
end
def OpenURLOnWindow(selenium,params)
selenium.open_window(params[0],params[1])
end
#def GetAllLinks(selenium,params)
# return selenium.get_all_links
#end
#def GetTitle(selenium,params)
# return selenium.get_title
# #return get_string_array("getAllLinks", [])
#end
end
end
|
require "listen"
module RSpecLive
class Watcher
def initialize(suite)
@suite = suite
end
def start
reset
Listen.to(Dir.pwd) do |updated, added, removed|
@suite.files_touched(updated + removed)
@suite.files_removed removed
inventory if added.any?
update
end.start
while perform_key_command; end
rescue Interrupt
end
private
def perform_key_command
key = STDIN.getc.chr.downcase
@suite.toggle_all if key == "a"
@suite.focus_next if key == "n"
return false if key == "q"
reset if key == "r"
@suite.cycle_verbosity if key == "v"
true
end
def reset
@suite.clear_status
inventory
update
end
def inventory
@suite.inventory
end
def update
@suite.update
end
end
end
Minor refactor of Watcher
require "listen"
module RSpecLive
class Watcher
def initialize(suite)
@suite = suite
end
def start
reset
Listen.to(Dir.pwd) do |updated, added, removed|
@suite.files_touched(updated + removed)
@suite.files_removed removed
@suite.inventory if added.any?
@suite.update
end.start
while perform_key_command; end
rescue Interrupt
end
private
def perform_key_command
key = STDIN.getc.chr.downcase
@suite.toggle_all if key == "a"
@suite.focus_next if key == "n"
return false if key == "q"
reset if key == "r"
@suite.cycle_verbosity if key == "v"
true
end
def reset
@suite.clear_status
@suite.inventory
@suite.update
end
end
end
|
# encoding: BINARY
# vim: ts=2 sts=2 sw=2 expandtab
def hex(s) s.nil? ? 'nil' : "[#{s.bytesize}]:#{s.bytes.map{|b|'%02X' % b}.join '.'}" end
def ansi(n, *args) args.each {|arg| puts "\x1B[#{n}m#{arg}\x1B[0m" }; end
def black(*args) ansi 30, *args; end
def red(*args) ansi 31, *args; end
def green(*args) ansi 32, *args; end
def brown(*args) ansi 33, *args; end
def yellow(*args) ansi 93, *args; end
def blue(*args) ansi 94, *args; end
def magenta(*args) ansi 35, *args; end
def cyan(*args) ansi 36, *args; end
def silver(*args) ansi 37, *args; end
def white(*args) ansi 97, *args; end
def flg(f)
s = "#{f.to_s 16}"
a = []
n = 1
while n <= f
if (f & n) == n
a << ('%02X' % n)
end
n <<= 1
end
"#{f.to_s 16}[#{a.join '|'}]"
end
def frm(f)
t = RUBYH2::FrameTypes.constants.find {|t| f.type == RUBYH2::FrameTypes.const_get(t) }
t ||= f.type
"<#{t}: flags=#{flg f.flags} stream=#{f.sid} payload=#{hex f.payload}>"
end
require 'thread'
require 'zlib'
require 'stringio'
require_relative 'frame-deserialiser'
require_relative 'frame-serialiser'
require_relative 'frame-types'
require_relative 'headers-hook'
require_relative 'settings'
require_relative 'errors'
require_relative 'hpack'
require_relative 'http-request'
require_relative 'http-response'
require_relative 'stream'
module RUBYH2
PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
class HTTPAgent
FLAG_END_STREAM = 0x1
FLAG_ACK = 0x1
FLAG_END_HEADERS = 0x4
FLAG_PADDED = 0x8
FLAG_PRIORITY = 0x20
include Error
def initialize is_server, logger
# machinery state
@is_server = is_server
@request_proc = nil
@response_proc = nil
@hook = HeadersHook.new
@hook.on_frame {|f| recv_frame f }
@hpack = HPack.new
@logger = logger
# H2 state
@window_queue = {}
@first_frame_in = true
@first_frame_out = true
@streams = {}
@default_window_size = 65535
@window_size = @default_window_size
@max_frame_size = 16384
@max_streams = nil
@push_to_peer = true
@ext__send_gzip = true # are we config'd to send gzip data?
@ext__peer_gzip = false # is peer config'd to accept gzip data?
@ext__recv_gzip = true # are we config'd to accept gzip data?
@ext__veto_gzip = false # set if peer doesn't gzip right
@ext__sent_dropped_frame = {}
@ext__peer_dropped_frame = {}
# other settings
@pings = []
@goaway = false
@last_stream = 0 # last incoming stream handed up to application
@shutting_down = false
@send_lock = Mutex.new
@shutdown_lock = Mutex.new
end
def inspect
"\#<HTTPAgent @window_queue=#{@window_queue.inspect}, @streams=#{@streams.inspect}, @default_window_size=#{@default_window_size.inspect}, @window_size=#{@window_size.inspect}, @max_frame_size=#{@max_frame_size.inspect}, @max_streams=#{@max_streams.inspect}, @push_to_peer=#{@push_to_peer.inspect}>"
end
attr_reader :push_to_peer
##
# Set the callback to be invoked when a HTTP request arrives.
#
def on_request &b
@request_proc = b
self
end
##
# Set the callback to be invoked when a HTTP response arrives.
#
def on_response &b
@response_proc = b
self
end
##
# wrap a TCPSocket
# e.g.:
#
# require 'socket'
# server = TCPServer.new 4567
# http_client.wrap server.accept
#
def wrap s
@sil = FrameSerialiser.new {|b|
cyan "@sil: _write #{hex b}"
_write s, b rescue nil }
dsil = FrameDeserialiser.new
dsil.on_frame {|f|
brown "dsil: received #{frm f}"
@hook << f }
handle_prefaces s
#send_frame Settings.frame_from({Settings::INITIAL_WINDOW_SIZE => 0x7fffffff, Settings::ACCEPT_GZIPPED_DATA => 1}), true
#send_frame Settings.frame_from({Settings::INITIAL_WINDOW_SIZE => 0x7fffffff}), true
send_frame Settings.frame_from({Settings::INITIAL_WINDOW_SIZE => 0x20000, Settings::MAX_FRAME_SIZE => dsil.max_frame_size, Settings::ACCEPT_GZIPPED_DATA => 1}), true
loop do
bytes = begin
s.readpartial(4*1024*1024)
rescue EOFError
nil
end
if bytes.nil? or bytes.empty?
if s.is_a? OpenSSL::SSL::SSLSocket
@logger.info "client disconnected from #{s.io.remote_address.inspect_sockaddr}"
else
@logger.info "client disconnected from #{s.remote_address.inspect_sockaddr}"
end
break
end
red "read #{hex bytes}"
dsil << bytes
Thread.pass
end
ensure
s.close rescue nil
end
##
# Shut down the connection.
def shut_down
@shutdown_lock.synchronize {
return if @shutting_down
@shutting_down = true
}
g = Frame.new FrameTypes::GOAWAY, 0x00, 0, [@last_stream,NO_ERROR].pack('NN')
send_frame g
end
##
# deliver HTTPMessage object
def deliver m
@shutdown_lock.synchronize {
raise "delivering message after GOAWAY" if @shutting_down # FIXME
}
blue "deliver #{m.inspect}"
# create headers
hblock = @hpack.create_block m.headers
# split header block into chunks and deliver
chunks = hblock.scan(/.{1,#{@max_frame_size}}/m).map{|c| {type: FrameTypes::CONTINUATION, flags: 0, bytes: c} }
if chunks.empty?
# I cast no judgement here, but shouldn't there be some headers..?
chunks << {type: FrameTypes::HEADERS, flags: FLAG_END_HEADERS, bytes: String.new.b}
else
chunks.first[:type] = FrameTypes::HEADERS
chunks.last[:flags] |= FLAG_END_HEADERS
end
# without data, the HEADERS ends the stream
if m.body.empty?
chunks.last[:flags] |= FLAG_END_STREAM
end
# pad out to %256 bytes if required
_pad chunks.last if m.pad?
# send the headers frame(s)
chunks.each do |chunk|
g = Frame.new chunk[:type], chunk[:flags], m.stream, chunk[:bytes]
send_frame g
end
# create data
if !m.body.empty?
chunks = []
if send_gzip?
type = FrameTypes::GZIPPED_DATA
bytes = m.body.b
until bytes.empty?
# binary search for biggest data chunk that fits when gzipped
left = 0
right = bytes.bytesize
maxright = right
best = nil
rest = bytes
loop do
gzipped = ''.b
gzip = Zlib::GzipWriter.new(StringIO.new gzipped)
gzip.write bytes[0...right]
gzip.close
rest = bytes[right..-1]
if gzipped.bytesize > @max_frame_size
# try a smaller sample
maxright = right
right = maxright - (maxright - left) / 2
# is this a good as we'll get?
break if right == left
elsif gzipped.bytesize == @max_frame_size
# perfect!
best = gzipped
break
else
# try a bigger sample
best = gzipped
left = right
right = maxright - (maxright - left) / 2
# is this a good as we'll get?
break if right == left
end
end
bytes = rest
# create chunk
chunk = {flags: 0, bytes: best}
# pad out to %256 bytes if required
_pad chunk if m.pad?
# add to list
chunks << chunk
end
else
type = FrameTypes::DATA
chunks = m.body.b.scan(/.{1,#{@max_frame_size}}/m).map{|c| {flags: 0, bytes: c} }
# pad out to %256 bytes if required
_pad chunks.last if m.pad?
end
chunks.last[:flags] |= FLAG_END_STREAM
chunks.each do |chunk|
g = Frame.new type, chunk[:flags], m.stream, chunk[:bytes]
send_frame g
end
end
# half-close
@streams[m.stream].close_local!
end
##
# send a PING message
def ping message=nil
if message
message = (message.to_s.b + (0.chr * 8)).slice(0, 8)
else
now = Time.now
message = [now.to_i, now.usec].pack('NN')
end
@pings << message
g = Frame.new FrameTypes::PING, 0, 0, message
send_frame g
end
# returns truthy if the given frame carries HTTP semantics
# (so has to be sent in order)
def semantic_frame? f
f.type == FrameTypes::DATA || f.type == FrameTypes::HEADERS || f.type == FrameTypes::CONTINUATION || f.type == FrameTypes::GZIPPED_DATA
end
# Are we configured to accept GZIPPED_DATA frames from this peer?
# Takes into account peer's apparent ability to correctly send gzip.
def accept_gzip?
return if @ext__veto_gzip
@ext__recv_gzip
end
# tell the peer we'll accept GZIPPED_DATA frames
def accept_gzip!
return if @ext__veto_gzip
if !@ext__recv_gzip
send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})
@ext__recv_gzip = true
end
end
# tell the peer we don't accept GZIPPED_DATA frames
def no_accept_gzip!
return if @ext__veto_gzip
if @ext__recv_gzip
send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})
@ext__recv_gzip = false
end
end
# Are we configured to send GZIPPED_DATA frames to this peer?
# Takes into account peer's settings for receiving them.
def send_gzip?
return if !@ext__peer_gzip
@ext__send_gzip
end
# application lets us send GZIPPED_DATA frames to this peer
def send_gzip!
if !@ext__send_gzip
@ext__send_gzip = true
end
end
# application won't let us send GZIPPED_DATA frames to this peer
def no_send_gzip!
if @ext__send_gzip
@ext__send_gzip = false
end
end
private
def veto_gzip!
return if @ext__veto_gzip
if @ext__recv_gzip
send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})
@ext__veto_gzip = true
end
end
def _pad hash, modulus=256
len = hash[:bytes].bytesize
rem = (modulus - (len % modulus)) - 1
# don't overflow the frame!
if len + rem > @max_frame_size
rem = @max_frame_size - len - 1
end
if rem >= 0
padlen = [rem].pack('C')
padding = ''
padding = [0].pack('C') * rem if rem > 0
hash[:flags] |= FLAG_PADDED
hash[:bytes] = padlen + hash[:bytes] + padding
end
hash
end
def _write sock, bytes
bytes.force_encoding Encoding::BINARY
#sock.print bytes
until bytes.empty?
sent = sock.write bytes
#sent = sock.send bytes, 0
bytes = bytes[sent..-1]
end
#sock.flush
end
def handle_prefaces s
if @is_server
preface = String.new.b
while preface.length < 24
preface << s.readpartial(24 - preface.length)
end
raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface') if preface != PREFACE
else
_write s, PREFACE
end
end
def send_frame g, is_first_settings=false
if is_first_settings
# Unset @first_frame_out and transmit said first frame, atomically
@send_lock.synchronize do
@first_frame_out = false
_do_send_frame g
end
else
# FIXME: this is horrible
# Spin-lock on @first_frame_out being unset.
# Note that writes to @first_frame_out are sync'd by @send_lock
wait = false
@send_lock.synchronize { wait = @first_frame_out }
while wait
sleep 0.1
@send_lock.synchronize { wait = @first_frame_out }
end
# Actually transmit the frame, atomically.
@send_lock.synchronize do
_do_send_frame g
end
end
end
def _do_send_frame g
if !semantic_frame? g
@sil << g
elsif g.sid == 0
# FIXME: assumes .type != DATA, etc.
@sil << g
else
s = @streams[g.sid]
s = @streams[g.sid] = Stream.new(@default_window_size) if !s
q = @window_queue[g.sid]
if q && !q.empty?
# there's a queue; wait for a WINDOW_UPDATE
q << g
elsif g.type == FrameTypes::DATA
b = g.payload_size
if @window_size >= b && s.window_size >= b
@window_size -= b
s.window_size -= b
@sil << g
else
@window_queue[g.sid] ||= []
@window_queue[g.sid] << g
end
else
@sil << g
end
end
end
# triggered when a new H2 frame arrives
def recv_frame f
if @first_frame_in
# first frame has to be settings
# FIXME: make sure this is the actual settings, not the ACK to ours
raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface - no SETTINGS') if f.type != FrameTypes::SETTINGS
@first_frame_in = false
end
if @goaway
case f.type
when FrameTypes::DATA
when FrameTypes::HEADERS
when FrameTypes::PUSH_PROMISE
when FrameTypes::CONTINUATION
else
# FIXME
@logger.warn "Ignoring frame 0x#{f.type.to_s 16} after GOAWAY"
return
end
end
case f.type
when FrameTypes::DATA
handle_data f
when FrameTypes::HEADERS
handle_headers f
when FrameTypes::PRIORITY
# TODO
when FrameTypes::RST_STREAM
# TODO
when FrameTypes::SETTINGS
handle_settings f
when FrameTypes::PUSH_PROMISE
# TODO
when FrameTypes::PING
handle_ping f
when FrameTypes::GOAWAY
handle_goaway f
when FrameTypes::WINDOW_UPDATE
handle_window_update f
when FrameTypes::CONTINUATION
# never emitted by the Hook
raise 'unexpected CONTINUATION frame'
# EXTENSION FRAME HANDLING
when FrameTypes::GZIPPED_DATA
handle_gzipped_data f
when FrameTypes::DROPPED_FRAME
handle_dropped_frame f
else
# ignore unrecognised/extension frames
drop_frame f
end
end
# tell the peer we ignored it
def drop_frame f
if !@ext__sent_dropped_frame[f.type]
@ext__sent_dropped_frame[f.type] = true
g = Frame.new FrameTypes::DROPPED_FRAME, 0x00, 0, [f.type].pack('C')
send_frame g
end
end
def handle_dropped_frame f
raise ConnectionError.new(PROTOCOL_ERROR, "DROPPED_FRAME must be sent on stream 0, received #{f.sid}") if f.sid != 0
raise ConnectionError.new(PROTOCOL_ERROR, "DROPPED_FRAME payload must be exactly 1 byte, received #{f.payload.bytesize}") if f.payload.bytesize != 1
type = f.payload.bytes.first
@logger.info "peer dropped extension frame type 0x#{type.to_s 16}"
@ext__peer_dropped_frame[type] = true
end
# triggered when a completed HTTP message arrives
# (farms it off to the registered callback)
def emit_message sid, stream
# NB: this function only invoked once we get an END_STREAM flag
stream.close_remote!
@last_stream = sid
# FIXME
headers = stream.headers
if @is_server
@request_proc.call HTTPRequest.new( sid, headers.delete(':method'), headers.delete(':path'), headers, stream.body )
else
@response_proc.call HTTPResponse.new( sid, headers.delete(':status'), headers, stream.body )
end
end
def strip_padding bytes
ints = bytes.bytes
pad_length = ints.shift
rst_length = ints.length
raise ConnectionError.new(PROTOCOL_ERROR, "Pad Length #{pad_length} exceeds frame payload size #{rst_length+1}") if pad_length > rst_length
ints[0...rst_length-pad_length].pack('C*')
end
def extract_priority bytes
stream, weight, bytes = bytes.unpack('NCa*')
exclusive = (stream & 0x80000000) == 0x80000000
stream &= 0x7fffffff
[{exclusive:exclusive, stream:stream, weight:weight}, bytes]
end
def handle_data f
raise ConnectionError.new(PROTOCOL_ERROR, "DATA must be sent on stream >0") if f.sid == 0
stream = @streams[f.sid]
raise SemanticError.new("DATA frame with invalid stream id #{f.sid}") unless stream
raise StreamError.new(STREAM_CLOSED, "DATA frame received on (half-)closed stream #{f.sid}") unless stream.open_remote?
return if @goaway
bytes = f.payload
bytes = strip_padding(bytes) if f.flag? FLAG_PADDED
# never run out of window space
g = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, 0, [bytes.bytesize].pack('N')
h = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, f.sid, [bytes.bytesize].pack('N')
send_frame g
send_frame h
stream << bytes
emit_message f.sid, stream if f.flag? FLAG_END_STREAM
end
def handle_gzipped_data f
#raise ConnectionError.new(PROTOCOL_ERROR, "GZIPPED_DATA cannot be sent without SETTINGS_ACCEPT_GZIP_DATA") unless accept_gzip
if !accept_gzip?
drop_frame f
return
end
raise ConnectionError.new(PROTOCOL_ERROR, "GZIPPED_DATA must be sent on stream >0") if f.sid == 0
stream = @streams[f.sid]
raise SemanticError.new("GZIPPED_DATA frame with invalid stream id #{f.sid}") unless stream
raise StreamError.new(STREAM_CLOSED, "GZIPPED_DATA frame received on (half-)closed stream #{f.sid}") unless stream.open_remote?
return if @goaway
bytes = f.payload
bytes = strip_padding(bytes) if f.flag? FLAG_PADDED
# never run out of window space
g = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, 0, [bytes.bytesize].pack('N')
send_frame g
inflated_bytes = nil
gunzip = Zlib::GzipReader.new(StringIO.new bytes)
begin
inflated_bytes = gunzip.read
rescue Zlib::Error => e
# bad gzip!
raise StreamError.new(DATA_ENCODING_ERROR, e.to_s)
ensure
veto_gzip! if inflated_bytes.nil?
end
# note: only update the frame window if gunzip succeeddededd
h = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, f.sid, [bytes.bytesize].pack('N')
send_frame h
stream << inflated_bytes
emit_message f.sid, stream if f.flag? FLAG_END_STREAM
end
def handle_headers f
stream = @streams[f.sid]
if stream
if @is_server
raise SemanticError.new("no END_STREAM on trailing headers") unless f.flag? FLAG_END_STREAM #FIXME: malformed => StreamError:PROTOCOL_ERROR ?
else
# FIXME: detect same thing on RESPONSE messages (server->client)
end
raise StreamError.new(STREAM_CLOSED, "HEADER frame received on (half-)closed stream #{f.sid}") unless stream.open_remote? # FIXME
else
raise ConnectionError.new(PROTOCOL_ERROR, "HEADERS must be sent on stream >0") if f.sid == 0
raise ConnectionError.new(PROTOCOL_ERROR, "new stream id #{f.sid} not greater than previous stream id #{@last_stream}") if f.sid <= @last_stream
if @is_server
raise ConnectionError.new(PROTOCOL_ERROR, "streams initiated by client must be odd, received #{f.sid}") if f.sid % 2 != 1
else
raise ConnectionError.new(PROTOCOL_ERROR, "streams initiated by server must be event, received #{f.sid}") if f.sid % 2 != 0
end
@streams[f.sid] = Stream.new(@default_window_size)
end
# read the header block
bytes = f.payload
bytes = strip_padding(bytes) if f.flag? FLAG_PADDED
priority, bytes = extract_priority(bytes) if f.flag? FLAG_PRIORITY
yellow "priority: #{priority.inspect}"
# TODO: handle priority?
@hpack.parse_block(bytes) do |k, v|
yellow " [#{k}]: [#{v}]"
@streams[f.sid][k] << v
end
yellow "--"
# if end-of-stream, emit the message
emit_message f.sid, @streams[f.sid] if !@goaway and f.flag? FLAG_END_STREAM
end
def handle_settings f
raise ConnectionError.new(PROTOCOL_ERROR, "SETTINGS must be sent on stream 0, received #{f.sid}") if f.sid != 0
if f.flag? FLAG_ACK
# TODO
else
hash = Settings.pairs_from(f)
hash.each_pair do |k, v|
case k
when Settings::HEADER_TABLE_SIZE
@hpack.max_size_out = v
when Settings::ENABLE_PUSH
raise ConnectionError.new(PROTOCOL_ERROR, "ENABLE_PUSH must be 0 or 1, received #{v}") unless v == 0 or v == 1 # FIXME
@push_to_peer = (v == 1)
when Settings::MAX_CONCURRENT_STREAMS
@max_streams = v
when Settings::INITIAL_WINDOW_SIZE
raise ConnectionError.new(FLOW_CONTROL_ERROR, "INITIAL_WINDOW_SIZE too large #{v}") if v > 0x7fffffff # FIXME
@default_window_size = v
when Settings::MAX_FRAME_SIZE
raise ConnectionError.new(PROTOCOL_ERROR, "MAX_FRAME_SIZE out of bounds #{v}") if v < 0x4000 or v > 0xffffff # FIXME
@max_frame_size = v
when Settings::MAX_HEADER_LIST_SIZE
# FIXME ???
when Settings::ACCEPT_GZIPPED_DATA
raise ConnectionError.new(PROTOCOL_ERROR, "ACCEPT_GZIPPED_DATA must be 0 or 1, received #{v}") unless v == 0 or v == 1 # FIXME
@ext__peer_gzip = (v == 1)
end
end
#send ACK
# FIXME: ensure we only send this after the initial settings
g = Frame.new FrameTypes::SETTINGS, FLAG_ACK, 0, ''
send_frame g
end
end
def handle_ping f
# FIXME: if f.sid > 0 ...
raise ConnectionError.new(PROTOCOL_ERROR, "received PING on stream id #{f.sid}") unless f.sid == 0
raise ConnectionError.new(FRAME_SIZE_ERROR, "PING payload must be 8 bytes, received #{f.payload.bytesize}") unless f.payload.bytesize == 8
if f.flag? FLAG_ACK
idx = @pings.find_index f.payload
if idx
@logger.info "ping pong #{f.payload.inspect}"
@pings.delete_at idx
else
# FIXME
raise ConnectionError.new(PROTOCOL_ERROR, "unexpected PONG or incorrect payload #{f.payload.inspect}")
end
else
# send pong
g = Frame.new FrameTypes::PING, FLAG_ACK, 0, f.payload
send_frame g
end
end
def handle_goaway f
raise ConnectionError.new(PROTOCOL_ERROR, "received GOAWAY on stream id #{f.sid}") unless f.sid == 0
# TODO
@goaway, error_code, debug_data = f.payload.unpack('NNa*')
@logger.info "received GOAWAY (last stream ID=#{@goaway}, error_code=0x#{error_code.to_s 16})"
@logger.info debug_data.inspect if debug_data && debug_data.bytesize > 0
shut_down
end
def handle_window_update f
# FIXME: stream states?
raise 'connection:FRAME_SIZE_ERROR' unless f.payload.bytesize == 4
increment = f.payload.unpack('N').first
#raise 'PROTOCOL_ERROR' if increment & 0x80000000 == 0x80000000
increment &= 0x7fffffff
raise 'stream:PROTOCOL_ERROR' if increment == 0
if f.sid != 0
@streams[f.sid].window_size += increment
else
@window_size += increment
end
catch :CONNECTION_EXHAUSTED do
@window_queue.each_pair do |sid, queue|
s = @streams[sid]
# note: sid can never be zero, since frames only
# enter the queue because of a blocked DATA
# (which isn't allowed on stream 0)
raise unless s # FIXME
catch :STREAM_EXHAUSED do
until queue.empty?
f = queue.first
b = (f.type == FrameTypes::DATA ? f.payload_size : 0)
throw :CONNECTION_EXHAUSED if @window_size < b
throw :STREAM_EXHAUSTED if s.window_size < b
queue.shift
@window_size -= b
s.window_size -= b
@sil << f
end
end# :STREAM_EXHAUSTED
end
end# :CONNECTION_EXHAUSTED
end
end
end
send more appropriate WINDOW_UPDATEs
# encoding: BINARY
# vim: ts=2 sts=2 sw=2 expandtab
def hex(s) s.nil? ? 'nil' : "[#{s.bytesize}]:#{s.bytes.map{|b|'%02X' % b}.join '.'}" end
def ansi(n, *args) args.each {|arg| puts "\x1B[#{n}m#{arg}\x1B[0m" }; end
def black(*args) ansi 30, *args; end
def red(*args) ansi 31, *args; end
def green(*args) ansi 32, *args; end
def brown(*args) ansi 33, *args; end
def yellow(*args) ansi 93, *args; end
def blue(*args) ansi 94, *args; end
def magenta(*args) ansi 35, *args; end
def cyan(*args) ansi 36, *args; end
def silver(*args) ansi 37, *args; end
def white(*args) ansi 97, *args; end
def flg(f)
s = "#{f.to_s 16}"
a = []
n = 1
while n <= f
if (f & n) == n
a << ('%02X' % n)
end
n <<= 1
end
"#{f.to_s 16}[#{a.join '|'}]"
end
def frm(f)
t = RUBYH2::FrameTypes.constants.find {|t| f.type == RUBYH2::FrameTypes.const_get(t) }
t ||= f.type
"<#{t}: flags=#{flg f.flags} stream=#{f.sid} payload=#{hex f.payload}>"
end
require 'thread'
require 'zlib'
require 'stringio'
require_relative 'frame-deserialiser'
require_relative 'frame-serialiser'
require_relative 'frame-types'
require_relative 'headers-hook'
require_relative 'settings'
require_relative 'errors'
require_relative 'hpack'
require_relative 'http-request'
require_relative 'http-response'
require_relative 'stream'
module RUBYH2
PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
class HTTPAgent
FLAG_END_STREAM = 0x1
FLAG_ACK = 0x1
FLAG_END_HEADERS = 0x4
FLAG_PADDED = 0x8
FLAG_PRIORITY = 0x20
include Error
def initialize is_server, logger
# machinery state
@is_server = is_server
@request_proc = nil
@response_proc = nil
@hook = HeadersHook.new
@hook.on_frame {|f| recv_frame f }
@hpack = HPack.new
@logger = logger
# H2 state
@window_queue = {}
@first_frame_in = true
@first_frame_out = true
@streams = {}
@default_window_size = 65535
@window_size = @default_window_size
@max_frame_size = 16384
@max_streams = nil
@push_to_peer = true
@ext__send_gzip = true # are we config'd to send gzip data?
@ext__peer_gzip = false # is peer config'd to accept gzip data?
@ext__recv_gzip = true # are we config'd to accept gzip data?
@ext__veto_gzip = false # set if peer doesn't gzip right
@ext__sent_dropped_frame = {}
@ext__peer_dropped_frame = {}
# other settings
@pings = []
@goaway = false
@last_stream = 0 # last incoming stream handed up to application
@shutting_down = false
@send_lock = Mutex.new
@shutdown_lock = Mutex.new
end
def inspect
"\#<HTTPAgent @window_queue=#{@window_queue.inspect}, @streams=#{@streams.inspect}, @default_window_size=#{@default_window_size.inspect}, @window_size=#{@window_size.inspect}, @max_frame_size=#{@max_frame_size.inspect}, @max_streams=#{@max_streams.inspect}, @push_to_peer=#{@push_to_peer.inspect}>"
end
attr_reader :push_to_peer
##
# Set the callback to be invoked when a HTTP request arrives.
#
def on_request &b
@request_proc = b
self
end
##
# Set the callback to be invoked when a HTTP response arrives.
#
def on_response &b
@response_proc = b
self
end
##
# wrap a TCPSocket
# e.g.:
#
# require 'socket'
# server = TCPServer.new 4567
# http_client.wrap server.accept
#
def wrap s
@sil = FrameSerialiser.new {|b|
cyan "@sil: _write #{hex b}"
_write s, b rescue nil }
dsil = FrameDeserialiser.new
dsil.on_frame {|f|
brown "dsil: received #{frm f}"
@hook << f }
handle_prefaces s
#send_frame Settings.frame_from({Settings::INITIAL_WINDOW_SIZE => 0x7fffffff, Settings::ACCEPT_GZIPPED_DATA => 1}), true
#send_frame Settings.frame_from({Settings::INITIAL_WINDOW_SIZE => 0x7fffffff}), true
send_frame Settings.frame_from({Settings::INITIAL_WINDOW_SIZE => 0x20000, Settings::MAX_FRAME_SIZE => dsil.max_frame_size, Settings::ACCEPT_GZIPPED_DATA => 1}), true
loop do
bytes = begin
s.readpartial(4*1024*1024)
rescue EOFError
nil
end
if bytes.nil? or bytes.empty?
if s.is_a? OpenSSL::SSL::SSLSocket
@logger.info "client disconnected from #{s.io.remote_address.inspect_sockaddr}"
else
@logger.info "client disconnected from #{s.remote_address.inspect_sockaddr}"
end
break
end
red "read #{hex bytes}"
dsil << bytes
Thread.pass
end
ensure
s.close rescue nil
end
##
# Shut down the connection.
def shut_down
@shutdown_lock.synchronize {
return if @shutting_down
@shutting_down = true
}
g = Frame.new FrameTypes::GOAWAY, 0x00, 0, [@last_stream,NO_ERROR].pack('NN')
send_frame g
end
##
# deliver HTTPMessage object
def deliver m
@shutdown_lock.synchronize {
raise "delivering message after GOAWAY" if @shutting_down # FIXME
}
blue "deliver #{m.inspect}"
# create headers
hblock = @hpack.create_block m.headers
# split header block into chunks and deliver
chunks = hblock.scan(/.{1,#{@max_frame_size}}/m).map{|c| {type: FrameTypes::CONTINUATION, flags: 0, bytes: c} }
if chunks.empty?
# I cast no judgement here, but shouldn't there be some headers..?
chunks << {type: FrameTypes::HEADERS, flags: FLAG_END_HEADERS, bytes: String.new.b}
else
chunks.first[:type] = FrameTypes::HEADERS
chunks.last[:flags] |= FLAG_END_HEADERS
end
# without data, the HEADERS ends the stream
if m.body.empty?
chunks.last[:flags] |= FLAG_END_STREAM
end
# pad out to %256 bytes if required
_pad chunks.last if m.pad?
# send the headers frame(s)
chunks.each do |chunk|
g = Frame.new chunk[:type], chunk[:flags], m.stream, chunk[:bytes]
send_frame g
end
# create data
if !m.body.empty?
chunks = []
if send_gzip?
type = FrameTypes::GZIPPED_DATA
bytes = m.body.b
until bytes.empty?
# binary search for biggest data chunk that fits when gzipped
left = 0
right = bytes.bytesize
maxright = right
best = nil
rest = bytes
loop do
gzipped = ''.b
gzip = Zlib::GzipWriter.new(StringIO.new gzipped)
gzip.write bytes[0...right]
gzip.close
rest = bytes[right..-1]
if gzipped.bytesize > @max_frame_size
# try a smaller sample
maxright = right
right = maxright - (maxright - left) / 2
# is this a good as we'll get?
break if right == left
elsif gzipped.bytesize == @max_frame_size
# perfect!
best = gzipped
break
else
# try a bigger sample
best = gzipped
left = right
right = maxright - (maxright - left) / 2
# is this a good as we'll get?
break if right == left
end
end
bytes = rest
# create chunk
chunk = {flags: 0, bytes: best}
# pad out to %256 bytes if required
_pad chunk if m.pad?
# add to list
chunks << chunk
end
else
type = FrameTypes::DATA
chunks = m.body.b.scan(/.{1,#{@max_frame_size}}/m).map{|c| {flags: 0, bytes: c} }
# pad out to %256 bytes if required
_pad chunks.last if m.pad?
end
chunks.last[:flags] |= FLAG_END_STREAM
chunks.each do |chunk|
g = Frame.new type, chunk[:flags], m.stream, chunk[:bytes]
send_frame g
end
end
# half-close
@streams[m.stream].close_local!
end
##
# send a PING message
def ping message=nil
if message
message = (message.to_s.b + (0.chr * 8)).slice(0, 8)
else
now = Time.now
message = [now.to_i, now.usec].pack('NN')
end
@pings << message
g = Frame.new FrameTypes::PING, 0, 0, message
send_frame g
end
# returns truthy if the given frame carries HTTP semantics
# (so has to be sent in order)
def semantic_frame? f
f.type == FrameTypes::DATA || f.type == FrameTypes::HEADERS || f.type == FrameTypes::CONTINUATION || f.type == FrameTypes::GZIPPED_DATA
end
# Are we configured to accept GZIPPED_DATA frames from this peer?
# Takes into account peer's apparent ability to correctly send gzip.
def accept_gzip?
return if @ext__veto_gzip
@ext__recv_gzip
end
# tell the peer we'll accept GZIPPED_DATA frames
def accept_gzip!
return if @ext__veto_gzip
if !@ext__recv_gzip
send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 1})
@ext__recv_gzip = true
end
end
# tell the peer we don't accept GZIPPED_DATA frames
def no_accept_gzip!
return if @ext__veto_gzip
if @ext__recv_gzip
send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})
@ext__recv_gzip = false
end
end
# Are we configured to send GZIPPED_DATA frames to this peer?
# Takes into account peer's settings for receiving them.
def send_gzip?
return if !@ext__peer_gzip
@ext__send_gzip
end
# application lets us send GZIPPED_DATA frames to this peer
def send_gzip!
if !@ext__send_gzip
@ext__send_gzip = true
end
end
# application won't let us send GZIPPED_DATA frames to this peer
def no_send_gzip!
if @ext__send_gzip
@ext__send_gzip = false
end
end
private
def veto_gzip!
return if @ext__veto_gzip
if @ext__recv_gzip
send_frame Settings.frame_from({Settings::ACCEPT_GZIPPED_DATA => 0})
@ext__veto_gzip = true
end
end
def _pad hash, modulus=256
len = hash[:bytes].bytesize
rem = (modulus - (len % modulus)) - 1
# don't overflow the frame!
if len + rem > @max_frame_size
rem = @max_frame_size - len - 1
end
if rem >= 0
padlen = [rem].pack('C')
padding = ''
padding = [0].pack('C') * rem if rem > 0
hash[:flags] |= FLAG_PADDED
hash[:bytes] = padlen + hash[:bytes] + padding
end
hash
end
def _write sock, bytes
bytes.force_encoding Encoding::BINARY
#sock.print bytes
until bytes.empty?
sent = sock.write bytes
#sent = sock.send bytes, 0
bytes = bytes[sent..-1]
end
#sock.flush
end
def handle_prefaces s
if @is_server
preface = String.new.b
while preface.length < 24
preface << s.readpartial(24 - preface.length)
end
raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface') if preface != PREFACE
else
_write s, PREFACE
end
end
def send_frame g, is_first_settings=false
if is_first_settings
# Unset @first_frame_out and transmit said first frame, atomically
@send_lock.synchronize do
@first_frame_out = false
_do_send_frame g
end
else
# FIXME: this is horrible
# Spin-lock on @first_frame_out being unset.
# Note that writes to @first_frame_out are sync'd by @send_lock
wait = false
@send_lock.synchronize { wait = @first_frame_out }
while wait
sleep 0.1
@send_lock.synchronize { wait = @first_frame_out }
end
# Actually transmit the frame, atomically.
@send_lock.synchronize do
_do_send_frame g
end
end
end
def _do_send_frame g
if !semantic_frame? g
@sil << g
elsif g.sid == 0
# FIXME: assumes .type != DATA, etc.
@sil << g
else
s = @streams[g.sid]
s = @streams[g.sid] = Stream.new(@default_window_size) if !s
q = @window_queue[g.sid]
if q && !q.empty?
# there's a queue; wait for a WINDOW_UPDATE
q << g
elsif g.type == FrameTypes::DATA
b = g.payload_size
if @window_size >= b && s.window_size >= b
@window_size -= b
s.window_size -= b
@sil << g
else
@window_queue[g.sid] ||= []
@window_queue[g.sid] << g
end
else
@sil << g
end
end
end
# triggered when a new H2 frame arrives
def recv_frame f
if @first_frame_in
# first frame has to be settings
# FIXME: make sure this is the actual settings, not the ACK to ours
raise ConnectionError.new(PROTOCOL_ERROR, 'invalid preface - no SETTINGS') if f.type != FrameTypes::SETTINGS
@first_frame_in = false
end
if @goaway
case f.type
when FrameTypes::DATA
when FrameTypes::HEADERS
when FrameTypes::PUSH_PROMISE
when FrameTypes::CONTINUATION
else
# FIXME
@logger.warn "Ignoring frame 0x#{f.type.to_s 16} after GOAWAY"
return
end
end
case f.type
when FrameTypes::DATA
handle_data f
when FrameTypes::HEADERS
handle_headers f
when FrameTypes::PRIORITY
# TODO
when FrameTypes::RST_STREAM
# TODO
when FrameTypes::SETTINGS
handle_settings f
when FrameTypes::PUSH_PROMISE
# TODO
when FrameTypes::PING
handle_ping f
when FrameTypes::GOAWAY
handle_goaway f
when FrameTypes::WINDOW_UPDATE
handle_window_update f
when FrameTypes::CONTINUATION
# never emitted by the Hook
raise 'unexpected CONTINUATION frame'
# EXTENSION FRAME HANDLING
when FrameTypes::GZIPPED_DATA
handle_gzipped_data f
when FrameTypes::DROPPED_FRAME
handle_dropped_frame f
else
# ignore unrecognised/extension frames
drop_frame f
end
end
# tell the peer we ignored it
def drop_frame f
if !@ext__sent_dropped_frame[f.type]
@ext__sent_dropped_frame[f.type] = true
g = Frame.new FrameTypes::DROPPED_FRAME, 0x00, 0, [f.type].pack('C')
send_frame g
end
end
def handle_dropped_frame f
raise ConnectionError.new(PROTOCOL_ERROR, "DROPPED_FRAME must be sent on stream 0, received #{f.sid}") if f.sid != 0
raise ConnectionError.new(PROTOCOL_ERROR, "DROPPED_FRAME payload must be exactly 1 byte, received #{f.payload.bytesize}") if f.payload.bytesize != 1
type = f.payload.bytes.first
@logger.info "peer dropped extension frame type 0x#{type.to_s 16}"
@ext__peer_dropped_frame[type] = true
end
# triggered when a completed HTTP message arrives
# (farms it off to the registered callback)
def emit_message sid, stream
# NB: this function only invoked once we get an END_STREAM flag
stream.close_remote!
@last_stream = sid
# FIXME
headers = stream.headers
if @is_server
@request_proc.call HTTPRequest.new( sid, headers.delete(':method'), headers.delete(':path'), headers, stream.body )
else
@response_proc.call HTTPResponse.new( sid, headers.delete(':status'), headers, stream.body )
end
end
def strip_padding bytes
ints = bytes.bytes
pad_length = ints.shift
rst_length = ints.length
raise ConnectionError.new(PROTOCOL_ERROR, "Pad Length #{pad_length} exceeds frame payload size #{rst_length+1}") if pad_length > rst_length
ints[0...rst_length-pad_length].pack('C*')
end
def extract_priority bytes
stream, weight, bytes = bytes.unpack('NCa*')
exclusive = (stream & 0x80000000) == 0x80000000
stream &= 0x7fffffff
[{exclusive:exclusive, stream:stream, weight:weight}, bytes]
end
def handle_data f
raise ConnectionError.new(PROTOCOL_ERROR, "DATA must be sent on stream >0") if f.sid == 0
stream = @streams[f.sid]
raise SemanticError.new("DATA frame with invalid stream id #{f.sid}") unless stream
raise StreamError.new(STREAM_CLOSED, "DATA frame received on (half-)closed stream #{f.sid}") unless stream.open_remote?
return if @goaway
bytes = f.payload
# never run out of window space
size = bytes.bytesize
if size > 0
g = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, 0, [size].pack('N')
h = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, f.sid, [size].pack('N')
send_frame g
send_frame h
end
bytes = strip_padding(bytes) if f.flag? FLAG_PADDED
stream << bytes
emit_message f.sid, stream if f.flag? FLAG_END_STREAM
end
def handle_gzipped_data f
#raise ConnectionError.new(PROTOCOL_ERROR, "GZIPPED_DATA cannot be sent without SETTINGS_ACCEPT_GZIP_DATA") unless accept_gzip
if !accept_gzip?
drop_frame f
return
end
raise ConnectionError.new(PROTOCOL_ERROR, "GZIPPED_DATA must be sent on stream >0") if f.sid == 0
stream = @streams[f.sid]
raise SemanticError.new("GZIPPED_DATA frame with invalid stream id #{f.sid}") unless stream
raise StreamError.new(STREAM_CLOSED, "GZIPPED_DATA frame received on (half-)closed stream #{f.sid}") unless stream.open_remote?
return if @goaway
bytes = f.payload
bytes = strip_padding(bytes) if f.flag? FLAG_PADDED
# never run out of window space
size = bytes.bytesize
if size > 0
g = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, 0, [size].pack('N')
send_frame g
end
inflated_bytes = nil
gunzip = Zlib::GzipReader.new(StringIO.new bytes)
begin
inflated_bytes = gunzip.read
rescue Zlib::Error => e
# bad gzip!
raise StreamError.new(DATA_ENCODING_ERROR, e.to_s)
ensure
veto_gzip! if inflated_bytes.nil?
end
# note: only update the frame window if gunzip succeeddededd
if size > 0
h = Frame.new FrameTypes::WINDOW_UPDATE, 0x00, f.sid, [size].pack('N')
send_frame h
end
stream << inflated_bytes
emit_message f.sid, stream if f.flag? FLAG_END_STREAM
end
def handle_headers f
stream = @streams[f.sid]
if stream
if @is_server
raise SemanticError.new("no END_STREAM on trailing headers") unless f.flag? FLAG_END_STREAM #FIXME: malformed => StreamError:PROTOCOL_ERROR ?
else
# FIXME: detect same thing on RESPONSE messages (server->client)
end
raise StreamError.new(STREAM_CLOSED, "HEADER frame received on (half-)closed stream #{f.sid}") unless stream.open_remote? # FIXME
else
raise ConnectionError.new(PROTOCOL_ERROR, "HEADERS must be sent on stream >0") if f.sid == 0
raise ConnectionError.new(PROTOCOL_ERROR, "new stream id #{f.sid} not greater than previous stream id #{@last_stream}") if f.sid <= @last_stream
if @is_server
raise ConnectionError.new(PROTOCOL_ERROR, "streams initiated by client must be odd, received #{f.sid}") if f.sid % 2 != 1
else
raise ConnectionError.new(PROTOCOL_ERROR, "streams initiated by server must be event, received #{f.sid}") if f.sid % 2 != 0
end
@streams[f.sid] = Stream.new(@default_window_size)
end
# read the header block
bytes = f.payload
bytes = strip_padding(bytes) if f.flag? FLAG_PADDED
priority, bytes = extract_priority(bytes) if f.flag? FLAG_PRIORITY
yellow "priority: #{priority.inspect}"
# TODO: handle priority?
@hpack.parse_block(bytes) do |k, v|
yellow " [#{k}]: [#{v}]"
@streams[f.sid][k] << v
end
yellow "--"
# if end-of-stream, emit the message
emit_message f.sid, @streams[f.sid] if !@goaway and f.flag? FLAG_END_STREAM
end
def handle_settings f
raise ConnectionError.new(PROTOCOL_ERROR, "SETTINGS must be sent on stream 0, received #{f.sid}") if f.sid != 0
if f.flag? FLAG_ACK
# TODO
else
hash = Settings.pairs_from(f)
hash.each_pair do |k, v|
case k
when Settings::HEADER_TABLE_SIZE
@hpack.max_size_out = v
when Settings::ENABLE_PUSH
raise ConnectionError.new(PROTOCOL_ERROR, "ENABLE_PUSH must be 0 or 1, received #{v}") unless v == 0 or v == 1 # FIXME
@push_to_peer = (v == 1)
when Settings::MAX_CONCURRENT_STREAMS
@max_streams = v
when Settings::INITIAL_WINDOW_SIZE
raise ConnectionError.new(FLOW_CONTROL_ERROR, "INITIAL_WINDOW_SIZE too large #{v}") if v > 0x7fffffff # FIXME
@default_window_size = v
when Settings::MAX_FRAME_SIZE
raise ConnectionError.new(PROTOCOL_ERROR, "MAX_FRAME_SIZE out of bounds #{v}") if v < 0x4000 or v > 0xffffff # FIXME
@max_frame_size = v
when Settings::MAX_HEADER_LIST_SIZE
# FIXME ???
when Settings::ACCEPT_GZIPPED_DATA
raise ConnectionError.new(PROTOCOL_ERROR, "ACCEPT_GZIPPED_DATA must be 0 or 1, received #{v}") unless v == 0 or v == 1 # FIXME
@ext__peer_gzip = (v == 1)
end
end
#send ACK
# FIXME: ensure we only send this after the initial settings
g = Frame.new FrameTypes::SETTINGS, FLAG_ACK, 0, ''
send_frame g
end
end
def handle_ping f
# FIXME: if f.sid > 0 ...
raise ConnectionError.new(PROTOCOL_ERROR, "received PING on stream id #{f.sid}") unless f.sid == 0
raise ConnectionError.new(FRAME_SIZE_ERROR, "PING payload must be 8 bytes, received #{f.payload.bytesize}") unless f.payload.bytesize == 8
if f.flag? FLAG_ACK
idx = @pings.find_index f.payload
if idx
@logger.info "ping pong #{f.payload.inspect}"
@pings.delete_at idx
else
# FIXME
raise ConnectionError.new(PROTOCOL_ERROR, "unexpected PONG or incorrect payload #{f.payload.inspect}")
end
else
# send pong
g = Frame.new FrameTypes::PING, FLAG_ACK, 0, f.payload
send_frame g
end
end
def handle_goaway f
raise ConnectionError.new(PROTOCOL_ERROR, "received GOAWAY on stream id #{f.sid}") unless f.sid == 0
# TODO
@goaway, error_code, debug_data = f.payload.unpack('NNa*')
@logger.info "received GOAWAY (last stream ID=#{@goaway}, error_code=0x#{error_code.to_s 16})"
@logger.info debug_data.inspect if debug_data && debug_data.bytesize > 0
shut_down
end
def handle_window_update f
# FIXME: stream states?
raise 'connection:FRAME_SIZE_ERROR' unless f.payload.bytesize == 4
increment = f.payload.unpack('N').first
#raise 'PROTOCOL_ERROR' if increment & 0x80000000 == 0x80000000
increment &= 0x7fffffff
raise 'stream:PROTOCOL_ERROR' if increment == 0
if f.sid != 0
@streams[f.sid].window_size += increment
else
@window_size += increment
end
catch :CONNECTION_EXHAUSTED do
@window_queue.each_pair do |sid, queue|
s = @streams[sid]
# note: sid can never be zero, since frames only
# enter the queue because of a blocked DATA
# (which isn't allowed on stream 0)
raise unless s # FIXME
catch :STREAM_EXHAUSED do
until queue.empty?
f = queue.first
b = (f.type == FrameTypes::DATA ? f.payload_size : 0)
throw :CONNECTION_EXHAUSED if @window_size < b
throw :STREAM_EXHAUSTED if s.window_size < b
queue.shift
@window_size -= b
s.window_size -= b
@sil << f
end
end# :STREAM_EXHAUSTED
end
end# :CONNECTION_EXHAUSTED
end
end
end
|
require 'jsonclient'
class Wechat::Core::Follower
extend Wechat::Core::Common
# 获取关注者列表
# http://mp.weixin.qq.com/wiki/0/d0e07720fc711c02a3eab6ec33054804.html
#
# Return hash format if success:
# {
# total: <TOTAL>,
# count: <COUNT>,
# data: { openid: [ <OPEN_ID_1>, <OPEN_ID_2>, ... ] },
# next_openid: <NEXT_OPEN_ID>
# }
def self.index(access_token, next_open_id: nil)
assert_present! :access_token, access_token
options = { access_token: access_token }
options[:next_openid] = next_open_id if next_open_id.present?
message = get_json 'https://api.weixin.qq.com/cgi-bin/user/get', body: options
message.body
end
end
1, Improve the Follower wrapper class to remove the un-used source
codes.
class Wechat::Core::Follower
extend Wechat::Core::Common
# 获取关注者列表
# http://mp.weixin.qq.com/wiki/0/d0e07720fc711c02a3eab6ec33054804.html
#
# Return hash format if success:
# {
# total: <TOTAL>,
# count: <COUNT>,
# data: { openid: [ <OPEN_ID_1>, <OPEN_ID_2>, ... ] },
# next_openid: <NEXT_OPEN_ID>
# }
def self.index(access_token, next_open_id: nil)
assert_present! :access_token, access_token
options = { access_token: access_token }
options[:next_openid] = next_open_id if next_open_id.present?
message = get_json 'https://api.weixin.qq.com/cgi-bin/user/get', body: options
message.body
end
end
|
require "/opt/engines/lib/ruby/ManagedContainer.rb"
require "/opt/engines/lib/ruby/ManagedContainerObjects.rb"
require "/opt/engines/lib/ruby/ManagedEngine.rb"
require "/opt/engines/lib/ruby/ManagedServices.rb"
require "/opt/engines/lib/ruby/SysConfig.rb"
require "rubygems"
require "git"
require 'fileutils'
require 'json'
require '/opt/engines/lib/ruby/SystemAccess.rb'
class EngineBuilder
@repoName=nil
@hostname=nil
@domain_name=nil
@build_name=nil
@web_protocol="HTTPS and HTTP"
attr_reader :last_error,
:repoName,
:hostname,
:domain_name,
:build_name,
:set_environments,
:container_name,
:environments,
:runtime,
:webPort,
:http_protocol,
:blueprint,
:first_build
class BuildError < StandardError
attr_reader :parent_exception,:method_name
def initialize(parent,method_name)
@parent_exception = parent
end
end
class DockerFileBuilder
def initialize(reader,containername,hostname,domain_name,webport,builder)
@hostname = hostname
@container_name = containername
@domain_name = domain_name
@webPort = webport
@blueprint_reader = reader
@builder=builder
@docker_file = File.open( @blueprint_reader.get_basedir + "/Dockerfile","a")
@layer_count=0
end
def log_build_output(line)
@builder.log_build_output(line)
end
def log_build_errors(line)
@builder.log_build_errors(line)
end
def count_layer
++@layer_count
if @layer_count >75
raise EngineBuilder.BuildError.new()
end
end
def write_files_for_docker
@docker_file.puts("")
write_environment_variables
write_stack_env
write_services
write_file_service
#write_db_service
#write_cron_jobs
write_os_packages
write_apache_modules
write_user_local = true
if write_user_local == true
@docker_file.puts("RUN ln -s /usr/local/ /home/local;\\")
@docker_file.puts(" chown -R $ContUser /usr/local/")
end
write_app_archives
write_container_user
chown_home_app
write_worker_commands
write_sed_strings
write_persistant_dirs
write_persistant_files
insert_framework_frag_in_dockerfile("builder.mid.tmpl")
@docker_file.puts("")
write_rake_list
write_pear_list
write_write_permissions_recursive #recursive firs (as can use to create blank dir)
write_write_permissions_single
@docker_file.puts("")
@docker_file.puts("USER 0")
count_layer()
@docker_file.puts("run mkdir -p /home/fs/local/")
count_layer()
@docker_file.puts("")
write_run_install_script
write_data_permissions
@docker_file.puts("USER 0")
count_layer()
@docker_file.puts("run mv /home/fs /home/fs_src")
count_layer()
@docker_file.puts("VOLUME /home/fs_src/")
count_layer()
@docker_file.puts("USER $ContUser")
count_layer()
insert_framework_frag_in_dockerfile("builder.end.tmpl")
@docker_file.puts("")
@docker_file.puts("VOLUME /home/fs/")
count_layer()
write_clear_env_variables
@docker_file.close
end
def write_clear_env_variables
@docker_file.puts("#Clear env")
@blueprint_reader.environments.each do |env|
if env.build_time_only == true
@docker_file.puts("ENV " + env.name + "\" \"")
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
def write_apache_modules
if @blueprint_reader.apache_modules.count <1
return
end
@docker_file.puts("#Apache Modules")
ap_modules_str = String.new
@blueprint_reader.apache_modules.each do |ap_module|
ap_modules_str += ap_module + " "
end
@docker_file.puts("RUN a2enmod " + ap_modules_str)
count_layer()
end
def write_environment_variables
begin
@docker_file.puts("#Environment Variables")
#Fixme
#kludge
@docker_file.puts("#System Envs")
@docker_file.puts("ENV TZ Sydney/Australia")
count_layer
@blueprint_reader.environments.each do |env|
@docker_file.puts("#Blueprint ENVs")
if env.value != nil
env.value.sub!(/ /,"\\ ")
end
if env.value !=nil && env.value.to_s.length >0 #env statement must have two arguments
@docker_file.puts("ENV " + env.name + " " + env.value.to_s )
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_persistant_dirs
begin
log_build_output("setup persistant Dirs")
n=0
@docker_file.puts("#Persistant Dirs")
@blueprint_reader.persistant_dirs.each do |path|
path.chomp!("/")
@docker_file.puts("")
@docker_file.puts("RUN \\")
dirname = File.dirname(path)
@docker_file.puts("mkdir -p $CONTFSVolHome/$VOLDIR/" + dirname + ";\\")
@docker_file.puts("if [ ! -d /home/" + path + " ];\\")
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir -p /home/" + path +" ;\\")
@docker_file.puts(" fi;\\")
@docker_file.puts("mv /home/" + path + " $CONTFSVolHome/$VOLDIR/" + dirname + "/;\\")
@docker_file.puts("ln -s $CONTFSVolHome/$VOLDIR/" + path + " /home/" + path)
n=n+1
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_data_permissions
@docker_file.puts("#Data Permissions")
@docker_file.puts("USER 0")
count_layer()
@docker_file.puts("")
@docker_file.puts("RUN /usr/sbin/usermod -u $data_uid data-user;\\")
@docker_file.puts("chown -R $data_uid.$data_gid /home/app /home/fs ;\\")
@docker_file.puts("chmod -R 770 /home/fs")
count_layer
@docker_file.puts("USER $ContUser")
count_layer
end
def write_run_install_script
@docker_file.puts("WorkDir /home/")
@docker_file.puts("#Setup templates and run installer")
@docker_file.puts("USER $ContUser")
count_layer
@docker_file.puts("RUN bash /home/setup.sh")
count_layer
end
def write_persistant_files
begin
@docker_file.puts("#Persistant Files")
log_build_output("set setup_env")
src_paths = @blueprint_reader.persistant_files[:src_paths]
dest_paths = @blueprint_reader.persistant_files[:dest_paths]
src_paths.each do |path|
# path = dest_paths[n]
p :path
p path
dir = File.dirname(path)
p :dir
p dir
if dir.present? == false || dir == nil || dir.length ==0 || dir =="."
dir = "app/"
end
p :dir
p dir
@docker_file.puts("")
@docker_file.puts("RUN mkdir -p /home/" + dir + ";\\")
@docker_file.puts(" if [ ! -f /home/" + path + " ];\\")
@docker_file.puts(" then \\")
@docker_file.puts(" touch /home/" + path +";\\")
@docker_file.puts(" fi;\\")
@docker_file.puts(" mkdir -p $CONTFSVolHome/$VOLDIR/" + dir +";\\")
@docker_file.puts("\\")
@docker_file.puts(" mv /home/" + path + " $CONTFSVolHome/$VOLDIR" + "/" + dir + ";\\")
@docker_file.puts(" ln -s $CONTFSVolHome/$VOLDIR/" + path + " /home/" + path)
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_file_service
begin
@docker_file.puts("#File Service")
@docker_file.puts("#FS Env")
# @docker_file.puts("ENV CONTFSVolHome /home/fs/" )
# count_layer
@blueprint_reader.volumes.each_value do |vol|
dest = File.basename(vol.remotepath)
# @docker_file.puts("ENV VOLDIR /home/fs/" + dest)
# count_layer
@docker_file.puts("RUN mkdir -p $CONTFSVolHome/" + dest)
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_services
services = @blueprint_reader.services
@docker_file.puts("#Service Environment Variables")
services.each do |service_hash|
p :service_hash
p service_hash
service_def = @builder.get_service_def(service_hash)
if service_def != nil
p :processing
p service_def
service_environment_variables = service_def[:target_environment_variables]
if service_environment_variables != nil
service_environment_variables.values.each do |env_variable_pair|
p :setting_values
p env_variable_pair
env_name = env_variable_pair[:environment_name]
value_name = env_variable_pair[:variable_name]
value=service_hash[:variables][value_name.to_sym]
p :looking_for_
p value_name
p :as_symbol
p value_name.to_sym
p :in_service_hash
p service_hash
p :and_found
p value
if value != nil && value.to_s.length >0
@docker_file.puts("ENV " + env_name + " " + value )
count_layer()
end
end
end
end
end
end
def write_sed_strings
begin
n=0
@docker_file.puts("#Sed Strings")
@blueprint_reader.sed_strings[:src_file].each do |src_file|
#src_file = @sed_strings[:src_file][n]
dest_file = @blueprint_reader.sed_strings[:dest_file][n]
sed_str = @blueprint_reader.sed_strings[:sed_str][n]
tmp_file = @blueprint_reader.sed_strings[:tmp_file][n]
@docker_file.puts("")
@docker_file.puts("RUN cat " + src_file + " | sed \"" + sed_str + "\" > " + tmp_file + " ;\\")
@docker_file.puts(" cp " + tmp_file + " " + dest_file)
count_layer
n=n+1
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_rake_list
begin
@docker_file.puts("#Rake Actions")
@blueprint_reader.rake_actions.each do |rake_action|
rake_cmd = rake_action[:action]
if @builder.first_build == false && rake_action[:always_run] == false
next
end
if rake_cmd !=nil
@docker_file.puts("RUN /usr/local/rbenv/shims/bundle exec rake " + rake_cmd )
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_os_packages
begin
packages=String.new
@docker_file.puts("#OS Packages")
@blueprint_reader.os_packages.each do |package|
if package != nil
packages = packages + package + " "
end
end
if packages.length >1
@docker_file.puts("\nRUN apt-get install -y " + packages )
count_layer
end
#FIXME Wrong spot
@blueprint_reader.workerPorts.each do |port|
@docker_file.puts("EXPOSE " + port.port.to_s)
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def insert_framework_frag_in_dockerfile(frag_name)
begin
log_build_output(frag_name)
@docker_file.puts("#Framework Frag")
frame_build_docker_frag = File.open(SysConfig.DeploymentTemplates + "/" + @blueprint_reader.framework + "/Dockerfile." + frag_name)
builder_frag = frame_build_docker_frag.read
@docker_file.write(builder_frag)
count_layer
rescue Exception=>e
log_exception(e)
return false
end
end
def chown_home_app
begin
@docker_file.puts("#Chown App Dir")
log_build_output("Dockerfile:Chown")
@docker_file.puts("USER 0")
count_layer
@docker_file.puts("RUN if [ ! -d /home/app ];\\")
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir -p /home/app ;\\")
@docker_file.puts(" fi;\\")
@docker_file.puts(" mkdir -p /home/fs ; mkdir -p /home/fs/local ;\\")
@docker_file.puts(" chown -R $ContUser /home/app /home/fs /home/fs/local")
count_layer
@docker_file.puts("USER $ContUser")
count_layer
rescue Exception=>e
log_exception(e)
return false
end
end
def write_worker_commands
begin
@docker_file.puts("#Worker Commands")
log_build_output("Dockerfile:Worker Commands")
scripts_path = @blueprint_reader.get_basedir + "/home/engines/scripts/"
if Dir.exist?(scripts_path) == false
FileUtils.mkdir_p(scripts_path)
end
if @blueprint_reader.worker_commands != nil && @blueprint_reader.worker_commands.length >0
cmdf= File.open( scripts_path + "pre-running.sh","w")
if !cmdf
puts("failed to open " + scripts_path + "pre-running.sh")
exit
end
cmdf.chmod(0755)
cmdf.puts("#!/bin/bash")
cmdf.puts("cd /home/app")
@blueprint_reader.worker_commands.each do |command|
cmdf.puts(command)
end
cmdf.close
File.chmod(0755,scripts_path + "pre-running.sh")
end
rescue Exception=>e
log_exception(e)
return false
end
end
# def write_cron_jobs
# begin
# if @blueprint_reader.cron_jobs.length >0
# @docker_file.puts("ENV CRONJOBS YES")
# count_layer
## @docker_file.puts("RUN crontab $data_uid /home/crontab ")
## count_layer cron run from cron service
# end
# return true
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
# def write_db_service
# begin
# @docker_file.puts("#Database Service")
# log_build_output("Dockerfile:DB env")
# @blueprint_reader.databases.each do |db|
# @docker_file.puts("#Database Env")
# @docker_file.puts("ENV dbname " + db.name)
# count_layer
# @docker_file.puts("ENV dbhost " + db.dbHost)
# count_layer
# @docker_file.puts("ENV dbuser " + db.dbUser)
# count_layer
# @docker_file.puts("ENV dbpasswd " + db.dbPass)
# count_layer
# flavor = db.flavor
# if flavor == "mysql"
# flavor = "mysql2"
# elsif flavor == "pgsql"
# flavor = "postgresql"
# end
# @docker_file.puts("ENV dbflavor " + flavor)
# count_layer
# end
#
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
def write_write_permissions_single
begin
@docker_file.puts("")
@docker_file.puts("#Write Permissions Non Recursive")
log_build_output("Dockerfile:Write Permissions Non Recursive")
if @blueprint_reader.single_chmods == nil
return
end
@blueprint_reader.single_chmods.each do |path|
if path !=nil
@docker_file.puts("RUN if [ ! -f /home/app/" + path + " ];\\" )
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir -p `dirname /home/app/" + path + "`;\\")
@docker_file.puts(" touch /home/app/" + path + ";\\")
@docker_file.puts(" fi;\\")
@docker_file.puts( " chmod 775 /home/app/" + path )
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_write_permissions_recursive
begin
@docker_file.puts("#Write Permissions Recursive")
@docker_file.puts("")
log_build_output("Dockerfile:Write Permissions Recursive")
if @blueprint_reader.recursive_chmods == nil
return
end
@blueprint_reader.recursive_chmods.each do |directory|
if directory !=nil
@docker_file.puts("RUN if [ -h /home/app/" + directory + " ] ;\\")
@docker_file.puts(" then \\")
@docker_file.puts(" dest=`ls -la /home/app/" + directory +" |cut -f2 -d\">\"`;\\")
@docker_file.puts(" chmod -R gu+rw $dest;\\")
@docker_file.puts(" elif [ ! -d /home/app/" + directory + " ] ;\\" )
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir \"/home/app/" + directory + "\";\\")
@docker_file.puts(" chmod -R gu+rw \"/home/app/" + directory + "\";\\" )
@docker_file.puts(" else\\")
@docker_file.puts(" chmod -R gu+rw \"/home/app/" + directory + "\";\\")
@docker_file.puts(" for dir in `find /home/app/" + directory + " -type d `;\\")
@docker_file.puts(" do\\")
@docker_file.puts(" adir=`echo $dir | sed \"/ /s//_+_/\" |grep -v _+_` ;\\")
@docker_file.puts(" if test -n $adir;\\")
@docker_file.puts(" then\\")
@docker_file.puts(" dirs=\"$dirs $adir\";\\");
@docker_file.puts(" fi;\\")
@docker_file.puts(" done;\\")
@docker_file.puts(" if test -n \"$dirs\" ;\\")
@docker_file.puts(" then\\")
@docker_file.puts(" chmod gu+x $dirs ;\\")
@docker_file.puts("fi;\\")
@docker_file.puts("fi")
count_layer
end
end
end
rescue Exception=>e
log_exception(e)
return false
end
def write_app_archives
begin
@docker_file.puts("#App Archives")
log_build_output("Dockerfile:App Archives")
n=0
# srcs=String.new
# names=String.new
# locations=String.new
# extracts=String.new
# dirs=String.new
@docker_file.puts("")
@blueprint_reader.archives_details.each do |archive_details|
arc_src = archive_details[:source_url]
arc_name = archive_details[:package_name]
arc_loc = archive_details[:destination]
arc_extract = archive_details[:extraction_command]
arc_dir = archive_details[:path_to_extracted]
# if(n >0)
# archive_details[:source_url]=arc_src
# archive_details[:package_name]=arc_name
# archive_details[:extraction_cmd]=arc_extract
# archive_details[:destination]=arc_loc
# archive_details[:path_to_extracted]=arc_dir
# srcs = srcs + " "
# names =names + " "
# locations = locations + " "
# extracts =extracts + " "
# dirs =dirs + " "
# end
p "_+_+_+_+_+_+_+_+_+_+_"
p archive_details
p arc_src + "_"
p arc_name + "_"
p arc_loc + "_"
p arc_extract + "_"
p arc_dir +"|"
if arc_loc == "./"
arc_loc=""
elsif arc_loc.end_with?("/")
arc_loc = arc_loc.chop() #note not String#chop
end
if arc_extract == "git"
@docker_file.puts("WORKDIR /tmp")
count_layer
@docker_file.puts("USER $ContUser")
count_layer
@docker_file.puts("RUN git clone " + arc_src + " --depth 1 " )
count_layer
@docker_file.puts("USER 0 ")
count_layer
@docker_file.puts("RUN mv " + arc_dir + " /home/app" + arc_loc )
count_layer
@docker_file.puts("USER $ContUser")
count_layer
else
@docker_file.puts("USER $ContUser")
count_layer
step_back=false
if arc_dir == nil
step_back=true
@docker_file.puts("RUN mkdir /tmp/app")
count_layer
arc_dir = "app"
@docker_file.puts("WORKDIR /tmp/app")
count_layer
else
@docker_file.puts("WORKDIR /tmp")
count_layer
end
@docker_file.puts("RUN wget -O \"" + arc_name + "\" \"" + arc_src + "\" ;\\" )
if arc_extract!= nil
@docker_file.puts(" " + arc_extract + " \"" + arc_name + "\" ;\\") # + "\"* 2>&1 > /dev/null ")
@docker_file.puts(" rm \"" + arc_name + "\"")
else
@docker_file.puts("echo") #step past the next shell line implied by preceeding ;
end
@docker_file.puts("USER 0 ")
count_layer
if step_back==true
@docker_file.puts("WORKDIR /tmp")
count_layer
end
if arc_loc.start_with?("/home/app") || arc_loc.start_with?("/home/local/")
dest_prefix=""
else
dest_prefix="/home/app"
end
@docker_file.puts("run if test ! -d " + arc_dir +" ;\\")
@docker_file.puts(" then\\")
@docker_file.puts(" mkdir -p /home/app ;\\")
@docker_file.puts(" fi;\\")
@docker_file.puts(" mv " + arc_dir + " " + dest_prefix + arc_loc )
count_layer
@docker_file.puts("USER $ContUser")
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_container_user
begin
@docker_file.puts("#Container Data User")
log_build_output("Dockerfile:User")
#FIXME needs to by dynamic
@docker_file.puts("ENV data_gid " + @blueprint_reader.data_uid)
count_layer
@docker_file.puts("ENV data_uid " + @blueprint_reader.data_gid)
count_layer
rescue Exception=>e
log_exception(e)
return false
end
end
def write_stack_env
begin
log_build_output("Dockerfile:Stack Environment")
@docker_file.puts("#Stack Env")
# stef = File.open(get_basedir + "/home/stack.env","w")
@docker_file.puts("")
@docker_file.puts("#Stack Env")
@docker_file.puts("ENV Memory " + @blueprint_reader.memory.to_s)
count_layer
@docker_file.puts("ENV Hostname " + @hostname)
count_layer
@docker_file.puts("ENV Domainname " + @domain_name )
count_layer
@docker_file.puts("ENV fqdn " + @hostname + "." + @domain_name )
count_layer
@docker_file.puts("ENV FRAMEWORK " + @blueprint_reader.framework )
count_layer
@docker_file.puts("ENV RUNTIME " + @blueprint_reader.runtime )
count_layer
@docker_file.puts("ENV PORT " + @webPort.to_s )
count_layer
wports = String.new
n=0
@blueprint_reader.workerPorts.each do |port|
if n < 0
wports =wports + " "
end
@docker_file.puts("EXPOSE " + port.port.to_s)
count_layer
wports = wports + port.port.to_s
n=n+1
end
if wports.length >0
@docker_file.puts("ENV WorkerPorts " + "\"" + wports +"\"")
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_pear_list
@docker_file.puts("#OPear List")
log_build_output("Dockerfile:Pear List")
if @blueprint_reader.pear_modules.count >0
@docker_file.puts("RUN wget http://pear.php.net/go-pear.phar;\\")
@docker_file.puts(" echo suhosin.executor.include.whitelist = phar >>/etc/php5/conf.d/suhosin.ini ;\\")
@docker_file.puts(" php go-pear.phar")
count_layer
@blueprint_reader.pear_modules.each do |pear_mod|
if pear_mod !=nil
@docker_file.puts("RUN pear install pear_mod " + pear_mod )
count_layer
end
end
end
rescue Exception=>e
log_exception(e)
return false
end
protected
def log_exception(e)
log_build_errors( e.to_s)
puts(e.to_s)
@last_error= e.to_s
e.backtrace.each do |bt |
p bt
end
return false
end
##################### End of
end
class BluePrintReader
def initialize(build_name,contname,blue_print,builder)
@build_name = build_name
@data_uid="11111"
@data_gid="11111"
@builder=builder
@container_name = contname
@blueprint = blue_print
@web_port=nil
@services = Array.new
end
attr_reader :persistant_files,
:persistant_dirs,
:last_error,
:workerPorts,
:environments,
:recursive_chmods,
:single_chmods,
:framework,
:runtime,
:memory,
:rake_actions,
:os_packages,
:pear_modules,
:archives_details,
:worker_commands,
:cron_jobs,
:sed_strings,
:volumes,
:databases,
:apache_modules,
:data_uid,
:data_gid,
:cron_job_list,
:web_port,
:services
def log_build_output(line)
@builder.log_build_output(line)
end
def log_build_errors(line)
@builder.log_build_errors(line)
end
def clean_path(path)
#FIXME remove preceeding ./(s) and /(s) as well as obliterate any /../ or preceeding ../ and any " " or ";" or "&" or "|" etc
return path
end
def get_basedir
return SysConfig.DeploymentDir + "/" + @build_name
end
def log_exception(e)
log_build_errors(e.to_s)
puts(e.to_s)
#@last_error= e.to_s
e.backtrace.each do |bt |
p bt
end
end
def process_blueprint
begin
log_build_output("Process BluePrint")
read_services
read_environment_variables
read_os_packages
read_lang_fw_values
read_pear_list
read_app_packages
read_apache_modules
read_write_permissions_recursive
read_write_permissions_single
read_worker_commands
# read_cron_jobs
read_sed_strings
read_work_ports
read_os_packages
read_app_packages
read_rake_list
read_persistant_files
read_persistant_dirs
read_web_port_overide
rescue Exception=>e
log_exception(e)
end
end
def read_web_port_overide
if @blueprint[:software].has_key?(:read_web_port_overide) == true
@web_port=@blueprint[:software][:read_web_port_overide]
end
end
def read_persistant_dirs
begin
log_build_output("Read Persistant Dirs")
@persistant_dirs = Array.new
pds = @blueprint[:software][:persistent_directories]
pds.each do |dir|
@persistant_dirs.push(dir[:path])
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_persistant_files
begin
log_build_output("Read Persistant Files")
@persistant_files = Hash.new
src_paths = Array.new
dest_paths = Array.new
pfs = @blueprint[:software][:persistent_files]
if pfs == nil
return
end
files= String.new
pfs.each do |file|
path = clean_path(file[:path])
#link_src = path.sub(/app/,"")
src_paths.push(path)
end
p :src_paths
p src_paths
p :dest_paths
p dest_paths
@persistant_files[:src_paths]= src_paths
rescue Exception=>e
log_exception(e)
return false
end
end
def read_rake_list
begin
@rake_actions = Array.new
log_build_output("Read Rake List")
rake_cmds = @blueprint[:software][:rake_tasks]
if rake_cmds == nil
return
end
rake_cmds.each do |rake_cmd|
@rake_actions.push(rake_cmd)
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_services
@databases=Array.new
@volumes=Hash.new
log_build_output("Read Services")
services=@blueprint[:software][:service_configurations]
if services == nil
return
end
services.each do |service|
if service.has_key?(:publisher_namespace) == false || service[:publisher_namespace] == nil
service[:publisher_namespace] = "EnginesSystem"
end
service[:service_type]=service[:type_path]
p :service_provider
p service[:publisher_namespace]
p :servicetype_name
p service[:type_path]
# servicetype=service[:type_path]
#
# if servicetype == "database/sql/mysql" || servicetype == "database/sql/pgsql"
# dbname = service[:name]
# dest = service[:dest]
# if dest =="local" || dest == nil
# #FIXME
# #kludge until BPDS is complete
# service[:dest] = SysConfig.DBHost
# service[:type] = servicetype.sub(/.*database\/.*\//,"")
# p :kludge_set_type
# p service[:type]
# service[:dbfavor] = "mysql2"
# p :kludge_set_dbfavor
# p service[:dbfavor]
#
# # if flavor == "mysql"
# # flavor = "mysql2"
# # elsif flavor == "pgsql"
# end
# elsif servicetype=="filesystem"
# service[:name] = clean_path(service[:name])
# service[:dest] = clean_path(service[:dest])
# add_file_service(service[:name], service[:dest])
# end
add_service(service)
# end
# end
end
end #FIXME
def add_service (service_hash)
p :add_service
p service_hash
@builder.fill_in_dynamic_vars(service_hash)
if service_hash[:service_type] == "filesystem"
add_file_service(service_hash[:variables][:name],service_hash[:variables][:engine_path])
end
@services.push(service_hash)
end
def add_file_service(name,dest) #FIXME and put me in coreapi
begin
log_build_output("Add File Service " + name)
if dest == nil || dest == ""
dest=name
end
if(dest.start_with?("/home/app/") == false )
if(dest.start_with?("/home/fs/") == false)
if dest != "/home/app"
p :dest
p "_" + dest + "_"
dest="/home/fs/" + dest
end
end
end
permissions = PermissionRights.new(@container_name,"","")
vol=Volume.new(name,SysConfig.LocalFSVolHome + "/" + @container_name + "/" + name,dest,"rw",permissions)
@volumes[name]=vol
rescue Exception=>e
p name
p dest
p @container_name
log_exception(e)
return false
end
end
# def add_db_service(dbname,servicetype)
# p servicetype
# flavor = servicetype.sub(/.*database\//,"")
# p :adding_db
# p dbname
# p servicetype
# log_build_output("Add DB Service " + dbname)
# hostname = flavor + "." + SysConfig.internalDomain
# db = DatabaseService.new(@container_name,dbname,hostname,dbname,dbname,flavor)
#
# @databases.push(db)
#
# end
def read_os_packages
begin
@os_packages = Array.new
log_build_output("Read OS Packages")
ospackages = @blueprint[:software][:system_packages]
if ospackages == nil
return
end
ospackages.each do |package|
@os_packages.push(package[:name])
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_lang_fw_values
log_build_output("Read Framework Settings")
begin
@framework = @blueprint[:software][:framework]
p @framework
@runtime = @blueprint[:software][:language]
@memory = @blueprint[:software][:required_memory]
rescue Exception=>e
log_exception(e)
return false
end
end
def read_pear_list
begin
@pear_modules = Array.new
log_build_output("Read Pear List")
pear_mods = @blueprint[:software][:pear_mod]
if pear_mods == nil || pear_mods.length == 0
return
pear_mods.each do |pear_mod|
mod = pear_mod[:module]
if mod !=nil
@pear_modules.push(mod)
end
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_apache_modules
@apache_modules = Array.new
log_build_output("Read Apache Modules List")
mods = @blueprint[:software][:apache_modules]
if mods == nil
return true
end
mods.each do |ap_module|
mod = ap_module[:module]
os_package = ap_module[:os_package]
if mod != nil
@apache_modules.push(mod)
end
end
return true
rescue Exception=>e
log_exception(e)
return false
end
def read_app_packages
begin
log_build_output("Read App Packages ")
@archives_details = Array.new
log_build_output("Configuring install Environment")
archives = @blueprint[:software][:installed_packages]
n=0
archives.each do |archive|
archive_details = Hash.new
arc_src=clean_path(archive[:source_url])
arc_name=clean_path(archive[:name])
arc_loc =clean_path(archive[:destination])
arc_extract=clean_path(archive[:extraction_command])
arc_dir=clean_path(archive[:path_to_extracted])
if arc_loc == "./"
arc_loc=""
elsif arc_loc.end_with?("/")
arc_loc = arc_loc.chop() #note not String#chop
end
archive_details[:source_url]=arc_src
archive_details[:package_name]=arc_name
archive_details[:extraction_command]=arc_extract
archive_details[:destination]=arc_loc
archive_details[:path_to_extracted]=arc_dir
p :read_in_arc_details
p archive_details
@archives_details.push(archive_details)
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_write_permissions_recursive
begin
log_build_output("Read Recursive Write Permissions")
@recursive_chmods = Array.new
log_build_output("set permissions recussive")
chmods = @blueprint[:software][:file_write_permissions]
p :Single_Chmods
if chmods != nil
chmods.each do |chmod |
p chmod
if chmod[:recursive]==true
directory = clean_path(chmod[:path])
p directory
@recursive_chmods.push(directory)
end
end
#FIXME need to strip any ../ and any preceeding ./
return
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_write_permissions_single
begin
log_build_output("Read Non-Recursive Write Permissions")
@single_chmods =Array.new
log_build_output("set permissions single")
chmods = @blueprint[:software][:file_write_permissions]
p :Recursive_Chmods
if chmods != nil
chmods.each do |chmod |
p chmod
if chmod[:recursive]==false
p chmod[:path]
directory = clean_path(chmod[:path])
@single_chmods.push(directory)
end
end
end
return true
rescue Exception=>e
log_exception(e)
return false
end
end
def read_worker_commands
begin
log_build_output("Read Workers")
@worker_commands = Array.new
workers =@blueprint[:software][:workers]
workers.each do |worker|
@worker_commands.push(worker[:command])
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_sed_strings
begin
log_build_output("Read Sed Strings")
@sed_strings = Hash.new
@sed_strings[:src_file] = Array.new
@sed_strings[:dest_file] = Array.new
@sed_strings[:sed_str] = Array.new
@sed_strings[:tmp_file] = Array.new
log_build_output("set sed strings")
seds=@blueprint[:software][:replacement_strings]
if seds == nil || seds.empty? == true
return
end
n=0
seds.each do |sed|
file = clean_path(sed[:file])
dest = clean_path(sed[:destination])
tmp_file = "/tmp/" + File.basename(file) + "." + n.to_s
if file.match(/^_TEMPLATES.*/) != nil
template_file = file.gsub(/^_TEMPLATES/,"")
else
template_file = nil
end
if template_file != nil
src_file = "/home/engines/templates/" + template_file
else
src_file = "/home/app/" + file
end
dest_file = "/home/app/" + dest
sedstr = sed[:replacement_string]
@sed_strings[:src_file].push(src_file)
@sed_strings[:dest_file].push(dest_file)
@sed_strings[:tmp_file].push(tmp_file)
@sed_strings[:sed_str].push(sedstr)
n=n+1
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_work_ports
begin
@workerPorts = Array.new
log_build_output("Read Work Ports")
ports = @blueprint[:software][:worker_ports]
puts("Ports Json" + ports.to_s)
if ports != nil
ports.each do |port|
portnum = port[:port]
name = port[:name]
external = port['external']
type = port['protocol']
if type == nil
type='tcp'
end
#FIX ME when public ports supported
puts "Port " + portnum.to_s + ":" + external.to_s
@workerPorts.push(WorkPort.new(name,portnum,external,false,type))
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_environment_variables
log_build_output("Read Environment Variables")
@environments = Array.new
p :set_environment_variables
p @builder.set_environments
begin
envs = @blueprint[:software][:variables]
envs.each do |env|
p env
name=env[:name]
value=env[:value]
ask=env[:ask_at_build_time]
mandatory = env[:mandatory]
build_time_only = env[:build_time_only]
label = env[:label]
immutable = env[:immutable]
lookup_system_values = env[:lookup_system_values]
if @builder.set_environments != nil
p :looking_for_
p name
if ask == true && @builder.set_environments.has_key?(name) == true
entered_value=@builder.set_environments[name]
if entered_value != nil && entered_value.count !=0#FIXme needs to be removed
value = entered_value
end
end
end
name.sub!(/ /,"_")
p :name_and_value
p name
p value
ev = EnvironmentVariable.new(name,value,ask,mandatory,build_time_only,label,immutable)
p ev
@environments.push(ev)
end
rescue Exception=>e
log_exception(e)
return false
end
end
end
#This class is to isolate the builder from the docker template output
class BuilderPublic
def initialize(builder)
@builder = builder
end
def engine_name
@builder.container_name
end
def domain_name
@builder.domain_name
end
def hostname
@builder.hostname
end
def http_protocol
@builder.http_protocol
end
def repoName
@builder.repoName
end
def webPort
@builder.webPort
end
def build_name
@builder.build_name
end
def runtime
@builder.runtime
end
def set_environments
@builder.set_environments
end
def environments
@builder.environments
end
def mysql_host
return "mysql.engines.internal"
end
def blueprint
return @builder.blueprint
end
def random cnt
p :RANDOM__________
p cnt
return "random" + cnt
end
end
def initialize(params,core_api)
@container_name = params[:engine_name]
@domain_name = params[:domain_name]
@hostname = params[:host_name]
custom_env= params[:software_environment_variables]
# custom_env=params
@core_api = core_api
@http_protocol = params[:http_protocol]
p params
@repoName= params[:repository_url]
@cron_job_list = Array.new
@build_name = File.basename(@repoName).sub(/\.git$/,"")
@workerPorts=Array.new
@webPort=8000
@vols=Array.new
@first_build = true
#FIXme will be false but for now
@overwrite_existing_services = true
@builder_public = BuilderPublic.new(self)
@system_access = SystemAccess.new()
p :custom_env
p custom_env
if custom_env == nil
@set_environments = Hash.new
@environments = Array.new
elsif custom_env.instance_of?(Array) == true
@environments = custom_env # happens on rebuild as custom env is saved in env on disk
#FIXME need to vet all environment variables
@set_environments = Hash.new
else
env_array = custom_env.values
custom_env_hash = Hash.new
env_array.each do |env_hash|
p :env_hash
p env_hash
if env_hash != nil && env_hash[:name] !=nil && env_hash[:value] != nil
env_hash[:name] = env_hash[:name].sub(/_/,"")
custom_env_hash.store(env_hash[:name],env_hash[:value])
end
end
p :Merged_custom_env
p custom_env_hash
@set_environments = custom_env_hash
@environments = Array.new
end
@runtime=String.new
@databases= Array.new
begin
FileUtils.mkdir_p(get_basedir)
@log_file= File.new(SysConfig.DeploymentDir + "/build.out", File::CREAT|File::TRUNC|File::RDWR, 0644)
@err_file= File.new(SysConfig.DeploymentDir + "/build.err", File::CREAT|File::TRUNC|File::RDWR, 0644)
@log_pipe_rd, @log_pipe_wr = IO.pipe
@error_pipe_rd, @error_pipe_wr = IO.pipe
rescue
log_exception(e)
end
end
def close_all
if @log_file.closed? == false
@log_file.close()
end
if@err_file.closed? == false
@err_file.close()
end
if @log_pipe_wr.closed? == false
@log_pipe_wr.close()
end
if @error_pipe_wr.closed? == false
@error_pipe_wr.close()
end
end
def get_build_log_stream
return @log_pipe_rd
end
def get_build_err_stream
@error_pipe_rd
end
def log_build_output(line)
@log_file.puts(line)
@log_file.flush
# @log_pipe_wr.puts(line)
rescue
return
end
def log_build_errors(line)
@err_file.puts(line)
@err_file.flush
# @error_pipe_wr.puts(line)
end
def setup_framework_logging
begin
rmt_log_dir_var_fname=get_basedir + "/home/LOG_DIR"
if File.exist?(rmt_log_dir_var_fname)
rmt_log_dir_varfile = File.open(rmt_log_dir_var_fname)
rmt_log_dir = rmt_log_dir_varfile.read
else
rmt_log_dir="/var/log"
end
local_log_dir = SysConfig.SystemLogRoot + "/containers/" + @hostname
if Dir.exist?(local_log_dir) == false
Dir.mkdir( local_log_dir)
end
return " -v " + local_log_dir + ":" + rmt_log_dir + ":rw "
rescue Exception=>e
log_exception(e)
return false
end
end
def backup_lastbuild
begin
dir=get_basedir
if Dir.exist?(dir)
backup=dir + ".backup"
if Dir.exist?(backup)
FileUtils.rm_rf backup
end
FileUtils.mv(dir,backup)
end
rescue Exception=>e
log_exception(e)
return false
#throw BuildException.new(e,"backup_lastbuild")
end
end
def load_blueprint
begin
log_build_output("Reading Blueprint")
blueprint_file_name= get_basedir + "/blueprint.json"
blueprint_file = File.open(blueprint_file_name,"r")
blueprint_json_str = blueprint_file.read
blueprint_file.close
# @blueprint = JSON.parse(blueprint_json_str)
json_hash = JSON.parse(blueprint_json_str)
p :symbolized_hash
# test_hash = json_hash
# test_hash.keys.each do |key|
# test_hash[(key.to_sym rescue key) || key] = myhash.delete(key)
# end
# p test_hash
hash = SystemUtils.symbolize_keys(json_hash)
return hash
rescue Exception=>e
log_exception(e)
return false
end
end
def clone_repo
begin
log_build_output("Clone Blueprint Repository")
g = Git.clone(@repoName, @build_name, :path => SysConfig.DeploymentDir)
rescue Exception=>e
log_exception(e)
return false
end
end
# def create_cron_service
# begin
#
# log_build_output("Cron file")
#
# if @blueprint_reader.cron_jobs != nil && @blueprint_reader.cron_jobs.length >0
#
# @blueprint_reader.cron_jobs.each do |cj|
# cj_hash = Hash.new
# cj_hash[:name] =@container_name
# cj_hash[:container_name] = @container_name
# cj_hash[:cron_job]=cj
# cj_hash[:parent_engine] = @containerName
# # cron_file.puts(cj)
# # p :write_cron_job
# # p cj
# @cron_job_list.push(cj_hash)
# p @cron_job_list
# end
# # cron_file.close
# end
#
# return true
#
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
def setup_default_files
log_build_output("Setup Default Files")
if setup_global_defaults == false
return false
else
return setup_framework_defaults
end
end
#
# def create_db_service(name,flavor)
# begin
# log_build_output("Create DB Service")
# db = DatabaseService.new(@hostname,name,SysConfig.DBHost,name,name,flavor)
# databases.push(db)
# create_database_service db
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
def build_init
begin
log_build_output("Building Image")
# cmd="cd " + get_basedir + "; docker build -t " + @hostname + "/init ."
cmd="/usr/bin/docker build -t " + @container_name + "/deploy " + get_basedir
puts cmd
res = run_system(cmd)
if res != true
puts "build init failed " + res.to_s
return res
end
return res
rescue Exception=>e
log_exception(e)
return false
end
end
def launch_deploy managed_container
begin
log_build_output("Lauching Engine")
retval = managed_container.create_container
if retval == false
puts "Failed to Start Container " + managed_container.last_error
log_build_errors("Failed to Launch")
end
return retval
rescue Exception=>e
log_exception(e)
return false
end
end
def setup_global_defaults
begin
log_build_output("Setup globel defaults")
cmd= "cp -r " + SysConfig.DeploymentTemplates + "/global/* " + get_basedir
system cmd
rescue Exception=>e
log_exception(e)
return false
end
end
def setup_framework_defaults
log_build_output("Copy in default templates")
begin
cmd= "cp -r " + SysConfig.DeploymentTemplates + "/" + @blueprint_reader.framework + "/* " + get_basedir
system cmd
rescue Exception=>e
log_exception(e)
return false
end
end
def get_blueprint_from_repo
log_build_output("Backup last build")
if backup_lastbuild == false
return false
end
puts("Cloning Blueprint")
return clone_repo
end
def build_from_blue_print
if get_blueprint_from_repo == false
return false
end
return build_container
end
def read_web_port
log_build_output("Setting Web port")
begin
stef = File.open( get_basedir + "/home/stack.env","r")
while line=stef.gets do
if line.include?("PORT")
i= line.split('=')
@webPort= i[1].strip
p :web_port_line
p line
end
p @webPort
puts(@webPort)
end
rescue Exception=>e
log_exception(e)
# throw BuildException.new(e,"setting web port")
return false
end
end
def read_web_user
begin
log_build_output("Read Web User")
stef = File.open( get_basedir + "/home/stack.env","r")
while line=stef.gets do
if line.include?("USER")
i= line.split('=')
@webUser= i[1].strip
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def build_container
begin
log_build_output("Reading Blueprint")
@blueprint = load_blueprint
if @blueprint == nil || @blueprint == false
return false
end
@blueprint_reader = BluePrintReader.new(@build_name,@container_name,@blueprint,self)
@blueprint_reader.process_blueprint
if setup_default_files == false
return false
end
compile_base_docker_files
if @blueprint_reader.web_port != nil
@webPort = @blueprint_reader.web_port
else
read_web_port
end
read_web_user
create_persistant_services #need to de-register these if build fails But not deregister those that existed prior
create_template_files
create_php_ini
create_apache_config
create_scritps
@blueprint_reader.environments.each do |env|
env.value = process_templated_string(env.value)
end
index=0
#FIXME There has to be a ruby way
@blueprint_reader.sed_strings.each do |sed_string|
sed_string = process_templated_string(sed_string[:sed_str])
sed_strings[index][:sed_str] = sed_string
index+=1
end
dockerfile_builder = DockerFileBuilder.new( @blueprint_reader,@container_name, @hostname,@domain_name,@webPort,self)
dockerfile_builder.write_files_for_docker
env_file = File.new(get_basedir + "/home/app.env","a")
env_file.puts("")
@blueprint_reader.environments.each do |env|
env_file.puts(env.name)
end
@set_environments.each do |env|
env_file.puts(env[0])
end
env_file.close
setup_framework_logging
# log_build_output("Creating db Services")
# @blueprint_reader.databases.each() do |db|
# create_database_service db
# end
if build_init == false
log_build_errors("Error Build Image failed")
@last_error = " " + tail_of_build_log
post_failed_build_clean_up
return false
else
if @core_api.image_exists?(@container_name) == false
@last_error = " " + tail_of_build_log
post_failed_build_clean_up
return false
#return EnginesOSapiResult.failed(@container_name,"Build Image failed","build Image")
end
#needs to be moved to services dependant on the new BPDS
#create_cron_service
# log_build_output("Creating vol Services")
# @blueprint_reader.databases.each() do |db|
# create_database_service db
# end
#
# primary_vol=nil
# @blueprint_reader.volumes.each_value() do |vol|
# create_file_service vol
# if primary_vol == nil
# primary_vol =vol
# end
# end
log_build_output("Creating Deploy Image")
mc = create_managed_container()
if mc != nil
create_non_persistant_services
end
end
close_all
return mc
rescue Exception=>e
log_exception(e)
post_failed_build_clean_up
close_all
return false
end
end
def post_failed_build_clean_up
#remove containers
#remove persistant services (if created/new)
#deregister non persistant services (if created)
p :Clean_up_Failed_build
@blueprint_reader.services.each do |service_hash|
if service_hash[:fresh] == true
service_hash[:delete_persistant]=true
@core_api.dettach_service(service_hash) #true is delete persistant
end
end
end
def create_template_files
if @blueprint[:software].has_key?(:template_files) && @blueprint[:software][:template_files] != nil
@blueprint[:software][:template_files].each do |template_hash|
write_software_file( "/home/engines/templates/" + template_hash[:path],template_hash[:content])
end
end
end
def create_httaccess
if @blueprint[:software].has_key?(:apache_htaccess_files) && @blueprint[:software][:apache_htaccess_files] != nil
@blueprint[:software][:apache_htaccess_files].each do |htaccess_hash|
write_software_file("/home/engines/htaccess_files" + template_hash[:directory]+"/.htaccess",template_hash[:htaccess_content])
end
end
end
def create_scritps
FileUtils.mkdir_p(get_basedir() + SysConfig.ScriptsDir)
create_start_script
create_install_script
create_post_install_script
end
def create_start_script
if @blueprint[:software].has_key?(:custom_start_script) && @blueprint[:software][:custom_start_script] != nil
start_script_file = File.open(get_basedir() + SysConfig.StartScript,"w", :crlf_newline => false)
start_script_file.puts(@blueprint[:software][:custom_start_script])
start_script_file.close
File.chmod(0755,get_basedir() + SysConfig.StartScript)
end
end
def create_install_script
if @blueprint[:software].has_key?(:custom_install_script) && @blueprint[:software][:custom_install_script] != nil
install_script_file = File.open(get_basedir() + SysConfig.InstallScript,"w", :crlf_newline => false)
install_script_file.puts(@blueprint[:software][:custom_install_script])
install_script_file.close
File.chmod(0755,get_basedir() + SysConfig.InstallScript)
end
end
def create_post_install_script
if @blueprint[:software].has_key?(:custom_post_install_script) && @blueprint[:software][:custom_post_install_script] != nil
post_install_script_file = File.open(get_basedir() + SysConfig.PostInstallScript,"w", :crlf_newline => false)
post_install_script_file.puts(@blueprint[:software][:custom_post_install_script])
post_install_script_file.close
File.chmod(0755,get_basedir() + SysConfig.PostInstallScript)
end
end
def create_php_ini
FileUtils.mkdir_p(get_basedir() + File.dirname(SysConfig.CustomPHPiniFile))
if @blueprint[:software].has_key?(:custom_php_inis) && @blueprint[:software][:custom_php_inis] != nil
php_ini_file = File.open(get_basedir() + SysConfig.CustomPHPiniFile,"w", :crlf_newline => false)
@blueprint[:software][:custom_php_inis].each do |php_ini_hash|
php_ini_file.puts(php_ini_hash[:content])
end
php_ini_file.close
end
end
def create_apache_config
FileUtils.mkdir_p(get_basedir() + File.dirname(SysConfig.CustomApacheConfFile))
if @blueprint[:software].has_key?(:custom_apache_conf) && @blueprint[:software][:custom_apache_conf] != nil
write_software_file(SysConfig.CustomApacheConfFile,@blueprint[:software][:custom_apache_conf])
end
end
def write_software_file(container_filename_path,content)
dir = File.dirname(get_basedir() + container_filename_path)
p :dir_for_write_software_file
p dir
if Dir.exist?(dir) == false
FileUtils.mkdir_p(dir)
end
out_file = File.open(get_basedir() + container_filename_path ,"w", :crlf_newline => false)
content = process_templated_string(content)
out_file.puts(content)
end
def compile_base_docker_files
file_list = Dir.glob(@blueprint_reader.get_basedir + "/Dockerfile*.tmpl")
file_list.each do |file|
process_dockerfile_tmpl(file)
end
end
def process_templated_string(template)
template = apply_system_variables(template)
template = apply_build_variables(template)
template = apply_blueprint_variables(template)
template = apply_engines_variables(template)
return template
end
def process_dockerfile_tmpl(filename)
p :dockerfile_template_processing
p filename
template = File.read(filename)
template = process_templated_string(template)
output_filename = filename.sub(/.tmpl/,"")
out_file = File.new(output_filename,"w")
out_file.write(template)
out_file.close()
end
def apply_system_variables(template)
template.gsub!(/_System\([a-z].*\)/) { | match |
resolve_system_variable(match)
}
return template
end
def apply_build_variables(template)
template.gsub!(/_Builder\([a-z].*\)/) { | match |
resolve_build_variable(match)
}
return template
end
def resolve_system_variable(match)
name = match.sub!(/_System\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name
var_method = @system_access.method(name.to_sym)
val = var_method.call
p :got_val
p val
return val
rescue Exception=>e
SystemUtils.log_exception(e)
return ""
end
#_Blueprint(software,license_name)
#_Blueprint(software,rake_tasks,name)
def apply_blueprint_variables(template)
template.gsub!(/_Blueprint\([a-z,].*\)/) { | match |
resolve_blueprint_variable(match)
}
return template
end
def resolve_blueprint_variable(match)
name = match.sub!(/_Blueprint\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name
val =""
keys = name.split(',')
hash = @builder_public.blueprint
keys.each do |key|
if key == nil || key.length < 1
break
end
p :key
p key
val = hash[key.to_sym]
p :val
p val
if val != nil
hash=val
end
end
p :got_val
p val
return val
rescue Exception=>e
SystemUtils.log_exception(e)
return ""
end
def resolve_build_variable(match)
name = match.sub!(/_Builder\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name.to_sym
if name.include?('(') == true
cmd = name.split('(')
name = cmd[0]
if cmd.count >1
args = cmd[1]
args_array = args.split
end
end
var_method = @builder_public.method(name.to_sym)
if args
p :got_args
val = var_method.call args
else
val = var_method.call
end
p :got_val
p val
return val
rescue Exception=>e
SystemUtils.log_exception(e)
return ""
end
def resolve_engines_variable
name = match.sub!(/_Engines\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name.to_sym
return @blueprint_reader.environments[name.to_sym]
rescue Exception=>e
p @blueprint_reader.environments
SystemUtils.log_exception(e)
return ""
end
def apply_engines_variables(template)
template.gsub!(/_Engines\([a-z].*\)/) { | match |
resolve_engines_variable(match)
}
return template
end
def create_non_persistant_services
@blueprint_reader.services.each() do |service_hash|
#FIX ME Should call this but Keys dont match blueprint designer issue
#@core_api.add_service(service,mc)
service_hash[:parent_engine]=@container_name
service_def = get_service_def(service_hash)
if service_def == nil
p :failed_to_load_service_definition
p service_hash[:type_path]
p service_hash[:publisher_namespace]
return false
end
if service_def[:persistant] == true
next
end
service_hash[:service_handle] = service_hash[:variables][:name]
p :adding_service
p service_hash
@core_api.attach_service(service_hash)
end
end
def get_service_def(service_hash)
p service_hash[:type_path]
p service_hash[:publisher_namespace]
return SoftwareServiceDefinition.find(service_hash[:type_path], service_hash[:publisher_namespace] )
end
def create_persistant_services
@blueprint_reader.services.each() do |service_hash|
service_hash[:parent_engine]=@container_name
# p :service_def_for
# p service_hash[:type_path]
# p service_hash[:publisher_namespace]
service_def = get_service_def(service_hash)
# p service_def
if service_def == nil
p :failed_to_load_service_definition
p :servicetype_name
p service_hash[:service_type]
p :service_provider
p service_hash[:publisher_namespace]
return false
end
if service_def[:persistant] == false
next
end
p :adding_service
puts "+=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++"
p service_hash
puts "+=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++"
p :target_envs
p service_def[:target_environment_variables]
if service_hash[:servicetype_name] == "filesystem"
add_file_service(service[:name], service[:engine_path])
end
service_hash[:service_handle] = service_hash[:variables][:name]
p :LOOKING_FOR_
p service_hash
if @core_api.find_service_consumers(service_hash) == false
@first_build = true
service_hash[:fresh]=true
else
service_hash[:fresh]=false
@first_build = false
end
p :attach_service
p service_hash
@core_api.attach_service(service_hash)
end
end
def fill_in_dynamic_vars(service_hash)
p "FILLING_+@+#+@+@+@+@+@+"
if service_hash.has_key?(:variables) == false || service_hash[:variables] == nil
return
end
service_hash[:variables].each do |variable|
p variable
if variable[1] != nil && variable[1].start_with?("$_")
variable[1].sub!(/\$/,"")
result = evaluate_function(variable[1])
service_hash[:variables][variable[0]] = result
end
end
end
def evaluate_function(function)
if function.start_with?("_System")
return resolve_system_variable(function)
elsif function.start_with?("_Builder")
return resolve_build_variable(function)
elsif function.start_with?("_Blueprint")
return resolve_blueprint_variable(function)
end
rescue Exception=> e
return ""
end
def tail_of_build_log
retval = String.new
lines = File.readlines(SysConfig.DeploymentDir + "/build.out")
lines_count = lines.count -1
start = lines_count - 10
for n in start..lines_count
retval+=lines[n]
end
return retval
end
def rebuild_managed_container engine
@engine = engine
log_build_output("Starting Rebuild")
if backup_lastbuild == false
return false
elsif setup_rebuild == false
return false
else
return build_container
end
end
def setup_rebuild
begin
log_build_output("Setting up rebuild")
FileUtils.mkdir_p(get_basedir)
blueprint = @core_api.load_blueprint(@engine)
statefile= get_basedir + "/blueprint.json"
f = File.new(statefile,File::CREAT|File::TRUNC|File::RDWR, 0644)
f.write(blueprint.to_json)
f.close
rescue Exception=>e
log_exception(e)
return false
end
end
def create_managed_container
log_build_output("Creating ManagedEngine")
mc = ManagedEngine.new(@hostname,
@blueprint_reader.memory.to_s ,
@hostname,
@domain_name,
@container_name + "/deploy",
@blueprint_reader.volumes,
@webPort,
@blueprint_reader.workerPorts,
@repoName,
@blueprint_reader.databases,
@blueprint_reader.environments,
@blueprint_reader.framework,
@blueprint_reader.runtime,
@core_api,
@blueprint_reader.data_uid,
@blueprint_reader.data_gid
)
p :set_cron_job_list
p @cron_job_list
mc.set_cron_job_list(@cron_job_list)
#:http_protocol=>"HTTPS and HTTP"
mc.set_protocol(@protocol)
mc.conf_register_site=( true) # needs some intelligence here for worker only
mc.conf_self_start= (true)
mc.save_state # no config.yaml throws a no such container so save so others can use
if mc.save_blueprint(@blueprint) == false
log_build_errors( "Failed to save blueprint " + @blueprint.to_s)
end
bp = mc.load_blueprint
p bp
log_build_output("Launching")
#this will fail as no api at this stage
if mc.core_api != nil
if launch_deploy(mc) == false
log_build_errors("Failed to Launch")
end
log_build_output("Applying Volume settings and Log Permissions")
#FIXME need to check results from following
@core_api.run_volume_builder(mc ,@webUser)
# mc.start_container
end
return mc
end
protected
def log_exception(e)
log_build_errors( e.to_s)
puts(e.to_s)
@last_error= e.to_s
n=0
e.backtrace.each do |bt |
p bt
if n>10
break
end
++n
end
#close_all
end
def debug(fld)
puts "ERROR: "
p fld
end
require 'open3'
def run_system(cmd)
log_build_output("Running " + cmd)
ret_val=false
res = String.new
error_mesg = String.new
begin
Open3.popen3( cmd ) do |stdin, stdout, stderr, th|
oline = String.new
stderr_is_open=true
begin
stdout.each { |line|
# print line
line = line.gsub(/\\\"/,"")
res += line.chop
oline = line
log_build_output(line)
if stderr_is_open
err = stderr.read_nonblock(1000)
error_mesg += err
log_build_errors(err)
end
}
rescue Errno::EIO
res += line.chop
log_build_output(oline)
if stderr_is_open
err = stderr.read_nonblock(1000)
error_mesg += err
log_build_errors(err)
p :EIO_retry
retry
end
rescue IO::WaitReadable
# p :wait_readable_retrt
retry
rescue EOFError
if stdout.closed? == false
stderr_is_open = false
p :EOF_retry
retry
else if stderr.closed? == true
return
else
err = stderr.read_nonblock(1000)
error_mesg += err
log_build_errors(err)
return
end
end
end
if error_mesg.include?("Error:") || error_mesg.include?("FATA")
p "docker_cmd error " + error_mesg
return false
end
return true
end
end
end
def get_basedir
return SysConfig.DeploymentDir + "/" + @build_name
end
end
sed_strings is a hash of arrays
require "/opt/engines/lib/ruby/ManagedContainer.rb"
require "/opt/engines/lib/ruby/ManagedContainerObjects.rb"
require "/opt/engines/lib/ruby/ManagedEngine.rb"
require "/opt/engines/lib/ruby/ManagedServices.rb"
require "/opt/engines/lib/ruby/SysConfig.rb"
require "rubygems"
require "git"
require 'fileutils'
require 'json'
require '/opt/engines/lib/ruby/SystemAccess.rb'
class EngineBuilder
@repoName=nil
@hostname=nil
@domain_name=nil
@build_name=nil
@web_protocol="HTTPS and HTTP"
attr_reader :last_error,
:repoName,
:hostname,
:domain_name,
:build_name,
:set_environments,
:container_name,
:environments,
:runtime,
:webPort,
:http_protocol,
:blueprint,
:first_build
class BuildError < StandardError
attr_reader :parent_exception,:method_name
def initialize(parent,method_name)
@parent_exception = parent
end
end
class DockerFileBuilder
def initialize(reader,containername,hostname,domain_name,webport,builder)
@hostname = hostname
@container_name = containername
@domain_name = domain_name
@webPort = webport
@blueprint_reader = reader
@builder=builder
@docker_file = File.open( @blueprint_reader.get_basedir + "/Dockerfile","a")
@layer_count=0
end
def log_build_output(line)
@builder.log_build_output(line)
end
def log_build_errors(line)
@builder.log_build_errors(line)
end
def count_layer
++@layer_count
if @layer_count >75
raise EngineBuilder.BuildError.new()
end
end
def write_files_for_docker
@docker_file.puts("")
write_environment_variables
write_stack_env
write_services
write_file_service
#write_db_service
#write_cron_jobs
write_os_packages
write_apache_modules
write_user_local = true
if write_user_local == true
@docker_file.puts("RUN ln -s /usr/local/ /home/local;\\")
@docker_file.puts(" chown -R $ContUser /usr/local/")
end
write_app_archives
write_container_user
chown_home_app
write_worker_commands
write_sed_strings
write_persistant_dirs
write_persistant_files
insert_framework_frag_in_dockerfile("builder.mid.tmpl")
@docker_file.puts("")
write_rake_list
write_pear_list
write_write_permissions_recursive #recursive firs (as can use to create blank dir)
write_write_permissions_single
@docker_file.puts("")
@docker_file.puts("USER 0")
count_layer()
@docker_file.puts("run mkdir -p /home/fs/local/")
count_layer()
@docker_file.puts("")
write_run_install_script
write_data_permissions
@docker_file.puts("USER 0")
count_layer()
@docker_file.puts("run mv /home/fs /home/fs_src")
count_layer()
@docker_file.puts("VOLUME /home/fs_src/")
count_layer()
@docker_file.puts("USER $ContUser")
count_layer()
insert_framework_frag_in_dockerfile("builder.end.tmpl")
@docker_file.puts("")
@docker_file.puts("VOLUME /home/fs/")
count_layer()
write_clear_env_variables
@docker_file.close
end
def write_clear_env_variables
@docker_file.puts("#Clear env")
@blueprint_reader.environments.each do |env|
if env.build_time_only == true
@docker_file.puts("ENV " + env.name + "\" \"")
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
def write_apache_modules
if @blueprint_reader.apache_modules.count <1
return
end
@docker_file.puts("#Apache Modules")
ap_modules_str = String.new
@blueprint_reader.apache_modules.each do |ap_module|
ap_modules_str += ap_module + " "
end
@docker_file.puts("RUN a2enmod " + ap_modules_str)
count_layer()
end
def write_environment_variables
begin
@docker_file.puts("#Environment Variables")
#Fixme
#kludge
@docker_file.puts("#System Envs")
@docker_file.puts("ENV TZ Sydney/Australia")
count_layer
@blueprint_reader.environments.each do |env|
@docker_file.puts("#Blueprint ENVs")
if env.value != nil
env.value.sub!(/ /,"\\ ")
end
if env.value !=nil && env.value.to_s.length >0 #env statement must have two arguments
@docker_file.puts("ENV " + env.name + " " + env.value.to_s )
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_persistant_dirs
begin
log_build_output("setup persistant Dirs")
n=0
@docker_file.puts("#Persistant Dirs")
@blueprint_reader.persistant_dirs.each do |path|
path.chomp!("/")
@docker_file.puts("")
@docker_file.puts("RUN \\")
dirname = File.dirname(path)
@docker_file.puts("mkdir -p $CONTFSVolHome/$VOLDIR/" + dirname + ";\\")
@docker_file.puts("if [ ! -d /home/" + path + " ];\\")
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir -p /home/" + path +" ;\\")
@docker_file.puts(" fi;\\")
@docker_file.puts("mv /home/" + path + " $CONTFSVolHome/$VOLDIR/" + dirname + "/;\\")
@docker_file.puts("ln -s $CONTFSVolHome/$VOLDIR/" + path + " /home/" + path)
n=n+1
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_data_permissions
@docker_file.puts("#Data Permissions")
@docker_file.puts("USER 0")
count_layer()
@docker_file.puts("")
@docker_file.puts("RUN /usr/sbin/usermod -u $data_uid data-user;\\")
@docker_file.puts("chown -R $data_uid.$data_gid /home/app /home/fs ;\\")
@docker_file.puts("chmod -R 770 /home/fs")
count_layer
@docker_file.puts("USER $ContUser")
count_layer
end
def write_run_install_script
@docker_file.puts("WorkDir /home/")
@docker_file.puts("#Setup templates and run installer")
@docker_file.puts("USER $ContUser")
count_layer
@docker_file.puts("RUN bash /home/setup.sh")
count_layer
end
def write_persistant_files
begin
@docker_file.puts("#Persistant Files")
log_build_output("set setup_env")
src_paths = @blueprint_reader.persistant_files[:src_paths]
dest_paths = @blueprint_reader.persistant_files[:dest_paths]
src_paths.each do |path|
# path = dest_paths[n]
p :path
p path
dir = File.dirname(path)
p :dir
p dir
if dir.present? == false || dir == nil || dir.length ==0 || dir =="."
dir = "app/"
end
p :dir
p dir
@docker_file.puts("")
@docker_file.puts("RUN mkdir -p /home/" + dir + ";\\")
@docker_file.puts(" if [ ! -f /home/" + path + " ];\\")
@docker_file.puts(" then \\")
@docker_file.puts(" touch /home/" + path +";\\")
@docker_file.puts(" fi;\\")
@docker_file.puts(" mkdir -p $CONTFSVolHome/$VOLDIR/" + dir +";\\")
@docker_file.puts("\\")
@docker_file.puts(" mv /home/" + path + " $CONTFSVolHome/$VOLDIR" + "/" + dir + ";\\")
@docker_file.puts(" ln -s $CONTFSVolHome/$VOLDIR/" + path + " /home/" + path)
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_file_service
begin
@docker_file.puts("#File Service")
@docker_file.puts("#FS Env")
# @docker_file.puts("ENV CONTFSVolHome /home/fs/" )
# count_layer
@blueprint_reader.volumes.each_value do |vol|
dest = File.basename(vol.remotepath)
# @docker_file.puts("ENV VOLDIR /home/fs/" + dest)
# count_layer
@docker_file.puts("RUN mkdir -p $CONTFSVolHome/" + dest)
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_services
services = @blueprint_reader.services
@docker_file.puts("#Service Environment Variables")
services.each do |service_hash|
p :service_hash
p service_hash
service_def = @builder.get_service_def(service_hash)
if service_def != nil
p :processing
p service_def
service_environment_variables = service_def[:target_environment_variables]
if service_environment_variables != nil
service_environment_variables.values.each do |env_variable_pair|
p :setting_values
p env_variable_pair
env_name = env_variable_pair[:environment_name]
value_name = env_variable_pair[:variable_name]
value=service_hash[:variables][value_name.to_sym]
p :looking_for_
p value_name
p :as_symbol
p value_name.to_sym
p :in_service_hash
p service_hash
p :and_found
p value
if value != nil && value.to_s.length >0
@docker_file.puts("ENV " + env_name + " " + value )
count_layer()
end
end
end
end
end
end
def write_sed_strings
begin
n=0
@docker_file.puts("#Sed Strings")
@blueprint_reader.sed_strings[:src_file].each do |src_file|
#src_file = @sed_strings[:src_file][n]
dest_file = @blueprint_reader.sed_strings[:dest_file][n]
sed_str = @blueprint_reader.sed_strings[:sed_str][n]
tmp_file = @blueprint_reader.sed_strings[:tmp_file][n]
@docker_file.puts("")
@docker_file.puts("RUN cat " + src_file + " | sed \"" + sed_str + "\" > " + tmp_file + " ;\\")
@docker_file.puts(" cp " + tmp_file + " " + dest_file)
count_layer
n=n+1
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_rake_list
begin
@docker_file.puts("#Rake Actions")
@blueprint_reader.rake_actions.each do |rake_action|
rake_cmd = rake_action[:action]
if @builder.first_build == false && rake_action[:always_run] == false
next
end
if rake_cmd !=nil
@docker_file.puts("RUN /usr/local/rbenv/shims/bundle exec rake " + rake_cmd )
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_os_packages
begin
packages=String.new
@docker_file.puts("#OS Packages")
@blueprint_reader.os_packages.each do |package|
if package != nil
packages = packages + package + " "
end
end
if packages.length >1
@docker_file.puts("\nRUN apt-get install -y " + packages )
count_layer
end
#FIXME Wrong spot
@blueprint_reader.workerPorts.each do |port|
@docker_file.puts("EXPOSE " + port.port.to_s)
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def insert_framework_frag_in_dockerfile(frag_name)
begin
log_build_output(frag_name)
@docker_file.puts("#Framework Frag")
frame_build_docker_frag = File.open(SysConfig.DeploymentTemplates + "/" + @blueprint_reader.framework + "/Dockerfile." + frag_name)
builder_frag = frame_build_docker_frag.read
@docker_file.write(builder_frag)
count_layer
rescue Exception=>e
log_exception(e)
return false
end
end
def chown_home_app
begin
@docker_file.puts("#Chown App Dir")
log_build_output("Dockerfile:Chown")
@docker_file.puts("USER 0")
count_layer
@docker_file.puts("RUN if [ ! -d /home/app ];\\")
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir -p /home/app ;\\")
@docker_file.puts(" fi;\\")
@docker_file.puts(" mkdir -p /home/fs ; mkdir -p /home/fs/local ;\\")
@docker_file.puts(" chown -R $ContUser /home/app /home/fs /home/fs/local")
count_layer
@docker_file.puts("USER $ContUser")
count_layer
rescue Exception=>e
log_exception(e)
return false
end
end
def write_worker_commands
begin
@docker_file.puts("#Worker Commands")
log_build_output("Dockerfile:Worker Commands")
scripts_path = @blueprint_reader.get_basedir + "/home/engines/scripts/"
if Dir.exist?(scripts_path) == false
FileUtils.mkdir_p(scripts_path)
end
if @blueprint_reader.worker_commands != nil && @blueprint_reader.worker_commands.length >0
cmdf= File.open( scripts_path + "pre-running.sh","w")
if !cmdf
puts("failed to open " + scripts_path + "pre-running.sh")
exit
end
cmdf.chmod(0755)
cmdf.puts("#!/bin/bash")
cmdf.puts("cd /home/app")
@blueprint_reader.worker_commands.each do |command|
cmdf.puts(command)
end
cmdf.close
File.chmod(0755,scripts_path + "pre-running.sh")
end
rescue Exception=>e
log_exception(e)
return false
end
end
# def write_cron_jobs
# begin
# if @blueprint_reader.cron_jobs.length >0
# @docker_file.puts("ENV CRONJOBS YES")
# count_layer
## @docker_file.puts("RUN crontab $data_uid /home/crontab ")
## count_layer cron run from cron service
# end
# return true
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
# def write_db_service
# begin
# @docker_file.puts("#Database Service")
# log_build_output("Dockerfile:DB env")
# @blueprint_reader.databases.each do |db|
# @docker_file.puts("#Database Env")
# @docker_file.puts("ENV dbname " + db.name)
# count_layer
# @docker_file.puts("ENV dbhost " + db.dbHost)
# count_layer
# @docker_file.puts("ENV dbuser " + db.dbUser)
# count_layer
# @docker_file.puts("ENV dbpasswd " + db.dbPass)
# count_layer
# flavor = db.flavor
# if flavor == "mysql"
# flavor = "mysql2"
# elsif flavor == "pgsql"
# flavor = "postgresql"
# end
# @docker_file.puts("ENV dbflavor " + flavor)
# count_layer
# end
#
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
def write_write_permissions_single
begin
@docker_file.puts("")
@docker_file.puts("#Write Permissions Non Recursive")
log_build_output("Dockerfile:Write Permissions Non Recursive")
if @blueprint_reader.single_chmods == nil
return
end
@blueprint_reader.single_chmods.each do |path|
if path !=nil
@docker_file.puts("RUN if [ ! -f /home/app/" + path + " ];\\" )
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir -p `dirname /home/app/" + path + "`;\\")
@docker_file.puts(" touch /home/app/" + path + ";\\")
@docker_file.puts(" fi;\\")
@docker_file.puts( " chmod 775 /home/app/" + path )
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_write_permissions_recursive
begin
@docker_file.puts("#Write Permissions Recursive")
@docker_file.puts("")
log_build_output("Dockerfile:Write Permissions Recursive")
if @blueprint_reader.recursive_chmods == nil
return
end
@blueprint_reader.recursive_chmods.each do |directory|
if directory !=nil
@docker_file.puts("RUN if [ -h /home/app/" + directory + " ] ;\\")
@docker_file.puts(" then \\")
@docker_file.puts(" dest=`ls -la /home/app/" + directory +" |cut -f2 -d\">\"`;\\")
@docker_file.puts(" chmod -R gu+rw $dest;\\")
@docker_file.puts(" elif [ ! -d /home/app/" + directory + " ] ;\\" )
@docker_file.puts(" then \\")
@docker_file.puts(" mkdir \"/home/app/" + directory + "\";\\")
@docker_file.puts(" chmod -R gu+rw \"/home/app/" + directory + "\";\\" )
@docker_file.puts(" else\\")
@docker_file.puts(" chmod -R gu+rw \"/home/app/" + directory + "\";\\")
@docker_file.puts(" for dir in `find /home/app/" + directory + " -type d `;\\")
@docker_file.puts(" do\\")
@docker_file.puts(" adir=`echo $dir | sed \"/ /s//_+_/\" |grep -v _+_` ;\\")
@docker_file.puts(" if test -n $adir;\\")
@docker_file.puts(" then\\")
@docker_file.puts(" dirs=\"$dirs $adir\";\\");
@docker_file.puts(" fi;\\")
@docker_file.puts(" done;\\")
@docker_file.puts(" if test -n \"$dirs\" ;\\")
@docker_file.puts(" then\\")
@docker_file.puts(" chmod gu+x $dirs ;\\")
@docker_file.puts("fi;\\")
@docker_file.puts("fi")
count_layer
end
end
end
rescue Exception=>e
log_exception(e)
return false
end
def write_app_archives
begin
@docker_file.puts("#App Archives")
log_build_output("Dockerfile:App Archives")
n=0
# srcs=String.new
# names=String.new
# locations=String.new
# extracts=String.new
# dirs=String.new
@docker_file.puts("")
@blueprint_reader.archives_details.each do |archive_details|
arc_src = archive_details[:source_url]
arc_name = archive_details[:package_name]
arc_loc = archive_details[:destination]
arc_extract = archive_details[:extraction_command]
arc_dir = archive_details[:path_to_extracted]
# if(n >0)
# archive_details[:source_url]=arc_src
# archive_details[:package_name]=arc_name
# archive_details[:extraction_cmd]=arc_extract
# archive_details[:destination]=arc_loc
# archive_details[:path_to_extracted]=arc_dir
# srcs = srcs + " "
# names =names + " "
# locations = locations + " "
# extracts =extracts + " "
# dirs =dirs + " "
# end
p "_+_+_+_+_+_+_+_+_+_+_"
p archive_details
p arc_src + "_"
p arc_name + "_"
p arc_loc + "_"
p arc_extract + "_"
p arc_dir +"|"
if arc_loc == "./"
arc_loc=""
elsif arc_loc.end_with?("/")
arc_loc = arc_loc.chop() #note not String#chop
end
if arc_extract == "git"
@docker_file.puts("WORKDIR /tmp")
count_layer
@docker_file.puts("USER $ContUser")
count_layer
@docker_file.puts("RUN git clone " + arc_src + " --depth 1 " )
count_layer
@docker_file.puts("USER 0 ")
count_layer
@docker_file.puts("RUN mv " + arc_dir + " /home/app" + arc_loc )
count_layer
@docker_file.puts("USER $ContUser")
count_layer
else
@docker_file.puts("USER $ContUser")
count_layer
step_back=false
if arc_dir == nil
step_back=true
@docker_file.puts("RUN mkdir /tmp/app")
count_layer
arc_dir = "app"
@docker_file.puts("WORKDIR /tmp/app")
count_layer
else
@docker_file.puts("WORKDIR /tmp")
count_layer
end
@docker_file.puts("RUN wget -O \"" + arc_name + "\" \"" + arc_src + "\" ;\\" )
if arc_extract!= nil
@docker_file.puts(" " + arc_extract + " \"" + arc_name + "\" ;\\") # + "\"* 2>&1 > /dev/null ")
@docker_file.puts(" rm \"" + arc_name + "\"")
else
@docker_file.puts("echo") #step past the next shell line implied by preceeding ;
end
@docker_file.puts("USER 0 ")
count_layer
if step_back==true
@docker_file.puts("WORKDIR /tmp")
count_layer
end
if arc_loc.start_with?("/home/app") || arc_loc.start_with?("/home/local/")
dest_prefix=""
else
dest_prefix="/home/app"
end
@docker_file.puts("run if test ! -d " + arc_dir +" ;\\")
@docker_file.puts(" then\\")
@docker_file.puts(" mkdir -p /home/app ;\\")
@docker_file.puts(" fi;\\")
@docker_file.puts(" mv " + arc_dir + " " + dest_prefix + arc_loc )
count_layer
@docker_file.puts("USER $ContUser")
count_layer
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_container_user
begin
@docker_file.puts("#Container Data User")
log_build_output("Dockerfile:User")
#FIXME needs to by dynamic
@docker_file.puts("ENV data_gid " + @blueprint_reader.data_uid)
count_layer
@docker_file.puts("ENV data_uid " + @blueprint_reader.data_gid)
count_layer
rescue Exception=>e
log_exception(e)
return false
end
end
def write_stack_env
begin
log_build_output("Dockerfile:Stack Environment")
@docker_file.puts("#Stack Env")
# stef = File.open(get_basedir + "/home/stack.env","w")
@docker_file.puts("")
@docker_file.puts("#Stack Env")
@docker_file.puts("ENV Memory " + @blueprint_reader.memory.to_s)
count_layer
@docker_file.puts("ENV Hostname " + @hostname)
count_layer
@docker_file.puts("ENV Domainname " + @domain_name )
count_layer
@docker_file.puts("ENV fqdn " + @hostname + "." + @domain_name )
count_layer
@docker_file.puts("ENV FRAMEWORK " + @blueprint_reader.framework )
count_layer
@docker_file.puts("ENV RUNTIME " + @blueprint_reader.runtime )
count_layer
@docker_file.puts("ENV PORT " + @webPort.to_s )
count_layer
wports = String.new
n=0
@blueprint_reader.workerPorts.each do |port|
if n < 0
wports =wports + " "
end
@docker_file.puts("EXPOSE " + port.port.to_s)
count_layer
wports = wports + port.port.to_s
n=n+1
end
if wports.length >0
@docker_file.puts("ENV WorkerPorts " + "\"" + wports +"\"")
count_layer
end
rescue Exception=>e
log_exception(e)
return false
end
end
def write_pear_list
@docker_file.puts("#OPear List")
log_build_output("Dockerfile:Pear List")
if @blueprint_reader.pear_modules.count >0
@docker_file.puts("RUN wget http://pear.php.net/go-pear.phar;\\")
@docker_file.puts(" echo suhosin.executor.include.whitelist = phar >>/etc/php5/conf.d/suhosin.ini ;\\")
@docker_file.puts(" php go-pear.phar")
count_layer
@blueprint_reader.pear_modules.each do |pear_mod|
if pear_mod !=nil
@docker_file.puts("RUN pear install pear_mod " + pear_mod )
count_layer
end
end
end
rescue Exception=>e
log_exception(e)
return false
end
protected
def log_exception(e)
log_build_errors( e.to_s)
puts(e.to_s)
@last_error= e.to_s
e.backtrace.each do |bt |
p bt
end
return false
end
##################### End of
end
class BluePrintReader
def initialize(build_name,contname,blue_print,builder)
@build_name = build_name
@data_uid="11111"
@data_gid="11111"
@builder=builder
@container_name = contname
@blueprint = blue_print
@web_port=nil
@services = Array.new
end
attr_reader :persistant_files,
:persistant_dirs,
:last_error,
:workerPorts,
:environments,
:recursive_chmods,
:single_chmods,
:framework,
:runtime,
:memory,
:rake_actions,
:os_packages,
:pear_modules,
:archives_details,
:worker_commands,
:cron_jobs,
:sed_strings,
:volumes,
:databases,
:apache_modules,
:data_uid,
:data_gid,
:cron_job_list,
:web_port,
:services
def log_build_output(line)
@builder.log_build_output(line)
end
def log_build_errors(line)
@builder.log_build_errors(line)
end
def clean_path(path)
#FIXME remove preceeding ./(s) and /(s) as well as obliterate any /../ or preceeding ../ and any " " or ";" or "&" or "|" etc
return path
end
def get_basedir
return SysConfig.DeploymentDir + "/" + @build_name
end
def log_exception(e)
log_build_errors(e.to_s)
puts(e.to_s)
#@last_error= e.to_s
e.backtrace.each do |bt |
p bt
end
end
def process_blueprint
begin
log_build_output("Process BluePrint")
read_services
read_environment_variables
read_os_packages
read_lang_fw_values
read_pear_list
read_app_packages
read_apache_modules
read_write_permissions_recursive
read_write_permissions_single
read_worker_commands
# read_cron_jobs
read_sed_strings
read_work_ports
read_os_packages
read_app_packages
read_rake_list
read_persistant_files
read_persistant_dirs
read_web_port_overide
rescue Exception=>e
log_exception(e)
end
end
def read_web_port_overide
if @blueprint[:software].has_key?(:read_web_port_overide) == true
@web_port=@blueprint[:software][:read_web_port_overide]
end
end
def read_persistant_dirs
begin
log_build_output("Read Persistant Dirs")
@persistant_dirs = Array.new
pds = @blueprint[:software][:persistent_directories]
pds.each do |dir|
@persistant_dirs.push(dir[:path])
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_persistant_files
begin
log_build_output("Read Persistant Files")
@persistant_files = Hash.new
src_paths = Array.new
dest_paths = Array.new
pfs = @blueprint[:software][:persistent_files]
if pfs == nil
return
end
files= String.new
pfs.each do |file|
path = clean_path(file[:path])
#link_src = path.sub(/app/,"")
src_paths.push(path)
end
p :src_paths
p src_paths
p :dest_paths
p dest_paths
@persistant_files[:src_paths]= src_paths
rescue Exception=>e
log_exception(e)
return false
end
end
def read_rake_list
begin
@rake_actions = Array.new
log_build_output("Read Rake List")
rake_cmds = @blueprint[:software][:rake_tasks]
if rake_cmds == nil
return
end
rake_cmds.each do |rake_cmd|
@rake_actions.push(rake_cmd)
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_services
@databases=Array.new
@volumes=Hash.new
log_build_output("Read Services")
services=@blueprint[:software][:service_configurations]
if services == nil
return
end
services.each do |service|
if service.has_key?(:publisher_namespace) == false || service[:publisher_namespace] == nil
service[:publisher_namespace] = "EnginesSystem"
end
service[:service_type]=service[:type_path]
p :service_provider
p service[:publisher_namespace]
p :servicetype_name
p service[:type_path]
# servicetype=service[:type_path]
#
# if servicetype == "database/sql/mysql" || servicetype == "database/sql/pgsql"
# dbname = service[:name]
# dest = service[:dest]
# if dest =="local" || dest == nil
# #FIXME
# #kludge until BPDS is complete
# service[:dest] = SysConfig.DBHost
# service[:type] = servicetype.sub(/.*database\/.*\//,"")
# p :kludge_set_type
# p service[:type]
# service[:dbfavor] = "mysql2"
# p :kludge_set_dbfavor
# p service[:dbfavor]
#
# # if flavor == "mysql"
# # flavor = "mysql2"
# # elsif flavor == "pgsql"
# end
# elsif servicetype=="filesystem"
# service[:name] = clean_path(service[:name])
# service[:dest] = clean_path(service[:dest])
# add_file_service(service[:name], service[:dest])
# end
add_service(service)
# end
# end
end
end #FIXME
def add_service (service_hash)
p :add_service
p service_hash
@builder.fill_in_dynamic_vars(service_hash)
if service_hash[:service_type] == "filesystem"
add_file_service(service_hash[:variables][:name],service_hash[:variables][:engine_path])
end
@services.push(service_hash)
end
def add_file_service(name,dest) #FIXME and put me in coreapi
begin
log_build_output("Add File Service " + name)
if dest == nil || dest == ""
dest=name
end
if(dest.start_with?("/home/app/") == false )
if(dest.start_with?("/home/fs/") == false)
if dest != "/home/app"
p :dest
p "_" + dest + "_"
dest="/home/fs/" + dest
end
end
end
permissions = PermissionRights.new(@container_name,"","")
vol=Volume.new(name,SysConfig.LocalFSVolHome + "/" + @container_name + "/" + name,dest,"rw",permissions)
@volumes[name]=vol
rescue Exception=>e
p name
p dest
p @container_name
log_exception(e)
return false
end
end
# def add_db_service(dbname,servicetype)
# p servicetype
# flavor = servicetype.sub(/.*database\//,"")
# p :adding_db
# p dbname
# p servicetype
# log_build_output("Add DB Service " + dbname)
# hostname = flavor + "." + SysConfig.internalDomain
# db = DatabaseService.new(@container_name,dbname,hostname,dbname,dbname,flavor)
#
# @databases.push(db)
#
# end
def read_os_packages
begin
@os_packages = Array.new
log_build_output("Read OS Packages")
ospackages = @blueprint[:software][:system_packages]
if ospackages == nil
return
end
ospackages.each do |package|
@os_packages.push(package[:name])
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_lang_fw_values
log_build_output("Read Framework Settings")
begin
@framework = @blueprint[:software][:framework]
p @framework
@runtime = @blueprint[:software][:language]
@memory = @blueprint[:software][:required_memory]
rescue Exception=>e
log_exception(e)
return false
end
end
def read_pear_list
begin
@pear_modules = Array.new
log_build_output("Read Pear List")
pear_mods = @blueprint[:software][:pear_mod]
if pear_mods == nil || pear_mods.length == 0
return
pear_mods.each do |pear_mod|
mod = pear_mod[:module]
if mod !=nil
@pear_modules.push(mod)
end
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_apache_modules
@apache_modules = Array.new
log_build_output("Read Apache Modules List")
mods = @blueprint[:software][:apache_modules]
if mods == nil
return true
end
mods.each do |ap_module|
mod = ap_module[:module]
os_package = ap_module[:os_package]
if mod != nil
@apache_modules.push(mod)
end
end
return true
rescue Exception=>e
log_exception(e)
return false
end
def read_app_packages
begin
log_build_output("Read App Packages ")
@archives_details = Array.new
log_build_output("Configuring install Environment")
archives = @blueprint[:software][:installed_packages]
n=0
archives.each do |archive|
archive_details = Hash.new
arc_src=clean_path(archive[:source_url])
arc_name=clean_path(archive[:name])
arc_loc =clean_path(archive[:destination])
arc_extract=clean_path(archive[:extraction_command])
arc_dir=clean_path(archive[:path_to_extracted])
if arc_loc == "./"
arc_loc=""
elsif arc_loc.end_with?("/")
arc_loc = arc_loc.chop() #note not String#chop
end
archive_details[:source_url]=arc_src
archive_details[:package_name]=arc_name
archive_details[:extraction_command]=arc_extract
archive_details[:destination]=arc_loc
archive_details[:path_to_extracted]=arc_dir
p :read_in_arc_details
p archive_details
@archives_details.push(archive_details)
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_write_permissions_recursive
begin
log_build_output("Read Recursive Write Permissions")
@recursive_chmods = Array.new
log_build_output("set permissions recussive")
chmods = @blueprint[:software][:file_write_permissions]
p :Single_Chmods
if chmods != nil
chmods.each do |chmod |
p chmod
if chmod[:recursive]==true
directory = clean_path(chmod[:path])
p directory
@recursive_chmods.push(directory)
end
end
#FIXME need to strip any ../ and any preceeding ./
return
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_write_permissions_single
begin
log_build_output("Read Non-Recursive Write Permissions")
@single_chmods =Array.new
log_build_output("set permissions single")
chmods = @blueprint[:software][:file_write_permissions]
p :Recursive_Chmods
if chmods != nil
chmods.each do |chmod |
p chmod
if chmod[:recursive]==false
p chmod[:path]
directory = clean_path(chmod[:path])
@single_chmods.push(directory)
end
end
end
return true
rescue Exception=>e
log_exception(e)
return false
end
end
def read_worker_commands
begin
log_build_output("Read Workers")
@worker_commands = Array.new
workers =@blueprint[:software][:workers]
workers.each do |worker|
@worker_commands.push(worker[:command])
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_sed_strings
begin
log_build_output("Read Sed Strings")
@sed_strings = Hash.new
@sed_strings[:src_file] = Array.new
@sed_strings[:dest_file] = Array.new
@sed_strings[:sed_str] = Array.new
@sed_strings[:tmp_file] = Array.new
log_build_output("set sed strings")
seds=@blueprint[:software][:replacement_strings]
if seds == nil || seds.empty? == true
return
end
n=0
seds.each do |sed|
file = clean_path(sed[:file])
dest = clean_path(sed[:destination])
tmp_file = "/tmp/" + File.basename(file) + "." + n.to_s
if file.match(/^_TEMPLATES.*/) != nil
template_file = file.gsub(/^_TEMPLATES/,"")
else
template_file = nil
end
if template_file != nil
src_file = "/home/engines/templates/" + template_file
else
src_file = "/home/app/" + file
end
dest_file = "/home/app/" + dest
sedstr = sed[:replacement_string]
@sed_strings[:src_file].push(src_file)
@sed_strings[:dest_file].push(dest_file)
@sed_strings[:tmp_file].push(tmp_file)
@sed_strings[:sed_str].push(sedstr)
n=n+1
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_work_ports
begin
@workerPorts = Array.new
log_build_output("Read Work Ports")
ports = @blueprint[:software][:worker_ports]
puts("Ports Json" + ports.to_s)
if ports != nil
ports.each do |port|
portnum = port[:port]
name = port[:name]
external = port['external']
type = port['protocol']
if type == nil
type='tcp'
end
#FIX ME when public ports supported
puts "Port " + portnum.to_s + ":" + external.to_s
@workerPorts.push(WorkPort.new(name,portnum,external,false,type))
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def read_environment_variables
log_build_output("Read Environment Variables")
@environments = Array.new
p :set_environment_variables
p @builder.set_environments
begin
envs = @blueprint[:software][:variables]
envs.each do |env|
p env
name=env[:name]
value=env[:value]
ask=env[:ask_at_build_time]
mandatory = env[:mandatory]
build_time_only = env[:build_time_only]
label = env[:label]
immutable = env[:immutable]
lookup_system_values = env[:lookup_system_values]
if @builder.set_environments != nil
p :looking_for_
p name
if ask == true && @builder.set_environments.has_key?(name) == true
entered_value=@builder.set_environments[name]
if entered_value != nil && entered_value.count !=0#FIXme needs to be removed
value = entered_value
end
end
end
name.sub!(/ /,"_")
p :name_and_value
p name
p value
ev = EnvironmentVariable.new(name,value,ask,mandatory,build_time_only,label,immutable)
p ev
@environments.push(ev)
end
rescue Exception=>e
log_exception(e)
return false
end
end
end
#This class is to isolate the builder from the docker template output
class BuilderPublic
def initialize(builder)
@builder = builder
end
def engine_name
@builder.container_name
end
def domain_name
@builder.domain_name
end
def hostname
@builder.hostname
end
def http_protocol
@builder.http_protocol
end
def repoName
@builder.repoName
end
def webPort
@builder.webPort
end
def build_name
@builder.build_name
end
def runtime
@builder.runtime
end
def set_environments
@builder.set_environments
end
def environments
@builder.environments
end
def mysql_host
return "mysql.engines.internal"
end
def blueprint
return @builder.blueprint
end
def random cnt
p :RANDOM__________
p cnt
return "random" + cnt
end
end
def initialize(params,core_api)
@container_name = params[:engine_name]
@domain_name = params[:domain_name]
@hostname = params[:host_name]
custom_env= params[:software_environment_variables]
# custom_env=params
@core_api = core_api
@http_protocol = params[:http_protocol]
p params
@repoName= params[:repository_url]
@cron_job_list = Array.new
@build_name = File.basename(@repoName).sub(/\.git$/,"")
@workerPorts=Array.new
@webPort=8000
@vols=Array.new
@first_build = true
#FIXme will be false but for now
@overwrite_existing_services = true
@builder_public = BuilderPublic.new(self)
@system_access = SystemAccess.new()
p :custom_env
p custom_env
if custom_env == nil
@set_environments = Hash.new
@environments = Array.new
elsif custom_env.instance_of?(Array) == true
@environments = custom_env # happens on rebuild as custom env is saved in env on disk
#FIXME need to vet all environment variables
@set_environments = Hash.new
else
env_array = custom_env.values
custom_env_hash = Hash.new
env_array.each do |env_hash|
p :env_hash
p env_hash
if env_hash != nil && env_hash[:name] !=nil && env_hash[:value] != nil
env_hash[:name] = env_hash[:name].sub(/_/,"")
custom_env_hash.store(env_hash[:name],env_hash[:value])
end
end
p :Merged_custom_env
p custom_env_hash
@set_environments = custom_env_hash
@environments = Array.new
end
@runtime=String.new
@databases= Array.new
begin
FileUtils.mkdir_p(get_basedir)
@log_file= File.new(SysConfig.DeploymentDir + "/build.out", File::CREAT|File::TRUNC|File::RDWR, 0644)
@err_file= File.new(SysConfig.DeploymentDir + "/build.err", File::CREAT|File::TRUNC|File::RDWR, 0644)
@log_pipe_rd, @log_pipe_wr = IO.pipe
@error_pipe_rd, @error_pipe_wr = IO.pipe
rescue
log_exception(e)
end
end
def close_all
if @log_file.closed? == false
@log_file.close()
end
if@err_file.closed? == false
@err_file.close()
end
if @log_pipe_wr.closed? == false
@log_pipe_wr.close()
end
if @error_pipe_wr.closed? == false
@error_pipe_wr.close()
end
end
def get_build_log_stream
return @log_pipe_rd
end
def get_build_err_stream
@error_pipe_rd
end
def log_build_output(line)
@log_file.puts(line)
@log_file.flush
# @log_pipe_wr.puts(line)
rescue
return
end
def log_build_errors(line)
@err_file.puts(line)
@err_file.flush
# @error_pipe_wr.puts(line)
end
def setup_framework_logging
begin
rmt_log_dir_var_fname=get_basedir + "/home/LOG_DIR"
if File.exist?(rmt_log_dir_var_fname)
rmt_log_dir_varfile = File.open(rmt_log_dir_var_fname)
rmt_log_dir = rmt_log_dir_varfile.read
else
rmt_log_dir="/var/log"
end
local_log_dir = SysConfig.SystemLogRoot + "/containers/" + @hostname
if Dir.exist?(local_log_dir) == false
Dir.mkdir( local_log_dir)
end
return " -v " + local_log_dir + ":" + rmt_log_dir + ":rw "
rescue Exception=>e
log_exception(e)
return false
end
end
def backup_lastbuild
begin
dir=get_basedir
if Dir.exist?(dir)
backup=dir + ".backup"
if Dir.exist?(backup)
FileUtils.rm_rf backup
end
FileUtils.mv(dir,backup)
end
rescue Exception=>e
log_exception(e)
return false
#throw BuildException.new(e,"backup_lastbuild")
end
end
def load_blueprint
begin
log_build_output("Reading Blueprint")
blueprint_file_name= get_basedir + "/blueprint.json"
blueprint_file = File.open(blueprint_file_name,"r")
blueprint_json_str = blueprint_file.read
blueprint_file.close
# @blueprint = JSON.parse(blueprint_json_str)
json_hash = JSON.parse(blueprint_json_str)
p :symbolized_hash
# test_hash = json_hash
# test_hash.keys.each do |key|
# test_hash[(key.to_sym rescue key) || key] = myhash.delete(key)
# end
# p test_hash
hash = SystemUtils.symbolize_keys(json_hash)
return hash
rescue Exception=>e
log_exception(e)
return false
end
end
def clone_repo
begin
log_build_output("Clone Blueprint Repository")
g = Git.clone(@repoName, @build_name, :path => SysConfig.DeploymentDir)
rescue Exception=>e
log_exception(e)
return false
end
end
# def create_cron_service
# begin
#
# log_build_output("Cron file")
#
# if @blueprint_reader.cron_jobs != nil && @blueprint_reader.cron_jobs.length >0
#
# @blueprint_reader.cron_jobs.each do |cj|
# cj_hash = Hash.new
# cj_hash[:name] =@container_name
# cj_hash[:container_name] = @container_name
# cj_hash[:cron_job]=cj
# cj_hash[:parent_engine] = @containerName
# # cron_file.puts(cj)
# # p :write_cron_job
# # p cj
# @cron_job_list.push(cj_hash)
# p @cron_job_list
# end
# # cron_file.close
# end
#
# return true
#
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
def setup_default_files
log_build_output("Setup Default Files")
if setup_global_defaults == false
return false
else
return setup_framework_defaults
end
end
#
# def create_db_service(name,flavor)
# begin
# log_build_output("Create DB Service")
# db = DatabaseService.new(@hostname,name,SysConfig.DBHost,name,name,flavor)
# databases.push(db)
# create_database_service db
# rescue Exception=>e
# log_exception(e)
# return false
# end
# end
def build_init
begin
log_build_output("Building Image")
# cmd="cd " + get_basedir + "; docker build -t " + @hostname + "/init ."
cmd="/usr/bin/docker build -t " + @container_name + "/deploy " + get_basedir
puts cmd
res = run_system(cmd)
if res != true
puts "build init failed " + res.to_s
return res
end
return res
rescue Exception=>e
log_exception(e)
return false
end
end
def launch_deploy managed_container
begin
log_build_output("Lauching Engine")
retval = managed_container.create_container
if retval == false
puts "Failed to Start Container " + managed_container.last_error
log_build_errors("Failed to Launch")
end
return retval
rescue Exception=>e
log_exception(e)
return false
end
end
def setup_global_defaults
begin
log_build_output("Setup globel defaults")
cmd= "cp -r " + SysConfig.DeploymentTemplates + "/global/* " + get_basedir
system cmd
rescue Exception=>e
log_exception(e)
return false
end
end
def setup_framework_defaults
log_build_output("Copy in default templates")
begin
cmd= "cp -r " + SysConfig.DeploymentTemplates + "/" + @blueprint_reader.framework + "/* " + get_basedir
system cmd
rescue Exception=>e
log_exception(e)
return false
end
end
def get_blueprint_from_repo
log_build_output("Backup last build")
if backup_lastbuild == false
return false
end
puts("Cloning Blueprint")
return clone_repo
end
def build_from_blue_print
if get_blueprint_from_repo == false
return false
end
return build_container
end
def read_web_port
log_build_output("Setting Web port")
begin
stef = File.open( get_basedir + "/home/stack.env","r")
while line=stef.gets do
if line.include?("PORT")
i= line.split('=')
@webPort= i[1].strip
p :web_port_line
p line
end
p @webPort
puts(@webPort)
end
rescue Exception=>e
log_exception(e)
# throw BuildException.new(e,"setting web port")
return false
end
end
def read_web_user
begin
log_build_output("Read Web User")
stef = File.open( get_basedir + "/home/stack.env","r")
while line=stef.gets do
if line.include?("USER")
i= line.split('=')
@webUser= i[1].strip
end
end
rescue Exception=>e
log_exception(e)
return false
end
end
def build_container
begin
log_build_output("Reading Blueprint")
@blueprint = load_blueprint
if @blueprint == nil || @blueprint == false
return false
end
@blueprint_reader = BluePrintReader.new(@build_name,@container_name,@blueprint,self)
@blueprint_reader.process_blueprint
if setup_default_files == false
return false
end
compile_base_docker_files
if @blueprint_reader.web_port != nil
@webPort = @blueprint_reader.web_port
else
read_web_port
end
read_web_user
create_persistant_services #need to de-register these if build fails But not deregister those that existed prior
create_template_files
create_php_ini
create_apache_config
create_scritps
@blueprint_reader.environments.each do |env|
env.value = process_templated_string(env.value)
end
index=0
#FIXME There has to be a ruby way
@blueprint_reader.sed_strings[:sed_str].each do |sed_string|
sed_string = process_templated_string(sed_string)
sed_strings[:sed_str][index] = sed_string
index+=1
end
dockerfile_builder = DockerFileBuilder.new( @blueprint_reader,@container_name, @hostname,@domain_name,@webPort,self)
dockerfile_builder.write_files_for_docker
env_file = File.new(get_basedir + "/home/app.env","a")
env_file.puts("")
@blueprint_reader.environments.each do |env|
env_file.puts(env.name)
end
@set_environments.each do |env|
env_file.puts(env[0])
end
env_file.close
setup_framework_logging
# log_build_output("Creating db Services")
# @blueprint_reader.databases.each() do |db|
# create_database_service db
# end
if build_init == false
log_build_errors("Error Build Image failed")
@last_error = " " + tail_of_build_log
post_failed_build_clean_up
return false
else
if @core_api.image_exists?(@container_name) == false
@last_error = " " + tail_of_build_log
post_failed_build_clean_up
return false
#return EnginesOSapiResult.failed(@container_name,"Build Image failed","build Image")
end
#needs to be moved to services dependant on the new BPDS
#create_cron_service
# log_build_output("Creating vol Services")
# @blueprint_reader.databases.each() do |db|
# create_database_service db
# end
#
# primary_vol=nil
# @blueprint_reader.volumes.each_value() do |vol|
# create_file_service vol
# if primary_vol == nil
# primary_vol =vol
# end
# end
log_build_output("Creating Deploy Image")
mc = create_managed_container()
if mc != nil
create_non_persistant_services
end
end
close_all
return mc
rescue Exception=>e
log_exception(e)
post_failed_build_clean_up
close_all
return false
end
end
def post_failed_build_clean_up
#remove containers
#remove persistant services (if created/new)
#deregister non persistant services (if created)
p :Clean_up_Failed_build
@blueprint_reader.services.each do |service_hash|
if service_hash[:fresh] == true
service_hash[:delete_persistant]=true
@core_api.dettach_service(service_hash) #true is delete persistant
end
end
end
def create_template_files
if @blueprint[:software].has_key?(:template_files) && @blueprint[:software][:template_files] != nil
@blueprint[:software][:template_files].each do |template_hash|
write_software_file( "/home/engines/templates/" + template_hash[:path],template_hash[:content])
end
end
end
def create_httaccess
if @blueprint[:software].has_key?(:apache_htaccess_files) && @blueprint[:software][:apache_htaccess_files] != nil
@blueprint[:software][:apache_htaccess_files].each do |htaccess_hash|
write_software_file("/home/engines/htaccess_files" + template_hash[:directory]+"/.htaccess",template_hash[:htaccess_content])
end
end
end
def create_scritps
FileUtils.mkdir_p(get_basedir() + SysConfig.ScriptsDir)
create_start_script
create_install_script
create_post_install_script
end
def create_start_script
if @blueprint[:software].has_key?(:custom_start_script) && @blueprint[:software][:custom_start_script] != nil
start_script_file = File.open(get_basedir() + SysConfig.StartScript,"w", :crlf_newline => false)
start_script_file.puts(@blueprint[:software][:custom_start_script])
start_script_file.close
File.chmod(0755,get_basedir() + SysConfig.StartScript)
end
end
def create_install_script
if @blueprint[:software].has_key?(:custom_install_script) && @blueprint[:software][:custom_install_script] != nil
install_script_file = File.open(get_basedir() + SysConfig.InstallScript,"w", :crlf_newline => false)
install_script_file.puts(@blueprint[:software][:custom_install_script])
install_script_file.close
File.chmod(0755,get_basedir() + SysConfig.InstallScript)
end
end
def create_post_install_script
if @blueprint[:software].has_key?(:custom_post_install_script) && @blueprint[:software][:custom_post_install_script] != nil
post_install_script_file = File.open(get_basedir() + SysConfig.PostInstallScript,"w", :crlf_newline => false)
post_install_script_file.puts(@blueprint[:software][:custom_post_install_script])
post_install_script_file.close
File.chmod(0755,get_basedir() + SysConfig.PostInstallScript)
end
end
def create_php_ini
FileUtils.mkdir_p(get_basedir() + File.dirname(SysConfig.CustomPHPiniFile))
if @blueprint[:software].has_key?(:custom_php_inis) && @blueprint[:software][:custom_php_inis] != nil
php_ini_file = File.open(get_basedir() + SysConfig.CustomPHPiniFile,"w", :crlf_newline => false)
@blueprint[:software][:custom_php_inis].each do |php_ini_hash|
php_ini_file.puts(php_ini_hash[:content])
end
php_ini_file.close
end
end
def create_apache_config
FileUtils.mkdir_p(get_basedir() + File.dirname(SysConfig.CustomApacheConfFile))
if @blueprint[:software].has_key?(:custom_apache_conf) && @blueprint[:software][:custom_apache_conf] != nil
write_software_file(SysConfig.CustomApacheConfFile,@blueprint[:software][:custom_apache_conf])
end
end
def write_software_file(container_filename_path,content)
dir = File.dirname(get_basedir() + container_filename_path)
p :dir_for_write_software_file
p dir
if Dir.exist?(dir) == false
FileUtils.mkdir_p(dir)
end
out_file = File.open(get_basedir() + container_filename_path ,"w", :crlf_newline => false)
content = process_templated_string(content)
out_file.puts(content)
end
def compile_base_docker_files
file_list = Dir.glob(@blueprint_reader.get_basedir + "/Dockerfile*.tmpl")
file_list.each do |file|
process_dockerfile_tmpl(file)
end
end
def process_templated_string(template)
template = apply_system_variables(template)
template = apply_build_variables(template)
template = apply_blueprint_variables(template)
template = apply_engines_variables(template)
return template
end
def process_dockerfile_tmpl(filename)
p :dockerfile_template_processing
p filename
template = File.read(filename)
template = process_templated_string(template)
output_filename = filename.sub(/.tmpl/,"")
out_file = File.new(output_filename,"w")
out_file.write(template)
out_file.close()
end
def apply_system_variables(template)
template.gsub!(/_System\([a-z].*\)/) { | match |
resolve_system_variable(match)
}
return template
end
def apply_build_variables(template)
template.gsub!(/_Builder\([a-z].*\)/) { | match |
resolve_build_variable(match)
}
return template
end
def resolve_system_variable(match)
name = match.sub!(/_System\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name
var_method = @system_access.method(name.to_sym)
val = var_method.call
p :got_val
p val
return val
rescue Exception=>e
SystemUtils.log_exception(e)
return ""
end
#_Blueprint(software,license_name)
#_Blueprint(software,rake_tasks,name)
def apply_blueprint_variables(template)
template.gsub!(/_Blueprint\([a-z,].*\)/) { | match |
resolve_blueprint_variable(match)
}
return template
end
def resolve_blueprint_variable(match)
name = match.sub!(/_Blueprint\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name
val =""
keys = name.split(',')
hash = @builder_public.blueprint
keys.each do |key|
if key == nil || key.length < 1
break
end
p :key
p key
val = hash[key.to_sym]
p :val
p val
if val != nil
hash=val
end
end
p :got_val
p val
return val
rescue Exception=>e
SystemUtils.log_exception(e)
return ""
end
def resolve_build_variable(match)
name = match.sub!(/_Builder\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name.to_sym
if name.include?('(') == true
cmd = name.split('(')
name = cmd[0]
if cmd.count >1
args = cmd[1]
args_array = args.split
end
end
var_method = @builder_public.method(name.to_sym)
if args
p :got_args
val = var_method.call args
else
val = var_method.call
end
p :got_val
p val
return val
rescue Exception=>e
SystemUtils.log_exception(e)
return ""
end
def resolve_engines_variable
name = match.sub!(/_Engines\(/,"")
name.sub!(/[\)]/,"")
p :getting_system_value_for
p name.to_sym
return @blueprint_reader.environments[name.to_sym]
rescue Exception=>e
p @blueprint_reader.environments
SystemUtils.log_exception(e)
return ""
end
def apply_engines_variables(template)
template.gsub!(/_Engines\([a-z].*\)/) { | match |
resolve_engines_variable(match)
}
return template
end
def create_non_persistant_services
@blueprint_reader.services.each() do |service_hash|
#FIX ME Should call this but Keys dont match blueprint designer issue
#@core_api.add_service(service,mc)
service_hash[:parent_engine]=@container_name
service_def = get_service_def(service_hash)
if service_def == nil
p :failed_to_load_service_definition
p service_hash[:type_path]
p service_hash[:publisher_namespace]
return false
end
if service_def[:persistant] == true
next
end
service_hash[:service_handle] = service_hash[:variables][:name]
p :adding_service
p service_hash
@core_api.attach_service(service_hash)
end
end
def get_service_def(service_hash)
p service_hash[:type_path]
p service_hash[:publisher_namespace]
return SoftwareServiceDefinition.find(service_hash[:type_path], service_hash[:publisher_namespace] )
end
def create_persistant_services
@blueprint_reader.services.each() do |service_hash|
service_hash[:parent_engine]=@container_name
# p :service_def_for
# p service_hash[:type_path]
# p service_hash[:publisher_namespace]
service_def = get_service_def(service_hash)
# p service_def
if service_def == nil
p :failed_to_load_service_definition
p :servicetype_name
p service_hash[:service_type]
p :service_provider
p service_hash[:publisher_namespace]
return false
end
if service_def[:persistant] == false
next
end
p :adding_service
puts "+=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++"
p service_hash
puts "+=++=++=++=++=++=++=++=++=++=++=++=++=++=++=++"
p :target_envs
p service_def[:target_environment_variables]
if service_hash[:servicetype_name] == "filesystem"
add_file_service(service[:name], service[:engine_path])
end
service_hash[:service_handle] = service_hash[:variables][:name]
p :LOOKING_FOR_
p service_hash
if @core_api.find_service_consumers(service_hash) == false
@first_build = true
service_hash[:fresh]=true
else
service_hash[:fresh]=false
@first_build = false
end
p :attach_service
p service_hash
@core_api.attach_service(service_hash)
end
end
def fill_in_dynamic_vars(service_hash)
p "FILLING_+@+#+@+@+@+@+@+"
if service_hash.has_key?(:variables) == false || service_hash[:variables] == nil
return
end
service_hash[:variables].each do |variable|
p variable
if variable[1] != nil && variable[1].start_with?("$_")
variable[1].sub!(/\$/,"")
result = evaluate_function(variable[1])
service_hash[:variables][variable[0]] = result
end
end
end
def evaluate_function(function)
if function.start_with?("_System")
return resolve_system_variable(function)
elsif function.start_with?("_Builder")
return resolve_build_variable(function)
elsif function.start_with?("_Blueprint")
return resolve_blueprint_variable(function)
end
rescue Exception=> e
return ""
end
def tail_of_build_log
retval = String.new
lines = File.readlines(SysConfig.DeploymentDir + "/build.out")
lines_count = lines.count -1
start = lines_count - 10
for n in start..lines_count
retval+=lines[n]
end
return retval
end
def rebuild_managed_container engine
@engine = engine
log_build_output("Starting Rebuild")
if backup_lastbuild == false
return false
elsif setup_rebuild == false
return false
else
return build_container
end
end
def setup_rebuild
begin
log_build_output("Setting up rebuild")
FileUtils.mkdir_p(get_basedir)
blueprint = @core_api.load_blueprint(@engine)
statefile= get_basedir + "/blueprint.json"
f = File.new(statefile,File::CREAT|File::TRUNC|File::RDWR, 0644)
f.write(blueprint.to_json)
f.close
rescue Exception=>e
log_exception(e)
return false
end
end
def create_managed_container
log_build_output("Creating ManagedEngine")
mc = ManagedEngine.new(@hostname,
@blueprint_reader.memory.to_s ,
@hostname,
@domain_name,
@container_name + "/deploy",
@blueprint_reader.volumes,
@webPort,
@blueprint_reader.workerPorts,
@repoName,
@blueprint_reader.databases,
@blueprint_reader.environments,
@blueprint_reader.framework,
@blueprint_reader.runtime,
@core_api,
@blueprint_reader.data_uid,
@blueprint_reader.data_gid
)
p :set_cron_job_list
p @cron_job_list
mc.set_cron_job_list(@cron_job_list)
#:http_protocol=>"HTTPS and HTTP"
mc.set_protocol(@protocol)
mc.conf_register_site=( true) # needs some intelligence here for worker only
mc.conf_self_start= (true)
mc.save_state # no config.yaml throws a no such container so save so others can use
if mc.save_blueprint(@blueprint) == false
log_build_errors( "Failed to save blueprint " + @blueprint.to_s)
end
bp = mc.load_blueprint
p bp
log_build_output("Launching")
#this will fail as no api at this stage
if mc.core_api != nil
if launch_deploy(mc) == false
log_build_errors("Failed to Launch")
end
log_build_output("Applying Volume settings and Log Permissions")
#FIXME need to check results from following
@core_api.run_volume_builder(mc ,@webUser)
# mc.start_container
end
return mc
end
protected
def log_exception(e)
log_build_errors( e.to_s)
puts(e.to_s)
@last_error= e.to_s
n=0
e.backtrace.each do |bt |
p bt
if n>10
break
end
++n
end
#close_all
end
def debug(fld)
puts "ERROR: "
p fld
end
require 'open3'
def run_system(cmd)
log_build_output("Running " + cmd)
ret_val=false
res = String.new
error_mesg = String.new
begin
Open3.popen3( cmd ) do |stdin, stdout, stderr, th|
oline = String.new
stderr_is_open=true
begin
stdout.each { |line|
# print line
line = line.gsub(/\\\"/,"")
res += line.chop
oline = line
log_build_output(line)
if stderr_is_open
err = stderr.read_nonblock(1000)
error_mesg += err
log_build_errors(err)
end
}
rescue Errno::EIO
res += line.chop
log_build_output(oline)
if stderr_is_open
err = stderr.read_nonblock(1000)
error_mesg += err
log_build_errors(err)
p :EIO_retry
retry
end
rescue IO::WaitReadable
# p :wait_readable_retrt
retry
rescue EOFError
if stdout.closed? == false
stderr_is_open = false
p :EOF_retry
retry
else if stderr.closed? == true
return
else
err = stderr.read_nonblock(1000)
error_mesg += err
log_build_errors(err)
return
end
end
end
if error_mesg.include?("Error:") || error_mesg.include?("FATA")
p "docker_cmd error " + error_mesg
return false
end
return true
end
end
end
def get_basedir
return SysConfig.DeploymentDir + "/" + @build_name
end
end
|
module Widgets
module TableHelper
include CssTemplate
# Returns an HTML table with +:collection+ disposed in rows. Add
# HTML attributes by passing an attributes hash to +html+.
# The content of each item is rendered using the given block.
#
# +:collection+ array of items
# +:cols+ number of columns (default 3)
# +:html+ table html attributes (+:class+, +:id+)
# +:name+ name of table (dafault +:main+)
#
# <% tableize @users, :name => 'credential', :html => {:class => 'people'}, :cols => 2 do |user| -%>
# login: <%= user.name %>
# <% end -%>
#
# # => <table id="credential_table" class="people"><tbody><tr>
# <td>login: scooby</td><td> </td>
# </tr></tbody></table>
#
def tableize(collection = nil, opts = {}, &block)
table = Tableizer.new(collection, opts, self, &block)
table.render
end
class Tableizer
def initialize(collection, opts, template, &block)
@collection = collection
@collection ||= opts[:collection]
@columns = opts[:cols] || 3
raise ArgumentError, 'Missing collection parameter in tableize call' unless @collection
raise ArgumentError, 'Missing block in tableize call' unless block_given?
raise ArgumentError, 'Tableize columns must be two or more' unless @columns > 1
@generate_css = opts[:generate_css] || false
@opts = opts
@name = opts[:name] || :main
@html = opts[:html] || {} # setup default html options
@html[:id] ||= @name.to_s.underscore << '_table'
@html[:class] ||= @html[:id]
@header = opts[:header]
@template = template
@block = block
end
def method_missing(*args, &block)
@template.send(*args, &block)
end
def render
_out = @generate_css ? render_css('table') : ''
_out << tag('table', {:id => @html[:id], :class => @html[:class]}, true)
_out << tag('tbody', nil, true)
_out << tag('tr', nil, true)
index = 0
size = @collection.size
empty_cell = content_tag('td', ' ', :class => 'blank')
# add header
if (@header)
_out << content_tag('th', @header)
index += 1
size += 1
end
# fill line with items, breaking if needed
@collection.each do |item|
index += 1
_out << content_tag('td', capture(item, &@block))
should_wrap = ( index.remainder(@columns) == 0 and index != size )
_out << '</tr>' << tag('tr', nil, true) if should_wrap
# prepend every line with an empty cell
if should_wrap && @opts[:skip_header_column] == true
_out << empty_cell
index += 1; size += 1
end
end
# fill remaining columns with empty boxes
remaining = size.remainder(@columns)
(@columns - remaining).times do
_out << empty_cell
end unless remaining == 0
_out << '</tr>' << '</tbody>' << '</table>'
concat(_out)
nil # avoid duplication if called with <%= %>
end
end
end
end
More refactoring to Tableizer
module Widgets
module TableHelper
include CssTemplate
# Returns an HTML table with +:collection+ disposed in rows. Add
# HTML attributes by passing an attributes hash to +html+.
# The content of each item is rendered using the given block.
#
# +:collection+ array of items
# +:cols+ number of columns (default 3)
# +:html+ table html attributes (+:class+, +:id+)
# +:name+ name of table (dafault +:main+)
#
# <% tableize @users, :name => 'credential', :html => {:class => 'people'}, :cols => 2 do |user| -%>
# login: <%= user.name %>
# <% end -%>
#
# # => <table id="credential_table" class="people"><tbody><tr>
# <td>login: scooby</td><td> </td>
# </tr></tbody></table>
#
def tableize(collection = nil, opts = {}, &block)
table = Tableizer.new(collection, opts, self, &block)
table.render
end
class Tableizer
def initialize(collection, opts, template, &block)
parse_args(collection, opts, template, &block)
raise ArgumentError, 'Missing collection parameter in tableize call' unless @collection
raise ArgumentError, 'Missing block in tableize call' unless block_given?
raise ArgumentError, 'Tableize columns must be two or more' unless @columns >= 2
end
def render
generate_css
generate_html
concat(@output_buffer)
nil # avoid duplication if called with <%= %>
end
protected
def parse_args(collection, opts, template, &block)
@collection = collection
@collection ||= opts[:collection]
@columns = opts[:cols] || 3
@generate_css = opts[:generate_css] || false
@name = opts[:name] || :main
@html = opts[:html] || {} # setup default html options
@html[:id] ||= @name.to_s.underscore << '_table'
@html[:class] ||= @html[:id]
@header = opts[:header]
@skip_header_column = opts[:skip_header_column]
@template = template
@block = block
@output_buffer = ''
end
def generate_css
@output_buffer << render_css('table') if generate_css?
end
def generate_html
@output_buffer << tag('table', {:id => @html[:id], :class => @html[:class]}, true)
@output_buffer << tag('tbody', nil, true)
@output_buffer << tag('tr', nil, true)
index = 0
size = @collection.size
empty_cell = content_tag('td', ' ', :class => 'blank')
# add header
if (@header)
@output_buffer << content_tag('th', @header)
index += 1
size += 1
end
# fill line with items, breaking if needed
@collection.each do |item|
index += 1
@output_buffer << content_tag('td', capture(item, &@block))
should_wrap = ( index.remainder(@columns) == 0 and index != size )
@output_buffer << '</tr>' << tag('tr', nil, true) if should_wrap
# prepend every line with an empty cell
if should_wrap && @skip_header_column == true
@output_buffer << empty_cell
index += 1; size += 1
end
end
# fill remaining columns with empty boxes
remaining = size.remainder(@columns)
(@columns - remaining).times do
@output_buffer << empty_cell
end unless remaining == 0
@output_buffer << '</tr>' << '</tbody>' << '</table>'
end
def generate_css?
@generate_css
end
def method_missing(*args, &block)
@template.send(*args, &block)
end
end
end
end
|
# Various extensions to core and library classes.
# TODO move gem declarations elsewhere
gem 'dm-core', '= 0.9.5'
gem 'dm-validations', '= 0.9.5'
gem 'dm-ar-finders', '= 0.9.5'
require 'dm-core'
require 'date'
require 'time'
class DateTime #:nodoc:
# ISO 8601 formatted time value. This is
alias_method :iso8601, :to_s
def inspect
"#<DateTime: #{to_s}>"
end
def to_date
Date.civil(year, mon, mday)
end
def to_time
if self.offset == 0
::Time.utc(year, month, day, hour, min, sec)
else
new_offset(0).to_time
end
end
end
class Date #:nodoc:
def inspect
"#<Date: #{to_s}>"
end
end
class Time
def to_datetime
jd = DateTime.civil_to_jd(year, mon, mday, DateTime::ITALY)
fr = DateTime.time_to_day_fraction(hour, min, [sec, 59].min) +
usec.to_r/86400000000
of = utc_offset.to_r/86400
DateTime.new!(DateTime.jd_to_ajd(jd, fr, of), of, DateTime::ITALY)
end
end
require 'rack'
module Rack
class Request
# The IP address of the upstream-most client (e.g., the browser). This
# is reliable even when the request is made through a reverse proxy or
# other gateway.
def remote_ip
@env['HTTP_X_FORWARDED_FOR'] || @env['HTTP_CLIENT_IP'] || @env['REMOTE_ADDR']
end
end
end
require 'sinatra'
# The running environment as a Symbol; obtained from Sinatra's
# application options.
def environment
Sinatra.application.options.env.to_sym
end
# Truthful when the application is in the process of being reloaded
# by Sinatra.
def reloading?
Sinatra.application.reloading?
end
Should work with latest version of DataMapper
# Various extensions to core and library classes.
# TODO move gem declarations elsewhere
gem 'dm-core'
gem 'dm-validations'
gem 'dm-ar-finders'
require 'dm-core'
require 'date'
require 'time'
class DateTime #:nodoc:
# ISO 8601 formatted time value. This is
alias_method :iso8601, :to_s
def inspect
"#<DateTime: #{to_s}>"
end
def to_date
Date.civil(year, mon, mday)
end
def to_time
if self.offset == 0
::Time.utc(year, month, day, hour, min, sec)
else
new_offset(0).to_time
end
end
end
class Date #:nodoc:
def inspect
"#<Date: #{to_s}>"
end
end
class Time
def to_datetime
jd = DateTime.civil_to_jd(year, mon, mday, DateTime::ITALY)
fr = DateTime.time_to_day_fraction(hour, min, [sec, 59].min) +
usec.to_r/86400000000
of = utc_offset.to_r/86400
DateTime.new!(DateTime.jd_to_ajd(jd, fr, of), of, DateTime::ITALY)
end
end
require 'rack'
module Rack
class Request
# The IP address of the upstream-most client (e.g., the browser). This
# is reliable even when the request is made through a reverse proxy or
# other gateway.
def remote_ip
@env['HTTP_X_FORWARDED_FOR'] || @env['HTTP_CLIENT_IP'] || @env['REMOTE_ADDR']
end
end
end
require 'sinatra'
# The running environment as a Symbol; obtained from Sinatra's
# application options.
def environment
Sinatra.application.options.env.to_sym
end
# Truthful when the application is in the process of being reloaded
# by Sinatra.
def reloading?
Sinatra.application.reloading?
end
|
$:.push File.expand_path("../lib", __FILE__)
version = File.read(File.expand_path("../../VERSION",__FILE__)).strip
Gem::Specification.new do |s|
s.name = "brightcontent-pages"
s.version = version
s.email = "developers@brightin.nl"
s.homepage = "http://brightin.nl"
s.summary = "Pages resource for brightcontent"
s.description = "Separate pages resource for brightcontent"
s.authors = ["Developers at Brightin"]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "brightcontent-core", version
s.add_dependency "brightcontent-attachments", version
s.add_dependency "awesome_nested_set", ">= 3.0.0.rc.3"
s.add_dependency "jquery-ui-rails", ">= 2.3.0"
s.add_dependency "the_sortable_tree", "~> 2.3.0"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec", "~> 2.14.1"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "capybara"
s.add_development_dependency "launchy"
s.add_development_dependency "factory_girl_rails"
end
Update jquery-ui-rails dependency in gemspec
$:.push File.expand_path("../lib", __FILE__)
version = File.read(File.expand_path("../../VERSION",__FILE__)).strip
Gem::Specification.new do |s|
s.name = "brightcontent-pages"
s.version = version
s.email = "developers@brightin.nl"
s.homepage = "http://brightin.nl"
s.summary = "Pages resource for brightcontent"
s.description = "Separate pages resource for brightcontent"
s.authors = ["Developers at Brightin"]
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_paths = ["lib"]
s.add_dependency "brightcontent-core", version
s.add_dependency "brightcontent-attachments", version
s.add_dependency "awesome_nested_set", ">= 3.0.0.rc.3"
s.add_dependency "jquery-ui-rails", "~> 5.0.0"
s.add_dependency "the_sortable_tree", "~> 2.3.0"
s.add_development_dependency "sqlite3"
s.add_development_dependency "rspec", "~> 2.14.1"
s.add_development_dependency "rspec-rails"
s.add_development_dependency "capybara"
s.add_development_dependency "launchy"
s.add_development_dependency "factory_girl_rails"
end
|
require 'spec_helper'
describe Nicorepo do
before(:all) do
mail, pass = Netrc.read["nicovideo.jp"]
@nicorepo = Nicorepo.new
@nicorepo.login(mail, pass)
end
describe "#login" do
context "with right account" do
it "should be success" do
expect(@nicorepo.agent).to be_truthy
end
end
context "with wrong account" do
it "should raise error" do
repo = Nicorepo.new
expect{ repo.login('test', 'testpass') }.to raise_error(Nicorepo::LoginError)
end
end
end
describe "#all" do
context "with 5" do
it "should return 5 reports" do
expect(@nicorepo.all(5).size).to eq(5)
end
end
context "with 50" do
it "should return 50 reports" do
expect(@nicorepo.all(50).size).to eq(50)
end
end
end
describe "#videos" do
context "with request_num = 5, limit_page = 3" do
it "should return only video reports" do
videos = @nicorepo.videos
not_videos = videos.reject{ |v| v.kind =~ /video/ }
expect(not_videos.size).to eq(0)
end
it "should return 5 reports at the most" do
expect(@nicorepo.videos(5, 3).size).to be <= 5
end
end
end
describe "#lives" do
it "should return only live reports" do
lives = @nicorepo.lives
not_lives = lives.reject{ |l| l.kind =~ /live/ }
expect(not_lives.size).to eq(0)
end
end
end
Add specs for error reports
require 'spec_helper'
describe Nicorepo do
before(:all) do
mail, pass = Netrc.read["nicovideo.jp"]
@nicorepo = Nicorepo.new
@nicorepo.login(mail, pass)
end
describe "#login" do
context "with right account" do
it "should be success" do
expect(@nicorepo.agent).to be_truthy
end
end
context "with wrong account" do
it "should raise error" do
repo = Nicorepo.new
expect{ repo.login('test', 'testpass') }.to raise_error(Nicorepo::LoginError)
end
end
end
describe "#all" do
context "with 5" do
it "should return 5 reports" do
expect(@nicorepo.all(5).size).to eq(5)
end
end
context "with 50" do
it "should return 50 reports" do
expect(@nicorepo.all(50).size).to eq(50)
end
end
context "when an error occured" do
before do
allow_any_instance_of(Nicorepo::Parser).to receive(:parse_title).and_raise("SomeError")
end
it "should return erorr reports" do
error_report = @nicorepo.all(1).first
expect(error_report.title).to eq("An exception occured: SomeError")
end
end
end
describe "#videos" do
context "with request_num = 5, limit_page = 3" do
it "should return only video reports" do
videos = @nicorepo.videos
not_videos = videos.reject{ |v| v.kind =~ /video/ }
expect(not_videos.size).to eq(0)
end
it "should return 5 reports at the most" do
expect(@nicorepo.videos(5, 3).size).to be <= 5
end
end
end
describe "#lives" do
it "should return only live reports" do
lives = @nicorepo.lives
not_lives = lives.reject{ |l| l.kind =~ /live/ }
expect(not_lives.size).to eq(0)
end
end
end
|
describe "NSString" do
it "should have a #nsurl method" do
url = 'https://github.com/status'.nsurl
NSURL.should === url
url.absoluteString.should == 'https://github.com/status'
url.host.should == 'github.com'
end
it "should have a #nsdata method" do
data = 'test'.nsdata
NSData.should === data
bytes = data.bytes
bytes[0].should == 116
bytes[1].should == 101
bytes[2].should == 115
bytes[3].should == 116
end
it "should have a #uiimage method" do
UIImage.imageNamed('little_square').should == 'little_square'.uiimage
end
it "should have a #uiimageview method" do
view = 'little_square'.uiimageview
UIView.should === view
view.image.should == UIImage.imageNamed('little_square')
end
it "should have a #uifont method" do
font = 'Helvetica'.uifont
UIFont.should === font
font.familyName.should == 'Helvetica'
font.pointSize.should == UIFont.systemFontSize
end
it "should have a #uicolor method" do
color = '#ffffff'.uicolor
UIColor.should === color
color.red.should == 1.0
color.green.should == 1.0
color.blue.should == 1.0
color = '#808080'.uicolor
UIColor.should === color
((color.red * 2).round / 2.0).should == 0.5
((color.green * 2).round / 2.0).should == 0.5
((color.blue * 2).round / 2.0).should == 0.5
end
it "should have a #uilabel method" do
str = 'test'
str_size = str.sizeWithFont(UIFont.systemFontOfSize(UIFont.labelFontSize))
label = str.uilabel
label.size.width == str_size.width
label.size.height == str_size.height
label.backgroundColor == UIColor.clearColor
end
it "should have a #uilabel(font) method" do
str = 'test'
font = UIFont.boldSystemFontOfSize(20)
str_size = str.sizeWithFont(font)
label = str.uilabel(font)
label.font.should == font
label.size.width == str_size.width
label.size.height == str_size.height
label.backgroundColor == UIColor.clearColor
end
it "should have a #escape_url method" do
' '.escape_url.should == '%20'
'?<>&=;%'.escape_url.should == '%3F%3C%3E%26%3D%3B%25'
end
it "should have a #unescape_url method" do
'%20'.unescape_url.should == ' '
'%3F%3C%3E%26%3D%3B%25'.unescape_url.should == '?<>&=;%'
end
it "should have a #localized method" do
'hello'.localized.should == 'howdy'
'hello'._.should == 'howdy'
end
end
test should have some shoulds, me thinks
describe "NSString" do
it "should have a #nsurl method" do
url = 'https://github.com/status'.nsurl
NSURL.should === url
url.absoluteString.should == 'https://github.com/status'
url.host.should == 'github.com'
end
it "should have a #nsdata method" do
data = 'test'.nsdata
NSData.should === data
bytes = data.bytes
bytes[0].should == 116
bytes[1].should == 101
bytes[2].should == 115
bytes[3].should == 116
end
it "should have a #uiimage method" do
UIImage.imageNamed('little_square').should == 'little_square'.uiimage
end
it "should have a #uiimageview method" do
view = 'little_square'.uiimageview
UIView.should === view
view.image.should == UIImage.imageNamed('little_square')
end
it "should have a #uifont method" do
font = 'Helvetica'.uifont
UIFont.should === font
font.familyName.should == 'Helvetica'
font.pointSize.should == UIFont.systemFontSize
end
it "should have a #uicolor method" do
color = '#ffffff'.uicolor
UIColor.should === color
color.red.should == 1.0
color.green.should == 1.0
color.blue.should == 1.0
color = '#808080'.uicolor
UIColor.should === color
((color.red * 2).round / 2.0).should == 0.5
((color.green * 2).round / 2.0).should == 0.5
((color.blue * 2).round / 2.0).should == 0.5
end
it "should have a #uilabel method" do
str = 'test'
str_size = str.sizeWithFont(UIFont.systemFontOfSize(UIFont.labelFontSize))
label = str.uilabel
label.size.width.should == str_size.width
label.size.height.should == str_size.height
label.backgroundColor.should == UIColor.clearColor
end
it "should have a #uilabel(font) method" do
str = 'test'
font = UIFont.boldSystemFontOfSize(20)
str_size = str.sizeWithFont(font)
label = str.uilabel(font)
label.font.should == font
label.size.width.should == str_size.width
label.size.height.should == str_size.height
label.backgroundColor.should == UIColor.clearColor
end
it "should have a #escape_url method" do
' '.escape_url.should == '%20'
'?<>&=;%'.escape_url.should == '%3F%3C%3E%26%3D%3B%25'
end
it "should have a #unescape_url method" do
'%20'.unescape_url.should == ' '
'%3F%3C%3E%26%3D%3B%25'.unescape_url.should == '?<>&=;%'
end
it "should have a #localized method" do
'hello'.localized.should == 'howdy'
'hello'._.should == 'howdy'
end
end
|
require 'reindeer'
describe Reindeer do
it 'can be extended' do
expect { Class.new { extend Reindeer } }.to_not raise_error
end
context 'when extended' do
let(:example) { Class.new { extend Reindeer } }
it 'provides a has class method' do
expect(example.methods).to include(:has)
end
end
describe :has do
let(:attribute_name) { :attribute_name }
let(:getter) { :attribute_name }
let(:setter) { :"#{:attribute_name}=" }
let(:example) do
example = Class.new { extend Reindeer }
example.has attribute_name, params
example
end
context 'with read-only accessors' do
let(:params) { { is: :ro } }
it 'creates a reader' do
expect(example.new.methods).to include(getter)
end
it 'does not create a writer' do
expect(example.new.methods).to_not include(setter)
end
end
context 'with read/write accessors' do
let(:params) { { is: :rw } }
it 'creates a reader' do
expect(example.new.methods).to include(getter)
end
it 'creates a writer' do
expect(example.new.methods).to include(setter)
end
end
context 'with bad is' do
let(:is) { :jabbajabba }
let(:params) { { is: is } }
it 'throws an exception' do
expect { example }.to raise_error(Reindeer::BadIs, "#{is} invalid")
end
end
context 'with no is' do
let(:params) { {} }
it 'does not create a reader' do
expect(example.new.methods).to_not include(getter)
end
it 'does not create a writer' do
expect(example.new.methods).to_not include(setter)
end
end
context 'when constructing an object' do
let(:params) { { is: :rw } }
let(:expected_value) { 42 }
it 'accepts & records parameters to new' do
instance = example.new( attribute_name => expected_value )
expect(instance.instance_variable_get :"@#{getter}").to eq expected_value
end
end
context 'when generating a predicate' do
let(:params) { { is: :ro, predicate: true } }
let(:predicate) { :"#{attribute_name}?" }
it 'evaluates true when the value is set' do
expect(example.new( attribute_name => 42 ).send predicate).to be_true
end
it 'evaluates true when the value is set' do
expect(example.new.send predicate).to be_false
end
end
end
end
Test when a predicate is not added.
require 'reindeer'
describe Reindeer do
it 'can be extended' do
expect { Class.new { extend Reindeer } }.to_not raise_error
end
context 'when extended' do
let(:example) { Class.new { extend Reindeer } }
it 'provides a has class method' do
expect(example.methods).to include(:has)
end
end
describe :has do
let(:attribute_name) { :attribute_name }
let(:getter) { :attribute_name }
let(:setter) { :"#{:attribute_name}=" }
let(:example) do
example = Class.new { extend Reindeer }
example.has attribute_name, params
example
end
context 'with read-only accessors' do
let(:params) { { is: :ro } }
it 'creates a reader' do
expect(example.new.methods).to include(getter)
end
it 'does not create a writer' do
expect(example.new.methods).to_not include(setter)
end
end
context 'with read/write accessors' do
let(:params) { { is: :rw } }
it 'creates a reader' do
expect(example.new.methods).to include(getter)
end
it 'creates a writer' do
expect(example.new.methods).to include(setter)
end
end
context 'with bad is' do
let(:is) { :jabbajabba }
let(:params) { { is: is } }
it 'throws an exception' do
expect { example }.to raise_error(Reindeer::BadIs, "#{is} invalid")
end
end
context 'with no is' do
let(:params) { {} }
it 'does not create a reader' do
expect(example.new.methods).to_not include(getter)
end
it 'does not create a writer' do
expect(example.new.methods).to_not include(setter)
end
end
context 'when constructing an object' do
let(:params) { { is: :rw } }
let(:expected_value) { 42 }
it 'accepts & records parameters to new' do
instance = example.new( attribute_name => expected_value )
expect(instance.instance_variable_get :"@#{getter}").to eq expected_value
end
end
context 'when generating a predicate' do
let(:params) { { is: :ro, predicate: true } }
let(:predicate) { :"#{attribute_name}?" }
it 'evaluates true when the value is set' do
expect(example.new( attribute_name => 42 ).send predicate).to be_true
end
it 'evaluates true when the value is set' do
expect(example.new.send predicate).to be_false
end
end
context 'when not generating a predicate' do
let(:params) { { is: :ro } }
let(:predicate) { :"#{attribute_name}?" }
it 'does not have a predicate' do
expect(example.methods).to_not include(predicate)
end
end
end
end
|
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'spec_helper'
require 'wright/resource'
include Wright
describe Resource do
before(:each) do
# duplicate Wright::Resource for testing
resource_module = Resource.dup
@recipe = Class.new do
extend resource_module
end
@resource_module = resource_module
end
it 'should register new resources at runtime' do
resource_class = Class.new do
def self.name; 'ResourceKlass'; end
def initialize(name); end
end
@resource_module.register(resource_class)
resource_name = Util.class_to_resource_name(resource_class)
@recipe.must_respond_to(resource_name)
resource = @recipe.send(resource_name)
resource.must_be_instance_of(resource_class)
end
end
Use require_relative in resource spec
require_relative 'spec_helper'
require 'wright/resource'
include Wright
describe Resource do
before(:each) do
# duplicate Wright::Resource for testing
resource_module = Resource.dup
@recipe = Class.new do
extend resource_module
end
@resource_module = resource_module
end
it 'should register new resources at runtime' do
resource_class = Class.new do
def self.name; 'ResourceKlass'; end
def initialize(name); end
end
@resource_module.register(resource_class)
resource_name = Util.class_to_resource_name(resource_class)
@recipe.must_respond_to(resource_name)
resource = @recipe.send(resource_name)
resource.must_be_instance_of(resource_class)
end
end
|
#!/usr/bin/env ruby
require 'bundler'
require 'bundler/setup'
require 'chef_zero/server'
require 'rspec/core'
def start_server(chef_repo_path)
require 'chef/version'
require 'chef/config'
require 'chef/chef_fs/config'
require 'chef/chef_fs/chef_fs_data_store'
require 'chef_zero/server'
Dir.mkdir(chef_repo_path) if !File.exists?(chef_repo_path)
# 11.6 and below had a bug where it couldn't create the repo children automatically
if Chef::VERSION.to_f < 11.8
%w(clients cookbooks data_bags environments nodes roles users).each do |child|
Dir.mkdir("#{chef_repo_path}/#{child}") if !File.exists?("#{chef_repo_path}/#{child}")
end
end
# Start the new server
Chef::Config.repo_mode = 'everything'
Chef::Config.chef_repo_path = chef_repo_path
Chef::Config.versioned_cookbooks = true
chef_fs = Chef::ChefFS::Config.new.local_fs
data_store = Chef::ChefFS::ChefFSDataStore.new(chef_fs)
server = ChefZero::Server.new(:port => 8889, :single_org => false, :data_store => data_store)#, :log_level => :debug)
server.start_background
server
end
tmpdir = nil
begin
if ENV['FILE_STORE']
require 'tmpdir'
require 'chef_zero/data_store/raw_file_store'
tmpdir = Dir.mktmpdir
data_store = ChefZero::DataStore::RawFileStore.new(tmpdir, true)
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, false, false)
server = ChefZero::Server.new(:port => 8889, :single_org => false, :data_store => data_store)
server.start_background
elsif ENV['CHEF_FS']
require 'tmpdir'
tmpdir = Dir.mktmpdir
start_server(tmpdir)
else
server = ChefZero::Server.new(:port => 8889, :single_org => false)#, :log_level => :debug)
server.start_background
end
require 'rspec/core'
require 'pedant'
require 'pedant/organization'
# Pedant::Config.rerun = true
Pedant.config.suite = 'api'
Pedant.config.internal_server = Pedant::Config.search_server = 'http://localhost:8889'
# see dummy_endpoint.rb.
Pedant.config.search_commit_url = "/dummy"
Pedant::Config.search_url_fmt = "/dummy?fq=+X_CHEF_type_CHEF_X:%{type}&q=%{query}&wt=json"
Pedant.config[:config_file] = 'spec/support/oc_pedant.rb'
Pedant.config[:server_api_version] = 0
# "the goal is that only authorization, authentication and validation tests are turned off" - @jkeiser
Pedant.setup([
'--skip-knife',
'--skip-keys',
'--skip-controls',
'--skip-acl',
'--skip-validation',
'--skip-authentication',
'--skip-authorization',
'--skip-omnibus',
'--skip-usags',
'--exclude-internal-orgs',
'--skip-headers',
# Chef 12 features not yet 100% supported by Chef Zero
'--skip-cookbook-artifacts',
'--skip-containers',
'--skip-api-v1'
])
result = RSpec::Core::Runner.run(Pedant.config.rspec_args)
server.stop if server.running?
ensure
FileUtils.remove_entry_secure(tmpdir) if tmpdir
end
exit(result)
Convert ChefFS data to use DefaultFacade.
#!/usr/bin/env ruby
require 'bundler'
require 'bundler/setup'
require 'chef_zero/server'
require 'rspec/core'
def start_server(chef_repo_path)
require 'chef/version'
require 'chef/config'
require 'chef/chef_fs/config'
require 'chef/chef_fs/chef_fs_data_store'
require 'chef_zero/server'
Dir.mkdir(chef_repo_path) if !File.exists?(chef_repo_path)
# 11.6 and below had a bug where it couldn't create the repo children automatically
if Chef::VERSION.to_f < 11.8
%w(clients cookbooks data_bags environments nodes roles users).each do |child|
Dir.mkdir("#{chef_repo_path}/#{child}") if !File.exists?("#{chef_repo_path}/#{child}")
end
end
# Start the new server
Chef::Config.repo_mode = 'everything'
Chef::Config.chef_repo_path = chef_repo_path
Chef::Config.versioned_cookbooks = true
chef_fs = Chef::ChefFS::Config.new.local_fs
data_store = Chef::ChefFS::ChefFSDataStore.new(chef_fs)
data_store = ChefZero::DataStore::V1ToV2Adapter.new(data_store, 'pedant-testorg')
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, 'pedant-testorg', false)
server = ChefZero::Server.new(
port: 8889,
data_store: data_store,
single_org: false,
#log_level: :debug
)
server.start_background
server
end
tmpdir = nil
begin
if ENV['FILE_STORE']
require 'tmpdir'
require 'chef_zero/data_store/raw_file_store'
tmpdir = Dir.mktmpdir
data_store = ChefZero::DataStore::RawFileStore.new(tmpdir, true)
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, false, false)
server = ChefZero::Server.new(:port => 8889, :single_org => false, :data_store => data_store)
server.start_background
elsif ENV['CHEF_FS']
require 'tmpdir'
tmpdir = Dir.mktmpdir
start_server(tmpdir)
else
server = ChefZero::Server.new(:port => 8889, :single_org => false)#, :log_level => :debug)
server.start_background
end
require 'rspec/core'
require 'pedant'
require 'pedant/organization'
# Pedant::Config.rerun = true
Pedant.config.suite = 'api'
Pedant.config.internal_server = Pedant::Config.search_server = 'http://localhost:8889'
# see dummy_endpoint.rb.
Pedant.config.search_commit_url = "/dummy"
Pedant::Config.search_url_fmt = "/dummy?fq=+X_CHEF_type_CHEF_X:%{type}&q=%{query}&wt=json"
Pedant.config[:config_file] = 'spec/support/oc_pedant.rb'
Pedant.config[:server_api_version] = 0
# "the goal is that only authorization, authentication and validation tests are turned off" - @jkeiser
Pedant.setup([
'--skip-knife',
'--skip-keys',
'--skip-controls',
'--skip-acl',
'--skip-validation',
'--skip-authentication',
'--skip-authorization',
'--skip-omnibus',
'--skip-usags',
'--exclude-internal-orgs',
'--skip-headers',
# Chef 12 features not yet 100% supported by Chef Zero
'--skip-cookbook-artifacts',
'--skip-containers',
'--skip-api-v1'
])
result = RSpec::Core::Runner.run(Pedant.config.rspec_args)
server.stop if server.running?
ensure
FileUtils.remove_entry_secure(tmpdir) if tmpdir
end
exit(result)
|
#!/usr/bin/env ruby
require 'bundler'
require 'bundler/setup'
require 'chef_zero/server'
require 'rspec/core'
def start_cheffs_server(chef_repo_path)
require 'chef/version'
require 'chef/config'
require 'chef/chef_fs/config'
require 'chef/chef_fs/chef_fs_data_store'
require 'chef_zero/server'
Dir.mkdir(chef_repo_path) if !File.exists?(chef_repo_path)
# 11.6 and below had a bug where it couldn't create the repo children automatically
if Chef::VERSION.to_f < 11.8
%w(clients cookbooks data_bags environments nodes roles users).each do |child|
Dir.mkdir("#{chef_repo_path}/#{child}") if !File.exists?("#{chef_repo_path}/#{child}")
end
end
# Start the new server
Chef::Config.repo_mode = 'hosted_everything'
Chef::Config.chef_repo_path = chef_repo_path
Chef::Config.versioned_cookbooks = true
chef_fs_config = Chef::ChefFS::Config.new
data_store = Chef::ChefFS::ChefFSDataStore.new(chef_fs_config.local_fs, chef_fs_config.chef_config)
data_store = ChefZero::DataStore::V1ToV2Adapter.new(data_store, 'pedant-testorg')
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, 'pedant-testorg', false)
data_store.create(%w(organizations pedant-testorg users), 'pivotal', '{}')
data_store.set(%w(organizations pedant-testorg groups admins), '{ "users": [ "pivotal" ] }')
data_store.set(%w(organizations pedant-testorg groups users), '{ "users": [ "pivotal" ] }')
server = ChefZero::Server.new(
port: 8889,
data_store: data_store,
single_org: false,
#log_level: :debug
)
server.start_background
server
end
tmpdir = nil
begin
if ENV['FILE_STORE']
require 'tmpdir'
require 'chef_zero/data_store/raw_file_store'
tmpdir = Dir.mktmpdir
data_store = ChefZero::DataStore::RawFileStore.new(tmpdir, true)
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, false, false)
server = ChefZero::Server.new(:port => 8889, :single_org => false, :data_store => data_store)
server.start_background
elsif ENV['CHEF_FS']
require 'tmpdir'
tmpdir = Dir.mktmpdir
server = start_cheffs_server(tmpdir)
else
server = ChefZero::Server.new(:port => 8889, :single_org => false)#, :log_level => :debug)
server.start_background
end
require 'rspec/core'
require 'pedant'
require 'pedant/organization'
# Pedant::Config.rerun = true
Pedant.config.suite = 'api'
Pedant.config[:config_file] = 'spec/support/oc_pedant.rb'
# Because ChefFS can only ever have one user (pivotal), we can't do most of the
# tests that involve multiple
chef_fs_skips = if ENV['CHEF_FS']
[ '--skip-association',
'--skip-users',
'--skip-organizations',
'--skip-multiuser',
# chef-zero has some non-removable quirks, such as the fact that files
# with 255-character names cannot be stored in local mode. This is
# reserved only for quirks that are *irrevocable* and by design; and
# should barely be used at all.
'--skip-chef-zero-quirks',
]
else
[]
end
# These things aren't supported by Chef Zero in any mode of operation:
default_skips = [
# "the goal is that only authorization, authentication and validation tests
# are turned off" - @jkeiser
#
# ...but we're not there yet
'--skip-keys',
# Chef Zero does not intend to support validation the way erchef does.
'--skip-validation',
# Chef Zero does not intend to support authentication the way erchef does.
'--skip-authentication',
# Chef Zero does not intend to support authorization the way erchef does.
'--skip-authorization',
# Omnibus tests depend on erchef features that are specific to erchef and
# bundled in the omnibus package. Currently the only test in this category
# is for the search reindexing script.
'--skip-omnibus',
# USAGs (user-specific association groups) are Authz groups that contain
# only one user and represent that user's association with an org. Though
# there are good reasons for them, they don't work well in practice and
# only the manage console really uses them. Since Chef Zero + Manage is a
# quite unusual configuration, we're ignoring them.
'--skip-usags',
# Chef 12 features not yet 100% supported by Chef Zero
'--skip-api-v1',
# The universe endpoint is unlikely to ever make sense for Chef Zero
'--skip-universe',
]
# The knife tests are very slow and don't give us a lot of extra coverage,
# so we run them in a different entry in the travis test matrix.
pedant_args =
if ENV["PEDANT_KNIFE_TESTS"]
default_skips + %w{ --focus-knife }
else
default_skips + chef_fs_skips + %w{ --skip-knife }
end
Pedant.setup(pedant_args)
fail_fast = []
# fail_fast = ["--fail-fast"]
result = RSpec::Core::Runner.run(Pedant.config.rspec_args + fail_fast)
server.stop if server.running?
ensure
FileUtils.remove_entry_secure(tmpdir) if tmpdir
end
exit(result)
Move skip-acl to ChefFS
#!/usr/bin/env ruby
require 'bundler'
require 'bundler/setup'
require 'chef_zero/server'
require 'rspec/core'
def start_cheffs_server(chef_repo_path)
require 'chef/version'
require 'chef/config'
require 'chef/chef_fs/config'
require 'chef/chef_fs/chef_fs_data_store'
require 'chef_zero/server'
Dir.mkdir(chef_repo_path) if !File.exists?(chef_repo_path)
# 11.6 and below had a bug where it couldn't create the repo children automatically
if Chef::VERSION.to_f < 11.8
%w(clients cookbooks data_bags environments nodes roles users).each do |child|
Dir.mkdir("#{chef_repo_path}/#{child}") if !File.exists?("#{chef_repo_path}/#{child}")
end
end
# Start the new server
Chef::Config.repo_mode = 'hosted_everything'
Chef::Config.chef_repo_path = chef_repo_path
Chef::Config.versioned_cookbooks = true
chef_fs_config = Chef::ChefFS::Config.new
data_store = Chef::ChefFS::ChefFSDataStore.new(chef_fs_config.local_fs, chef_fs_config.chef_config)
data_store = ChefZero::DataStore::V1ToV2Adapter.new(data_store, 'pedant-testorg')
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, 'pedant-testorg', false)
data_store.create(%w(organizations pedant-testorg users), 'pivotal', '{}')
data_store.set(%w(organizations pedant-testorg groups admins), '{ "users": [ "pivotal" ] }')
data_store.set(%w(organizations pedant-testorg groups users), '{ "users": [ "pivotal" ] }')
server = ChefZero::Server.new(
port: 8889,
data_store: data_store,
single_org: false,
#log_level: :debug
)
server.start_background
server
end
tmpdir = nil
begin
if ENV['FILE_STORE']
require 'tmpdir'
require 'chef_zero/data_store/raw_file_store'
tmpdir = Dir.mktmpdir
data_store = ChefZero::DataStore::RawFileStore.new(tmpdir, true)
data_store = ChefZero::DataStore::DefaultFacade.new(data_store, false, false)
server = ChefZero::Server.new(:port => 8889, :single_org => false, :data_store => data_store)
server.start_background
elsif ENV['CHEF_FS']
require 'tmpdir'
tmpdir = Dir.mktmpdir
server = start_cheffs_server(tmpdir)
else
server = ChefZero::Server.new(:port => 8889, :single_org => false)#, :log_level => :debug)
server.start_background
end
require 'rspec/core'
require 'pedant'
require 'pedant/organization'
# Pedant::Config.rerun = true
Pedant.config.suite = 'api'
Pedant.config[:config_file] = 'spec/support/oc_pedant.rb'
# Because ChefFS can only ever have one user (pivotal), we can't do most of the
# tests that involve multiple
chef_fs_skips = if ENV['CHEF_FS']
[ '--skip-association',
'--skip-users',
'--skip-organizations',
'--skip-multiuser',
'--skip-acl',
# chef-zero has some non-removable quirks, such as the fact that files
# with 255-character names cannot be stored in local mode. This is
# reserved only for quirks that are *irrevocable* and by design; and
# should barely be used at all.
'--skip-chef-zero-quirks',
]
else
[]
end
# These things aren't supported by Chef Zero in any mode of operation:
default_skips = [
# "the goal is that only authorization, authentication and validation tests
# are turned off" - @jkeiser
#
# ...but we're not there yet
'--skip-keys',
# Chef Zero does not intend to support validation the way erchef does.
'--skip-validation',
# Chef Zero does not intend to support authentication the way erchef does.
'--skip-authentication',
# Chef Zero does not intend to support authorization the way erchef does.
'--skip-authorization',
# Omnibus tests depend on erchef features that are specific to erchef and
# bundled in the omnibus package. Currently the only test in this category
# is for the search reindexing script.
'--skip-omnibus',
# USAGs (user-specific association groups) are Authz groups that contain
# only one user and represent that user's association with an org. Though
# there are good reasons for them, they don't work well in practice and
# only the manage console really uses them. Since Chef Zero + Manage is a
# quite unusual configuration, we're ignoring them.
'--skip-usags',
# Chef 12 features not yet 100% supported by Chef Zero
'--skip-api-v1',
# The universe endpoint is unlikely to ever make sense for Chef Zero
'--skip-universe',
]
# The knife tests are very slow and don't give us a lot of extra coverage,
# so we run them in a different entry in the travis test matrix.
pedant_args =
if ENV["PEDANT_KNIFE_TESTS"]
default_skips + %w{ --focus-knife }
else
default_skips + chef_fs_skips + %w{ --skip-knife }
end
Pedant.setup(pedant_args)
# fail_fast = ["--fail-fast"]
result = RSpec::Core::Runner.run(Pedant.config.rspec_args + fail_fast)
server.stop if server.running?
ensure
FileUtils.remove_entry_secure(tmpdir) if tmpdir
end
exit(result)
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara do
describe 'Selectors' do
let :string do
described_class.string <<-STRING
<html>
<head>
<title>selectors</title>
</head>
<body>
<div class="aa" id="page">
<div class="bb" id="content">
<h1 class="aa">Totally awesome</h1>
<p>Yes it is</p>
</div>
<p class="bb cc">Some Content</p>
<p class="bb dd !mine"></p>
</div>
<div id="#special">
</div>
<div class="some random words" id="random_words">
Something
</div>
<input id="2checkbox" class="2checkbox" type="checkbox"/>
<input type="radio"/>
<label for="my_text_input">My Text Input</label>
<input type="text" name="form[my_text_input]" placeholder="my text" id="my_text_input"/>
<input type="file" id="file" class=".special file"/>
<input type="hidden" id="hidden_field" value="this is hidden"/>
<input type="submit" value="click me" title="submit button"/>
<input type="button" value="don't click me" title="Other button 1" style="line-height: 30px;"/>
<a href="#">link</a>
<fieldset></fieldset>
<select id="select">
<option value="a">A</option>
<option value="b" disabled>B</option>
<option value="c" selected>C</option>
</select>
<table>
<tr><td></td></tr>
</table>
<table id="rows">
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr>
<td>D</td><td>E</td><td>F</td>
</tr>
</table>
<table id="cols">
<tbody>
<tr>
<td>A</td><td>D</td>
</tr>
<tr>
<td>B</td><td>E</td>
</tr>
<tr>
<td>C</td><td>F</td>
</tr>
</tbody>
</table>
</body>
</html>
STRING
end
before do
described_class.add_selector :custom_selector do
css { |css_class| "div.#{css_class}" }
node_filter(:not_empty, boolean: true, default: true, skip_if: :all) { |node, value| value ^ (node.text == '') }
end
described_class.add_selector :custom_css_selector do
css(:name, :other_name) do |selector, name: nil, **|
selector ||= ''
selector += "[name='#{name}']" if name
selector
end
expression_filter(:placeholder) do |expr, val|
expr + "[placeholder='#{val}']"
end
expression_filter(:value) do |expr, val|
expr + "[value='#{val}']"
end
expression_filter(:title) do |expr, val|
expr + "[title='#{val}']"
end
end
described_class.add_selector :custom_xpath_selector do
xpath(:valid1, :valid2) { |selector| selector }
match { |value| value == 'match_me' }
end
end
it 'supports `filter` as an alias for `node_filter`' do
expect do
described_class.add_selector :filter_alias_selector do
css { |_unused| 'div' }
filter(:something) { |_node, _value| true }
end
end.not_to raise_error
end
describe 'adding a selector' do
it 'can set default visiblity' do
described_class.add_selector :hidden_field do
visible :hidden
css { |_sel| 'input[type="hidden"]' }
end
expect(string).to have_no_css('input[type="hidden"]')
expect(string).to have_selector(:hidden_field)
end
end
describe 'modify_selector' do
it 'allows modifying a selector' do
el = string.find(:custom_selector, 'aa')
expect(el.tag_name).to eq 'div'
described_class.modify_selector :custom_selector do
css { |css_class| "h1.#{css_class}" }
end
el = string.find(:custom_selector, 'aa')
expect(el.tag_name).to eq 'h1'
end
it "doesn't change existing filters" do
described_class.modify_selector :custom_selector do
css { |css_class| "p.#{css_class}" }
end
expect(string).to have_selector(:custom_selector, 'bb', count: 1)
expect(string).to have_selector(:custom_selector, 'bb', not_empty: false, count: 1)
expect(string).to have_selector(:custom_selector, 'bb', not_empty: :all, count: 2)
end
end
describe '::[]' do
it 'can find a selector' do
expect(Capybara::Selector[:field]).not_to be_nil
end
it 'raises if no selector found' do
expect { Capybara::Selector[:no_exist] }.to raise_error(ArgumentError, /Unknown selector type/)
end
end
describe '::for' do
it 'finds selector that matches the locator' do
expect(Capybara::Selector.for('match_me').name).to eq :custom_xpath_selector
end
it 'returns nil if no match' do
expect(Capybara::Selector.for('nothing')).to be nil
end
end
describe 'xpath' do
it 'uses filter names passed in' do
described_class.add_selector :test do
xpath(:something, :other) { |_locator| XPath.descendant }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:something, :other)
end
it 'gets filter names from block if none passed to xpath method' do
described_class.add_selector :test do
xpath { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid3, :valid4)
end
it 'ignores block parameters if names passed in' do
described_class.add_selector :test do
xpath(:valid1) { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid1)
expect(selector.expression_filters.keys).not_to include(:valid3, :valid4)
end
end
describe 'css' do
it "supports filters specified in 'css' definition" do
expect(string).to have_selector(:custom_css_selector, 'input', name: 'form[my_text_input]')
expect(string).to have_no_selector(:custom_css_selector, 'input', name: 'form[not_my_text_input]')
end
it 'supports explicitly defined expression filters' do
expect(string).to have_selector(:custom_css_selector, placeholder: 'my text')
expect(string).to have_no_selector(:custom_css_selector, placeholder: 'not my text')
expect(string).to have_selector(:custom_css_selector, value: 'click me', title: 'submit button')
end
it 'uses filter names passed in' do
described_class.add_selector :test do
css(:name, :other_name) { |_locator| '' }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:name, :other_name)
end
it 'gets filter names from block if none passed to css method' do
described_class.add_selector :test do
css { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid3, :valid4)
end
it 'ignores block parameters if names passed in' do
described_class.add_selector :test do
css(:valid1) { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid1)
expect(selector.expression_filters.keys).not_to include(:valid3, :valid4)
end
end
describe 'builtin selectors' do
context 'when locator is nil' do
it 'devolves to just finding element types' do
selectors = {
field: ".//*[self::input | self::textarea | self::select][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')]",
fieldset: './/fieldset',
link: './/a[./@href]',
link_or_button: ".//a[./@href] | .//input[./@type = 'submit' or ./@type = 'reset' or ./@type = 'image' or ./@type = 'button'] | .//button",
fillable_field: ".//*[self::input | self::textarea][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'radio' or ./@type = 'checkbox' or ./@type = 'hidden' or ./@type = 'file')]",
radio_button: ".//input[./@type = 'radio']",
checkbox: ".//input[./@type = 'checkbox']",
select: './/select',
option: './/option',
file_field: ".//input[./@type = 'file']",
table: './/table'
}
selectors.each do |selector, xpath|
results = string.all(selector, nil).to_a.map(&:native)
expect(results.size).to be > 0
expect(results).to eq string.all(:xpath, xpath).to_a.map(&:native)
end
end
end
context 'with :id option' do
it 'works with compound css selectors' do
expect(string.all(:custom_css_selector, 'div, h1', id: 'page').size).to eq 1
expect(string.all(:custom_css_selector, 'h1, div', id: 'page').size).to eq 1
end
it "works with 'special' characters" do
expect(string.find(:custom_css_selector, 'div', id: '#special')[:id]).to eq '#special'
expect(string.find(:custom_css_selector, 'input', id: '2checkbox')[:id]).to eq '2checkbox'
end
it 'accepts XPath expression for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', id: XPath.contains('peci'))[:id]).to eq '#special'
expect(string.find(:custom_xpath_selector, './/input', id: XPath.ends_with('box'))[:id]).to eq '2checkbox'
end
it 'errors XPath expression for CSS based selectors' do
expect { string.find(:custom_css_selector, 'div', id: XPath.contains('peci')) }
.to raise_error(ArgumentError, /not supported/)
end
it 'accepts Regexp for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', id: /peci/)[:id]).to eq '#special'
expect(string.find(:custom_xpath_selector, './/div', id: /pEcI/i)[:id]).to eq '#special'
end
it 'accepts Regexp for css based selectors' do
expect(string.find(:custom_css_selector, 'div', id: /sp.*al/)[:id]).to eq '#special'
end
end
context 'with :class option' do
it 'works with compound css selectors' do
expect(string.all(:custom_css_selector, 'div, h1', class: 'aa').size).to eq 2
expect(string.all(:custom_css_selector, 'h1, div', class: 'aa').size).to eq 2
end
it 'handles negated classes' do
expect(string.all(:custom_css_selector, 'div, p', class: ['bb', '!cc']).size).to eq 2
expect(string.all(:custom_css_selector, 'div, p', class: ['!cc', '!dd', 'bb']).size).to eq 1
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['bb', '!cc']).size).to eq 2
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['!cc', '!dd', 'bb']).size).to eq 1
end
it 'handles classes starting with ! by requiring negated negated first' do
expect(string.all(:custom_css_selector, 'div, p', class: ['!!!mine']).size).to eq 1
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['!!!mine']).size).to eq 1
end
it "works with 'special' characters" do
expect(string.find(:custom_css_selector, 'input', class: '.special')[:id]).to eq 'file'
expect(string.find(:custom_css_selector, 'input', class: '2checkbox')[:id]).to eq '2checkbox'
end
it 'accepts XPath expression for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: XPath.contains('dom wor'))[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: XPath.ends_with('words'))[:id]).to eq 'random_words'
end
it 'errors XPath expression for CSS based selectors' do
expect { string.find(:custom_css_selector, 'div', class: XPath.contains('random')) }
.to raise_error(ArgumentError, /not supported/)
end
it 'accepts Regexp for XPath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: /dom wor/)[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: /dOm WoR/i)[:id]).to eq 'random_words'
end
it 'accepts Regexp for CSS base selectors' do
expect(string.find(:custom_css_selector, 'div', class: /random/)[:id]).to eq 'random_words'
end
end
context 'with :style option' do
it 'accepts string for CSS based selectors' do
expect(string.find(:custom_css_selector, 'input', style: 'line-height: 30px;')[:title]).to eq 'Other button 1'
end
it 'accepts Regexp for CSS base selectors' do
expect(string.find(:custom_css_selector, 'input', style: /30px/)[:title]).to eq 'Other button 1'
end
end
# :css, :xpath, :id, :field, :fieldset, :link, :button, :link_or_button, :fillable_field, :radio_button, :checkbox, :select,
# :option, :file_field, :label, :table, :frame
describe ':css selector' do
it 'finds by CSS locator' do
expect(string.find(:css, 'input#my_text_input')[:name]).to eq 'form[my_text_input]'
end
end
describe ':xpath selector' do
it 'finds by XPath locator' do
expect(string.find(:xpath, './/input[@id="my_text_input"]')[:name]).to eq 'form[my_text_input]'
end
end
describe ':id selector' do
it 'finds by locator' do
expect(string.find(:id, 'my_text_input')[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /my_text_input/)[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /_text_/)[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /i[nmo]/)[:name]).to eq 'form[my_text_input]'
end
end
describe ':field selector' do
it 'finds by locator' do
expect(string.find(:field, 'My Text Input')[:id]).to eq 'my_text_input'
expect(string.find(:field, 'my_text_input')[:id]).to eq 'my_text_input'
expect(string.find(:field, 'form[my_text_input]')[:id]).to eq 'my_text_input'
end
it 'finds by id string' do
expect(string.find(:field, id: 'my_text_input')[:name]).to eq 'form[my_text_input]'
end
it 'finds by id regexp' do
expect(string.find(:field, id: /my_text_inp/)[:name]).to eq 'form[my_text_input]'
end
it 'finds by name' do
expect(string.find(:field, name: 'form[my_text_input]')[:id]).to eq 'my_text_input'
end
it 'finds by placeholder' do
expect(string.find(:field, placeholder: 'my text')[:id]).to eq 'my_text_input'
end
it 'finds by type' do
expect(string.find(:field, type: 'file')[:id]).to eq 'file'
expect(string.find(:field, type: 'select')[:id]).to eq 'select'
end
end
describe ':option selector' do
it 'finds disabled options' do
expect(string.find(:option, disabled: true).value).to eq 'b'
end
it 'finds selected options' do
expect(string.find(:option, selected: true).value).to eq 'c'
end
it 'finds not selected and not disabled options' do
expect(string.find(:option, disabled: false, selected: false).value).to eq 'a'
end
end
describe ':button selector' do
it 'finds by value' do
expect(string.find(:button, 'click me').value).to eq 'click me'
end
it 'finds by title' do
expect(string.find(:button, 'submit button').value).to eq 'click me'
end
it 'includes non-matching parameters in failure message' do
expect { string.find(:button, 'click me', title: 'click me') }.to raise_error(/with title click me/)
end
end
describe ':element selector' do
it 'finds by any attributes' do
expect(string.find(:element, 'input', type: 'submit').value).to eq 'click me'
end
it 'supports regexp matching' do
expect(string.find(:element, 'input', type: /sub/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub\w.*button/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub.* b.*ton/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub.*mit.*/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^submit button$/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^(?:submit|other) button$/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /SuB.*mIt/i).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^Su.*Bm.*It/i).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^Ot.*he.*r b.*\d/i).value).to eq "don't click me"
end
it 'still works with system keys' do
expect { string.all(:element, 'input', type: 'submit', count: 1) }.not_to raise_error
end
it 'works without element type' do
expect(string.find(:element, type: 'submit').value).to eq 'click me'
end
it 'validates attribute presence when true' do
expect(string.find(:element, name: true)[:id]).to eq 'my_text_input'
end
it 'validates attribute absence when false' do
expect(string.find(:element, 'option', disabled: false, selected: false).value).to eq 'a'
end
it 'includes wildcarded keys in description' do
expect { string.find(:element, 'input', not_there: 'bad', presence: true, absence: false, count: 1) }
.to(raise_error do |e|
expect(e).to be_a(Capybara::ElementNotFound)
expect(e.message).to include 'not_there => bad'
expect(e.message).to include 'with presence attribute'
expect(e.message).to include 'without absence attribute'
expect(e.message).not_to include 'count 1'
end)
end
it 'accepts XPath::Expression' do
expect(string.find(:element, 'input', type: XPath.starts_with('subm')).value).to eq 'click me'
expect(string.find(:element, 'input', type: XPath.ends_with('ext'))[:type]).to eq 'text'
expect(string.find(:element, 'input', type: XPath.contains('ckb'))[:type]).to eq 'checkbox'
expect(string.find(:element, 'input', title: XPath.contains_word('submit'))[:type]).to eq 'submit'
expect(string.find(:element, 'input', title: XPath.contains_word('button 1'))[:type]).to eq 'button'
end
end
describe ':link_or_button selector' do
around(:all) do |example|
described_class.modify_selector(:link_or_button) do
expression_filter(:random) { |xpath, _| xpath } # do nothing filter
end
example.run
Capybara::Selector[:link_or_button].expression_filters.delete(:random)
end
it 'should not find links when disabled == true' do
expect(string.all(:link_or_button, disabled: true).size).to eq 0
end
context 'when modified' do
it 'should still work' do
filter = Capybara::Selector[:link_or_button].expression_filters[:random]
allow(filter).to receive(:apply_filter).and_call_original
expect(string.find(:link_or_button, 'click me', random: 'blah').value).to eq 'click me'
expect(filter).to have_received(:apply_filter).with(anything, :random, 'blah', anything)
end
end
end
describe ':table selector' do
it 'finds by rows' do
expect(string.find(:table, with_rows: [%w[D E F]])[:id]).to eq 'rows'
end
it 'finds by columns' do
expect(string.find(:table, with_cols: [%w[A B C]])[:id]).to eq 'cols'
end
end
end
end
end
Fix RSpec warning
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Capybara do
describe 'Selectors' do
let :string do
described_class.string <<-STRING
<html>
<head>
<title>selectors</title>
</head>
<body>
<div class="aa" id="page">
<div class="bb" id="content">
<h1 class="aa">Totally awesome</h1>
<p>Yes it is</p>
</div>
<p class="bb cc">Some Content</p>
<p class="bb dd !mine"></p>
</div>
<div id="#special">
</div>
<div class="some random words" id="random_words">
Something
</div>
<input id="2checkbox" class="2checkbox" type="checkbox"/>
<input type="radio"/>
<label for="my_text_input">My Text Input</label>
<input type="text" name="form[my_text_input]" placeholder="my text" id="my_text_input"/>
<input type="file" id="file" class=".special file"/>
<input type="hidden" id="hidden_field" value="this is hidden"/>
<input type="submit" value="click me" title="submit button"/>
<input type="button" value="don't click me" title="Other button 1" style="line-height: 30px;"/>
<a href="#">link</a>
<fieldset></fieldset>
<select id="select">
<option value="a">A</option>
<option value="b" disabled>B</option>
<option value="c" selected>C</option>
</select>
<table>
<tr><td></td></tr>
</table>
<table id="rows">
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr>
<td>D</td><td>E</td><td>F</td>
</tr>
</table>
<table id="cols">
<tbody>
<tr>
<td>A</td><td>D</td>
</tr>
<tr>
<td>B</td><td>E</td>
</tr>
<tr>
<td>C</td><td>F</td>
</tr>
</tbody>
</table>
</body>
</html>
STRING
end
before do
described_class.add_selector :custom_selector do
css { |css_class| "div.#{css_class}" }
node_filter(:not_empty, boolean: true, default: true, skip_if: :all) { |node, value| value ^ (node.text == '') }
end
described_class.add_selector :custom_css_selector do
css(:name, :other_name) do |selector, name: nil, **|
selector ||= ''
selector += "[name='#{name}']" if name
selector
end
expression_filter(:placeholder) do |expr, val|
expr + "[placeholder='#{val}']"
end
expression_filter(:value) do |expr, val|
expr + "[value='#{val}']"
end
expression_filter(:title) do |expr, val|
expr + "[title='#{val}']"
end
end
described_class.add_selector :custom_xpath_selector do
xpath(:valid1, :valid2) { |selector| selector }
match { |value| value == 'match_me' }
end
end
it 'supports `filter` as an alias for `node_filter`' do
expect do
described_class.add_selector :filter_alias_selector do
css { |_unused| 'div' }
filter(:something) { |_node, _value| true }
end
end.not_to raise_error
end
describe 'adding a selector' do
it 'can set default visiblity' do
described_class.add_selector :hidden_field do
visible :hidden
css { |_sel| 'input[type="hidden"]' }
end
expect(string).to have_no_css('input[type="hidden"]')
expect(string).to have_selector(:hidden_field)
end
end
describe 'modify_selector' do
it 'allows modifying a selector' do
el = string.find(:custom_selector, 'aa')
expect(el.tag_name).to eq 'div'
described_class.modify_selector :custom_selector do
css { |css_class| "h1.#{css_class}" }
end
el = string.find(:custom_selector, 'aa')
expect(el.tag_name).to eq 'h1'
end
it "doesn't change existing filters" do
described_class.modify_selector :custom_selector do
css { |css_class| "p.#{css_class}" }
end
expect(string).to have_selector(:custom_selector, 'bb', count: 1)
expect(string).to have_selector(:custom_selector, 'bb', not_empty: false, count: 1)
expect(string).to have_selector(:custom_selector, 'bb', not_empty: :all, count: 2)
end
end
describe '::[]' do
it 'can find a selector' do
expect(Capybara::Selector[:field]).not_to be_nil
end
it 'raises if no selector found' do
expect { Capybara::Selector[:no_exist] }.to raise_error(ArgumentError, /Unknown selector type/)
end
end
describe '::for' do
it 'finds selector that matches the locator' do
expect(Capybara::Selector.for('match_me').name).to eq :custom_xpath_selector
end
it 'returns nil if no match' do
expect(Capybara::Selector.for('nothing')).to be nil
end
end
describe 'xpath' do
it 'uses filter names passed in' do
described_class.add_selector :test do
xpath(:something, :other) { |_locator| XPath.descendant }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:something, :other)
end
it 'gets filter names from block if none passed to xpath method' do
described_class.add_selector :test do
xpath { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid3, :valid4)
end
it 'ignores block parameters if names passed in' do
described_class.add_selector :test do
xpath(:valid1) { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid1)
expect(selector.expression_filters.keys).not_to include(:valid3, :valid4)
end
end
describe 'css' do
it "supports filters specified in 'css' definition" do
expect(string).to have_selector(:custom_css_selector, 'input', name: 'form[my_text_input]')
expect(string).to have_no_selector(:custom_css_selector, 'input', name: 'form[not_my_text_input]')
end
it 'supports explicitly defined expression filters' do
expect(string).to have_selector(:custom_css_selector, placeholder: 'my text')
expect(string).to have_no_selector(:custom_css_selector, placeholder: 'not my text')
expect(string).to have_selector(:custom_css_selector, value: 'click me', title: 'submit button')
end
it 'uses filter names passed in' do
described_class.add_selector :test do
css(:name, :other_name) { |_locator| '' }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:name, :other_name)
end
it 'gets filter names from block if none passed to css method' do
described_class.add_selector :test do
css { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid3, :valid4)
end
it 'ignores block parameters if names passed in' do
described_class.add_selector :test do
css(:valid1) { |_locator, valid3:, valid4: nil| "#{valid3} #{valid4}" }
end
selector = Capybara::Selector.new :test, config: nil, format: nil
expect(selector.expression_filters.keys).to include(:valid1)
expect(selector.expression_filters.keys).not_to include(:valid3, :valid4)
end
end
describe 'builtin selectors' do
context 'when locator is nil' do
it 'devolves to just finding element types' do
selectors = {
field: ".//*[self::input | self::textarea | self::select][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'hidden')]",
fieldset: './/fieldset',
link: './/a[./@href]',
link_or_button: ".//a[./@href] | .//input[./@type = 'submit' or ./@type = 'reset' or ./@type = 'image' or ./@type = 'button'] | .//button",
fillable_field: ".//*[self::input | self::textarea][not(./@type = 'submit' or ./@type = 'image' or ./@type = 'radio' or ./@type = 'checkbox' or ./@type = 'hidden' or ./@type = 'file')]",
radio_button: ".//input[./@type = 'radio']",
checkbox: ".//input[./@type = 'checkbox']",
select: './/select',
option: './/option',
file_field: ".//input[./@type = 'file']",
table: './/table'
}
selectors.each do |selector, xpath|
results = string.all(selector, nil).to_a.map(&:native)
expect(results.size).to be > 0
expect(results).to eq string.all(:xpath, xpath).to_a.map(&:native)
end
end
end
context 'with :id option' do
it 'works with compound css selectors' do
expect(string.all(:custom_css_selector, 'div, h1', id: 'page').size).to eq 1
expect(string.all(:custom_css_selector, 'h1, div', id: 'page').size).to eq 1
end
it "works with 'special' characters" do
expect(string.find(:custom_css_selector, 'div', id: '#special')[:id]).to eq '#special'
expect(string.find(:custom_css_selector, 'input', id: '2checkbox')[:id]).to eq '2checkbox'
end
it 'accepts XPath expression for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', id: XPath.contains('peci'))[:id]).to eq '#special'
expect(string.find(:custom_xpath_selector, './/input', id: XPath.ends_with('box'))[:id]).to eq '2checkbox'
end
it 'errors XPath expression for CSS based selectors' do
expect { string.find(:custom_css_selector, 'div', id: XPath.contains('peci')) }
.to raise_error(ArgumentError, /not supported/)
end
it 'accepts Regexp for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', id: /peci/)[:id]).to eq '#special'
expect(string.find(:custom_xpath_selector, './/div', id: /pEcI/i)[:id]).to eq '#special'
end
it 'accepts Regexp for css based selectors' do
expect(string.find(:custom_css_selector, 'div', id: /sp.*al/)[:id]).to eq '#special'
end
end
context 'with :class option' do
it 'works with compound css selectors' do
expect(string.all(:custom_css_selector, 'div, h1', class: 'aa').size).to eq 2
expect(string.all(:custom_css_selector, 'h1, div', class: 'aa').size).to eq 2
end
it 'handles negated classes' do
expect(string.all(:custom_css_selector, 'div, p', class: ['bb', '!cc']).size).to eq 2
expect(string.all(:custom_css_selector, 'div, p', class: ['!cc', '!dd', 'bb']).size).to eq 1
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['bb', '!cc']).size).to eq 2
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['!cc', '!dd', 'bb']).size).to eq 1
end
it 'handles classes starting with ! by requiring negated negated first' do
expect(string.all(:custom_css_selector, 'div, p', class: ['!!!mine']).size).to eq 1
expect(string.all(:custom_xpath_selector, XPath.descendant(:div, :p), class: ['!!!mine']).size).to eq 1
end
it "works with 'special' characters" do
expect(string.find(:custom_css_selector, 'input', class: '.special')[:id]).to eq 'file'
expect(string.find(:custom_css_selector, 'input', class: '2checkbox')[:id]).to eq '2checkbox'
end
it 'accepts XPath expression for xpath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: XPath.contains('dom wor'))[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: XPath.ends_with('words'))[:id]).to eq 'random_words'
end
it 'errors XPath expression for CSS based selectors' do
expect { string.find(:custom_css_selector, 'div', class: XPath.contains('random')) }
.to raise_error(ArgumentError, /not supported/)
end
it 'accepts Regexp for XPath based selectors' do
expect(string.find(:custom_xpath_selector, './/div', class: /dom wor/)[:id]).to eq 'random_words'
expect(string.find(:custom_xpath_selector, './/div', class: /dOm WoR/i)[:id]).to eq 'random_words'
end
it 'accepts Regexp for CSS base selectors' do
expect(string.find(:custom_css_selector, 'div', class: /random/)[:id]).to eq 'random_words'
end
end
context 'with :style option' do
it 'accepts string for CSS based selectors' do
expect(string.find(:custom_css_selector, 'input', style: 'line-height: 30px;')[:title]).to eq 'Other button 1'
end
it 'accepts Regexp for CSS base selectors' do
expect(string.find(:custom_css_selector, 'input', style: /30px/)[:title]).to eq 'Other button 1'
end
end
# :css, :xpath, :id, :field, :fieldset, :link, :button, :link_or_button, :fillable_field, :radio_button, :checkbox, :select,
# :option, :file_field, :label, :table, :frame
describe ':css selector' do
it 'finds by CSS locator' do
expect(string.find(:css, 'input#my_text_input')[:name]).to eq 'form[my_text_input]'
end
end
describe ':xpath selector' do
it 'finds by XPath locator' do
expect(string.find(:xpath, './/input[@id="my_text_input"]')[:name]).to eq 'form[my_text_input]'
end
end
describe ':id selector' do
it 'finds by locator' do
expect(string.find(:id, 'my_text_input')[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /my_text_input/)[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /_text_/)[:name]).to eq 'form[my_text_input]'
expect(string.find(:id, /i[nmo]/)[:name]).to eq 'form[my_text_input]'
end
end
describe ':field selector' do
it 'finds by locator' do
expect(string.find(:field, 'My Text Input')[:id]).to eq 'my_text_input'
expect(string.find(:field, 'my_text_input')[:id]).to eq 'my_text_input'
expect(string.find(:field, 'form[my_text_input]')[:id]).to eq 'my_text_input'
end
it 'finds by id string' do
expect(string.find(:field, id: 'my_text_input')[:name]).to eq 'form[my_text_input]'
end
it 'finds by id regexp' do
expect(string.find(:field, id: /my_text_inp/)[:name]).to eq 'form[my_text_input]'
end
it 'finds by name' do
expect(string.find(:field, name: 'form[my_text_input]')[:id]).to eq 'my_text_input'
end
it 'finds by placeholder' do
expect(string.find(:field, placeholder: 'my text')[:id]).to eq 'my_text_input'
end
it 'finds by type' do
expect(string.find(:field, type: 'file')[:id]).to eq 'file'
expect(string.find(:field, type: 'select')[:id]).to eq 'select'
end
end
describe ':option selector' do
it 'finds disabled options' do
expect(string.find(:option, disabled: true).value).to eq 'b'
end
it 'finds selected options' do
expect(string.find(:option, selected: true).value).to eq 'c'
end
it 'finds not selected and not disabled options' do
expect(string.find(:option, disabled: false, selected: false).value).to eq 'a'
end
end
describe ':button selector' do
it 'finds by value' do
expect(string.find(:button, 'click me').value).to eq 'click me'
end
it 'finds by title' do
expect(string.find(:button, 'submit button').value).to eq 'click me'
end
it 'includes non-matching parameters in failure message' do
expect { string.find(:button, 'click me', title: 'click me') }.to raise_error(/with title click me/)
end
end
describe ':element selector' do
it 'finds by any attributes' do
expect(string.find(:element, 'input', type: 'submit').value).to eq 'click me'
end
it 'supports regexp matching' do
expect(string.find(:element, 'input', type: /sub/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub\w.*button/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub.* b.*ton/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /sub.*mit.*/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^submit button$/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^(?:submit|other) button$/).value).to eq 'click me'
expect(string.find(:element, 'input', title: /SuB.*mIt/i).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^Su.*Bm.*It/i).value).to eq 'click me'
expect(string.find(:element, 'input', title: /^Ot.*he.*r b.*\d/i).value).to eq "don't click me"
end
it 'still works with system keys' do
expect { string.all(:element, 'input', type: 'submit', count: 1) }.not_to raise_error
end
it 'works without element type' do
expect(string.find(:element, type: 'submit').value).to eq 'click me'
end
it 'validates attribute presence when true' do
expect(string.find(:element, name: true)[:id]).to eq 'my_text_input'
end
it 'validates attribute absence when false' do
expect(string.find(:element, 'option', disabled: false, selected: false).value).to eq 'a'
end
it 'includes wildcarded keys in description' do
expect { string.find(:element, 'input', not_there: 'bad', presence: true, absence: false, count: 1) }
.to(raise_error do |e|
expect(e).to be_a(Capybara::ElementNotFound)
expect(e.message).to include 'not_there => bad'
expect(e.message).to include 'with presence attribute'
expect(e.message).to include 'without absence attribute'
expect(e.message).not_to include 'count 1'
end)
end
it 'accepts XPath::Expression' do
expect(string.find(:element, 'input', type: XPath.starts_with('subm')).value).to eq 'click me'
expect(string.find(:element, 'input', type: XPath.ends_with('ext'))[:type]).to eq 'text'
expect(string.find(:element, 'input', type: XPath.contains('ckb'))[:type]).to eq 'checkbox'
expect(string.find(:element, 'input', title: XPath.contains_word('submit'))[:type]).to eq 'submit'
expect(string.find(:element, 'input', title: XPath.contains_word('button 1'))[:type]).to eq 'button'
end
end
describe ':link_or_button selector' do
around do |example|
described_class.modify_selector(:link_or_button) do
expression_filter(:random) { |xpath, _| xpath } # do nothing filter
end
example.run
Capybara::Selector[:link_or_button].expression_filters.delete(:random)
end
it 'should not find links when disabled == true' do
expect(string.all(:link_or_button, disabled: true).size).to eq 0
end
context 'when modified' do
it 'should still work' do
filter = Capybara::Selector[:link_or_button].expression_filters[:random]
allow(filter).to receive(:apply_filter).and_call_original
expect(string.find(:link_or_button, 'click me', random: 'blah').value).to eq 'click me'
expect(filter).to have_received(:apply_filter).with(anything, :random, 'blah', anything)
end
end
end
describe ':table selector' do
it 'finds by rows' do
expect(string.find(:table, with_rows: [%w[D E F]])[:id]).to eq 'rows'
end
it 'finds by columns' do
expect(string.find(:table, with_cols: [%w[A B C]])[:id]).to eq 'cols'
end
end
end
end
end
|
require 'spec_helper'
require 'sequenceserver/sequence'
require 'digest/md5'
# Test Sequence class.
module SequenceServer
describe 'Sequence type detection' do
it 'should be able to detect nucleotide sequences' do
sequences = [
'AAAAAAAAAAAAAAAAAAAAAT',
' CAGATGCRRCAAAGCAAACGGCAA 34523453 652352',
'ACCNNNNNNXXXXCAUUUUUU',
"ACGT\n\t\t\nACCACGGACCACGAAAGCG"
]
sequences.each do |sequence|
Sequence.guess_type(sequence).should == :nucleotide
end
end
it 'should be able to detect protein sequences' do
sequences = [
'ADSACGHKSJLFCVMGTL',
' 345 KSSYPHYSPPPPHS 345 23453 652352',
'GEYSNLNNNNNNXXXXSSSSSSSSSSSSSSSSSSSSSSS',
"EE\n\t\t\n \t\t\EEQRRQQSARTSRRQR"
]
sequences.each do |sequence|
Sequence.guess_type(sequence).should == :protein
end
end
it 'should be able to say sequence type detection impossible' do
Sequence.guess_type('ACSFGT').should be_nil
end
it 'should be able to tell composition of a sequence string' do
Sequence.composition('asdfasdfffffAsdf').should == { 'a' => 2, 'd' => 3,
'f' => 7, 's' => 3,
'A' => 1 }
end
end
describe 'Sequence retrieval' do
root = SequenceServer.root
database_dir = File.join(root, 'spec', 'database')
let 'a_normal_database_id' do
Digest::MD5.hexdigest File.join(database_dir, 'sample', 'proteins',
'Solenopsis_invicta',
'Sinvicta2-2-3.prot.subset.fasta')
end
let 'funky_ids_database_id' do
Digest::MD5.hexdigest File.join(database_dir, 'funky_ids',
'funky_ids.fa')
end
before :all do
SequenceServer.config[:database_dir] = database_dir
Database.scan_databases_dir
end
it 'should be able to retrieve sequences from database' do
sequences = Sequence::Retriever.new('SI2.2.0_06267',
a_normal_database_id).sequences
sequences.length.should eq 1
sequences.first.gi.should be_nil
sequences.first.seqid.should eq 'lcl|SI2.2.0_06267'
sequences.first.accession.should eq 'SI2.2.0_06267'
sequences.first.id.should eq 'lcl|SI2.2.0_06267'
sequences.first.title.should eq 'locus=Si_gnF.scaffold02592'\
'[1282609..1284114].pep_2 quality=100.00'
sequences.first.value.should == "\
MNTLWLSLWDYPGKLPLNFMVFDTKDDLQAAYWRDPYSIPLAVIFEDPQPISQRLIYEIRTNPSYTLPPPPTKLYSAPI\
SCRKNKTGHWMDDILSIKTGESCPVNNYLHSGFLALQMITDITKIKLENSDVTIPDIKLIMFPKEPYTADWMLAFRVVI\
PLYMVLALSQFITYLLILIVGEKENKIKEGMKMMGLNDSVF"
end
it 'should be able to retrieve more than one sequence from a database' do
sequences = Sequence::Retriever.new(['SI2.2.0_06267', 'SI2.2.0_13722'],
a_normal_database_id).sequences
sequences.length.should == 2
end
# it 'should be able to retrieve sequences from database even if accession'\
# 'contains only numbers' do
# Database.scan_databases_dir
# sequences = Sequence.from_blastdb(123456, funky_ids_database_id)
# sequences.length.should == 1
# end
it 'should be able to retrieve sequences from database for all kinds of'\
'funky accessions' do
funky_accessions = ['abcdef#', 'abc#def', '123#456'] # , '123456#']
sequences = Sequence::Retriever.new(funky_accessions,
funky_ids_database_id).sequences
sequences.length.should == 3
end
end
end
Update sequence_spec as per commit f38596e3
Signed-off-by: Anurag Priyam <6e6ab5ea9cb59fe7c35d2a1fc74443577eb60635@gmail.com>
require 'spec_helper'
require 'sequenceserver/sequence'
require 'digest/md5'
# Test Sequence class.
module SequenceServer
describe 'Sequence type detection' do
it 'should be able to detect nucleotide sequences' do
sequences = [
'AAAAAAAAAAAAAAAAAAAAAT',
' CAGATGCRRCAAAGCAAACGGCAA 34523453 652352',
'ACCNNNNNNXXXXCAUUUUUU',
"ACGT\n\t\t\nACCACGGACCACGAAAGCG"
]
sequences.each do |sequence|
Sequence.guess_type(sequence).should == :nucleotide
end
end
it 'should be able to detect protein sequences' do
sequences = [
'ADSACGHKSJLFCVMGTL',
' 345 KSSYPHYSPPPPHS 345 23453 652352',
'GEYSNLNNNNNNXXXXSSSSSSSSSSSSSSSSSSSSSSS',
"EE\n\t\t\n \t\t\EEQRRQQSARTSRRQR"
]
sequences.each do |sequence|
Sequence.guess_type(sequence).should == :protein
end
end
it 'should be able to say sequence type detection impossible' do
Sequence.guess_type('ACSFGT').should be_nil
end
it 'should be able to tell composition of a sequence string' do
Sequence.composition('asdfasdfffffAsdf').should == { 'a' => 2, 'd' => 3,
'f' => 7, 's' => 3,
'A' => 1 }
end
end
describe 'Sequence retrieval' do
root = SequenceServer.root
database_dir = File.join(root, 'spec', 'database')
let 'a_normal_database_id' do
Digest::MD5.hexdigest File.join(database_dir, 'sample', 'proteins',
'Solenopsis_invicta',
'Sinvicta2-2-3.prot.subset.fasta')
end
let 'funky_ids_database_id' do
Digest::MD5.hexdigest File.join(database_dir, 'funky_ids',
'funky_ids.fa')
end
before :all do
SequenceServer.config[:database_dir] = database_dir
Database.scan_databases_dir
end
it 'should be able to retrieve sequences from database' do
sequences = Sequence::Retriever.new('SI2.2.0_06267',
a_normal_database_id).sequences
sequences.length.should eq 1
sequences.first.gi.should be_nil
sequences.first.seqid.should eq 'SI2.2.0_06267'
sequences.first.accession.should eq 'SI2.2.0_06267'
sequences.first.id.should eq 'SI2.2.0_06267'
sequences.first.title.should eq 'locus=Si_gnF.scaffold02592'\
'[1282609..1284114].pep_2 quality=100.00'
sequences.first.value.should == "\
MNTLWLSLWDYPGKLPLNFMVFDTKDDLQAAYWRDPYSIPLAVIFEDPQPISQRLIYEIRTNPSYTLPPPPTKLYSAPI\
SCRKNKTGHWMDDILSIKTGESCPVNNYLHSGFLALQMITDITKIKLENSDVTIPDIKLIMFPKEPYTADWMLAFRVVI\
PLYMVLALSQFITYLLILIVGEKENKIKEGMKMMGLNDSVF"
end
it 'should be able to retrieve more than one sequence from a database' do
sequences = Sequence::Retriever.new(['SI2.2.0_06267', 'SI2.2.0_13722'],
a_normal_database_id).sequences
sequences.length.should == 2
end
# it 'should be able to retrieve sequences from database even if accession'\
# 'contains only numbers' do
# Database.scan_databases_dir
# sequences = Sequence.from_blastdb(123456, funky_ids_database_id)
# sequences.length.should == 1
# end
it 'should be able to retrieve sequences from database for all kinds of'\
'funky accessions' do
funky_accessions = ['abcdef#', 'abc#def', '123#456'] # , '123456#']
sequences = Sequence::Retriever.new(funky_accessions,
funky_ids_database_id).sequences
sequences.length.should == 3
end
end
end
|
require_relative 'spec_helper'
describe 'Sequence' do
it 'should create empty sequence when iterable is nil' do
expect(sequence(nil)).to eq(empty)
end
it 'should support head' do
expect(sequence(1, 2).head).to eq(1)
end
it 'should return same result when head called many times' do
expect(sequence(1, 2).head).to eq(1)
expect(sequence(1, 2).head).to eq(1)
end
it 'should support head_option' do
expect(sequence(1).head_option).to eq(some(1))
expect(empty.head_option).to eq(none)
end
it 'should support reverse' do
expect(sequence(1, 2, 3).reverse).to eq(sequence(3, 2, 1))
end
it 'should support last' do
expect(sequence(1, 2, 3).last).to eq(3)
end
it 'should support last_option' do
expect(sequence(1, 2, 3).last_option).to eq(some(3))
expect(empty.last_option).to eq(none)
end
it 'should support tail' do
expect(sequence(1, 2, 3).tail).to eq(sequence(2, 3))
end
it 'should lazily return tail' do
expect(Sequence.new((1..Float::INFINITY).lazy).tail.head).to eq(2)
end
it 'should return empty tail on sequence with 1 item' do
expect(sequence(1).tail).to eq(empty)
end
it 'should raise NoSuchElementException when getting a tail of empty' do
expect { empty.tail }.to raise_error(NoSuchElementException)
end
it 'should support init' do
expect(sequence(1, 2, 3).init).to eq(sequence(1, 2))
end
it 'should raise NoSuchElementException when getting init of an empty' do
expect { empty.init }.to raise_error(NoSuchElementException)
end
it 'should support map' do
expect(sequence(1, 2, 3).map(->(a) { a*2 })).to eq(sequence(2, 4, 6))
end
it 'should support fold (aka fold_left)' do
expect(sequence(1, 2, 3).fold(0, sum)).to eq(6)
expect(sequence(1, 2, 3).fold_left(0, sum)).to eq(6)
expect(sequence('1', '2', '3').fold(0, join)).to eq('0123')
expect(sequence('1', '2', '3').fold_left(0, join)).to eq('0123')
end
it 'should support reduce (aka reduce_left)' do
expect(sequence(1, 2, 3).reduce(sum)).to eq(6)
expect(sequence(1, 2, 3).reduce_left(sum)).to eq(6)
expect(sequence('1', '2', '3').reduce(join)).to eq('123')
expect(sequence('1', '2', '3').reduce_left(join)).to eq('123')
end
it 'should support fold_right' do
expect(empty.fold_right(4, sum)).to eq(4)
expect(sequence(1).fold_right(4, sum)).to eq(5)
expect(sequence(1, 2).fold_right(4, sum)).to eq(7)
expect(sequence(1, 2, 3).fold_right(4, sum)).to eq(10)
expect(empty.fold_right('4', join)).to eq('4')
expect(sequence('1').fold_right('4', join)).to eq('14')
expect(sequence('1', '2').fold_right('4', join)).to eq('124')
expect(sequence('1', '2', '3').fold_right('4', join)).to eq('1234')
end
it 'should support reduce_right' do
# expect(sequence().reduce_right(sum)).to eq(0) <-- need a monoid to do this
expect(sequence(1).reduce_right(sum)).to eq(1)
expect(sequence(1, 2).reduce_right(sum)).to eq(3)
expect(sequence(1, 2, 3).reduce_right(sum)).to eq(6)
# expect(sequence().reduce_right()).to eq('') <-- need a monoid to do this
expect(sequence('1').reduce_right(join)).to eq('1')
expect(sequence('1', '2').reduce_right(join)).to eq('12')
expect(sequence('1', '2', '3').reduce_right(join)).to eq('123')
end
it 'should support find' do
expect(empty.find(even)).to eq(none)
expect(sequence(1, 3, 5).find(even)).to eq(none)
expect(sequence(1, 2, 3).find(even)).to eq(some(2))
end
it 'should support find_index_of' do
expect(sequence(1, 3, 5).find_index_of(even)).to eq(none)
expect(sequence(1, 3, 6).find_index_of(even)).to eq(some(2))
end
it 'should support zip_with_index' do
a = sequence('Dan', 'Kings', 'Raymond').zip_with_index
expect(a).to eq(sequence(pair(0, 'Dan'), pair(1, 'Kings'), pair(2, 'Raymond')))
end
it 'should support zip' do
sequence = sequence(1,3,5)
expect(sequence.zip(sequence(2, 4, 6, 8))).to eq(sequence(pair(1, 2), pair(3, 4), pair(5, 6)))
expect(sequence.zip(sequence(2,4,6))).to eq(sequence(pair(1,2),pair(3,4),pair(5,6)))
expect(sequence.zip(sequence(2,4))).to eq(sequence(pair(1,2),pair(3,4)))
end
end
added another test case to 'should lazily return tail'
require_relative 'spec_helper'
describe 'Sequence' do
it 'should create empty sequence when iterable is nil' do
expect(sequence(nil)).to eq(empty)
end
it 'should support head' do
expect(sequence(1, 2).head).to eq(1)
end
it 'should return same result when head called many times' do
expect(sequence(1, 2).head).to eq(1)
expect(sequence(1, 2).head).to eq(1)
end
it 'should support head_option' do
expect(sequence(1).head_option).to eq(some(1))
expect(empty.head_option).to eq(none)
end
it 'should support reverse' do
expect(sequence(1, 2, 3).reverse).to eq(sequence(3, 2, 1))
end
it 'should support last' do
expect(sequence(1, 2, 3).last).to eq(3)
end
it 'should support last_option' do
expect(sequence(1, 2, 3).last_option).to eq(some(3))
expect(empty.last_option).to eq(none)
end
it 'should support tail' do
expect(sequence(1, 2, 3).tail).to eq(sequence(2, 3))
end
it 'should lazily return tail' do
expect(Sequence.new((1..Float::INFINITY).lazy).tail.head).to eq(2)
expect(range(100).tail.head).to eq(101)
end
it 'should return empty tail on sequence with 1 item' do
expect(sequence(1).tail).to eq(empty)
end
it 'should raise NoSuchElementException when getting a tail of empty' do
expect { empty.tail }.to raise_error(NoSuchElementException)
end
it 'should support init' do
expect(sequence(1, 2, 3).init).to eq(sequence(1, 2))
end
it 'should raise NoSuchElementException when getting init of an empty' do
expect { empty.init }.to raise_error(NoSuchElementException)
end
it 'should support map' do
expect(sequence(1, 2, 3).map(->(a) { a*2 })).to eq(sequence(2, 4, 6))
end
it 'should support fold (aka fold_left)' do
expect(sequence(1, 2, 3).fold(0, sum)).to eq(6)
expect(sequence(1, 2, 3).fold_left(0, sum)).to eq(6)
expect(sequence('1', '2', '3').fold(0, join)).to eq('0123')
expect(sequence('1', '2', '3').fold_left(0, join)).to eq('0123')
end
it 'should support reduce (aka reduce_left)' do
expect(sequence(1, 2, 3).reduce(sum)).to eq(6)
expect(sequence(1, 2, 3).reduce_left(sum)).to eq(6)
expect(sequence('1', '2', '3').reduce(join)).to eq('123')
expect(sequence('1', '2', '3').reduce_left(join)).to eq('123')
end
it 'should support fold_right' do
expect(empty.fold_right(4, sum)).to eq(4)
expect(sequence(1).fold_right(4, sum)).to eq(5)
expect(sequence(1, 2).fold_right(4, sum)).to eq(7)
expect(sequence(1, 2, 3).fold_right(4, sum)).to eq(10)
expect(empty.fold_right('4', join)).to eq('4')
expect(sequence('1').fold_right('4', join)).to eq('14')
expect(sequence('1', '2').fold_right('4', join)).to eq('124')
expect(sequence('1', '2', '3').fold_right('4', join)).to eq('1234')
end
it 'should support reduce_right' do
# expect(sequence().reduce_right(sum)).to eq(0) <-- need a monoid to do this
expect(sequence(1).reduce_right(sum)).to eq(1)
expect(sequence(1, 2).reduce_right(sum)).to eq(3)
expect(sequence(1, 2, 3).reduce_right(sum)).to eq(6)
# expect(sequence().reduce_right()).to eq('') <-- need a monoid to do this
expect(sequence('1').reduce_right(join)).to eq('1')
expect(sequence('1', '2').reduce_right(join)).to eq('12')
expect(sequence('1', '2', '3').reduce_right(join)).to eq('123')
end
it 'should support find' do
expect(empty.find(even)).to eq(none)
expect(sequence(1, 3, 5).find(even)).to eq(none)
expect(sequence(1, 2, 3).find(even)).to eq(some(2))
end
it 'should support find_index_of' do
expect(sequence(1, 3, 5).find_index_of(even)).to eq(none)
expect(sequence(1, 3, 6).find_index_of(even)).to eq(some(2))
end
it 'should support zip_with_index' do
a = sequence('Dan', 'Kings', 'Raymond').zip_with_index
expect(a).to eq(sequence(pair(0, 'Dan'), pair(1, 'Kings'), pair(2, 'Raymond')))
end
it 'should support zip' do
sequence = sequence(1,3,5)
expect(sequence.zip(sequence(2, 4, 6, 8))).to eq(sequence(pair(1, 2), pair(3, 4), pair(5, 6)))
expect(sequence.zip(sequence(2,4,6))).to eq(sequence(pair(1,2),pair(3,4),pair(5,6)))
expect(sequence.zip(sequence(2,4))).to eq(sequence(pair(1,2),pair(3,4)))
end
end |
module SharedModelSpecs
shared_examples_for "exportable" do
it "Model#export returns all records with extra attributes added" do
# User/assignee for the second record has no first/last name.
exported.size.should == 2
exported[0].user_id_full_name.should == "#{exported[0].user.first_name} #{exported[0].user.last_name}"
exported[1].user_id_full_name.should == "#{exported[1].user.email}"
if exported[0].respond_to?(:assigned_to)
if exported[0].assigned_to?
exported[0].assigned_to_full_name.should == "#{exported[0].assignee.first_name} #{exported[0].assignee.last_name}"
else
exported[0].assigned_to_full_name.should == ''
end
if exported[1].assigned_to?
exported[1].assigned_to_full_name.should == "#{exported[1].assignee.email}"
else
exported[1].assigned_to_full_name.should == ''
end
end
if exported[0].respond_to?(:completed_by)
if exported[0].completed_by?
exported[0].completed_by_full_name.should == "#{exported[0].completor.first_name} #{exported[0].completor.last_name}"
else
exported[0].completed_by_full_name.should == ''
end
if exported[1].completed_by?
exported[1].completed_by_full_name.should == "#{exported[1].completor.email}"
else
exported[1].completed_by_full_name.should == ''
end
end
end
end
end
shared/models.rb specs keep randomly failing. Pending for now
module SharedModelSpecs
shared_examples_for "exportable" do
it "Model#export returns all records with extra attributes added" do
pending
# User/assignee for the second record has no first/last name.
exported.size.should == 2
exported[0].user_id_full_name.should == "#{exported[0].user.first_name} #{exported[0].user.last_name}"
exported[1].user_id_full_name.should == "#{exported[1].user.email}"
if exported[0].respond_to?(:assigned_to)
if exported[0].assigned_to?
exported[0].assigned_to_full_name.should == "#{exported[0].assignee.first_name} #{exported[0].assignee.last_name}"
else
exported[0].assigned_to_full_name.should == ''
end
if exported[1].assigned_to?
exported[1].assigned_to_full_name.should == "#{exported[1].assignee.email}"
else
exported[1].assigned_to_full_name.should == ''
end
end
if exported[0].respond_to?(:completed_by)
if exported[0].completed_by?
exported[0].completed_by_full_name.should == "#{exported[0].completor.first_name} #{exported[0].completor.last_name}"
else
exported[0].completed_by_full_name.should == ''
end
if exported[1].completed_by?
exported[1].completed_by_full_name.should == "#{exported[1].completor.email}"
else
exported[1].completed_by_full_name.should == ''
end
end
end
end
end
|
ENV['RAILS_ENV'] = 'test'
module AlfredRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
config.secret_token = 'existing secret token'
if Rails::VERSION::STRING >= "4.0.0"
config.secret_key_base = 'new secret key base'
end
end
end
#AlfredRailsTest::Application.initialize!
Better token
ENV['RAILS_ENV'] = 'test'
module AlfredRailsTest
class Application < Rails::Application
config.active_support.deprecation = :log
config.secret_token = '8f62080da9dd946a6555635c46fbebfb'
if Rails::VERSION::STRING >= "4.0.0"
config.secret_key_base = '8f62080da9dd946a6555635c46fbebfb'
end
end
end
#AlfredRailsTest::Application.initialize! |
finish spec/template_spec.rb
# encoding: utf-8
require 'spec_helper'
describe SmartSMS::Template do
describe '#find_default' do
let(:url) { 'http://yunpian.com/v1/tpl/get_default.json' }
let(:tpl_id) { '1' }
subject { SmartSMS::Template.find_default tpl_id }
before do
stub_request(:post, url).with(
body: {
'apikey' => SmartSMS.config.api_key,
'tpl_id' => tpl_id
},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded'
}
).to_return(
body: {
'code' => 0,
'msg' => 'OK',
'template' => {
'tpl_id' => tpl_id,
'tpl_content' => '您的验证码是#code#【#company#】',
'check_status' => 'SUCCESS',
'reason' => nil
}
}.to_json
)
end
its(['code']) { should eq 0 }
its(['msg']) { should eq 'OK' }
its(:keys) { should include 'template' }
end
describe '#find' do
let(:url) { 'http://yunpian.com/v1/tpl/get.json' }
let(:tpl_id) { '325207' }
subject { SmartSMS::Template.find tpl_id }
before do
stub_request(:post, url).with(
body: {
'apikey' => SmartSMS.config.api_key,
'tpl_id' => tpl_id
},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded'
}
).to_return(
body: {
'code' => 0,
'msg' => 'OK',
'template' => {
'tpl_id' => tpl_id,
'tpl_content' => '您的验证码是#code#【#company#】',
'check_status' => 'SUCCESS',
'reason' => nil
}
}.to_json
)
end
its(['code']) { should eq 0 }
its(['msg']) { should eq 'OK' }
its(:keys) { should include 'template' }
end
describe '#create' do
let(:url) { 'http://yunpian.com/v1/tpl/add.json' }
let(:tpl_content) { '您的验证码是: #code#' }
subject { SmartSMS::Template.create tpl_content }
before do
stub_request(:post, url).with(
body: {
'apikey' => SmartSMS.config.api_key,
'tpl_content' => tpl_content
},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded'
}
).to_return(
body: {
'code' => 0,
'msg' => 'OK',
'template' => {
'tpl_id' => '43243242',
'tpl_content' => tpl_content,
'check_status' => 'SUCCESS',
'reason' => nil
}
}.to_json
)
end
its(['code']) { should eq 0 }
its(['msg']) { should eq 'OK' }
its(:keys) { should include 'template' }
end
describe '#update' do
let(:url) { 'http://yunpian.com/v1/tpl/update.json' }
let(:tpl_id) { '43243242' }
let(:tpl_content) { '您的验证码是: #code#' }
subject { SmartSMS::Template.update tpl_id, tpl_content }
before do
stub_request(:post, url).with(
body: {
'apikey' => SmartSMS.config.api_key,
'tpl_id' => tpl_id,
'tpl_content' => tpl_content
},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded'
}
).to_return(
body: {
'code' => 0,
'msg' => 'OK',
'template' => {
'tpl_id' => tpl_id,
'tpl_content' => tpl_content,
'check_status' => 'SUCCESS',
'reason' => nil
}
}.to_json
)
end
its(['code']) { should eq 0 }
its(['msg']) { should eq 'OK' }
its(:keys) { should include 'template' }
end
describe '#destroy' do
let(:url) { 'http://yunpian.com/v1/tpl/del.json' }
let(:tpl_id) { '43243242' }
subject { SmartSMS::Template.destroy tpl_id }
before do
stub_request(:post, url).with(
body: {
'apikey' => SmartSMS.config.api_key,
'tpl_id' => tpl_id
},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded'
}
).to_return(
body: {
'code' => 0,
'msg' => 'OK',
'detail' => nil
}.to_json
)
end
its(['code']) { should eq 0 }
its(['msg']) { should eq 'OK' }
its(:keys) { should include 'detail' }
its(['detail']) { should be_nil }
end
end
|
require 'spec_helper'
describe Twig::Cli do
describe '.prompt_with_choices' do
it 'prints a prompt with the given choices' do
stdout_orig = $stdout
stdout_test = StringIO.new
$stdout = stdout_test
prompt = 'What does the fox say?'
choices = [
'Ring-ding-ding-ding-dingeringeding!',
'Wa-pa-pa-pa-pa-pa-pow!',
'Hatee-hatee-hatee-ho!',
'Joff-tchoff-tchoffo-tchoffo-tchoff!'
]
expect($stdin).to receive(:gets).and_return('4')
result = Twig::Cli.prompt_with_choices(prompt, choices)
$stdout = stdout_orig
expect(stdout_test.string).to eq(
prompt + "\n" +
" 1. #{choices[0]}\n" +
" 2. #{choices[1]}\n" +
" 3. #{choices[2]}\n" +
" 4. #{choices[3]}\n" +
'> '
)
expect(result).to eq(choices[3])
end
it 'requires at least two choices' do
expect {
Twig::Cli.prompt_with_choices(
'What does the fox say?',
['Ring-ding-ding-ding-dingeringeding!']
)
}.to raise_exception(ArgumentError)
end
end
describe '#help_description' do
before :each do
@twig = Twig.new
end
it 'returns short text in a single line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80)
expect(result).to eq([text])
end
it 'returns long text in a string with line breaks' do
text = 'The quick brown fox jumps over the lazy, lazy dog.'
result = @twig.help_description(text, :width => 20)
expect(result).to eq([
'The quick brown fox',
'jumps over the lazy,',
'lazy dog.'
])
end
it 'breaks a long word by max line length' do
text = 'Thequickbrownfoxjumpsoverthelazydog.'
result = @twig.help_description(text, :width => 20)
expect(result).to eq([
'Thequickbrownfoxjump',
'soverthelazydog.'
])
end
it 'adds a separator line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80, :add_separator => true)
expect(result).to eq([text, ' '])
end
end
describe '#help_description_for_custom_property' do
before :each do
@twig = Twig.new
end
it 'returns a help string for a custom property' do
option_parser = OptionParser.new
expect(@twig).to receive(:help_separator) do |opt_parser, desc, options|
expect(opt_parser).to eq(option_parser)
expect(desc).to eq(" --test-option Test option description\n")
expect(options).to eq(:trailing => "\n")
end
@twig.help_description_for_custom_property(option_parser, [
['--test-option', 'Test option description']
])
end
it 'supports custom trailing whitespace' do
option_parser = OptionParser.new
expect(@twig).to receive(:help_separator) do |opt_parser, desc, options|
expect(opt_parser).to eq(option_parser)
expect(desc).to eq(" --test-option Test option description\n")
expect(options).to eq(:trailing => '')
end
@twig.help_description_for_custom_property(option_parser, [
['--test-option', 'Test option description']
], :trailing => '')
end
end
describe '#help_paragraph' do
before :each do
@twig = Twig.new
end
it 'returns long text in a paragraph with line breaks' do
text = Array.new(5) {
'The quick brown fox jumps over the lazy dog.'
}.join(' ')
result = @twig.help_paragraph(text)
expect(result).to eq([
"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the",
"lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps",
"over the lazy dog. The quick brown fox jumps over the lazy dog."
].join("\n"))
end
end
describe '#help_line_for_custom_property?' do
before :each do
@twig = Twig.new
end
it 'returns true for `--except-foo`' do
expect(@twig.help_line_for_custom_property?(' --except-foo ')).to be_true
end
it 'returns false for `--except-branch`' do
expect(@twig.help_line_for_custom_property?(' --except-branch ')).to be_false
end
it 'returns false for `--except-property`' do
expect(@twig.help_line_for_custom_property?(' --except-property ')).to be_false
end
it 'returns false for `--except-PROPERTY`' do
expect(@twig.help_line_for_custom_property?(' --except-PROPERTY ')).to be_false
end
it 'returns true for `--only-foo`' do
expect(@twig.help_line_for_custom_property?(' --only-foo ')).to be_true
end
it 'returns false for `--only-branch`' do
expect(@twig.help_line_for_custom_property?(' --only-branch ')).to be_false
end
it 'returns false for `--only-property`' do
expect(@twig.help_line_for_custom_property?(' --only-property ')).to be_false
end
it 'returns false for `--only-PROPERTY`' do
expect(@twig.help_line_for_custom_property?(' --only-PROPERTY ')).to be_false
end
it 'returns true for `--foo-width`' do
expect(@twig.help_line_for_custom_property?(' --foo-width ')).to be_true
end
it 'returns false for `--branch-width`' do
expect(@twig.help_line_for_custom_property?(' --branch-width ')).to be_false
end
it 'returns false for `--PROPERTY-width`' do
expect(@twig.help_line_for_custom_property?(' --PROPERTY-width ')).to be_false
end
end
describe '#run_pager' do
before :each do
@twig = Twig.new
end
it 'turns the current process into a `less` pager' do
allow(Kernel).to receive(:fork) { true }
expect(@twig).to receive(:exec).with('less')
@twig.run_pager
end
it 'turns the current process into a custom pager' do
allow(Kernel).to receive(:fork) { true }
pager = 'arbitrary'
expect(ENV).to receive(:[]).with('PAGER').and_return(pager)
expect(@twig).to receive(:exec).with(pager)
@twig.run_pager
end
it 'does nothing if running on Windows' do
expect(Twig::System).to receive(:windows?).and_return(true)
expect(Kernel).not_to receive(:fork)
@twig.run_pager
end
it 'does nothing if not running on a terminal device' do
allow($stdout).to receive(:tty?) { false }
expect(Kernel).not_to receive(:fork)
@twig.run_pager
end
end
describe '#read_cli_options!' do
before :each do
@twig = Twig.new
allow(@twig).to receive(:run_pager)
end
it 'recognizes `--unset` and sets an `:unset_property` option' do
expect(@twig.options[:unset_property]).to be_nil
@twig.read_cli_options!(%w[--unset test])
expect(@twig.options[:unset_property]).to eq('test')
end
it 'recognizes `--help` and prints the help content' do
help_lines = []
allow(@twig).to receive(:puts) { |message| help_lines << message.strip }
expect(@twig).to receive(:exit)
@twig.read_cli_options!(['--help'])
expect(help_lines).to include("Twig v#{Twig::VERSION}")
expect(help_lines).to include('http://rondevera.github.io/twig/')
end
it 'recognizes `--version` and prints the current version' do
expect(@twig).to receive(:puts).with(Twig::VERSION)
expect(@twig).to receive(:exit)
@twig.read_cli_options!(['--version'])
end
it 'recognizes `-b` and sets a `:branch` option' do
expect(Twig::Branch).to receive(:all_branch_names).and_return(['test'])
expect(@twig.options[:branch]).to be_nil
@twig.read_cli_options!(%w[-b test])
expect(@twig.options[:branch]).to eq('test')
end
it 'recognizes `--branch` and sets a `:branch` option' do
expect(Twig::Branch).to receive(:all_branch_names).and_return(['test'])
expect(@twig.options[:branch]).to be_nil
@twig.read_cli_options!(%w[--branch test])
expect(@twig.options[:branch]).to eq('test')
end
it 'recognizes `--max-days-old` and sets a `:max_days_old` option' do
expect(@twig.options[:max_days_old]).to be_nil
@twig.read_cli_options!(%w[--max-days-old 30])
expect(@twig.options[:max_days_old]).to eq(30)
end
it 'recognizes `--except-branch` and sets a `:property_except` option' do
expect(@twig.options[:property_except]).to be_nil
@twig.read_cli_options!(%w[--except-branch test])
expect(@twig.options[:property_except]).to eq(:branch => /test/)
end
it 'recognizes `--only-branch` and sets a `:property_only` option' do
expect(@twig.options[:property_only]).to be_nil
@twig.read_cli_options!(%w[--only-branch test])
expect(@twig.options[:property_only]).to eq(:branch => /test/)
end
context 'with custom property "only" filtering' do
before :each do
expect(@twig.options[:property_only]).to be_nil
end
it 'recognizes `--only-<property>` and sets a `:property_only` option' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--only-foo test])
expect(@twig.options[:property_only]).to eq(:foo => /test/)
end
it 'recognizes `--only-branch` and `--only-<property>` together' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--only-branch test --only-foo bar])
expect(@twig.options[:property_only]).to eq(
:branch => /test/,
:foo => /bar/
)
end
it 'does not recognize `--only-<property>` for a missing property' do
property_name = 'foo'
expect(Twig::Branch.all_property_names).not_to include(property_name)
allow(@twig).to receive(:puts)
expect {
@twig.read_cli_options!(["--only-#{property_name}", 'test'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(1)
}
expect(@twig.options[:property_only]).to be_nil
end
end
context 'with custom property "except" filtering' do
before :each do
expect(@twig.options[:property_except]).to be_nil
end
it 'recognizes `--except-<property>` and sets a `:property_except` option' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--except-foo test])
expect(@twig.options[:property_except]).to eq(:foo => /test/)
end
it 'recognizes `--except-branch` and `--except-<property>` together' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--except-branch test --except-foo bar])
expect(@twig.options[:property_except]).to eq(
:branch => /test/,
:foo => /bar/
)
end
it 'does not recognize `--except-<property>` for a missing property' do
property_name = 'foo'
expect(Twig::Branch.all_property_names).not_to include(property_name)
allow(@twig).to receive(:puts)
expect {
@twig.read_cli_options!(["--except-#{property_name}", 'test'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(1)
}
expect(@twig.options[:property_except]).to be_nil
end
end
it 'recognizes `--format` and sets a `:format` option' do
expect(@twig.options[:format]).to be_nil
@twig.read_cli_options!(%w[--format json])
expect(@twig.options[:format]).to eq(:json)
end
it 'recognizes `--all` and unsets other options except `:branch`' do
@twig.set_option(:max_days_old, 30)
@twig.set_option(:property_except, :branch => /test/)
@twig.set_option(:property_only, :branch => /test/)
@twig.read_cli_options!(['--all'])
expect(@twig.options[:max_days_old]).to be_nil
expect(@twig.options[:property_except]).to be_nil
expect(@twig.options[:property_only]).to be_nil
end
it 'recognizes `--branch-width`' do
expect(@twig.options[:property_width]).to be_nil
expect(@twig).to receive(:set_option).with(:property_width, :branch => '10')
@twig.read_cli_options!(%w[--branch-width 10])
end
it 'recognizes `--<property>-width`' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
expect(@twig.options[:property_width]).to be_nil
expect(@twig).to receive(:set_option).with(:property_width, :foo => '10')
@twig.read_cli_options!(%w[--foo-width 10])
end
it 'recognizes `--only-property`' do
expect(@twig.options[:property_only_name]).to be_nil
@twig.read_cli_options!(%w[--only-property foo])
expect(@twig.options[:property_only_name]).to eq(/foo/)
end
it 'recognizes `--except-property`' do
expect(@twig.options[:property_except_name]).to be_nil
@twig.read_cli_options!(%w[--except-property foo])
expect(@twig.options[:property_except_name]).to eq(/foo/)
end
it 'recognizes `--header-style`' do
expect(@twig.options[:header_color]).to eq(Twig::DEFAULT_HEADER_COLOR)
expect(@twig.options[:header_weight]).to be_nil
@twig.read_cli_options!(['--header-style', 'green bold'])
expect(@twig.options[:header_color]).to eq(:green)
expect(@twig.options[:header_weight]).to eq(:bold)
end
it 'recognizes `--reverse`' do
expect(@twig.options[:reverse]).to be_nil
@twig.read_cli_options!(['--reverse'])
expect(@twig.options[:reverse]).to be_true
end
it 'recognizes `--github-api-uri-prefix`' do
expect(@twig.options[:github_api_uri_prefix]).to eq(Twig::DEFAULT_GITHUB_API_URI_PREFIX)
prefix = 'https://github-enterprise.example.com/api/v3'
@twig.read_cli_options!(['--github-api-uri-prefix', prefix])
expect(@twig.options[:github_api_uri_prefix]).to eq(prefix)
end
it 'recognizes `--github-uri-prefix`' do
expect(@twig.options[:github_uri_prefix]).to eq(Twig::DEFAULT_GITHUB_URI_PREFIX)
prefix = 'https://github-enterprise.example.com'
@twig.read_cli_options!(['--github-uri-prefix', prefix])
expect(@twig.options[:github_uri_prefix]).to eq(prefix)
end
it 'handles invalid options' do
expect(@twig).to receive(:abort_for_option_exception) do |exception|
expect(exception).to be_a(OptionParser::InvalidOption)
expect(exception.message).to include('invalid option: --foo')
end
@twig.read_cli_options!(['--foo'])
end
it 'handles missing arguments' do
expect(@twig).to receive(:abort_for_option_exception) do |exception|
expect(exception).to be_a(OptionParser::MissingArgument)
expect(exception.message).to include('missing argument: --branch')
end
@twig.read_cli_options!(['--branch'])
end
end
describe '#abort_for_option_exception' do
before :each do
@twig = Twig.new
end
it 'prints a message and aborts' do
exception = Exception.new('test exception')
expect(@twig).to receive(:puts) do |message|
expect(message).to include('`twig --help`')
end
expect {
@twig.abort_for_option_exception(exception)
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(1)
}
end
end
describe '#exec_subcommand_if_any' do
before :each do
@twig = Twig.new
@branch_name = 'test'
allow(Twig).to receive(:run)
allow(@twig).to receive(:current_branch_name) { @branch_name }
end
it 'recognizes a subcommand' do
command_path = '/path/to/bin/twig-subcommand'
expect(Twig).to receive(:run).with('which twig-subcommand 2>/dev/null').
and_return(command_path)
expect(@twig).to receive(:exec).with(command_path) { exit }
# Since we're stubbing `exec` (with an expectation), we still need it
# to exit early like the real implementation. The following handles the
# exit somewhat gracefully.
expect {
@twig.read_cli_args!(['subcommand'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(0)
}
end
it 'does not recognize a subcommand' do
expect(Twig).to receive(:run).
with('which twig-subcommand 2>/dev/null').and_return('')
expect(@twig).not_to receive(:exec)
allow(@twig).to receive(:abort)
@twig.read_cli_args!(['subcommand'])
end
end
describe '#read_cli_args!' do
before :each do
@twig = Twig.new
end
it 'checks for and executes a subcommand if there are any args' do
expect(@twig).to receive(:exec_subcommand_if_any).with(['foo']) { exit }
expect {
@twig.read_cli_args!(['foo'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(0)
}
end
it 'does not check for a subcommand if there are no args' do
branch_list = %[foo bar]
expect(@twig).not_to receive(:exec_subcommand_if_any)
allow(@twig).to receive(:list_branches).and_return(branch_list)
allow(@twig).to receive(:puts).with(branch_list)
@twig.read_cli_args!([])
end
it 'lists branches' do
branch_list = %[foo bar]
expect(@twig).to receive(:list_branches).and_return(branch_list)
expect(@twig).to receive(:puts).with(branch_list)
@twig.read_cli_args!([])
end
it 'prints branch properties as JSON' do
branches_json = {
'branch1' => { 'last-commit-time' => '2000-01-01' },
'branch2' => { 'last-commit-time' => '2000-01-01' }
}.to_json
expect(@twig).to receive(:branches_json).and_return(branches_json)
expect(@twig).to receive(:puts).with(branches_json)
@twig.read_cli_args!(%w[--format json])
end
context 'getting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
end
it 'gets a property for the current branch' do
expect(@twig).to receive(:current_branch_name).and_return(@branch_name)
expect(@twig).to receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
it 'gets a property for a specified branch' do
expect(Twig::Branch).to receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
expect(@twig).to receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
end
context 'setting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
@message = 'Saved.'
end
it 'sets a property for the current branch' do
expect(@twig).to receive(:current_branch_name).and_return(@branch_name)
expect(@twig).to receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value)
@twig.read_cli_args!([@property_name, @property_value])
end
it 'sets a property for a specified branch' do
expect(Twig::Branch).to receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
expect(@twig).to receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value).
and_return(@message)
@twig.read_cli_args!([@property_name, @property_value])
end
end
context 'unsetting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@message = 'Removed.'
@twig.set_option(:unset_property, @property_name)
end
it 'unsets a property for the current branch' do
expect(@twig).to receive(:current_branch_name).and_return(@branch_name)
expect(@twig).to receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
it 'unsets a property for a specified branch' do
expect(Twig::Branch).to receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
expect(@twig).to receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
end
end
describe '#get_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'gets a property' do
property_value = 'bar'
expect(@twig).to receive(:get_branch_property).
with(@branch_name, @property_name).and_return(property_value)
expect(@twig).to receive(:puts).with(property_value)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'shows an error when getting a property that is not set' do
error_message = 'test error'
expect(@twig).to receive(:get_branch_property).
with(@branch_name, @property_name).and_return(nil)
allow_any_instance_of(Twig::Branch::MissingPropertyError).
to receive(:message) { error_message }
expect(@twig).to receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when getting an invalid branch property name' do
bad_property_name = ''
error_message = 'test error'
expect(@twig).to receive(:get_branch_property).
with(@branch_name, bad_property_name) do
raise ArgumentError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, bad_property_name)
end
end
describe '#set_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'sets a property for the specified branch' do
success_message = 'test success'
property_value = 'bar'
expect(@twig).to receive(:set_branch_property).
with(@branch_name, @property_name, property_value).
and_return(success_message)
expect(@twig).to receive(:puts).with(success_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
property_value = ''
expect(@twig).to receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise ArgumentError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles RuntimeError when Git is unable to set a branch property' do
error_message = 'test error'
property_value = ''
expect(@twig).to receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise RuntimeError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
end
describe '#unset_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'unsets a property for the specified branch' do
success_message = 'test success'
expect(@twig).to receive(:unset_branch_property).
with(@branch_name, @property_name).and_return(success_message)
expect(@twig).to receive(:puts).with(success_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
expect(@twig).to receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise ArgumentError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles MissingPropertyError when unsetting a branch property that is not set' do
error_message = 'test error'
expect(@twig).to receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise Twig::Branch::MissingPropertyError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
end
end
Avoid shadowing variable
require 'spec_helper'
describe Twig::Cli do
describe '.prompt_with_choices' do
it 'prints a prompt with the given choices' do
stdout_orig = $stdout
stdout_test = StringIO.new
$stdout = stdout_test
prompt = 'What does the fox say?'
choices = [
'Ring-ding-ding-ding-dingeringeding!',
'Wa-pa-pa-pa-pa-pa-pow!',
'Hatee-hatee-hatee-ho!',
'Joff-tchoff-tchoffo-tchoffo-tchoff!'
]
expect($stdin).to receive(:gets).and_return('4')
result = Twig::Cli.prompt_with_choices(prompt, choices)
$stdout = stdout_orig
expect(stdout_test.string).to eq(
prompt + "\n" +
" 1. #{choices[0]}\n" +
" 2. #{choices[1]}\n" +
" 3. #{choices[2]}\n" +
" 4. #{choices[3]}\n" +
'> '
)
expect(result).to eq(choices[3])
end
it 'requires at least two choices' do
expect {
Twig::Cli.prompt_with_choices(
'What does the fox say?',
['Ring-ding-ding-ding-dingeringeding!']
)
}.to raise_exception(ArgumentError)
end
end
describe '#help_description' do
before :each do
@twig = Twig.new
end
it 'returns short text in a single line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80)
expect(result).to eq([text])
end
it 'returns long text in a string with line breaks' do
text = 'The quick brown fox jumps over the lazy, lazy dog.'
result = @twig.help_description(text, :width => 20)
expect(result).to eq([
'The quick brown fox',
'jumps over the lazy,',
'lazy dog.'
])
end
it 'breaks a long word by max line length' do
text = 'Thequickbrownfoxjumpsoverthelazydog.'
result = @twig.help_description(text, :width => 20)
expect(result).to eq([
'Thequickbrownfoxjump',
'soverthelazydog.'
])
end
it 'adds a separator line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80, :add_separator => true)
expect(result).to eq([text, ' '])
end
end
describe '#help_description_for_custom_property' do
before :each do
@twig = Twig.new
end
it 'returns a help string for a custom property' do
option_parser = OptionParser.new
expect(@twig).to receive(:help_separator) do |opt_parser, desc, options|
expect(opt_parser).to eq(option_parser)
expect(desc).to eq(" --test-option Test option description\n")
expect(options).to eq(:trailing => "\n")
end
@twig.help_description_for_custom_property(option_parser, [
['--test-option', 'Test option description']
])
end
it 'supports custom trailing whitespace' do
option_parser = OptionParser.new
expect(@twig).to receive(:help_separator) do |opt_parser, desc, options|
expect(opt_parser).to eq(option_parser)
expect(desc).to eq(" --test-option Test option description\n")
expect(options).to eq(:trailing => '')
end
@twig.help_description_for_custom_property(option_parser, [
['--test-option', 'Test option description']
], :trailing => '')
end
end
describe '#help_paragraph' do
before :each do
@twig = Twig.new
end
it 'returns long text in a paragraph with line breaks' do
text = Array.new(5) {
'The quick brown fox jumps over the lazy dog.'
}.join(' ')
result = @twig.help_paragraph(text)
expect(result).to eq([
"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the",
"lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps",
"over the lazy dog. The quick brown fox jumps over the lazy dog."
].join("\n"))
end
end
describe '#help_line_for_custom_property?' do
before :each do
@twig = Twig.new
end
it 'returns true for `--except-foo`' do
expect(@twig.help_line_for_custom_property?(' --except-foo ')).to be_true
end
it 'returns false for `--except-branch`' do
expect(@twig.help_line_for_custom_property?(' --except-branch ')).to be_false
end
it 'returns false for `--except-property`' do
expect(@twig.help_line_for_custom_property?(' --except-property ')).to be_false
end
it 'returns false for `--except-PROPERTY`' do
expect(@twig.help_line_for_custom_property?(' --except-PROPERTY ')).to be_false
end
it 'returns true for `--only-foo`' do
expect(@twig.help_line_for_custom_property?(' --only-foo ')).to be_true
end
it 'returns false for `--only-branch`' do
expect(@twig.help_line_for_custom_property?(' --only-branch ')).to be_false
end
it 'returns false for `--only-property`' do
expect(@twig.help_line_for_custom_property?(' --only-property ')).to be_false
end
it 'returns false for `--only-PROPERTY`' do
expect(@twig.help_line_for_custom_property?(' --only-PROPERTY ')).to be_false
end
it 'returns true for `--foo-width`' do
expect(@twig.help_line_for_custom_property?(' --foo-width ')).to be_true
end
it 'returns false for `--branch-width`' do
expect(@twig.help_line_for_custom_property?(' --branch-width ')).to be_false
end
it 'returns false for `--PROPERTY-width`' do
expect(@twig.help_line_for_custom_property?(' --PROPERTY-width ')).to be_false
end
end
describe '#run_pager' do
before :each do
@twig = Twig.new
end
it 'turns the current process into a `less` pager' do
allow(Kernel).to receive(:fork) { true }
expect(@twig).to receive(:exec).with('less')
@twig.run_pager
end
it 'turns the current process into a custom pager' do
allow(Kernel).to receive(:fork) { true }
pager = 'arbitrary'
expect(ENV).to receive(:[]).with('PAGER').and_return(pager)
expect(@twig).to receive(:exec).with(pager)
@twig.run_pager
end
it 'does nothing if running on Windows' do
expect(Twig::System).to receive(:windows?).and_return(true)
expect(Kernel).not_to receive(:fork)
@twig.run_pager
end
it 'does nothing if not running on a terminal device' do
allow($stdout).to receive(:tty?) { false }
expect(Kernel).not_to receive(:fork)
@twig.run_pager
end
end
describe '#read_cli_options!' do
before :each do
@twig = Twig.new
allow(@twig).to receive(:run_pager)
end
it 'recognizes `--unset` and sets an `:unset_property` option' do
expect(@twig.options[:unset_property]).to be_nil
@twig.read_cli_options!(%w[--unset test])
expect(@twig.options[:unset_property]).to eq('test')
end
it 'recognizes `--help` and prints the help content' do
help_lines = []
allow(@twig).to receive(:puts) { |message| help_lines << message.strip }
expect(@twig).to receive(:exit)
@twig.read_cli_options!(['--help'])
expect(help_lines).to include("Twig v#{Twig::VERSION}")
expect(help_lines).to include('http://rondevera.github.io/twig/')
end
it 'recognizes `--version` and prints the current version' do
expect(@twig).to receive(:puts).with(Twig::VERSION)
expect(@twig).to receive(:exit)
@twig.read_cli_options!(['--version'])
end
it 'recognizes `-b` and sets a `:branch` option' do
expect(Twig::Branch).to receive(:all_branch_names).and_return(['test'])
expect(@twig.options[:branch]).to be_nil
@twig.read_cli_options!(%w[-b test])
expect(@twig.options[:branch]).to eq('test')
end
it 'recognizes `--branch` and sets a `:branch` option' do
expect(Twig::Branch).to receive(:all_branch_names).and_return(['test'])
expect(@twig.options[:branch]).to be_nil
@twig.read_cli_options!(%w[--branch test])
expect(@twig.options[:branch]).to eq('test')
end
it 'recognizes `--max-days-old` and sets a `:max_days_old` option' do
expect(@twig.options[:max_days_old]).to be_nil
@twig.read_cli_options!(%w[--max-days-old 30])
expect(@twig.options[:max_days_old]).to eq(30)
end
it 'recognizes `--except-branch` and sets a `:property_except` option' do
expect(@twig.options[:property_except]).to be_nil
@twig.read_cli_options!(%w[--except-branch test])
expect(@twig.options[:property_except]).to eq(:branch => /test/)
end
it 'recognizes `--only-branch` and sets a `:property_only` option' do
expect(@twig.options[:property_only]).to be_nil
@twig.read_cli_options!(%w[--only-branch test])
expect(@twig.options[:property_only]).to eq(:branch => /test/)
end
context 'with custom property "only" filtering' do
before :each do
expect(@twig.options[:property_only]).to be_nil
end
it 'recognizes `--only-<property>` and sets a `:property_only` option' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--only-foo test])
expect(@twig.options[:property_only]).to eq(:foo => /test/)
end
it 'recognizes `--only-branch` and `--only-<property>` together' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--only-branch test --only-foo bar])
expect(@twig.options[:property_only]).to eq(
:branch => /test/,
:foo => /bar/
)
end
it 'does not recognize `--only-<property>` for a missing property' do
property_name = 'foo'
expect(Twig::Branch.all_property_names).not_to include(property_name)
allow(@twig).to receive(:puts)
expect {
@twig.read_cli_options!(["--only-#{property_name}", 'test'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(1)
}
expect(@twig.options[:property_only]).to be_nil
end
end
context 'with custom property "except" filtering' do
before :each do
expect(@twig.options[:property_except]).to be_nil
end
it 'recognizes `--except-<property>` and sets a `:property_except` option' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--except-foo test])
expect(@twig.options[:property_except]).to eq(:foo => /test/)
end
it 'recognizes `--except-branch` and `--except-<property>` together' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
@twig.read_cli_options!(%w[--except-branch test --except-foo bar])
expect(@twig.options[:property_except]).to eq(
:branch => /test/,
:foo => /bar/
)
end
it 'does not recognize `--except-<property>` for a missing property' do
property_name = 'foo'
expect(Twig::Branch.all_property_names).not_to include(property_name)
allow(@twig).to receive(:puts)
expect {
@twig.read_cli_options!(["--except-#{property_name}", 'test'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(1)
}
expect(@twig.options[:property_except]).to be_nil
end
end
it 'recognizes `--format` and sets a `:format` option' do
expect(@twig.options[:format]).to be_nil
@twig.read_cli_options!(%w[--format json])
expect(@twig.options[:format]).to eq(:json)
end
it 'recognizes `--all` and unsets other options except `:branch`' do
@twig.set_option(:max_days_old, 30)
@twig.set_option(:property_except, :branch => /test/)
@twig.set_option(:property_only, :branch => /test/)
@twig.read_cli_options!(['--all'])
expect(@twig.options[:max_days_old]).to be_nil
expect(@twig.options[:property_except]).to be_nil
expect(@twig.options[:property_only]).to be_nil
end
it 'recognizes `--branch-width`' do
expect(@twig.options[:property_width]).to be_nil
expect(@twig).to receive(:set_option).with(:property_width, :branch => '10')
@twig.read_cli_options!(%w[--branch-width 10])
end
it 'recognizes `--<property>-width`' do
allow(Twig::Branch).to receive(:all_property_names) { %w[foo] }
expect(@twig.options[:property_width]).to be_nil
expect(@twig).to receive(:set_option).with(:property_width, :foo => '10')
@twig.read_cli_options!(%w[--foo-width 10])
end
it 'recognizes `--only-property`' do
expect(@twig.options[:property_only_name]).to be_nil
@twig.read_cli_options!(%w[--only-property foo])
expect(@twig.options[:property_only_name]).to eq(/foo/)
end
it 'recognizes `--except-property`' do
expect(@twig.options[:property_except_name]).to be_nil
@twig.read_cli_options!(%w[--except-property foo])
expect(@twig.options[:property_except_name]).to eq(/foo/)
end
it 'recognizes `--header-style`' do
expect(@twig.options[:header_color]).to eq(Twig::DEFAULT_HEADER_COLOR)
expect(@twig.options[:header_weight]).to be_nil
@twig.read_cli_options!(['--header-style', 'green bold'])
expect(@twig.options[:header_color]).to eq(:green)
expect(@twig.options[:header_weight]).to eq(:bold)
end
it 'recognizes `--reverse`' do
expect(@twig.options[:reverse]).to be_nil
@twig.read_cli_options!(['--reverse'])
expect(@twig.options[:reverse]).to be_true
end
it 'recognizes `--github-api-uri-prefix`' do
expect(@twig.options[:github_api_uri_prefix]).to eq(Twig::DEFAULT_GITHUB_API_URI_PREFIX)
prefix = 'https://github-enterprise.example.com/api/v3'
@twig.read_cli_options!(['--github-api-uri-prefix', prefix])
expect(@twig.options[:github_api_uri_prefix]).to eq(prefix)
end
it 'recognizes `--github-uri-prefix`' do
expect(@twig.options[:github_uri_prefix]).to eq(Twig::DEFAULT_GITHUB_URI_PREFIX)
prefix = 'https://github-enterprise.example.com'
@twig.read_cli_options!(['--github-uri-prefix', prefix])
expect(@twig.options[:github_uri_prefix]).to eq(prefix)
end
it 'handles invalid options' do
expect(@twig).to receive(:abort_for_option_exception) do |exception|
expect(exception).to be_a(OptionParser::InvalidOption)
expect(exception.message).to include('invalid option: --foo')
end
@twig.read_cli_options!(['--foo'])
end
it 'handles missing arguments' do
expect(@twig).to receive(:abort_for_option_exception) do |exception|
expect(exception).to be_a(OptionParser::MissingArgument)
expect(exception.message).to include('missing argument: --branch')
end
@twig.read_cli_options!(['--branch'])
end
end
describe '#abort_for_option_exception' do
before :each do
@twig = Twig.new
end
it 'prints a message and aborts' do
expect(@twig).to receive(:puts) do |message|
expect(message).to include('`twig --help`')
end
expect {
exception = Exception.new('test exception')
@twig.abort_for_option_exception(exception)
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(1)
}
end
end
describe '#exec_subcommand_if_any' do
before :each do
@twig = Twig.new
@branch_name = 'test'
allow(Twig).to receive(:run)
allow(@twig).to receive(:current_branch_name) { @branch_name }
end
it 'recognizes a subcommand' do
command_path = '/path/to/bin/twig-subcommand'
expect(Twig).to receive(:run).with('which twig-subcommand 2>/dev/null').
and_return(command_path)
expect(@twig).to receive(:exec).with(command_path) { exit }
# Since we're stubbing `exec` (with an expectation), we still need it
# to exit early like the real implementation. The following handles the
# exit somewhat gracefully.
expect {
@twig.read_cli_args!(['subcommand'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(0)
}
end
it 'does not recognize a subcommand' do
expect(Twig).to receive(:run).
with('which twig-subcommand 2>/dev/null').and_return('')
expect(@twig).not_to receive(:exec)
allow(@twig).to receive(:abort)
@twig.read_cli_args!(['subcommand'])
end
end
describe '#read_cli_args!' do
before :each do
@twig = Twig.new
end
it 'checks for and executes a subcommand if there are any args' do
expect(@twig).to receive(:exec_subcommand_if_any).with(['foo']) { exit }
expect {
@twig.read_cli_args!(['foo'])
}.to raise_exception { |exception|
expect(exception).to be_a(SystemExit)
expect(exception.status).to eq(0)
}
end
it 'does not check for a subcommand if there are no args' do
branch_list = %[foo bar]
expect(@twig).not_to receive(:exec_subcommand_if_any)
allow(@twig).to receive(:list_branches).and_return(branch_list)
allow(@twig).to receive(:puts).with(branch_list)
@twig.read_cli_args!([])
end
it 'lists branches' do
branch_list = %[foo bar]
expect(@twig).to receive(:list_branches).and_return(branch_list)
expect(@twig).to receive(:puts).with(branch_list)
@twig.read_cli_args!([])
end
it 'prints branch properties as JSON' do
branches_json = {
'branch1' => { 'last-commit-time' => '2000-01-01' },
'branch2' => { 'last-commit-time' => '2000-01-01' }
}.to_json
expect(@twig).to receive(:branches_json).and_return(branches_json)
expect(@twig).to receive(:puts).with(branches_json)
@twig.read_cli_args!(%w[--format json])
end
context 'getting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
end
it 'gets a property for the current branch' do
expect(@twig).to receive(:current_branch_name).and_return(@branch_name)
expect(@twig).to receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
it 'gets a property for a specified branch' do
expect(Twig::Branch).to receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
expect(@twig).to receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
end
context 'setting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
@message = 'Saved.'
end
it 'sets a property for the current branch' do
expect(@twig).to receive(:current_branch_name).and_return(@branch_name)
expect(@twig).to receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value)
@twig.read_cli_args!([@property_name, @property_value])
end
it 'sets a property for a specified branch' do
expect(Twig::Branch).to receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
expect(@twig).to receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value).
and_return(@message)
@twig.read_cli_args!([@property_name, @property_value])
end
end
context 'unsetting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@message = 'Removed.'
@twig.set_option(:unset_property, @property_name)
end
it 'unsets a property for the current branch' do
expect(@twig).to receive(:current_branch_name).and_return(@branch_name)
expect(@twig).to receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
it 'unsets a property for a specified branch' do
expect(Twig::Branch).to receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
expect(@twig).to receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
end
end
describe '#get_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'gets a property' do
property_value = 'bar'
expect(@twig).to receive(:get_branch_property).
with(@branch_name, @property_name).and_return(property_value)
expect(@twig).to receive(:puts).with(property_value)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'shows an error when getting a property that is not set' do
error_message = 'test error'
expect(@twig).to receive(:get_branch_property).
with(@branch_name, @property_name).and_return(nil)
allow_any_instance_of(Twig::Branch::MissingPropertyError).
to receive(:message) { error_message }
expect(@twig).to receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when getting an invalid branch property name' do
bad_property_name = ''
error_message = 'test error'
expect(@twig).to receive(:get_branch_property).
with(@branch_name, bad_property_name) do
raise ArgumentError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, bad_property_name)
end
end
describe '#set_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'sets a property for the specified branch' do
success_message = 'test success'
property_value = 'bar'
expect(@twig).to receive(:set_branch_property).
with(@branch_name, @property_name, property_value).
and_return(success_message)
expect(@twig).to receive(:puts).with(success_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
property_value = ''
expect(@twig).to receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise ArgumentError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles RuntimeError when Git is unable to set a branch property' do
error_message = 'test error'
property_value = ''
expect(@twig).to receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise RuntimeError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
end
describe '#unset_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'unsets a property for the specified branch' do
success_message = 'test success'
expect(@twig).to receive(:unset_branch_property).
with(@branch_name, @property_name).and_return(success_message)
expect(@twig).to receive(:puts).with(success_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
expect(@twig).to receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise ArgumentError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles MissingPropertyError when unsetting a branch property that is not set' do
error_message = 'test error'
expect(@twig).to receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise Twig::Branch::MissingPropertyError, error_message
end
expect(@twig).to receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
end
end
|
require 'spec_helper'
describe Twig::Cli do
describe '#help_description' do
before :each do
@twig = Twig.new
end
it 'returns short text in a single line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80)
result.should == [text]
end
it 'returns long text in a string with line breaks' do
text = 'The quick brown fox jumps over the lazy, lazy dog.'
result = @twig.help_description(text, :width => 20)
result.should == [
'The quick brown fox',
'jumps over the lazy,',
'lazy dog.'
]
end
it 'breaks a long word by max line length' do
text = 'Thequickbrownfoxjumpsoverthelazydog.'
result = @twig.help_description(text, :width => 20)
result.should == [
'Thequickbrownfoxjump',
'soverthelazydog.'
]
end
it 'adds a separator line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80, :add_separator => true)
result.should == [text, ' ']
end
end
describe '#help_paragraph' do
before :each do
@twig = Twig.new
end
it 'returns long text in a paragraph with line breaks' do
text = Array.new(5) {
'The quick brown fox jumps over the lazy dog.'
}.join(' ')
result = @twig.help_paragraph(text)
result.should == [
"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the",
"lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps",
"over the lazy dog. The quick brown fox jumps over the lazy dog."
].join("\n")
end
end
describe '#read_cli_options!' do
before :each do
@twig = Twig.new
end
it 'recognizes `--unset` and sets an `:unset_property` option' do
@twig.options[:unset_property].should be_nil # Precondition
@twig.read_cli_options!(%w[--unset test])
@twig.options[:unset_property].should == 'test'
end
it 'recognizes `--version` and prints the current version' do
@twig.should_receive(:puts).with(Twig::VERSION)
@twig.should_receive(:exit)
@twig.read_cli_options!(['--version'])
end
it 'recognizes `-b` and sets a `:branch` option' do
@twig.should_receive(:all_branch_names).and_return(['test'])
@twig.options[:branch].should be_nil # Precondition
@twig.read_cli_options!(%w[-b test])
@twig.options[:branch].should == 'test'
end
it 'recognizes `--branch` and sets a `:branch` option' do
@twig.should_receive(:all_branch_names).and_return(['test'])
@twig.options[:branch].should be_nil # Precondition
@twig.read_cli_options!(%w[--branch test])
@twig.options[:branch].should == 'test'
end
it 'recognizes `--max-days-old` and sets a `:max_days_old` option' do
@twig.options[:max_days_old].should be_nil # Precondition
@twig.read_cli_options!(%w[--max-days-old 30])
@twig.options[:max_days_old].should == 30
end
it 'recognizes `--except-branch` and sets a `:property_except` option' do
@twig.options[:property_except].should be_nil # Precondition
@twig.read_cli_options!(%w[--except-branch test])
@twig.options[:property_except].should == { :branch => /test/ }
end
it 'recognizes `--only-branch` and sets a `:property_only` option' do
@twig.options[:property_only].should be_nil # Precondition
@twig.read_cli_options!(%w[--only-branch test])
@twig.options[:property_only].should == { :branch => /test/ }
end
context 'with custom property "only" filtering' do
before :each do
@twig.options[:property_only].should be_nil # Precondition
end
it 'recognizes `--only-<property>` and sets a `:property_only` option' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--only-foo test])
@twig.options[:property_only].should == { :foo => /test/ }
end
it 'recognizes `--only-branch` and `--only-<property>` together' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--only-branch test --only-foo bar])
@twig.options[:property_only].should == {
:branch => /test/,
:foo => /bar/
}
end
it 'does not recognize `--only-<property>` for a missing property' do
property_name = 'foo'
Twig::Branch.all_properties.should_not include(property_name) # Precondition
@twig.stub(:puts)
begin
@twig.read_cli_options!(["--only-#{property_name}", 'test'])
rescue SystemExit => exception
expected_exception = exception
end
expected_exception.should_not be_nil
expected_exception.status.should == 0
@twig.options[:property_only].should be_nil
end
end
context 'with custom property "except" filtering' do
before :each do
@twig.options[:property_except].should be_nil # Precondition
end
it 'recognizes `--except-<property>` and sets a `:property_except` option' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--except-foo test])
@twig.options[:property_except].should == { :foo => /test/ }
end
it 'recognizes `--except-branch` and `--except-<property>` together' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--except-branch test --except-foo bar])
@twig.options[:property_except].should == {
:branch => /test/,
:foo => /bar/
}
end
it 'does not recognize `--except-<property>` for a missing property' do
property_name = 'foo'
Twig::Branch.all_properties.should_not include(property_name) # Precondition
@twig.stub(:puts)
begin
@twig.read_cli_options!(["--except-#{property_name}", 'test'])
rescue SystemExit => exception
expected_exception = exception
end
expected_exception.should_not be_nil
expected_exception.status.should == 0
@twig.options[:property_except].should be_nil
end
end
it 'recognizes `--all` and unsets other options except `:branch`' do
@twig.set_option(:max_days_old, 30)
@twig.set_option(:property_except, :branch => /test/)
@twig.set_option(:property_only, :branch => /test/)
@twig.read_cli_options!(['--all'])
@twig.options[:max_days_old].should be_nil
@twig.options[:property_except].should be_nil
@twig.options[:property_only].should be_nil
end
it 'recognizes `--header-style`' do
@twig.options[:header_color].should == Twig::DEFAULT_HEADER_COLOR
@twig.options[:header_weight].should be_nil
@twig.read_cli_options!(['--header-style', 'green bold'])
@twig.options[:header_color].should == :green
@twig.options[:header_weight].should == :bold
end
it 'handles invalid options' do
@twig.should_receive(:abort_for_option_exception) do |exception|
exception.should be_a(OptionParser::InvalidOption)
exception.message.should include('invalid option: --foo')
end
@twig.read_cli_options!(['--foo'])
end
it 'handles missing arguments' do
@twig.should_receive(:abort_for_option_exception) do |exception|
exception.should be_a(OptionParser::MissingArgument)
exception.message.should include('missing argument: --branch')
end
@twig.read_cli_options!(['--branch'])
end
end
describe '#abort_for_option_exception' do
before :each do
@twig = Twig.new
end
it 'prints a message and exits' do
exception = Exception.new('test exception')
@twig.should_receive(:puts).with(exception.message)
@twig.should_receive(:puts) do |message|
message.should include('`twig --help`')
end
@twig.should_receive(:exit)
@twig.abort_for_option_exception(exception)
end
end
describe '#read_cli_args!' do
before :each do
@twig = Twig.new
end
it 'lists branches' do
branch_list = %[foo bar]
@twig.should_receive(:list_branches).and_return(branch_list)
@twig.should_receive(:puts).with(branch_list)
@twig.read_cli_args!([])
end
context 'running a subcommand' do
before :each do
Twig.stub(:run)
@branch_name = 'test'
@twig.stub(:current_branch_name => @branch_name)
end
it 'recognizes a subcommand' do
command_path = '/path/to/bin/twig-subcommand'
Twig.should_receive(:run).with('which twig-subcommand 2>/dev/null').
and_return(command_path)
@twig.should_receive(:exec).with(command_path) { exit }
# Since we're stubbing `exec` (with an expectation), we still need it
# to exit early like the real implementation. The following handles the
# exit somewhat gracefully.
begin
@twig.read_cli_args!(['subcommand'])
rescue SystemExit => exception
expected_exception = exception
end
expected_exception.should_not be_nil
expected_exception.status.should == 0
end
it 'does not recognize a subcommand' do
Twig.should_receive(:run).with('which twig-subcommand 2>/dev/null').and_return('')
@twig.should_not_receive(:exec)
@twig.stub(:abort)
@twig.read_cli_args!(['subcommand'])
end
end
context 'getting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
end
it 'gets a property for the current branch' do
@twig.should_receive(:current_branch_name).and_return(@branch_name)
@twig.should_receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
it 'gets a property for a specified branch' do
@twig.should_receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
@twig.should_receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
end
context 'setting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
@message = 'Saved.'
end
it 'sets a property for the current branch' do
@twig.should_receive(:current_branch_name).and_return(@branch_name)
@twig.should_receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value)
@twig.read_cli_args!([@property_name, @property_value])
end
it 'sets a property for a specified branch' do
@twig.should_receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
@twig.should_receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value).
and_return(@message)
@twig.read_cli_args!([@property_name, @property_value])
end
end
context 'unsetting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@message = 'Removed.'
@twig.set_option(:unset_property, @property_name)
end
it 'unsets a property for the current branch' do
@twig.should_receive(:current_branch_name).and_return(@branch_name)
@twig.should_receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
it 'unsets a property for a specified branch' do
@twig.should_receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
@twig.should_receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
end
end
describe '#get_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'gets a property' do
property_value = 'bar'
@twig.should_receive(:get_branch_property).
with(@branch_name, @property_name).and_return(property_value)
@twig.should_receive(:puts).with(property_value)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'shows an error when getting a property that is not set' do
error_message = 'test error'
@twig.should_receive(:get_branch_property).
with(@branch_name, @property_name).and_return(nil)
Twig::Branch::MissingPropertyError.any_instance.
stub(:message) { error_message }
@twig.should_receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when getting an invalid branch property name' do
bad_property_name = ''
error_message = 'test error'
@twig.should_receive(:get_branch_property).
with(@branch_name, bad_property_name) do
raise ArgumentError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, bad_property_name)
end
end
describe '#set_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'sets a property for the specified branch' do
success_message = 'test success'
property_value = 'bar'
@twig.should_receive(:set_branch_property).
with(@branch_name, @property_name, property_value).
and_return(success_message)
@twig.should_receive(:puts).with(success_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
property_value = ''
@twig.should_receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise ArgumentError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles RuntimeError when Git is unable to set a branch property' do
error_message = 'test error'
property_value = ''
@twig.should_receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise RuntimeError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
end
describe '#unset_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'unsets a property for the specified branch' do
success_message = 'test success'
@twig.should_receive(:unset_branch_property).
with(@branch_name, @property_name).and_return(success_message)
@twig.should_receive(:puts).with(success_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
@twig.should_receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise ArgumentError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles MissingPropertyError when unsetting a branch property that is not set' do
error_message = 'test error'
@twig.should_receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise Twig::Branch::MissingPropertyError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
end
end
Add specs for `--help`
require 'spec_helper'
describe Twig::Cli do
describe '#help_description' do
before :each do
@twig = Twig.new
end
it 'returns short text in a single line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80)
result.should == [text]
end
it 'returns long text in a string with line breaks' do
text = 'The quick brown fox jumps over the lazy, lazy dog.'
result = @twig.help_description(text, :width => 20)
result.should == [
'The quick brown fox',
'jumps over the lazy,',
'lazy dog.'
]
end
it 'breaks a long word by max line length' do
text = 'Thequickbrownfoxjumpsoverthelazydog.'
result = @twig.help_description(text, :width => 20)
result.should == [
'Thequickbrownfoxjump',
'soverthelazydog.'
]
end
it 'adds a separator line' do
text = 'The quick brown fox.'
result = @twig.help_description(text, :width => 80, :add_separator => true)
result.should == [text, ' ']
end
end
describe '#help_paragraph' do
before :each do
@twig = Twig.new
end
it 'returns long text in a paragraph with line breaks' do
text = Array.new(5) {
'The quick brown fox jumps over the lazy dog.'
}.join(' ')
result = @twig.help_paragraph(text)
result.should == [
"The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the",
"lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps",
"over the lazy dog. The quick brown fox jumps over the lazy dog."
].join("\n")
end
end
describe '#read_cli_options!' do
before :each do
@twig = Twig.new
end
it 'recognizes `--unset` and sets an `:unset_property` option' do
@twig.options[:unset_property].should be_nil # Precondition
@twig.read_cli_options!(%w[--unset test])
@twig.options[:unset_property].should == 'test'
end
it 'recognizes `--help` and prints the help content' do
help_lines = []
@twig.stub(:puts) { |message| help_lines << message.strip }
@twig.should_receive(:exit)
@twig.read_cli_options!(['--help'])
help_lines.should include("Twig v#{Twig::VERSION}")
help_lines.should include('http://rondevera.github.com/twig')
end
it 'recognizes `--version` and prints the current version' do
@twig.should_receive(:puts).with(Twig::VERSION)
@twig.should_receive(:exit)
@twig.read_cli_options!(['--version'])
end
it 'recognizes `-b` and sets a `:branch` option' do
@twig.should_receive(:all_branch_names).and_return(['test'])
@twig.options[:branch].should be_nil # Precondition
@twig.read_cli_options!(%w[-b test])
@twig.options[:branch].should == 'test'
end
it 'recognizes `--branch` and sets a `:branch` option' do
@twig.should_receive(:all_branch_names).and_return(['test'])
@twig.options[:branch].should be_nil # Precondition
@twig.read_cli_options!(%w[--branch test])
@twig.options[:branch].should == 'test'
end
it 'recognizes `--max-days-old` and sets a `:max_days_old` option' do
@twig.options[:max_days_old].should be_nil # Precondition
@twig.read_cli_options!(%w[--max-days-old 30])
@twig.options[:max_days_old].should == 30
end
it 'recognizes `--except-branch` and sets a `:property_except` option' do
@twig.options[:property_except].should be_nil # Precondition
@twig.read_cli_options!(%w[--except-branch test])
@twig.options[:property_except].should == { :branch => /test/ }
end
it 'recognizes `--only-branch` and sets a `:property_only` option' do
@twig.options[:property_only].should be_nil # Precondition
@twig.read_cli_options!(%w[--only-branch test])
@twig.options[:property_only].should == { :branch => /test/ }
end
context 'with custom property "only" filtering' do
before :each do
@twig.options[:property_only].should be_nil # Precondition
end
it 'recognizes `--only-<property>` and sets a `:property_only` option' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--only-foo test])
@twig.options[:property_only].should == { :foo => /test/ }
end
it 'recognizes `--only-branch` and `--only-<property>` together' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--only-branch test --only-foo bar])
@twig.options[:property_only].should == {
:branch => /test/,
:foo => /bar/
}
end
it 'does not recognize `--only-<property>` for a missing property' do
property_name = 'foo'
Twig::Branch.all_properties.should_not include(property_name) # Precondition
@twig.stub(:puts)
begin
@twig.read_cli_options!(["--only-#{property_name}", 'test'])
rescue SystemExit => exception
expected_exception = exception
end
expected_exception.should_not be_nil
expected_exception.status.should == 0
@twig.options[:property_only].should be_nil
end
end
context 'with custom property "except" filtering' do
before :each do
@twig.options[:property_except].should be_nil # Precondition
end
it 'recognizes `--except-<property>` and sets a `:property_except` option' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--except-foo test])
@twig.options[:property_except].should == { :foo => /test/ }
end
it 'recognizes `--except-branch` and `--except-<property>` together' do
Twig::Branch.stub(:all_properties) { %w[foo] }
@twig.read_cli_options!(%w[--except-branch test --except-foo bar])
@twig.options[:property_except].should == {
:branch => /test/,
:foo => /bar/
}
end
it 'does not recognize `--except-<property>` for a missing property' do
property_name = 'foo'
Twig::Branch.all_properties.should_not include(property_name) # Precondition
@twig.stub(:puts)
begin
@twig.read_cli_options!(["--except-#{property_name}", 'test'])
rescue SystemExit => exception
expected_exception = exception
end
expected_exception.should_not be_nil
expected_exception.status.should == 0
@twig.options[:property_except].should be_nil
end
end
it 'recognizes `--all` and unsets other options except `:branch`' do
@twig.set_option(:max_days_old, 30)
@twig.set_option(:property_except, :branch => /test/)
@twig.set_option(:property_only, :branch => /test/)
@twig.read_cli_options!(['--all'])
@twig.options[:max_days_old].should be_nil
@twig.options[:property_except].should be_nil
@twig.options[:property_only].should be_nil
end
it 'recognizes `--header-style`' do
@twig.options[:header_color].should == Twig::DEFAULT_HEADER_COLOR
@twig.options[:header_weight].should be_nil
@twig.read_cli_options!(['--header-style', 'green bold'])
@twig.options[:header_color].should == :green
@twig.options[:header_weight].should == :bold
end
it 'handles invalid options' do
@twig.should_receive(:abort_for_option_exception) do |exception|
exception.should be_a(OptionParser::InvalidOption)
exception.message.should include('invalid option: --foo')
end
@twig.read_cli_options!(['--foo'])
end
it 'handles missing arguments' do
@twig.should_receive(:abort_for_option_exception) do |exception|
exception.should be_a(OptionParser::MissingArgument)
exception.message.should include('missing argument: --branch')
end
@twig.read_cli_options!(['--branch'])
end
end
describe '#abort_for_option_exception' do
before :each do
@twig = Twig.new
end
it 'prints a message and exits' do
exception = Exception.new('test exception')
@twig.should_receive(:puts).with(exception.message)
@twig.should_receive(:puts) do |message|
message.should include('`twig --help`')
end
@twig.should_receive(:exit)
@twig.abort_for_option_exception(exception)
end
end
describe '#read_cli_args!' do
before :each do
@twig = Twig.new
end
it 'lists branches' do
branch_list = %[foo bar]
@twig.should_receive(:list_branches).and_return(branch_list)
@twig.should_receive(:puts).with(branch_list)
@twig.read_cli_args!([])
end
context 'running a subcommand' do
before :each do
Twig.stub(:run)
@branch_name = 'test'
@twig.stub(:current_branch_name => @branch_name)
end
it 'recognizes a subcommand' do
command_path = '/path/to/bin/twig-subcommand'
Twig.should_receive(:run).with('which twig-subcommand 2>/dev/null').
and_return(command_path)
@twig.should_receive(:exec).with(command_path) { exit }
# Since we're stubbing `exec` (with an expectation), we still need it
# to exit early like the real implementation. The following handles the
# exit somewhat gracefully.
begin
@twig.read_cli_args!(['subcommand'])
rescue SystemExit => exception
expected_exception = exception
end
expected_exception.should_not be_nil
expected_exception.status.should == 0
end
it 'does not recognize a subcommand' do
Twig.should_receive(:run).with('which twig-subcommand 2>/dev/null').and_return('')
@twig.should_not_receive(:exec)
@twig.stub(:abort)
@twig.read_cli_args!(['subcommand'])
end
end
context 'getting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
end
it 'gets a property for the current branch' do
@twig.should_receive(:current_branch_name).and_return(@branch_name)
@twig.should_receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
it 'gets a property for a specified branch' do
@twig.should_receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
@twig.should_receive(:get_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([@property_name])
end
end
context 'setting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@property_value = 'bar'
@message = 'Saved.'
end
it 'sets a property for the current branch' do
@twig.should_receive(:current_branch_name).and_return(@branch_name)
@twig.should_receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value)
@twig.read_cli_args!([@property_name, @property_value])
end
it 'sets a property for a specified branch' do
@twig.should_receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
@twig.should_receive(:set_branch_property_for_cli).
with(@branch_name, @property_name, @property_value).
and_return(@message)
@twig.read_cli_args!([@property_name, @property_value])
end
end
context 'unsetting properties' do
before :each do
@branch_name = 'test'
@property_name = 'foo'
@message = 'Removed.'
@twig.set_option(:unset_property, @property_name)
end
it 'unsets a property for the current branch' do
@twig.should_receive(:current_branch_name).and_return(@branch_name)
@twig.should_receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
it 'unsets a property for a specified branch' do
@twig.should_receive(:all_branch_names).and_return([@branch_name])
@twig.set_option(:branch, @branch_name)
@twig.should_receive(:unset_branch_property_for_cli).
with(@branch_name, @property_name)
@twig.read_cli_args!([])
end
end
end
describe '#get_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'gets a property' do
property_value = 'bar'
@twig.should_receive(:get_branch_property).
with(@branch_name, @property_name).and_return(property_value)
@twig.should_receive(:puts).with(property_value)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'shows an error when getting a property that is not set' do
error_message = 'test error'
@twig.should_receive(:get_branch_property).
with(@branch_name, @property_name).and_return(nil)
Twig::Branch::MissingPropertyError.any_instance.
stub(:message) { error_message }
@twig.should_receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when getting an invalid branch property name' do
bad_property_name = ''
error_message = 'test error'
@twig.should_receive(:get_branch_property).
with(@branch_name, bad_property_name) do
raise ArgumentError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.get_branch_property_for_cli(@branch_name, bad_property_name)
end
end
describe '#set_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'sets a property for the specified branch' do
success_message = 'test success'
property_value = 'bar'
@twig.should_receive(:set_branch_property).
with(@branch_name, @property_name, property_value).
and_return(success_message)
@twig.should_receive(:puts).with(success_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
property_value = ''
@twig.should_receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise ArgumentError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
it 'handles RuntimeError when Git is unable to set a branch property' do
error_message = 'test error'
property_value = ''
@twig.should_receive(:set_branch_property).
with(@branch_name, @property_name, property_value) do
raise RuntimeError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.set_branch_property_for_cli(@branch_name, @property_name, property_value)
end
end
describe '#unset_branch_property_for_cli' do
before :each do
@twig = Twig.new
@branch_name = 'test'
@property_name = 'foo'
end
it 'unsets a property for the specified branch' do
success_message = 'test success'
@twig.should_receive(:unset_branch_property).
with(@branch_name, @property_name).and_return(success_message)
@twig.should_receive(:puts).with(success_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles ArgumentError when unsetting an invalid branch property name' do
error_message = 'test error'
@twig.should_receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise ArgumentError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
it 'handles MissingPropertyError when unsetting a branch property that is not set' do
error_message = 'test error'
@twig.should_receive(:unset_branch_property).
with(@branch_name, @property_name) do
raise Twig::Branch::MissingPropertyError, error_message
end
@twig.should_receive(:abort).with(error_message)
@twig.unset_branch_property_for_cli(@branch_name, @property_name)
end
end
end
|
module XeroGateway
class Gateway
include Http
include Dates
attr_accessor :client, :xero_url, :logger
extend Forwardable
def_delegators :client, :request_token, :access_token, :authorize_from_request, :authorize_from_access
#
# The consumer key and secret here correspond to those provided
# to you by Xero inside the API Previewer.
def initialize(consumer_key, consumer_secret, options = {})
@xero_url = options[:xero_url] || "https://api.xero.com/api.xro/2.0"
@client = OAuth.new(consumer_key, consumer_secret, options)
end
#
# Retrieve all contacts from Xero
#
# Usage : get_contacts(:order => :name)
# get_contacts(:updated_after => Time)
#
# Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
def get_contacts(options = {})
request_params = {}
request_params[:ContactID] = options[:contact_id] if options[:contact_id]
request_params[:ContactNumber] = options[:contact_number] if options[:contact_number]
request_params[:OrderBy] = options[:order] if options[:order]
request_params[:ModifiedAfter] = Gateway.format_date_time(options[:updated_after]) if options[:updated_after]
request_params[:where] = options[:where] if options[:where]
response_xml = http_get(@client, "#{@xero_url}/Contacts", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contacts'})
end
# Retrieve a contact from Xero
# Usage get_contact_by_id(contact_id)
def get_contact_by_id(contact_id)
get_contact(contact_id)
end
# Retrieve a contact from Xero
# Usage get_contact_by_id(contact_id)
def get_contact_by_number(contact_number)
get_contact(nil, contact_number)
end
# Factory method for building new Contact objects associated with this gateway.
def build_contact(contact = {})
case contact
when Contact then contact.gateway = self
when Hash then contact = Contact.new(contact.merge({:gateway => self}))
end
contact
end
#
# Creates a contact in Xero
#
# Usage :
#
# contact = XeroGateway::Contact.new(:name => "THE NAME OF THE CONTACT #{Time.now.to_i}")
# contact.email = "whoever@something.com"
# contact.phone.number = "12345"
# contact.address.line_1 = "LINE 1 OF THE ADDRESS"
# contact.address.line_2 = "LINE 2 OF THE ADDRESS"
# contact.address.line_3 = "LINE 3 OF THE ADDRESS"
# contact.address.line_4 = "LINE 4 OF THE ADDRESS"
# contact.address.city = "WELLINGTON"
# contact.address.region = "WELLINGTON"
# contact.address.country = "NEW ZEALAND"
# contact.address.post_code = "6021"
#
# create_contact(contact)
def create_contact(contact)
save_contact(contact)
end
#
# Updates an existing Xero contact
#
# Usage :
#
# contact = xero_gateway.get_contact(some_contact_id)
# contact.email = "a_new_email_ddress"
#
# xero_gateway.update_contact(contact)
def update_contact(contact)
raise "contact_id or contact_number is required for updating contacts" if contact.contact_id.nil? and contact.contact_number.nil?
save_contact(contact)
end
#
# Updates an array of contacts in a single API operation.
#
# Usage :
# contacts = [XeroGateway::Contact.new(:name => 'Joe Bloggs'), XeroGateway::Contact.new(:name => 'Jane Doe')]
# result = gateway.update_contacts(contacts)
#
# Will update contacts with matching contact_id, contact_number or name or create if they don't exist.
#
def update_contacts(contacts)
b = Builder::XmlMarkup.new
request_xml = b.Contacts {
contacts.each do | contact |
contact.to_xml(b)
end
}
response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {})
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'POST/contacts'})
response.contacts.each_with_index do | response_contact, index |
contacts[index].contact_id = response_contact.contact_id if response_contact && response_contact.contact_id
end
response
end
# Retrieves all invoices from Xero
#
# Usage : get_invoices
# get_invoices(:invoice_id => " 297c2dc5-cc47-4afd-8ec8-74990b8761e9")
#
# Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
def get_invoices(options = {})
request_params = {}
request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id]
request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number]
request_params[:OrderBy] = options[:order] if options[:order]
request_params[:ModifiedAfter] = options[:modified_since]
request_params[:where] = options[:where] if options[:where]
response_xml = http_get(@client, "#{@xero_url}/Invoices", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoices'})
end
# Retrieves a single invoice
#
# Usage : get_invoice("297c2dc5-cc47-4afd-8ec8-74990b8761e9") # By ID
# get_invoice("OIT-12345") # By number
def get_invoice(invoice_id_or_number)
request_params = {}
url = "#{@xero_url}/Invoices/#{URI.escape(invoice_id_or_number)}"
response_xml = http_get(@client, url, request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoice'})
end
# Factory method for building new Invoice objects associated with this gateway.
def build_invoice(invoice = {})
case invoice
when Invoice then invoice.gateway = self
when Hash then invoice = Invoice.new(invoice.merge(:gateway => self))
end
invoice
end
# Creates an invoice in Xero based on an invoice object.
#
# Invoice and line item totals are calculated automatically.
#
# Usage :
#
# invoice = XeroGateway::Invoice.new({
# :invoice_type => "ACCREC",
# :due_date => 1.month.from_now,
# :invoice_number => "YOUR INVOICE NUMBER",
# :reference => "YOUR REFERENCE (NOT NECESSARILY UNIQUE!)",
# :line_amount_types => "Inclusive"
# })
# invoice.contact = XeroGateway::Contact.new(:name => "THE NAME OF THE CONTACT")
# invoice.contact.phone.number = "12345"
# invoice.contact.address.line_1 = "LINE 1 OF THE ADDRESS"
# invoice.line_items << XeroGateway::LineItem.new(
# :description => "THE DESCRIPTION OF THE LINE ITEM",
# :unit_amount => 100,
# :tax_amount => 12.5,
# :tracking_category => "THE TRACKING CATEGORY FOR THE LINE ITEM",
# :tracking_option => "THE TRACKING OPTION FOR THE LINE ITEM"
# )
#
# create_invoice(invoice)
def create_invoice(invoice)
request_xml = invoice.to_xml
response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml)
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoice'})
# Xero returns invoices inside an <Invoices> tag, even though there's only ever
# one for this request
response.response_item = response.invoices.first
if response.success? && response.invoice && response.invoice.invoice_id
invoice.invoice_id = response.invoice.invoice_id
end
response
end
#
# Creates an array of invoices with a single API request.
#
# Usage :
# invoices = [XeroGateway::Invoice.new(...), XeroGateway::Invoice.new(...)]
# result = gateway.create_invoices(invoices)
#
def create_invoices(invoices)
b = Builder::XmlMarkup.new
request_xml = b.Invoices {
invoices.each do | invoice |
invoice.to_xml(b)
end
}
response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml, {})
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'})
response.invoices.each_with_index do | response_invoice, index |
invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id
end
response
end
#
# Gets all accounts for a specific organization in Xero.
#
def get_accounts
response_xml = http_get(@client, "#{xero_url}/Accounts")
parse_response(response_xml, {}, {:request_signature => 'GET/accounts'})
end
#
# Returns a XeroGateway::AccountsList object that makes working with
# the Xero list of accounts easier and allows caching the results.
#
def get_accounts_list(load_on_init = true)
AccountsList.new(self, load_on_init)
end
#
# Gets all tracking categories for a specific organization in Xero.
#
def get_tracking_categories
response_xml = http_get(@client, "#{xero_url}/TrackingCategories")
parse_response(response_xml, {}, {:request_signature => 'GET/TrackingCategories'})
end
#
# Gets Organisation details
#
def get_organisation
response_xml = http_get(@client, "#{xero_url}/Organisation")
parse_response(response_xml, {}, {:request_signature => 'GET/organisation'})
end
#
# Gets all currencies for a specific organisation in Xero
#
def get_currencies
response_xml = http_get(@client, "#{xero_url}/Currencies")
parse_response(response_xml, {}, {:request_signature => 'GET/currencies'})
end
#
# Gets all Tax Rates for a specific organisation in Xero
#
def get_tax_rates
response_xml = http_get(@client, "#{xero_url}/TaxRates")
parse_response(response_xml, {}, {:request_signature => 'GET/tax_rates'})
end
private
def get_contact(contact_id = nil, contact_number = nil)
request_params = contact_id ? { :contactID => contact_id } : { :contactNumber => contact_number }
response_xml = http_get(@client, "#{@xero_url}/Contacts/#{URI.escape(contact_id||contact_number)}", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contact'})
end
# Create or update a contact record based on if it has a contact_id or contact_number.
def save_contact(contact)
request_xml = contact.to_xml
response_xml = nil
create_or_save = nil
if contact.contact_id.nil? && contact.contact_number.nil?
# Create new contact record.
response_xml = http_put(@client, "#{@xero_url}/Contacts", request_xml, {})
create_or_save = :create
else
# Update existing contact record.
response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {})
create_or_save = :save
end
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/contact"})
contact.contact_id = response.contact.contact_id if response.contact && response.contact.contact_id
response
end
def parse_response(raw_response, request = {}, options = {})
response = XeroGateway::Response.new
doc = REXML::Document.new(raw_response, :ignore_whitespace_nodes => :all)
# check for responses we don't understand
raise UnparseableResponse.new(doc.root.name) unless doc.root.name == "Response"
response_element = REXML::XPath.first(doc, "/Response")
response_element.children.reject { |e| e.is_a? REXML::Text }.each do |element|
case(element.name)
when "ID" then response.response_id = element.text
when "Status" then response.status = element.text
when "ProviderName" then response.provider = element.text
when "DateTimeUTC" then response.date_time = element.text
when "Contact" then response.response_item = Contact.from_xml(element, self)
when "Invoice" then response.response_item = Invoice.from_xml(element, self, {:line_items_downloaded => options[:request_signature] != "GET/Invoices"})
when "Contacts" then element.children.each {|child| response.response_item << Contact.from_xml(child, self) }
when "Invoices" then element.children.each {|child| response.response_item << Invoice.from_xml(child, self, {:line_items_downloaded => options[:request_signature] != "GET/Invoices"}) }
when "Accounts" then element.children.each {|child| response.response_item << Account.from_xml(child) }
when "TaxRates" then element.children.each {|child| response.response_item << TaxRate.from_xml(child) }
when "Currencies" then element.children.each {|child| response.response_item << Currency.from_xml(child) }
when "Organisations" then response.response_item = Organisation.from_xml(element.children.first) # Xero only returns the Authorized Organisation
when "TrackingCategories" then element.children.each {|child| response.response_item << TrackingCategory.from_xml(child) }
when "Errors" then element.children.each { |error| parse_error(error, response) }
end
end if response_element
# If a single result is returned don't put it in an array
if response.response_item.is_a?(Array) && response.response_item.size == 1
response.response_item = response.response_item.first
end
response.request_params = request[:request_params]
response.request_xml = request[:request_xml]
response.response_xml = raw_response
response
end
def parse_error(error_element, response)
response.errors << Error.new(
:description => REXML::XPath.first(error_element, "Description").text,
:date_time => REXML::XPath.first(error_element, "//DateTime").text,
:type => REXML::XPath.first(error_element, "//ExceptionType").text,
:message => REXML::XPath.first(error_element, "//Message").text
)
end
end
end
Only set ModifiedAfter param if present
Fixes bug whereby if gateway.get_invoices is called without a
:modified_since argument, the following URL is called from Xero:
https://api.xero.com/api.xro/2.0/Invoices?ModifiedSince=
module XeroGateway
class Gateway
include Http
include Dates
attr_accessor :client, :xero_url, :logger
extend Forwardable
def_delegators :client, :request_token, :access_token, :authorize_from_request, :authorize_from_access
#
# The consumer key and secret here correspond to those provided
# to you by Xero inside the API Previewer.
def initialize(consumer_key, consumer_secret, options = {})
@xero_url = options[:xero_url] || "https://api.xero.com/api.xro/2.0"
@client = OAuth.new(consumer_key, consumer_secret, options)
end
#
# Retrieve all contacts from Xero
#
# Usage : get_contacts(:order => :name)
# get_contacts(:updated_after => Time)
#
# Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
def get_contacts(options = {})
request_params = {}
request_params[:ContactID] = options[:contact_id] if options[:contact_id]
request_params[:ContactNumber] = options[:contact_number] if options[:contact_number]
request_params[:OrderBy] = options[:order] if options[:order]
request_params[:ModifiedAfter] = Gateway.format_date_time(options[:updated_after]) if options[:updated_after]
request_params[:where] = options[:where] if options[:where]
response_xml = http_get(@client, "#{@xero_url}/Contacts", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contacts'})
end
# Retrieve a contact from Xero
# Usage get_contact_by_id(contact_id)
def get_contact_by_id(contact_id)
get_contact(contact_id)
end
# Retrieve a contact from Xero
# Usage get_contact_by_id(contact_id)
def get_contact_by_number(contact_number)
get_contact(nil, contact_number)
end
# Factory method for building new Contact objects associated with this gateway.
def build_contact(contact = {})
case contact
when Contact then contact.gateway = self
when Hash then contact = Contact.new(contact.merge({:gateway => self}))
end
contact
end
#
# Creates a contact in Xero
#
# Usage :
#
# contact = XeroGateway::Contact.new(:name => "THE NAME OF THE CONTACT #{Time.now.to_i}")
# contact.email = "whoever@something.com"
# contact.phone.number = "12345"
# contact.address.line_1 = "LINE 1 OF THE ADDRESS"
# contact.address.line_2 = "LINE 2 OF THE ADDRESS"
# contact.address.line_3 = "LINE 3 OF THE ADDRESS"
# contact.address.line_4 = "LINE 4 OF THE ADDRESS"
# contact.address.city = "WELLINGTON"
# contact.address.region = "WELLINGTON"
# contact.address.country = "NEW ZEALAND"
# contact.address.post_code = "6021"
#
# create_contact(contact)
def create_contact(contact)
save_contact(contact)
end
#
# Updates an existing Xero contact
#
# Usage :
#
# contact = xero_gateway.get_contact(some_contact_id)
# contact.email = "a_new_email_ddress"
#
# xero_gateway.update_contact(contact)
def update_contact(contact)
raise "contact_id or contact_number is required for updating contacts" if contact.contact_id.nil? and contact.contact_number.nil?
save_contact(contact)
end
#
# Updates an array of contacts in a single API operation.
#
# Usage :
# contacts = [XeroGateway::Contact.new(:name => 'Joe Bloggs'), XeroGateway::Contact.new(:name => 'Jane Doe')]
# result = gateway.update_contacts(contacts)
#
# Will update contacts with matching contact_id, contact_number or name or create if they don't exist.
#
def update_contacts(contacts)
b = Builder::XmlMarkup.new
request_xml = b.Contacts {
contacts.each do | contact |
contact.to_xml(b)
end
}
response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {})
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'POST/contacts'})
response.contacts.each_with_index do | response_contact, index |
contacts[index].contact_id = response_contact.contact_id if response_contact && response_contact.contact_id
end
response
end
# Retrieves all invoices from Xero
#
# Usage : get_invoices
# get_invoices(:invoice_id => " 297c2dc5-cc47-4afd-8ec8-74990b8761e9")
#
# Note : modified_since is in UTC format (i.e. Brisbane is UTC+10)
def get_invoices(options = {})
request_params = {}
request_params[:InvoiceID] = options[:invoice_id] if options[:invoice_id]
request_params[:InvoiceNumber] = options[:invoice_number] if options[:invoice_number]
request_params[:OrderBy] = options[:order] if options[:order]
request_params[:ModifiedAfter] = options[:modified_since] if options[:modified_since]
request_params[:where] = options[:where] if options[:where]
response_xml = http_get(@client, "#{@xero_url}/Invoices", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoices'})
end
# Retrieves a single invoice
#
# Usage : get_invoice("297c2dc5-cc47-4afd-8ec8-74990b8761e9") # By ID
# get_invoice("OIT-12345") # By number
def get_invoice(invoice_id_or_number)
request_params = {}
url = "#{@xero_url}/Invoices/#{URI.escape(invoice_id_or_number)}"
response_xml = http_get(@client, url, request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/Invoice'})
end
# Factory method for building new Invoice objects associated with this gateway.
def build_invoice(invoice = {})
case invoice
when Invoice then invoice.gateway = self
when Hash then invoice = Invoice.new(invoice.merge(:gateway => self))
end
invoice
end
# Creates an invoice in Xero based on an invoice object.
#
# Invoice and line item totals are calculated automatically.
#
# Usage :
#
# invoice = XeroGateway::Invoice.new({
# :invoice_type => "ACCREC",
# :due_date => 1.month.from_now,
# :invoice_number => "YOUR INVOICE NUMBER",
# :reference => "YOUR REFERENCE (NOT NECESSARILY UNIQUE!)",
# :line_amount_types => "Inclusive"
# })
# invoice.contact = XeroGateway::Contact.new(:name => "THE NAME OF THE CONTACT")
# invoice.contact.phone.number = "12345"
# invoice.contact.address.line_1 = "LINE 1 OF THE ADDRESS"
# invoice.line_items << XeroGateway::LineItem.new(
# :description => "THE DESCRIPTION OF THE LINE ITEM",
# :unit_amount => 100,
# :tax_amount => 12.5,
# :tracking_category => "THE TRACKING CATEGORY FOR THE LINE ITEM",
# :tracking_option => "THE TRACKING OPTION FOR THE LINE ITEM"
# )
#
# create_invoice(invoice)
def create_invoice(invoice)
request_xml = invoice.to_xml
response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml)
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoice'})
# Xero returns invoices inside an <Invoices> tag, even though there's only ever
# one for this request
response.response_item = response.invoices.first
if response.success? && response.invoice && response.invoice.invoice_id
invoice.invoice_id = response.invoice.invoice_id
end
response
end
#
# Creates an array of invoices with a single API request.
#
# Usage :
# invoices = [XeroGateway::Invoice.new(...), XeroGateway::Invoice.new(...)]
# result = gateway.create_invoices(invoices)
#
def create_invoices(invoices)
b = Builder::XmlMarkup.new
request_xml = b.Invoices {
invoices.each do | invoice |
invoice.to_xml(b)
end
}
response_xml = http_put(@client, "#{@xero_url}/Invoices", request_xml, {})
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => 'PUT/invoices'})
response.invoices.each_with_index do | response_invoice, index |
invoices[index].invoice_id = response_invoice.invoice_id if response_invoice && response_invoice.invoice_id
end
response
end
#
# Gets all accounts for a specific organization in Xero.
#
def get_accounts
response_xml = http_get(@client, "#{xero_url}/Accounts")
parse_response(response_xml, {}, {:request_signature => 'GET/accounts'})
end
#
# Returns a XeroGateway::AccountsList object that makes working with
# the Xero list of accounts easier and allows caching the results.
#
def get_accounts_list(load_on_init = true)
AccountsList.new(self, load_on_init)
end
#
# Gets all tracking categories for a specific organization in Xero.
#
def get_tracking_categories
response_xml = http_get(@client, "#{xero_url}/TrackingCategories")
parse_response(response_xml, {}, {:request_signature => 'GET/TrackingCategories'})
end
#
# Gets Organisation details
#
def get_organisation
response_xml = http_get(@client, "#{xero_url}/Organisation")
parse_response(response_xml, {}, {:request_signature => 'GET/organisation'})
end
#
# Gets all currencies for a specific organisation in Xero
#
def get_currencies
response_xml = http_get(@client, "#{xero_url}/Currencies")
parse_response(response_xml, {}, {:request_signature => 'GET/currencies'})
end
#
# Gets all Tax Rates for a specific organisation in Xero
#
def get_tax_rates
response_xml = http_get(@client, "#{xero_url}/TaxRates")
parse_response(response_xml, {}, {:request_signature => 'GET/tax_rates'})
end
private
def get_contact(contact_id = nil, contact_number = nil)
request_params = contact_id ? { :contactID => contact_id } : { :contactNumber => contact_number }
response_xml = http_get(@client, "#{@xero_url}/Contacts/#{URI.escape(contact_id||contact_number)}", request_params)
parse_response(response_xml, {:request_params => request_params}, {:request_signature => 'GET/contact'})
end
# Create or update a contact record based on if it has a contact_id or contact_number.
def save_contact(contact)
request_xml = contact.to_xml
response_xml = nil
create_or_save = nil
if contact.contact_id.nil? && contact.contact_number.nil?
# Create new contact record.
response_xml = http_put(@client, "#{@xero_url}/Contacts", request_xml, {})
create_or_save = :create
else
# Update existing contact record.
response_xml = http_post(@client, "#{@xero_url}/Contacts", request_xml, {})
create_or_save = :save
end
response = parse_response(response_xml, {:request_xml => request_xml}, {:request_signature => "#{create_or_save == :create ? 'PUT' : 'POST'}/contact"})
contact.contact_id = response.contact.contact_id if response.contact && response.contact.contact_id
response
end
def parse_response(raw_response, request = {}, options = {})
response = XeroGateway::Response.new
doc = REXML::Document.new(raw_response, :ignore_whitespace_nodes => :all)
# check for responses we don't understand
raise UnparseableResponse.new(doc.root.name) unless doc.root.name == "Response"
response_element = REXML::XPath.first(doc, "/Response")
response_element.children.reject { |e| e.is_a? REXML::Text }.each do |element|
case(element.name)
when "ID" then response.response_id = element.text
when "Status" then response.status = element.text
when "ProviderName" then response.provider = element.text
when "DateTimeUTC" then response.date_time = element.text
when "Contact" then response.response_item = Contact.from_xml(element, self)
when "Invoice" then response.response_item = Invoice.from_xml(element, self, {:line_items_downloaded => options[:request_signature] != "GET/Invoices"})
when "Contacts" then element.children.each {|child| response.response_item << Contact.from_xml(child, self) }
when "Invoices" then element.children.each {|child| response.response_item << Invoice.from_xml(child, self, {:line_items_downloaded => options[:request_signature] != "GET/Invoices"}) }
when "Accounts" then element.children.each {|child| response.response_item << Account.from_xml(child) }
when "TaxRates" then element.children.each {|child| response.response_item << TaxRate.from_xml(child) }
when "Currencies" then element.children.each {|child| response.response_item << Currency.from_xml(child) }
when "Organisations" then response.response_item = Organisation.from_xml(element.children.first) # Xero only returns the Authorized Organisation
when "TrackingCategories" then element.children.each {|child| response.response_item << TrackingCategory.from_xml(child) }
when "Errors" then element.children.each { |error| parse_error(error, response) }
end
end if response_element
# If a single result is returned don't put it in an array
if response.response_item.is_a?(Array) && response.response_item.size == 1
response.response_item = response.response_item.first
end
response.request_params = request[:request_params]
response.request_xml = request[:request_xml]
response.response_xml = raw_response
response
end
def parse_error(error_element, response)
response.errors << Error.new(
:description => REXML::XPath.first(error_element, "Description").text,
:date_time => REXML::XPath.first(error_element, "//DateTime").text,
:type => REXML::XPath.first(error_element, "//ExceptionType").text,
:message => REXML::XPath.first(error_element, "//Message").text
)
end
end
end
|
require "xn_gem_release_tasks/version"
require 'rake'
module Bundler
class GemHelper
def perform_git_push(options = '')
cmd = "git push origin master:master #{options}"
out, code = sh_with_code(cmd)
raise "Couldn't git push. `#{cmd}' failed with the following output:\n\n#{out}\n" unless code == 0
end
def version
XNGemReleaseTasks::NAMESPACE::VERSION
end
end
end
module XNGemReleaseTasks
V = /(?<before>\s*\bVERSION\s*=\s*")(?<major>\d+)\.(?<minor>\d+)\.(?<point>\d+)(?:\.(?<pre>\w+))?(?<after>".*)/
def self.ensure_setup
raise "Must run XNGemReleaseTasks.setup(LibModule, 'path/to/version.rb') first" unless NAMESPACE
end
def self.change_version
ensure_setup
f = File.read(NAMESPACE::VERSION_FILE)
lines = f.each_line.map do |line|
match = V.match line
if match
yield line, match[:before], match[:major], match[:minor], match[:point], match[:pre], match[:after]
else
line
end
end
File.open(NAMESPACE::VERSION_FILE, 'w') do |f|
f.puts lines.join
end
end
def self.reload_version
ensure_setup
NAMESPACE.send :remove_const, :VERSION
load NAMESPACE::VERSION_FILE
NAMESPACE::VERSION
end
def self.setup(namespace, version_file)
raise "namespace must be a module" unless namespace.is_a? Module
raise "namespace does not have a current version" unless namespace::VERSION
raise "#{ version_file } file does not exist" unless File.exist? version_file
raise "You may not set up XNGemReleaseTasks multiple times" if defined? NAMESPACE
self.const_set :NAMESPACE, namespace
namespace.const_set :VERSION_FILE, version_file
end
def self.gemspec
eval(File.read(Dir['*.gemspec'].first))
end
end
task :validate_gemspec do
gemspec = XNGemReleaseTasks.gemspec
gemspec.validate
end
def command(task_name, name, &block)
s = `which #{name}`
if s == ""
task(task_name, &block)
else
task task_name do
# noop
end
end
end
desc "Ensures we are on a relesae version, and increments if we already are."
task :increment_release_version do
XNGemReleaseTasks.change_version do |line, before, major, minor, point, pre, after|
if pre
"#{before}#{major}.#{minor}.#{point}#{after}\n"
else
"#{before}#{major}.#{minor}.#{point.next}#{after}\n"
end
end
end
desc "Ensures we are on a release version, but does not increment version number"
task :set_release_version do
XNGemReleaseTasks.change_version do |line, before, major, minor, point, pre, after|
"#{before}#{major}.#{minor}.#{point}#{after}\n"
end
end
desc "Increments a release version number and adds .pre. Does not increment a version that is already .pre."
task :set_development_version do
XNGemReleaseTasks.change_version do |line, before, major, minor, point, pre, after|
if pre
line
else
"#{before}#{major}.#{minor}.#{point.next}.pre#{after}\n"
end
end
end
task :is_clean do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
sh "git status | grep 'working directory clean'"
end
end
task :is_on_master do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
unless ENV['IGNORE_BRANCH'] == 'true'
sh "git status | grep 'On branch master'"
end
end
end
task :is_on_origin_master do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
unless ENV['IGNORE_BRANCH'] == 'true'
result = `git log HEAD...origin/master | grep . || echo ok`
fail "Not on origin/master" unless result.chomp == 'ok'
end
end
end
task :is_up_to_date do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
sh "git pull | grep 'Already up-to-date.'"
end
end
task :is_release_version do
unless XNGemReleaseTasks.reload_version =~ /^\d+\.\d+\.\d+$/
fail "Not on a release version: #{ XNGemReleaseTasks::NAMESPACE::VERSION }"
end
end
task :prepare_release_push => [:is_clean, :is_on_master, :is_up_to_date, :set_release_version]
task :_only_push_release do
XNGemReleaseTasks.reload_version
if `git status | grep 'working directory clean'` == ''
skip_ci = '[skip ci] ' if ENV['TRAVIS_SECURE_ENV_VARS']
if sh "git add #{XNGemReleaseTasks::NAMESPACE::VERSION_FILE} && git commit -m '#{skip_ci}Version #{ XNGemReleaseTasks::NAMESPACE::VERSION }'"
sh "git push"
end
end
end
task :only_push_release => [:prepare_release_push, :_only_push_release]
task :next_dev_cycle => [:is_clean, :set_development_version] do
XNGemReleaseTasks.reload_version
sh "git add #{XNGemReleaseTasks::NAMESPACE::VERSION_FILE} && git commit -m '[skip ci] New development cycle with version #{ XNGemReleaseTasks::NAMESPACE::VERSION }' && git push"
end
desc "Configure environment"
task :env do
path = `echo $PATH`
home = `echo $HOME`
unless path.include? "#{home}/bin"
puts "Configuring path..."
`mkdir -p $HOME/bin`
if File.exist? "#{home}/.zshrc"
profile = "#{home}/.zshrc"
else
profile = "#{home}/.bashrc"
end
`echo 'export PATH="$PATH:$HOME/bin"' >> #{profile} && source #{profile}`
end
end
desc "Install tools to interact with s3"
command(:install_aws_cli, '$HOME/bin/aws') do
Rake::Task['env'].invoke
puts "Installing AWS CLI tools..."
`curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"`
`unzip -o awscli-bundle.zip`
`./awscli-bundle/install -i $HOME/bin/aws`
`rm -rf awscli-bundle awscli-bundle.zip`
`aws help`
end
desc "Install Leiningen, the clojure build tool"
command(:install_lein, '$HOME/bin/lein') do
if File.exist? 'project.clj'
Rake::Task['env'].invoke
puts "Installing Leiningen..."
`curl "https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein" -o "$HOME/bin/lein"`
`chmod a+x $HOME/bin/lein`
`lein`
end
end
desc "Run Leiningen tests"
task :lein_test => [:install_lein] do
if File.exist? 'project.clj'
puts "Running Leiningen tests..."
`lein test`
else
puts "Not a Clojure project"
end
end
desc "Check that AWS access is configured"
task :check_aws_credentials => [:install_aws_cli] do
gemspec = XNGemReleaseTasks.gemspec
check = `aws s3 ls s3://#{gemspec.name} 2>&1`
puts check
if check.to_s.include?("credentials")
fail "Credentials missing. Run `aws configure` to add them or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY"
end
end
desc "Check s3 to see if the gem we're building already exists"
task :validate_unique_gem => [:install_aws_cli,:check_aws_credentials] do
gemspec = XNGemReleaseTasks.gemspec
unless gemspec.version.to_s.include? "pre"
result = `aws s3 ls s3://#{gemspec.name}/gems/#{gemspec.name}-#{gemspec.version}-java.gem`
if result.to_s.include?("#{gemspec.name}-#{gemspec.version}-java.gem")
fail "Non-pre gem already exists on s3, only pre gems can be overwritten"
end
end
end
task :validate_major_push do
gemspec = XNGemReleaseTasks.gemspec
unless gemspec.version.to_s.include? "pre"
Rake::Task['is_clean'].invoke
Rake::Task['is_on_master'].invoke
Rake::Task['is_up_to_date'].invoke
end
end
desc "Build gem and push to s3"
task :up => [:install_aws_cli, :validate_unique_gem, :validate_gemspec, :validate_major_push, :lein_test, :build, :spec, :_up]
task :_up do
gemspec = XNGemReleaseTasks.gemspec
if defined?(gemspec.platform) && gemspec.platform != ''
gem = "#{gemspec.name}-#{gemspec.version}-#{gemspec.platform}.gem"
else
gem = "#{gemspec.name}-#{gemspec.version}.gem"
end
puts "Gem required, checking for presence..."
`test -f #{gem}`
puts "Pulling s3 repo and updating contents..."
sh "mkdir -p repo/gems"
sh "aws s3 sync s3://#{gemspec.name} repo"
sh "cp pkg/#{gem} repo/gems/"
puts "Rebuilding gem index..."
sh "gem generate_index -d repo"
puts "Pushing to s3 bucket #{gemspec.name}..."
sh "aws s3 sync repo s3://#{gemspec.name}"
sh "git tag -f v#{ gemspec.version }"
sh "git push -f origin v#{ gemspec.version }"
end
desc "Pull the repo, rebuild and push to s3"
task :repo_rebuild => [:check_aws_credentials] do
gemspec = XNGemReleaseTasks.gemspec
puts "Pulling s3 repo and updating contents..."
`mkdir -p repo/gems`
`aws s3 sync s3://#{gemspec.name} repo`
puts "Rebuilding gem index..."
`gem generate_index -d repo`
puts "Pushing to s3 bucket #{gemspec.name}..."
`aws s3 sync repo s3://#{gemspec.name}`
end
# Set a dependency to replace the :release task. For example, the following would cause :up to be used to
# release instead of :release. That allows the local_release task to work in either case.
#
# task release_with: :up
#
task :release_with do |this|
if this.prerequisites.empty?
Rake::Task[:release].invoke
end
end
desc "Release a new version locally rather than after a successful Travis build"
task :local_release => [:only_push_release, :release_with, :next_dev_cycle]
desc "Push a release candidate to Travis CI to release if it builds successfully"
task :push_release => [:only_push_release, :next_dev_cycle]
task :release => [:is_clean, :is_on_origin_master, :is_release_version]
Don't add ruby platform
require "xn_gem_release_tasks/version"
require 'rake'
module Bundler
class GemHelper
def perform_git_push(options = '')
cmd = "git push origin master:master #{options}"
out, code = sh_with_code(cmd)
raise "Couldn't git push. `#{cmd}' failed with the following output:\n\n#{out}\n" unless code == 0
end
def version
XNGemReleaseTasks::NAMESPACE::VERSION
end
end
end
module XNGemReleaseTasks
V = /(?<before>\s*\bVERSION\s*=\s*")(?<major>\d+)\.(?<minor>\d+)\.(?<point>\d+)(?:\.(?<pre>\w+))?(?<after>".*)/
def self.ensure_setup
raise "Must run XNGemReleaseTasks.setup(LibModule, 'path/to/version.rb') first" unless NAMESPACE
end
def self.change_version
ensure_setup
f = File.read(NAMESPACE::VERSION_FILE)
lines = f.each_line.map do |line|
match = V.match line
if match
yield line, match[:before], match[:major], match[:minor], match[:point], match[:pre], match[:after]
else
line
end
end
File.open(NAMESPACE::VERSION_FILE, 'w') do |f|
f.puts lines.join
end
end
def self.reload_version
ensure_setup
NAMESPACE.send :remove_const, :VERSION
load NAMESPACE::VERSION_FILE
NAMESPACE::VERSION
end
def self.setup(namespace, version_file)
raise "namespace must be a module" unless namespace.is_a? Module
raise "namespace does not have a current version" unless namespace::VERSION
raise "#{ version_file } file does not exist" unless File.exist? version_file
raise "You may not set up XNGemReleaseTasks multiple times" if defined? NAMESPACE
self.const_set :NAMESPACE, namespace
namespace.const_set :VERSION_FILE, version_file
end
def self.gemspec
eval(File.read(Dir['*.gemspec'].first))
end
end
task :validate_gemspec do
gemspec = XNGemReleaseTasks.gemspec
gemspec.validate
end
def command(task_name, name, &block)
s = `which #{name}`
if s == ""
task(task_name, &block)
else
task task_name do
# noop
end
end
end
desc "Ensures we are on a relesae version, and increments if we already are."
task :increment_release_version do
XNGemReleaseTasks.change_version do |line, before, major, minor, point, pre, after|
if pre
"#{before}#{major}.#{minor}.#{point}#{after}\n"
else
"#{before}#{major}.#{minor}.#{point.next}#{after}\n"
end
end
end
desc "Ensures we are on a release version, but does not increment version number"
task :set_release_version do
XNGemReleaseTasks.change_version do |line, before, major, minor, point, pre, after|
"#{before}#{major}.#{minor}.#{point}#{after}\n"
end
end
desc "Increments a release version number and adds .pre. Does not increment a version that is already .pre."
task :set_development_version do
XNGemReleaseTasks.change_version do |line, before, major, minor, point, pre, after|
if pre
line
else
"#{before}#{major}.#{minor}.#{point.next}.pre#{after}\n"
end
end
end
task :is_clean do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
sh "git status | grep 'working directory clean'"
end
end
task :is_on_master do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
unless ENV['IGNORE_BRANCH'] == 'true'
sh "git status | grep 'On branch master'"
end
end
end
task :is_on_origin_master do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
unless ENV['IGNORE_BRANCH'] == 'true'
result = `git log HEAD...origin/master | grep . || echo ok`
fail "Not on origin/master" unless result.chomp == 'ok'
end
end
end
task :is_up_to_date do
if ENV['TRAVIS_BRANCH'] == 'master'
true
else
sh "git pull | grep 'Already up-to-date.'"
end
end
task :is_release_version do
unless XNGemReleaseTasks.reload_version =~ /^\d+\.\d+\.\d+$/
fail "Not on a release version: #{ XNGemReleaseTasks::NAMESPACE::VERSION }"
end
end
task :prepare_release_push => [:is_clean, :is_on_master, :is_up_to_date, :set_release_version]
task :_only_push_release do
XNGemReleaseTasks.reload_version
if `git status | grep 'working directory clean'` == ''
skip_ci = '[skip ci] ' if ENV['TRAVIS_SECURE_ENV_VARS']
if sh "git add #{XNGemReleaseTasks::NAMESPACE::VERSION_FILE} && git commit -m '#{skip_ci}Version #{ XNGemReleaseTasks::NAMESPACE::VERSION }'"
sh "git push"
end
end
end
task :only_push_release => [:prepare_release_push, :_only_push_release]
task :next_dev_cycle => [:is_clean, :set_development_version] do
XNGemReleaseTasks.reload_version
sh "git add #{XNGemReleaseTasks::NAMESPACE::VERSION_FILE} && git commit -m '[skip ci] New development cycle with version #{ XNGemReleaseTasks::NAMESPACE::VERSION }' && git push"
end
desc "Configure environment"
task :env do
path = `echo $PATH`
home = `echo $HOME`
unless path.include? "#{home}/bin"
puts "Configuring path..."
`mkdir -p $HOME/bin`
if File.exist? "#{home}/.zshrc"
profile = "#{home}/.zshrc"
else
profile = "#{home}/.bashrc"
end
`echo 'export PATH="$PATH:$HOME/bin"' >> #{profile} && source #{profile}`
end
end
desc "Install tools to interact with s3"
command(:install_aws_cli, '$HOME/bin/aws') do
Rake::Task['env'].invoke
puts "Installing AWS CLI tools..."
`curl "https://s3.amazonaws.com/aws-cli/awscli-bundle.zip" -o "awscli-bundle.zip"`
`unzip -o awscli-bundle.zip`
`./awscli-bundle/install -i $HOME/bin/aws`
`rm -rf awscli-bundle awscli-bundle.zip`
`aws help`
end
desc "Install Leiningen, the clojure build tool"
command(:install_lein, '$HOME/bin/lein') do
if File.exist? 'project.clj'
Rake::Task['env'].invoke
puts "Installing Leiningen..."
`curl "https://raw.githubusercontent.com/technomancy/leiningen/stable/bin/lein" -o "$HOME/bin/lein"`
`chmod a+x $HOME/bin/lein`
`lein`
end
end
desc "Run Leiningen tests"
task :lein_test => [:install_lein] do
if File.exist? 'project.clj'
puts "Running Leiningen tests..."
`lein test`
else
puts "Not a Clojure project"
end
end
desc "Check that AWS access is configured"
task :check_aws_credentials => [:install_aws_cli] do
gemspec = XNGemReleaseTasks.gemspec
check = `aws s3 ls s3://#{gemspec.name} 2>&1`
puts check
if check.to_s.include?("credentials")
fail "Credentials missing. Run `aws configure` to add them or set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY"
end
end
desc "Check s3 to see if the gem we're building already exists"
task :validate_unique_gem => [:install_aws_cli,:check_aws_credentials] do
gemspec = XNGemReleaseTasks.gemspec
unless gemspec.version.to_s.include? "pre"
result = `aws s3 ls s3://#{gemspec.name}/gems/#{gemspec.name}-#{gemspec.version}-java.gem`
if result.to_s.include?("#{gemspec.name}-#{gemspec.version}-java.gem")
fail "Non-pre gem already exists on s3, only pre gems can be overwritten"
end
end
end
task :validate_major_push do
gemspec = XNGemReleaseTasks.gemspec
unless gemspec.version.to_s.include? "pre"
Rake::Task['is_clean'].invoke
Rake::Task['is_on_master'].invoke
Rake::Task['is_up_to_date'].invoke
end
end
desc "Build gem and push to s3"
task :up => [:install_aws_cli, :validate_unique_gem, :validate_gemspec, :validate_major_push, :lein_test, :build, :spec, :_up]
task :_up do
gemspec = XNGemReleaseTasks.gemspec
if defined?(gemspec.platform) and gemspec.platform != '' and gemspec.platform != 'ruby'
gem = "#{gemspec.name}-#{gemspec.version}-#{gemspec.platform}.gem"
else
gem = "#{gemspec.name}-#{gemspec.version}.gem"
end
puts "Gem required, checking for presence..."
`test -f #{gem}`
puts "Pulling s3 repo and updating contents..."
sh "mkdir -p repo/gems"
sh "aws s3 sync s3://#{gemspec.name} repo"
sh "cp pkg/#{gem} repo/gems/"
puts "Rebuilding gem index..."
sh "gem generate_index -d repo"
puts "Pushing to s3 bucket #{gemspec.name}..."
sh "aws s3 sync repo s3://#{gemspec.name}"
sh "git tag -f v#{ gemspec.version }"
sh "git push -f origin v#{ gemspec.version }"
end
desc "Pull the repo, rebuild and push to s3"
task :repo_rebuild => [:check_aws_credentials] do
gemspec = XNGemReleaseTasks.gemspec
puts "Pulling s3 repo and updating contents..."
`mkdir -p repo/gems`
`aws s3 sync s3://#{gemspec.name} repo`
puts "Rebuilding gem index..."
`gem generate_index -d repo`
puts "Pushing to s3 bucket #{gemspec.name}..."
`aws s3 sync repo s3://#{gemspec.name}`
end
# Set a dependency to replace the :release task. For example, the following would cause :up to be used to
# release instead of :release. That allows the local_release task to work in either case.
#
# task release_with: :up
#
task :release_with do |this|
if this.prerequisites.empty?
Rake::Task[:release].invoke
end
end
desc "Release a new version locally rather than after a successful Travis build"
task :local_release => [:only_push_release, :release_with, :next_dev_cycle]
desc "Push a release candidate to Travis CI to release if it builds successfully"
task :push_release => [:only_push_release, :next_dev_cycle]
task :release => [:is_clean, :is_on_origin_master, :is_release_version]
|
require 'socket'
Zeus::Server.define! do
stage :boot do
action do
ENV_PATH = File.expand_path('../config/environment', __FILE__)
BOOT_PATH = File.expand_path('../config/boot', __FILE__)
APP_PATH = File.expand_path('../config/application', __FILE__)
ROOT_PATH = File.expand_path('..', __FILE__)
require BOOT_PATH
require 'rails/all'
end
stage :default_bundle do
action { Bundler.require(:default) }
stage :dev do
action do
Bundler.require(:development)
Rails.env = ENV['RAILS_ENV'] = "development"
require APP_PATH
Rails.application.require_environment!
end
command :generate, :g do
require 'rails/commands/generate'
end
command :runner, :r do
require 'rails/commands/runner'
end
command :console, :c do
require 'rails/commands/console'
Rails::Console.start(Rails.application)
end
command :server, :s do
require 'rails/commands/server'
server = Rails::Server.new
Dir.chdir(Rails.application.root)
server.start
end
stage :prerake do
action do
require 'rake'
load 'Rakefile'
end
command :rake do
Rake.application.run
end
end
end
# stage :test do
# action do
# Rails.env = ENV['RAILS_ENV'] = "test"
# Bundler.require(:test)
# require APP_PATH
# Rails.application.require_environment!
# end
# command :testrb do
# (r = Test::Unit::AutoRunner.new(true)).process_args(ARGV) or
# abort r.options.banner + " tests..."
# exit r.run
# end
# end
end
end
end
Uncomment test stage/acceptor in template
require 'socket'
Zeus::Server.define! do
stage :boot do
action do
ENV_PATH = File.expand_path('../config/environment', __FILE__)
BOOT_PATH = File.expand_path('../config/boot', __FILE__)
APP_PATH = File.expand_path('../config/application', __FILE__)
ROOT_PATH = File.expand_path('..', __FILE__)
require BOOT_PATH
require 'rails/all'
end
stage :default_bundle do
action { Bundler.require(:default) }
stage :dev do
action do
Bundler.require(:development)
Rails.env = ENV['RAILS_ENV'] = "development"
require APP_PATH
Rails.application.require_environment!
end
command :generate, :g do
require 'rails/commands/generate'
end
command :runner, :r do
require 'rails/commands/runner'
end
command :console, :c do
require 'rails/commands/console'
Rails::Console.start(Rails.application)
end
command :server, :s do
require 'rails/commands/server'
server = Rails::Server.new
Dir.chdir(Rails.application.root)
server.start
end
stage :prerake do
action do
require 'rake'
load 'Rakefile'
end
command :rake do
Rake.application.run
end
end
end
stage :test do
action do
Rails.env = ENV['RAILS_ENV'] = "test"
Bundler.require(:test)
require APP_PATH
Rails.application.require_environment!
end
command :testrb do
(r = Test::Unit::AutoRunner.new(true)).process_args(ARGV) or
abort r.options.banner + " tests..."
exit r.run
end
end
end
end
end
|
require 'base64'
require 'ws/dummy_ws'
require 'time'
module Ldash
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Format time to Discord's format
def self.format_time(time)
time.iso8601
end
# Generic data base class, so I don't have to write the same kind of initializer over and over again
class DataObject
def self.data_attribute(name, &proc)
@data_attributes ||= []
@data_attributes << { name: name, proc: proc }
attr_accessor(name)
end
def initialize(data = {})
@session = $session
attrs = self.class.instance_variable_get('@data_attributes')
attrs.each do |attr|
val = data[attr[:name]]
val = attr[:proc].call($session, self) if !val && attr[:proc]
instance_variable_set("@#{attr[:name]}", val)
end
end
end
# Discord user
class User < DataObject
data_attribute :username
data_attribute :id, &:generate_id
data_attribute(:discriminator) { |s| s.generate_discrim(@username) }
data_attribute :avatar
data_attribute :email
data_attribute :password
data_attribute :verified
data_attribute :bot
def id_format
{
id: @id.to_s
}
end
def compact
result = {
username: @username.to_s,
id: @id.to_s,
discriminator: @discriminator.to_s,
avatar: @avatar.to_s
}
# Only add the bot tag if it's actually true
result[:bot] = true if @bot
result
end
# The email will only ever be defined on a possible bot user
def bot_user?
!@email.nil?
end
def bot_user_format
compact.merge(verified: @verified, email: @email.to_s)
end
end
# Users on servers
class Member < DataObject
data_attribute :user
data_attribute :server
# Server wide voice status
data_attribute(:mute) { false }
data_attribute(:deaf) { false }
data_attribute :voice_channel
data_attribute(:joined_at) { Time.now }
data_attribute(:roles) { [] }
data_attribute(:game) { nil }
data_attribute(:status) { 'online' }
def in_voice_channel?
!@voice_channel.nil?
end
# Format used in the READY and GUILD_CREATE members list
def guild_member_format
{
mute: @mute,
deaf: @deaf,
joined_at: Ldash.format_time(@joined_at),
user: @user.compact,
roles: @roles.map(&:id).map(&:to_s)
}
end
# Format used in the READY and GUILD_CREATE presences list
def presence_format
{
user: @user.id_format,
status: @status,
game: game_object
}
end
# Format used in the READY and GUILD_CREATE voice state list
def voice_state_format
{
user_id: @user.id.to_s,
suppress: false, # TODO: voice states
self_mute: false, # TODO: voice states
self_deaf: false, # TODO: voice states
mute: @mute,
deaf: @deaf,
session_id: @session.id,
channel_id: @voice_channel ? @voice_channel.id : nil
}
end
private
def game_object
return nil unless @game
{
name: @game
}
end
end
# Class for user avatars and server icons
class Avatar < DataObject
data_attribute :hash
data_attribute :image_data
# to_s should just be the hash
alias_method :to_s, :hash
end
# Channels
class Channel < DataObject
data_attribute :id, &:generate_id
data_attribute :name
data_attribute :topic
data_attribute :position
data_attribute :permission_overwrites
data_attribute :server
data_attribute :type
data_attribute :bitrate
data_attribute :recipient
def private?
!@server.nil?
end
# Format used in READY and GUILD_CREATE
def guild_channel_format
{
type: @type,
topic: @topic,
id: @id.to_s,
name: @name,
position: @position,
permission_overwrites: permission_overwrites_format,
bitrate: @bitrate
}
end
# Format used in CHANNEL_CREATE (private or public), CHANNEL_DELETE (private or public) and CHANNEL_UPDATE
def channel_create_format
if private?
{
id: @id.to_s,
is_private: true,
recipient: @recipient.compact
}
else
{
guild_id: @server.id.to_s,
id: @id.to_s,
is_private: false,
name: @name,
permission_overwrites: permission_overwrites_format,
position: @position,
topic: @topic,
type: @type,
bitrate: @bitrate
}
end
end
# Format used in the READY private_channels array
def private_channels_format
{
recipient: @recipient.compact,
is_private: true,
id: @id.to_s
}
end
private
def permission_overwrites_format
[
{ # TODO: change this default overwrite format into actual data
type: role,
id: @server.id.to_s,
deny: 0,
allow: 0
}
]
end
end
# Roles
class Role < DataObject
data_attribute :id, &:generate_id
DEFAULT_PERMISSIONS = 36_953_089
data_attribute(:permissions) { DEFAULT_PERMISSIONS }
data_attribute :server
data_attribute :position
data_attribute :name
data_attribute :hoist
data_attribute :colour
# Format used if this role is embedded into guild data (e.g. in READY or GUILD_CREATE)
def guild_role_format
{
position: @position,
permissions: @permissions,
managed: false, # TODO: investigate what this is (probably integration stuff)
id: @id.to_s,
name: @name,
hoist: @hoist,
color: @colour # damn American spelling
}
end
end
# Discord servers
class Server < DataObject
data_attribute :id, &:generate_id
data_attribute :name
data_attribute :icon
data_attribute :owner_id
data_attribute(:afk_timeout) { 300 }
data_attribute :afk_channel
data_attribute(:bot_joined_at) { Time.now }
data_attribute :roles do |_, this|
# @everyone role
Role.new(id: this.id, # role ID = server ID
name: '@everyone',
server: this,
position: -1,
hoist: false,
colour: 0)
end
data_attribute :channels do |_, this|
[
# #general text channel
Channel.new(id: this.id,
name: 'general',
server: this,
type: 'text',
position: 0),
# General voice channel
Channel.new(id: this.id + 1,
name: 'General',
server: this,
type: 'voice',
bitrate: 64_000)
]
end
data_attribute :members do
[]
end
data_attribute(:region) { 'london' }
def large?
@session.large?(@members.length)
end
def member_count
@members.length
end
# Format used in READY and GUILD_CREATE
def guild_format
channels = @channels.map(&:guild_channel_format)
roles = @roles.map(&:guild_role_format)
members = tiny_members.map(&:guild_member_format)
presences = tiny_members.map(&:presence_format)
voice_states = tiny_members.select(&:in_voice_channel?).map(&:voice_state_format)
{
afk_timeout: @afk_timeout,
joined_at: Ldash.format_time(@bot_joined_at),
afk_channel_id: @afk_channel.id,
id: @id.to_s,
icon: @icon,
name: @name,
large: large?,
owner_id: @owner_id.to_s,
region: @region,
member_count: member_count,
channels: channels,
roles: roles,
members: members,
presences: presences,
voice_states: voice_states
}
end
# Format used when a guild is unavailable due to an outage
def unavailable_format
{
id: @id.to_s,
unavailable: true
}
end
private
# Get a list of members according to large_threshold
def tiny_members
return @members unless large?
@members.select { |e| e.status != :offline }
end
end
# The default user in case l- needs one but none exists
DEFAULT_USER = User.new(id: 66237334693085184,
username: 'meew0',
avatar: 'd18a450706c3b6c379f7e2329f64c9e7',
discriminator: 3569,
email: 'meew0@example.com',
password: 'hunter2',
verified: true)
# Mixin to generate discrims
module DiscrimGenerator
def generate_discrim(username)
discrims = discrims_for_username(username)
raise "Can't find a new discrim for username #{username} - too many users with the same username! Calm down with your presets" if discrims.length == 9999
generated = nil
loop do
generated = rand(1..9999)
break unless discrims.include? generated
end
generated
end
private
def discrims_for_username(username)
@users.select { |e| e.username == username }.map(&:discriminator)
end
end
# L- session
class Session
attr_accessor :users, :private_channels, :servers, :messages, :tokens
attr_accessor :ws
attr_accessor :large_threshold, :heartbeat_interval
attr_reader :id
def initialize
@users = []
@private_channels = []
@servers = []
@messages = []
@tokens = []
@token_num = 0
@large_threshold = 100 # TODO
@heartbeat_interval = 41_250 # Discord doesn't always use this exact interval but it seems common enough to use it as the default
@ws = DummyWS.new
@id = object_id.to_s(16).rjust(32, '0')
end
def load_preset(name)
load("presets/#{name}.rb")
end
def ws?
!@ws.dummy?
end
def create_token(user)
# The first part of a token is the bot user ID, base 64 encoded.
first_part = Base64.encode64(user.id.to_s).strip
# The second part is seconds since Jan 1 2011, base 64 encoded.
second_part = Base64.encode64([@token_num].pack('Q>').sub(/^\x00+/, '')).strip
# The third part is apparently a HMAC - we don't care about that so just generate a random string
# WTF kind of library would rely on this anyway
third_part = Base64.encode64([*0..17].map { rand(0..255) }.pack('C*')).strip
token = "#{first_part}.#{second_part}.#{third_part}"
@tokens << token
token
end
# Generates an ID according to Discord's snowflake system
def generate_id(_)
accurate_timestamp = (Time.now.to_f * 1000).round
time_part = (accurate_timestamp - DISCORD_EPOCH) << 22
random_part = rand(0...2**22)
time_part | random_part
end
def large?(member_count)
member_count >= @large_threshold
end
include DiscrimGenerator
def token?(token)
@tokens.include? token
end
def bot_user
user = @users.find(&:bot_user_format)
# If none exists, use the default user
user || DEFAULT_USER
end
end
end
Use instance_eval rather than load to evaluate presets
require 'base64'
require 'ws/dummy_ws'
require 'time'
module Ldash
# The unix timestamp Discord IDs are based on
DISCORD_EPOCH = 1_420_070_400_000
# Format time to Discord's format
def self.format_time(time)
time.iso8601
end
# Generic data base class, so I don't have to write the same kind of initializer over and over again
class DataObject
def self.data_attribute(name, &proc)
@data_attributes ||= []
@data_attributes << { name: name, proc: proc }
attr_accessor(name)
end
def initialize(data = {})
@session = $session
attrs = self.class.instance_variable_get('@data_attributes')
attrs.each do |attr|
val = data[attr[:name]]
val = attr[:proc].call($session, self) if !val && attr[:proc]
instance_variable_set("@#{attr[:name]}", val)
end
end
end
# Discord user
class User < DataObject
data_attribute :username
data_attribute :id, &:generate_id
data_attribute(:discriminator) { |s| s.generate_discrim(@username) }
data_attribute :avatar
data_attribute :email
data_attribute :password
data_attribute :verified
data_attribute :bot
def id_format
{
id: @id.to_s
}
end
def compact
result = {
username: @username.to_s,
id: @id.to_s,
discriminator: @discriminator.to_s,
avatar: @avatar.to_s
}
# Only add the bot tag if it's actually true
result[:bot] = true if @bot
result
end
# The email will only ever be defined on a possible bot user
def bot_user?
!@email.nil?
end
def bot_user_format
compact.merge(verified: @verified, email: @email.to_s)
end
end
# Users on servers
class Member < DataObject
data_attribute :user
data_attribute :server
# Server wide voice status
data_attribute(:mute) { false }
data_attribute(:deaf) { false }
data_attribute :voice_channel
data_attribute(:joined_at) { Time.now }
data_attribute(:roles) { [] }
data_attribute(:game) { nil }
data_attribute(:status) { 'online' }
def in_voice_channel?
!@voice_channel.nil?
end
# Format used in the READY and GUILD_CREATE members list
def guild_member_format
{
mute: @mute,
deaf: @deaf,
joined_at: Ldash.format_time(@joined_at),
user: @user.compact,
roles: @roles.map(&:id).map(&:to_s)
}
end
# Format used in the READY and GUILD_CREATE presences list
def presence_format
{
user: @user.id_format,
status: @status,
game: game_object
}
end
# Format used in the READY and GUILD_CREATE voice state list
def voice_state_format
{
user_id: @user.id.to_s,
suppress: false, # TODO: voice states
self_mute: false, # TODO: voice states
self_deaf: false, # TODO: voice states
mute: @mute,
deaf: @deaf,
session_id: @session.id,
channel_id: @voice_channel ? @voice_channel.id : nil
}
end
private
def game_object
return nil unless @game
{
name: @game
}
end
end
# Class for user avatars and server icons
class Avatar < DataObject
data_attribute :hash
data_attribute :image_data
# to_s should just be the hash
alias_method :to_s, :hash
end
# Channels
class Channel < DataObject
data_attribute :id, &:generate_id
data_attribute :name
data_attribute :topic
data_attribute :position
data_attribute :permission_overwrites
data_attribute :server
data_attribute :type
data_attribute :bitrate
data_attribute :recipient
def private?
!@server.nil?
end
# Format used in READY and GUILD_CREATE
def guild_channel_format
{
type: @type,
topic: @topic,
id: @id.to_s,
name: @name,
position: @position,
permission_overwrites: permission_overwrites_format,
bitrate: @bitrate
}
end
# Format used in CHANNEL_CREATE (private or public), CHANNEL_DELETE (private or public) and CHANNEL_UPDATE
def channel_create_format
if private?
{
id: @id.to_s,
is_private: true,
recipient: @recipient.compact
}
else
{
guild_id: @server.id.to_s,
id: @id.to_s,
is_private: false,
name: @name,
permission_overwrites: permission_overwrites_format,
position: @position,
topic: @topic,
type: @type,
bitrate: @bitrate
}
end
end
# Format used in the READY private_channels array
def private_channels_format
{
recipient: @recipient.compact,
is_private: true,
id: @id.to_s
}
end
private
def permission_overwrites_format
[
{ # TODO: change this default overwrite format into actual data
type: role,
id: @server.id.to_s,
deny: 0,
allow: 0
}
]
end
end
# Roles
class Role < DataObject
data_attribute :id, &:generate_id
DEFAULT_PERMISSIONS = 36_953_089
data_attribute(:permissions) { DEFAULT_PERMISSIONS }
data_attribute :server
data_attribute :position
data_attribute :name
data_attribute :hoist
data_attribute :colour
# Format used if this role is embedded into guild data (e.g. in READY or GUILD_CREATE)
def guild_role_format
{
position: @position,
permissions: @permissions,
managed: false, # TODO: investigate what this is (probably integration stuff)
id: @id.to_s,
name: @name,
hoist: @hoist,
color: @colour # damn American spelling
}
end
end
# Discord servers
class Server < DataObject
data_attribute :id, &:generate_id
data_attribute :name
data_attribute :icon
data_attribute :owner_id
data_attribute(:afk_timeout) { 300 }
data_attribute :afk_channel
data_attribute(:bot_joined_at) { Time.now }
data_attribute :roles do |_, this|
# @everyone role
Role.new(id: this.id, # role ID = server ID
name: '@everyone',
server: this,
position: -1,
hoist: false,
colour: 0)
end
data_attribute :channels do |_, this|
[
# #general text channel
Channel.new(id: this.id,
name: 'general',
server: this,
type: 'text',
position: 0),
# General voice channel
Channel.new(id: this.id + 1,
name: 'General',
server: this,
type: 'voice',
bitrate: 64_000)
]
end
data_attribute :members do
[]
end
data_attribute(:region) { 'london' }
def large?
@session.large?(@members.length)
end
def member_count
@members.length
end
# Format used in READY and GUILD_CREATE
def guild_format
channels = @channels.map(&:guild_channel_format)
roles = @roles.map(&:guild_role_format)
members = tiny_members.map(&:guild_member_format)
presences = tiny_members.map(&:presence_format)
voice_states = tiny_members.select(&:in_voice_channel?).map(&:voice_state_format)
{
afk_timeout: @afk_timeout,
joined_at: Ldash.format_time(@bot_joined_at),
afk_channel_id: @afk_channel.id,
id: @id.to_s,
icon: @icon,
name: @name,
large: large?,
owner_id: @owner_id.to_s,
region: @region,
member_count: member_count,
channels: channels,
roles: roles,
members: members,
presences: presences,
voice_states: voice_states
}
end
# Format used when a guild is unavailable due to an outage
def unavailable_format
{
id: @id.to_s,
unavailable: true
}
end
private
# Get a list of members according to large_threshold
def tiny_members
return @members unless large?
@members.select { |e| e.status != :offline }
end
end
# The default user in case l- needs one but none exists
DEFAULT_USER = User.new(id: 66237334693085184,
username: 'meew0',
avatar: 'd18a450706c3b6c379f7e2329f64c9e7',
discriminator: 3569,
email: 'meew0@example.com',
password: 'hunter2',
verified: true)
# Mixin to generate discrims
module DiscrimGenerator
def generate_discrim(username)
discrims = discrims_for_username(username)
raise "Can't find a new discrim for username #{username} - too many users with the same username! Calm down with your presets" if discrims.length == 9999
generated = nil
loop do
generated = rand(1..9999)
break unless discrims.include? generated
end
generated
end
private
def discrims_for_username(username)
@users.select { |e| e.username == username }.map(&:discriminator)
end
end
# L- session
class Session
attr_accessor :users, :private_channels, :servers, :messages, :tokens
attr_accessor :ws
attr_accessor :large_threshold, :heartbeat_interval
attr_reader :id
def initialize
@users = []
@private_channels = []
@servers = []
@messages = []
@tokens = []
@token_num = 0
@large_threshold = 100 # TODO
@heartbeat_interval = 41_250 # Discord doesn't always use this exact interval but it seems common enough to use it as the default
@ws = DummyWS.new
@id = object_id.to_s(16).rjust(32, '0')
end
def load_preset(name)
instance_eval(File.read("presets/#{name}.rb"))
end
def ws?
!@ws.dummy?
end
def create_token(user)
# The first part of a token is the bot user ID, base 64 encoded.
first_part = Base64.encode64(user.id.to_s).strip
# The second part is seconds since Jan 1 2011, base 64 encoded.
second_part = Base64.encode64([@token_num].pack('Q>').sub(/^\x00+/, '')).strip
# The third part is apparently a HMAC - we don't care about that so just generate a random string
# WTF kind of library would rely on this anyway
third_part = Base64.encode64([*0..17].map { rand(0..255) }.pack('C*')).strip
token = "#{first_part}.#{second_part}.#{third_part}"
@tokens << token
token
end
# Generates an ID according to Discord's snowflake system
def generate_id(_)
accurate_timestamp = (Time.now.to_f * 1000).round
time_part = (accurate_timestamp - DISCORD_EPOCH) << 22
random_part = rand(0...2**22)
time_part | random_part
end
def large?(member_count)
member_count >= @large_threshold
end
include DiscrimGenerator
def token?(token)
@tokens.include? token
end
def bot_user
user = @users.find(&:bot_user_format)
# If none exists, use the default user
user || DEFAULT_USER
end
end
end
|
module Zookeeper
module Exceptions
include Constants
class ZookeeperException < StandardError
unless defined?(CONST_MISSING_WARNING)
CONST_MISSING_WARNING = <<-EOS
------------------------------------------------------------------------------------------
WARNING! THE ZOOKEEPER NAMESPACE HAS CHNAGED AS OF 1.0!
Please update your code to use the new heirarchy!
The constant that got you this was ZookeeperExceptions::ZookeeperException::%s
stacktrace:
%s
------------------------------------------------------------------------------------------
EOS
end
# NOTE(slyphon): Since 0.4 all of the ZookeeperException subclasses were
# defined inside of ZookeeperException, which always seemed well, icky.
# if someone references one of these we'll print out a warning and
# then give them the constant
#
def self.const_missing(const)
if Zookeeper::Exceptions.const_defined?(const)
stacktrace = caller[0..-2].reject {|n| n =~ %r%/rspec/% }.map { |n| "\t#{n}" }.join("\n")
Zookeeper.deprecation_warning(CONST_MISSING_WARNING % [const.to_s, stacktrace])
Zookeeper::Exceptions.const_get(const).tap do |const_val|
self.const_set(const, const_val)
end
else
super
end
end
end
class EverythingOk < ZookeeperException; end
class SystemError < ZookeeperException; end
class RunTimeInconsistency < ZookeeperException; end
class DataInconsistency < ZookeeperException; end
class ConnectionLoss < ZookeeperException; end
class MarshallingError < ZookeeperException; end
class Unimplemented < ZookeeperException; end
class OperationTimeOut < ZookeeperException; end
class BadArguments < ZookeeperException; end
class InvalidState < ZookeeperException; end
class ApiError < ZookeeperException; end
class NoNode < ZookeeperException; end
class NoAuth < ZookeeperException; end
class BadVersion < ZookeeperException; end
class NoChildrenForEphemerals < ZookeeperException; end
class NodeExists < ZookeeperException; end
class NotEmpty < ZookeeperException; end
class SessionExpired < ZookeeperException; end
class InvalidCallback < ZookeeperException; end
class InvalidACL < ZookeeperException; end
class AuthFailed < ZookeeperException; end
class Closing < ZookeeperException; end
class Nothing < ZookeeperException; end
class SessionMoved < ZookeeperException; end
# these are Ruby client exceptions
class ConnectionClosed < ZookeeperException; end
class NotConnected < ZookeeperException; end
class ShuttingDownException < ZookeeperException; end
class DataTooLargeException < ZookeeperException; end
# raised when an operation is performed on an instance without a valid
# zookeeper handle. (C version)
class HandleClosedException < ZookeeperException; end
# maybe use this for continuation
class InterruptedException < ZookeeperException ; end
# raised when a continuation operation takes more time than is reasonable and
# the thread should be awoken. (i.e. prevents a call that never returns)
class ContinuationTimeoutError < ZookeeperException; end
# raised when the user tries to use a connection after a fork()
# without calling reopen() in the C client
#
# (h/t: @pletern http://git.io/zIsq1Q)
class InheritedConnectionError < ZookeeperException; end
# yes, make an alias, this is the way zookeeper refers to it
ExpiredSession = SessionExpired unless defined?(ExpiredSession)
def self.by_code(code)
case code
when ZOK then EverythingOk
when ZSYSTEMERROR then SystemError
when ZRUNTIMEINCONSISTENCY then RunTimeInconsistency
when ZDATAINCONSISTENCY then DataInconsistency
when ZCONNECTIONLOSS then ConnectionLoss
when ZMARSHALLINGERROR then MarshallingError
when ZUNIMPLEMENTED then Unimplemented
when ZOPERATIONTIMEOUT then OperationTimeOut
when ZBADARGUMENTS then BadArguments
when ZINVALIDSTATE then InvalidState
when ZAPIERROR then ApiError
when ZNONODE then NoNode
when ZNOAUTH then NoAuth
when ZBADVERSION then BadVersion
when ZNOCHILDRENFOREPHEMERALS then NoChildrenForEphemerals
when ZNODEEXISTS then NodeExists
when ZNOTEMPTY then NotEmpty
when ZSESSIONEXPIRED then SessionExpired
when ZINVALIDCALLBACK then InvalidCallback
when ZINVALIDACL then InvalidACL
when ZAUTHFAILED then AuthFailed
when ZCLOSING then Closing
when ZNOTHING then Nothing
when ZSESSIONMOVED then SessionMoved
else ZookeeperException.new("no exception defined for code #{code}")
end
end
def self.raise_on_error(code)
exc = self.by_code(code)
raise exc unless exc == EverythingOk
end
end # Exceptions
end # Zookeeper
Fix typos in deprecation warning.
module Zookeeper
module Exceptions
include Constants
class ZookeeperException < StandardError
unless defined?(CONST_MISSING_WARNING)
CONST_MISSING_WARNING = <<-EOS
------------------------------------------------------------------------------------------
WARNING! THE ZOOKEEPER NAMESPACE HAS CHANGED AS OF 1.0!
Please update your code to use the new hierarchy!
The constant that got you this was ZookeeperExceptions::ZookeeperException::%s
stacktrace:
%s
------------------------------------------------------------------------------------------
EOS
end
# NOTE(slyphon): Since 0.4 all of the ZookeeperException subclasses were
# defined inside of ZookeeperException, which always seemed well, icky.
# if someone references one of these we'll print out a warning and
# then give them the constant
#
def self.const_missing(const)
if Zookeeper::Exceptions.const_defined?(const)
stacktrace = caller[0..-2].reject {|n| n =~ %r%/rspec/% }.map { |n| "\t#{n}" }.join("\n")
Zookeeper.deprecation_warning(CONST_MISSING_WARNING % [const.to_s, stacktrace])
Zookeeper::Exceptions.const_get(const).tap do |const_val|
self.const_set(const, const_val)
end
else
super
end
end
end
class EverythingOk < ZookeeperException; end
class SystemError < ZookeeperException; end
class RunTimeInconsistency < ZookeeperException; end
class DataInconsistency < ZookeeperException; end
class ConnectionLoss < ZookeeperException; end
class MarshallingError < ZookeeperException; end
class Unimplemented < ZookeeperException; end
class OperationTimeOut < ZookeeperException; end
class BadArguments < ZookeeperException; end
class InvalidState < ZookeeperException; end
class ApiError < ZookeeperException; end
class NoNode < ZookeeperException; end
class NoAuth < ZookeeperException; end
class BadVersion < ZookeeperException; end
class NoChildrenForEphemerals < ZookeeperException; end
class NodeExists < ZookeeperException; end
class NotEmpty < ZookeeperException; end
class SessionExpired < ZookeeperException; end
class InvalidCallback < ZookeeperException; end
class InvalidACL < ZookeeperException; end
class AuthFailed < ZookeeperException; end
class Closing < ZookeeperException; end
class Nothing < ZookeeperException; end
class SessionMoved < ZookeeperException; end
# these are Ruby client exceptions
class ConnectionClosed < ZookeeperException; end
class NotConnected < ZookeeperException; end
class ShuttingDownException < ZookeeperException; end
class DataTooLargeException < ZookeeperException; end
# raised when an operation is performed on an instance without a valid
# zookeeper handle. (C version)
class HandleClosedException < ZookeeperException; end
# maybe use this for continuation
class InterruptedException < ZookeeperException ; end
# raised when a continuation operation takes more time than is reasonable and
# the thread should be awoken. (i.e. prevents a call that never returns)
class ContinuationTimeoutError < ZookeeperException; end
# raised when the user tries to use a connection after a fork()
# without calling reopen() in the C client
#
# (h/t: @pletern http://git.io/zIsq1Q)
class InheritedConnectionError < ZookeeperException; end
# yes, make an alias, this is the way zookeeper refers to it
ExpiredSession = SessionExpired unless defined?(ExpiredSession)
def self.by_code(code)
case code
when ZOK then EverythingOk
when ZSYSTEMERROR then SystemError
when ZRUNTIMEINCONSISTENCY then RunTimeInconsistency
when ZDATAINCONSISTENCY then DataInconsistency
when ZCONNECTIONLOSS then ConnectionLoss
when ZMARSHALLINGERROR then MarshallingError
when ZUNIMPLEMENTED then Unimplemented
when ZOPERATIONTIMEOUT then OperationTimeOut
when ZBADARGUMENTS then BadArguments
when ZINVALIDSTATE then InvalidState
when ZAPIERROR then ApiError
when ZNONODE then NoNode
when ZNOAUTH then NoAuth
when ZBADVERSION then BadVersion
when ZNOCHILDRENFOREPHEMERALS then NoChildrenForEphemerals
when ZNODEEXISTS then NodeExists
when ZNOTEMPTY then NotEmpty
when ZSESSIONEXPIRED then SessionExpired
when ZINVALIDCALLBACK then InvalidCallback
when ZINVALIDACL then InvalidACL
when ZAUTHFAILED then AuthFailed
when ZCLOSING then Closing
when ZNOTHING then Nothing
when ZSESSIONMOVED then SessionMoved
else ZookeeperException.new("no exception defined for code #{code}")
end
end
def self.raise_on_error(code)
exc = self.by_code(code)
raise exc unless exc == EverythingOk
end
end # Exceptions
end # Zookeeper
|
# based on https://gist.github.com/mnutt/566725
require "active_support/core_ext/module/attr_internal"
module Searchkick
module QueryWithInstrumentation
def execute_search
name = searchkick_klass ? "#{searchkick_klass.name} Search" : "Search"
event = {
name: name,
query: params
}
ActiveSupport::Notifications.instrument("search.searchkick", event) do
super
end
end
end
module IndexWithInstrumentation
def store(record)
event = {
name: "#{record.searchkick_klass.name} Store",
id: search_id(record)
}
if Searchkick.callbacks_value == :bulk
super
else
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
end
end
def remove(record)
name = record && record.searchkick_klass ? "#{record.searchkick_klass.name} Remove" : "Remove"
event = {
name: name,
id: search_id(record)
}
if Searchkick.callbacks_value == :bulk
super
else
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
end
end
def import(records)
if records.any?
event = {
name: "#{records.first.searchkick_klass.name} Import",
count: records.size
}
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super(records)
end
end
end
end
module SearchkickWithInstrumentation
def multi_search(searches)
event = {
name: "Multi Search",
count: searches.size
}
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
end
def perform_items(items)
if callbacks_value == :bulk
event = {
name: "Bulk",
count: items.size
}
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
else
super
end
end
end
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/log_subscriber.rb
class LogSubscriber < ActiveSupport::LogSubscriber
def self.runtime=(value)
Thread.current[:searchkick_runtime] = value
end
def self.runtime
Thread.current[:searchkick_runtime] ||= 0
end
def self.reset_runtime
rt = runtime
self.runtime = 0
rt
end
def search(event)
self.class.runtime += event.duration
return unless logger.debug?
payload = event.payload
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
type = payload[:query][:type]
index = payload[:query][:index].is_a?(Array) ? payload[:query][:index].join(",") : payload[:query][:index]
# no easy way to tell which host the client will use
host = Searchkick.client.transport.hosts.first
debug " #{color(name, YELLOW, true)} curl #{host[:protocol]}://#{host[:host]}:#{host[:port]}/#{CGI.escape(index)}#{type ? "/#{type.map { |t| CGI.escape(t) }.join(',')}" : ''}/_search?pretty -d '#{payload[:query][:body].to_json}'"
end
def request(event)
self.class.runtime += event.duration
return unless logger.debug?
payload = event.payload
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
debug " #{color(name, YELLOW, true)} #{payload.except(:name).to_json}"
end
end
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/controller_runtime.rb
module ControllerRuntime
extend ActiveSupport::Concern
protected
attr_internal :searchkick_runtime
def process_action(action, *args)
# We also need to reset the runtime before each action
# because of queries in middleware or in cases we are streaming
# and it won't be cleaned up by the method below.
Searchkick::LogSubscriber.reset_runtime
super
end
def cleanup_view_runtime
searchkick_rt_before_render = Searchkick::LogSubscriber.reset_runtime
runtime = super
searchkick_rt_after_render = Searchkick::LogSubscriber.reset_runtime
self.searchkick_runtime = searchkick_rt_before_render + searchkick_rt_after_render
runtime - searchkick_rt_after_render
end
def append_info_to_payload(payload)
super
payload[:searchkick_runtime] = (searchkick_runtime || 0) + Searchkick::LogSubscriber.reset_runtime
end
module ClassMethods
def log_process_action(payload)
messages = super
runtime = payload[:searchkick_runtime]
messages << ("Searchkick: %.1fms" % runtime.to_f) if runtime.to_f > 0
messages
end
end
end
end
Searchkick::Query.send(:prepend, Searchkick::QueryWithInstrumentation)
Searchkick::Index.send(:prepend, Searchkick::IndexWithInstrumentation)
Searchkick.singleton_class.send(:prepend, Searchkick::SearchkickWithInstrumentation)
Searchkick::LogSubscriber.attach_to :searchkick
ActiveSupport.on_load(:action_controller) do
include Searchkick::ControllerRuntime
end
Added separate event for multi search
# based on https://gist.github.com/mnutt/566725
require "active_support/core_ext/module/attr_internal"
module Searchkick
module QueryWithInstrumentation
def execute_search
name = searchkick_klass ? "#{searchkick_klass.name} Search" : "Search"
event = {
name: name,
query: params
}
ActiveSupport::Notifications.instrument("search.searchkick", event) do
super
end
end
end
module IndexWithInstrumentation
def store(record)
event = {
name: "#{record.searchkick_klass.name} Store",
id: search_id(record)
}
if Searchkick.callbacks_value == :bulk
super
else
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
end
end
def remove(record)
name = record && record.searchkick_klass ? "#{record.searchkick_klass.name} Remove" : "Remove"
event = {
name: name,
id: search_id(record)
}
if Searchkick.callbacks_value == :bulk
super
else
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
end
end
def import(records)
if records.any?
event = {
name: "#{records.first.searchkick_klass.name} Import",
count: records.size
}
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super(records)
end
end
end
end
module SearchkickWithInstrumentation
def multi_search(searches)
event = {
name: "Multi Search",
body: searches.flat_map { |q| [q.params.except(:body).to_json, q.body.to_json] }.map { |v| "#{v}\n" }.join
}
ActiveSupport::Notifications.instrument("multi_search.searchkick", event) do
super
end
end
def perform_items(items)
if callbacks_value == :bulk
event = {
name: "Bulk",
count: items.size
}
ActiveSupport::Notifications.instrument("request.searchkick", event) do
super
end
else
super
end
end
end
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/log_subscriber.rb
class LogSubscriber < ActiveSupport::LogSubscriber
def self.runtime=(value)
Thread.current[:searchkick_runtime] = value
end
def self.runtime
Thread.current[:searchkick_runtime] ||= 0
end
def self.reset_runtime
rt = runtime
self.runtime = 0
rt
end
def search(event)
self.class.runtime += event.duration
return unless logger.debug?
payload = event.payload
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
type = payload[:query][:type]
index = payload[:query][:index].is_a?(Array) ? payload[:query][:index].join(",") : payload[:query][:index]
# no easy way to tell which host the client will use
host = Searchkick.client.transport.hosts.first
debug " #{color(name, YELLOW, true)} curl #{host[:protocol]}://#{host[:host]}:#{host[:port]}/#{CGI.escape(index)}#{type ? "/#{type.map { |t| CGI.escape(t) }.join(',')}" : ''}/_search?pretty -d '#{payload[:query][:body].to_json}'"
end
def request(event)
self.class.runtime += event.duration
return unless logger.debug?
payload = event.payload
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
debug " #{color(name, YELLOW, true)} #{payload.except(:name).to_json}"
end
def multi_search(event)
self.class.runtime += event.duration
return unless logger.debug?
payload = event.payload
name = "#{payload[:name]} (#{event.duration.round(1)}ms)"
# no easy way to tell which host the client will use
host = Searchkick.client.transport.hosts.first
debug " #{color(name, YELLOW, true)} curl #{host[:protocol]}://#{host[:host]}:#{host[:port]}/_msearch?pretty -d '#{payload[:body]}'"
end
end
# https://github.com/rails/rails/blob/master/activerecord/lib/active_record/railties/controller_runtime.rb
module ControllerRuntime
extend ActiveSupport::Concern
protected
attr_internal :searchkick_runtime
def process_action(action, *args)
# We also need to reset the runtime before each action
# because of queries in middleware or in cases we are streaming
# and it won't be cleaned up by the method below.
Searchkick::LogSubscriber.reset_runtime
super
end
def cleanup_view_runtime
searchkick_rt_before_render = Searchkick::LogSubscriber.reset_runtime
runtime = super
searchkick_rt_after_render = Searchkick::LogSubscriber.reset_runtime
self.searchkick_runtime = searchkick_rt_before_render + searchkick_rt_after_render
runtime - searchkick_rt_after_render
end
def append_info_to_payload(payload)
super
payload[:searchkick_runtime] = (searchkick_runtime || 0) + Searchkick::LogSubscriber.reset_runtime
end
module ClassMethods
def log_process_action(payload)
messages = super
runtime = payload[:searchkick_runtime]
messages << ("Searchkick: %.1fms" % runtime.to_f) if runtime.to_f > 0
messages
end
end
end
end
Searchkick::Query.send(:prepend, Searchkick::QueryWithInstrumentation)
Searchkick::Index.send(:prepend, Searchkick::IndexWithInstrumentation)
Searchkick.singleton_class.send(:prepend, Searchkick::SearchkickWithInstrumentation)
Searchkick::LogSubscriber.attach_to :searchkick
ActiveSupport.on_load(:action_controller) do
include Searchkick::ControllerRuntime
end
|
module Seek
module AssetsCommon
require 'net/ftp'
#required to get the icon_filename_for_key
include ImagesHelper
def url_response_code asset_url
url = URI.parse(asset_url)
code=""
if (["http","https"].include?(url.scheme))
Net::HTTP.start(url.host, url.port) do |http|
code = http.head(url.request_uri).code
end
elsif (url.scheme=="ftp")
username = 'anonymous'
password = nil
username, password = url.userinfo.split(/:/) if url.userinfo
begin
ftp = Net::FTP.new(url.host)
ftp.login(username,password)
ftp.getbinaryfile(url.path, '/dev/null', 20) { break }
ftp.close
code="200"
rescue Net::FTPPermError
code="401"
rescue Errno::ECONNREFUSED,SocketError
code="404"
end
else
raise Seek::IncompatibleProtocolException.new("Only http, https and ftp protocols are supported")
end
return code
end
def test_asset_url
c = self.controller_name.downcase
symb=c.singularize.to_sym
icon_filename=icon_filename_for_key("error")
code=""
msg=""
asset_url=params[symb][:data_url]
begin
code = url_response_code(asset_url)
if code == "200"
icon_filename=icon_filename_for_key("tick")
msg="The URL was accessed successfully"
elsif code == "302"
icon_filename=icon_filename_for_key("warn")
msg="The url responded with a <b>redirect</b>. It can still be used, but content type and filename may not be recorded.<br/>You will also not be able to make a copy. When a user downloads this file, they will be redirected to the URL."
elsif code == "401"
icon_filename=icon_filename_for_key("warn")
msg="The url responded with <b>unauthorized</b>.<br/> It can still be used, but content type and filename will not be recorded.<br/>You will also not be able to make a copy. When a user downloads this file, they will be redirected to the URL."
elsif code == "404"
msg="Nothing was found at the URL you provided. You can test the link by opening in another window or tab:<br/><a href=#{asset_url} target='_blank'>#{asset_url}</a>"
else
msg="There was a problem accessing the URL. You can test the link by opening in another window or tab:<br/><a href=#{asset_url} target='_blank'>#{asset_url}</a>"
end
rescue Seek::IncompatibleProtocolException=>e
msg = e.message
rescue Exception=>e
msg="There was a problem accessing the URL. You can test the link by opening in another window or tab:<br/><a href=#{asset_url}>#{asset_url}</a>"
end
image = "<img src='/images/#{icon_filename}'/>"
render :update do |page|
page.replace_html "test_url_result_icon",image
if msg.length>0
page.replace_html "test_url_msg",msg
page.show 'test_url_msg'
page.visual_effect :highlight,"test_url_msg"
if code=="302" || code=="401"
page['local_copy'].checked=false
page['local_copy'].disable
else
page['local_copy'].enable
end
end
end
end
def download_jerm_asset asset
project=asset.project
project.decrypt_credentials
downloader=Jerm::DownloaderFactory.create project.name
resource_type = asset.class.name.split("::")[0] #need to handle versions, e.g. Sop::Version
data_hash = downloader.get_remote_data asset.content_blob.url,project.site_username,project.site_password, resource_type
send_file data_hash[:data_tmp_path], :filename => data_hash[:filename] || asset.original_filename, :content_type => data_hash[:content_type] || asset.content_type, :disposition => 'attachment'
end
def download_via_url asset
code = url_response_code(asset.content_blob.url)
if (["302","401"].include?(code))
redirect_to(asset.content_blob.url,:target=>"_blank")
elsif code=="404"
flash[:error]="This item is referenced at a remote location, which is currently unavailable"
redirect_to asset.parent,:version=>asset.version
else
downloader=RemoteDownloader.new
data_hash = downloader.get_remote_data asset.content_blob.url
send_file data_hash[:data_tmp_path], :filename => data_hash[:filename] || asset.original_filename, :content_type => data_hash[:content_type] || asset.content_type, :disposition => 'attachment'
end
end
def handle_data render_action_on_error=:new
c = self.controller_name.downcase
symb=c.singularize.to_sym
if (params[symb][:data]).blank? && (params[symb][:data_url]).blank?
flash.now[:error] = "Please select a file to upload or provide a URL to the data."
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
elsif !(params[symb][:data]).blank? && (params[symb][:data]).size == 0 && (params[symb][:data_url]).blank?
flash.now[:error] = "The file that you are uploading is empty. Please check your selection and try again!"
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
else
#upload takes precendence if both params are present
begin
if !(params[symb][:data]).blank?
# store properties and contents of the file temporarily and remove the latter from params[],
# so that when saving main object params[] wouldn't contain the binary data anymore
params[symb][:content_type] = (params[symb][:data]).content_type
params[symb][:original_filename] = (params[symb][:data]).original_filename
@tmp_io_object = params[symb][:data]
elsif !(params[symb][:data_url]).blank?
make_local_copy = params[symb][:local_copy]=="1"
@data_url=params[symb][:data_url]
code = url_response_code @data_url
if (code == "200")
downloader=RemoteDownloader.new
data_hash = downloader.get_remote_data @data_url,nil,nil,nil,make_local_copy
@tmp_io_object=File.open data_hash[:data_tmp_path],"r" if make_local_copy
params[symb][:content_type] = data_hash[:content_type]
params[symb][:original_filename] = data_hash[:filename]
elsif (["302","401"].include?(code))
params[symb][:content_type] = ""
params[symb][:original_filename] = ""
else
flash.now[:error] = "Processing the URL responded with a response code (#{code}), indicating the URL is inaccessible."
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
end
end
rescue Seek::IncompatibleProtocolException=>e
flash.now[:error] = e.message
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
rescue Exception=>e
flash.now[:error] = "Unable to read from the URL."
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
end
params[symb].delete 'data_url'
params[symb].delete 'data'
params[symb].delete 'local_copy'
return true
end
end
def handle_download asset
if asset.content_blob.url.blank?
if asset.content_blob.file_exists?
send_file asset.content_blob.filepath, :filename => asset.original_filename, :content_type => asset.content_type, :disposition => 'attachment'
else
send_data asset.content_blob.data, :filename => asset.original_filename, :content_type => asset.content_type, :disposition => 'attachment'
end
else
if asset.contributor.nil? #A jerm generated resource
download_jerm_asset asset
else
if asset.content_blob.file_exists?
send_file asset.content_blob.filepath, :filename => asset.original_filename, :content_type => asset.content_type, :disposition => 'attachment'
else
download_via_url asset
end
end
end
end
end
end
report error correctly when url is unreachable
module Seek
module AssetsCommon
require 'net/ftp'
#required to get the icon_filename_for_key
include ImagesHelper
def url_response_code asset_url
url = URI.parse(asset_url)
code=""
if (["http","https"].include?(url.scheme))
Net::HTTP.start(url.host, url.port) do |http|
code = http.head(url.request_uri).code
end
elsif (url.scheme=="ftp")
username = 'anonymous'
password = nil
username, password = url.userinfo.split(/:/) if url.userinfo
begin
ftp = Net::FTP.new(url.host)
ftp.login(username,password)
ftp.getbinaryfile(url.path, '/dev/null', 20) { break }
ftp.close
code="200"
rescue Net::FTPPermError
code="401"
rescue Errno::ECONNREFUSED,SocketError,Errno::EHOSTUNREACH
code="404"
end
else
raise Seek::IncompatibleProtocolException.new("Only http, https and ftp protocols are supported")
end
return code
end
def test_asset_url
c = self.controller_name.downcase
symb=c.singularize.to_sym
icon_filename=icon_filename_for_key("error")
code=""
msg=""
asset_url=params[symb][:data_url]
begin
code = url_response_code(asset_url)
if code == "200"
icon_filename=icon_filename_for_key("tick")
msg="The URL was accessed successfully"
elsif code == "302"
icon_filename=icon_filename_for_key("warn")
msg="The url responded with a <b>redirect</b>. It can still be used, but content type and filename may not be recorded.<br/>You will also not be able to make a copy. When a user downloads this file, they will be redirected to the URL."
elsif code == "401"
icon_filename=icon_filename_for_key("warn")
msg="The url responded with <b>unauthorized</b>.<br/> It can still be used, but content type and filename will not be recorded.<br/>You will also not be able to make a copy. When a user downloads this file, they will be redirected to the URL."
elsif code == "404"
msg="Nothing was found at the URL you provided. You can test the link by opening in another window or tab:<br/><a href=#{asset_url} target='_blank'>#{asset_url}</a>"
else
msg="There was a problem accessing the URL. You can test the link by opening in another window or tab:<br/><a href=#{asset_url} target='_blank'>#{asset_url}</a>"
end
rescue Seek::IncompatibleProtocolException=>e
msg = e.message
rescue Exception=>e
msg="There was a problem accessing the URL. You can test the link by opening in another window or tab:<br/><a href=#{asset_url}>#{asset_url}</a>"
end
image = "<img src='/images/#{icon_filename}'/>"
render :update do |page|
page.replace_html "test_url_result_icon",image
if msg.length>0
page.replace_html "test_url_msg",msg
page.show 'test_url_msg'
page.visual_effect :highlight,"test_url_msg"
if code=="302" || code=="401"
page['local_copy'].checked=false
page['local_copy'].disable
else
page['local_copy'].enable
end
end
end
end
def download_jerm_asset asset
project=asset.project
project.decrypt_credentials
downloader=Jerm::DownloaderFactory.create project.name
resource_type = asset.class.name.split("::")[0] #need to handle versions, e.g. Sop::Version
data_hash = downloader.get_remote_data asset.content_blob.url,project.site_username,project.site_password, resource_type
send_file data_hash[:data_tmp_path], :filename => data_hash[:filename] || asset.original_filename, :content_type => data_hash[:content_type] || asset.content_type, :disposition => 'attachment'
end
def download_via_url asset
code = url_response_code(asset.content_blob.url)
if (["302","401"].include?(code))
redirect_to(asset.content_blob.url,:target=>"_blank")
elsif code=="404"
flash[:error]="This item is referenced at a remote location, which is currently unavailable"
redirect_to asset.parent,:version=>asset.version
else
downloader=RemoteDownloader.new
data_hash = downloader.get_remote_data asset.content_blob.url
send_file data_hash[:data_tmp_path], :filename => data_hash[:filename] || asset.original_filename, :content_type => data_hash[:content_type] || asset.content_type, :disposition => 'attachment'
end
end
def handle_data render_action_on_error=:new
c = self.controller_name.downcase
symb=c.singularize.to_sym
if (params[symb][:data]).blank? && (params[symb][:data_url]).blank?
flash.now[:error] = "Please select a file to upload or provide a URL to the data."
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
elsif !(params[symb][:data]).blank? && (params[symb][:data]).size == 0 && (params[symb][:data_url]).blank?
flash.now[:error] = "The file that you are uploading is empty. Please check your selection and try again!"
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
else
#upload takes precendence if both params are present
begin
if !(params[symb][:data]).blank?
# store properties and contents of the file temporarily and remove the latter from params[],
# so that when saving main object params[] wouldn't contain the binary data anymore
params[symb][:content_type] = (params[symb][:data]).content_type
params[symb][:original_filename] = (params[symb][:data]).original_filename
@tmp_io_object = params[symb][:data]
elsif !(params[symb][:data_url]).blank?
make_local_copy = params[symb][:local_copy]=="1"
@data_url=params[symb][:data_url]
code = url_response_code @data_url
if (code == "200")
downloader=RemoteDownloader.new
data_hash = downloader.get_remote_data @data_url,nil,nil,nil,make_local_copy
@tmp_io_object=File.open data_hash[:data_tmp_path],"r" if make_local_copy
params[symb][:content_type] = data_hash[:content_type]
params[symb][:original_filename] = data_hash[:filename]
elsif (["302","401"].include?(code))
params[symb][:content_type] = ""
params[symb][:original_filename] = ""
else
flash.now[:error] = "Processing the URL responded with a response code (#{code}), indicating the URL is inaccessible."
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
end
end
rescue Seek::IncompatibleProtocolException=>e
flash.now[:error] = e.message
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
rescue Exception=>e
flash.now[:error] = "Unable to read from the URL."
if render_action_on_error
respond_to do |format|
format.html do
set_parameters_for_sharing_form
render :action => render_action_on_error
end
end
end
return false
end
params[symb].delete 'data_url'
params[symb].delete 'data'
params[symb].delete 'local_copy'
return true
end
end
def handle_download asset
if asset.content_blob.url.blank?
if asset.content_blob.file_exists?
send_file asset.content_blob.filepath, :filename => asset.original_filename, :content_type => asset.content_type, :disposition => 'attachment'
else
send_data asset.content_blob.data, :filename => asset.original_filename, :content_type => asset.content_type, :disposition => 'attachment'
end
else
if asset.contributor.nil? #A jerm generated resource
download_jerm_asset asset
else
if asset.content_blob.file_exists?
send_file asset.content_blob.filepath, :filename => asset.original_filename, :content_type => asset.content_type, :disposition => 'attachment'
else
download_via_url asset
end
end
end
end
end
end
|
module Serverspec
VERSION = "0.5.0"
end
Bump up version
module Serverspec
VERSION = "0.5.1"
end
|
module Serverspec
VERSION = "2.37.0"
end
Bump up version
[skip ci]
module Serverspec
VERSION = "2.37.1"
end
|
module Sevenpages
VERSION = "1.1.0"
end
Bump version
module Sevenpages
VERSION = "1.2.0"
end
|
#
# Cookbook Name:: automount
# Provider:: automount
#
# Copyright (C) 2014 Nephila Graphic
#
# 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.
#
action :disable do
new_resource.updated_by_last_action(disable_direct)
end
action :enable do
new_resource.updated_by_last_action(enable_direct)
end
private
def mountline
# generate the automount line
options = [
"-fstype=#{new_resource.fstype}", new_resource.options
].flatten.join ','
case new_resource.device_type
when :device
target = ":#{new_resource.device}"
when :uuid
target = ":UUID=#{new_resource.device}"
when :label
target = ":LABEL=#{new_resource.device}"
end
line = "#{new_resource.mount_point} #{options} #{target}"
line
end
def mount_status?
# Check to see if there is a entry in /etc/auto.direct. Last entry for a volume wins.
enabled = false
::File.foreach('/etc/auto.direct') do |line|
case line
when /^[#\s]/
next
when /^\s*#{Regexp.escape(mountline)}\s*/
return :enabled
when /^\s*#{Regexp.escape(new_resource.mount_point)}\s+/
Chef::Log.debug("Found conflicting mount point #{@new_resource.mount_point} in /etc/auto.direct")
return :conflict
end
end
if enabled
return :enabled
else
return :missing
end
end
# Returns true if changed, otherwise false.
def enable_direct
case mount_status?
when :enabled
Chef::Log.debug("#{new_resource} is already enabled - nothing to do")
when :missing, :conflict
if mount_status? == :conflict
Chef::Log.error("#{@new_resource} is conflicting with existing mount at #{@new_resource.mount_point}")
disable_direct
end
::File.open('/etc/auto.direct', 'a') do |fstab|
fstab.puts(mountline)
Chef::Log.debug("#{@new_resource} is enabled at #{@new_resource.mount_point}")
end
return true
else
return false
end
end
# Returns true if changed, otherwise false
def disable_direct
case mount_status?
when :enabled, :conflict
contents = []
found = false
::File.readlines('/etc/auto.direct').reverse_each do |line|
if !found && line =~ /^\s*#{Regexp.escape(new_resource.mount_point)}\s+/
found = true
Chef::Log.debug("#{@new_resource} is removed from fstab")
next
else
contents << line
end
end
::File.open('/etc/auto.direct', 'w') do |fstab|
contents.reverse_each { |line| fstab.puts line }
end
return true
else
Chef::Log.debug("#{@new_resource} is not enabled - nothing to do")
return false
end
end
Update default.rb
Add target type "network."
#
# Cookbook Name:: automount
# Provider:: automount
#
# Copyright (C) 2014 Nephila Graphic
#
# 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.
#
action :disable do
new_resource.updated_by_last_action(disable_direct)
end
action :enable do
new_resource.updated_by_last_action(enable_direct)
end
private
def mountline
# generate the automount line
options = [
"-fstype=#{new_resource.fstype}", new_resource.options
].flatten.join ','
case new_resource.device_type
when :device
target = ":#{new_resource.device}"
when :uuid
target = ":UUID=#{new_resource.device}"
when :label
target = ":LABEL=#{new_resource.device}"
when :network
+ target = "#{new_resource.device}"
end
line = "#{new_resource.mount_point} #{options} #{target}"
line
end
def mount_status?
# Check to see if there is a entry in /etc/auto.direct. Last entry for a volume wins.
enabled = false
::File.foreach('/etc/auto.direct') do |line|
case line
when /^[#\s]/
next
when /^\s*#{Regexp.escape(mountline)}\s*/
return :enabled
when /^\s*#{Regexp.escape(new_resource.mount_point)}\s+/
Chef::Log.debug("Found conflicting mount point #{@new_resource.mount_point} in /etc/auto.direct")
return :conflict
end
end
if enabled
return :enabled
else
return :missing
end
end
# Returns true if changed, otherwise false.
def enable_direct
case mount_status?
when :enabled
Chef::Log.debug("#{new_resource} is already enabled - nothing to do")
when :missing, :conflict
if mount_status? == :conflict
Chef::Log.error("#{@new_resource} is conflicting with existing mount at #{@new_resource.mount_point}")
disable_direct
end
::File.open('/etc/auto.direct', 'a') do |fstab|
fstab.puts(mountline)
Chef::Log.debug("#{@new_resource} is enabled at #{@new_resource.mount_point}")
end
return true
else
return false
end
end
# Returns true if changed, otherwise false
def disable_direct
case mount_status?
when :enabled, :conflict
contents = []
found = false
::File.readlines('/etc/auto.direct').reverse_each do |line|
if !found && line =~ /^\s*#{Regexp.escape(new_resource.mount_point)}\s+/
found = true
Chef::Log.debug("#{@new_resource} is removed from fstab")
next
else
contents << line
end
end
::File.open('/etc/auto.direct', 'w') do |fstab|
contents.reverse_each { |line| fstab.puts line }
end
return true
else
Chef::Log.debug("#{@new_resource} is not enabled - nothing to do")
return false
end
end
|
use_inline_resources
action :create do
if new_resource.main_class && new_resource.jar
raise "You can specify a main_class or a jar file but not both."
end
unless new_resource.main_class || new_resource.jar
raise "You must specify main_class or jar"
end
template "#{node[:bluepill][:conf_dir]}/#{new_resource.service_name}.pill" do
source 'service.pill.erb'
cookbook 'java-service'
variables ({
:name => new_resource.service_name,
:java_command => java_command,
:user => new_resource.user
})
end
bluepill_service new_resource.service_name do
action [:enable, :load, :start]
end
end
def java_command
system_properties = new_resource.system_properties || node[new_resource.name]['java']['-D']
standard_options = new_resource.standard_options || node[new_resource.name]['java']['-']
non_standard_options = new_resource.non_standard_options || node[new_resource.name]['java']['-X']
hotspot_options = new_resource.hotspot_options || node[new_resource.name]['java']['-XX']
args = new_resource.args || node[new_resource.name]['java']['args']
JavaCommand.new(new_resource.main_class || new_resource.jar, {
:classpath => new_resource.classpath,
:system_properties => system_properties,
:standard_options => standard_options,
:non_standard_options => non_standard_options,
:hotspot_options => hotspot_options,
:args => args
})
end
fixing food critic violations in the provider
use_inline_resources
action :create do
if new_resource.main_class && new_resource.jar
raise 'You can specify a main_class or a jar file but not both.'
end
unless new_resource.main_class || new_resource.jar
raise 'You must specify main_class or jar'
end
template "#{node['bluepill']['conf_dir']}/#{new_resource.service_name}.pill" do
source 'service.pill.erb'
cookbook 'java-service'
variables ({
:name => new_resource.service_name,
:java_command => java_command,
:user => new_resource.user
})
end
bluepill_service new_resource.service_name do
action [:enable, :load, :start]
end
end
def java_command
system_properties = new_resource.system_properties || node[new_resource.name]['java']['-D']
standard_options = new_resource.standard_options || node[new_resource.name]['java']['-']
non_standard_options = new_resource.non_standard_options || node[new_resource.name]['java']['-X']
hotspot_options = new_resource.hotspot_options || node[new_resource.name]['java']['-XX']
args = new_resource.args || node[new_resource.name]['java']['args']
JavaCommand.new(new_resource.main_class || new_resource.jar, {
:classpath => new_resource.classpath,
:system_properties => system_properties,
:standard_options => standard_options,
:non_standard_options => non_standard_options,
:hotspot_options => hotspot_options,
:args => args
})
end |
#
# Author:: Seth Chisamore (<schisamo@opscode.com>)
# Cookbook Name:: windows
# Provider:: package
#
# Copyright:: 2011, Opscode, Inc.
#
# 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.
#
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require 'win32/registry'
end
require 'chef/mixin/shell_out'
require 'chef/mixin/language'
include Chef::Mixin::ShellOut
include Windows::Helper
# the logic in all action methods mirror that of
# the Chef::Provider::Package which will make
# refactoring into core chef easy
action :install do
# If we specified a version, and it's not the current version, move to the specified version
if @new_resource.version != nil && @new_resource.version != @current_resource.version
install_version = @new_resource.version
# If it's not installed at all, install it
elsif @current_resource.version == nil
install_version = candidate_version
end
if install_version
Chef::Log.info("Installing #{@new_resource} version #{install_version}")
status = install_package(@new_resource.package_name, install_version)
if status
@new_resource.updated_by_last_action(true)
end
end
end
action :upgrade do
if @current_resource.version != candidate_version
orig_version = @current_resource.version || "uninstalled"
Chef::Log.info("Upgrading #{@new_resource} version from #{orig_version} to #{candidate_version}")
status = upgrade_package(@new_resource.package_name, candidate_version)
if status
@new_resource.updated_by_last_action(true)
end
end
end
action :remove do
if removing_package?
Chef::Log.info("Removing #{@new_resource}")
remove_package(@current_resource.package_name, @new_resource.version)
@new_resource.updated_by_last_action(true)
else
end
end
def removing_package?
if @current_resource.version.nil?
false # nothing to remove
elsif @new_resource.version.nil?
true # remove any version of a package
elsif @new_resource.version == @current_resource.version
true # remove the version we have
else
false # we don't have the version we want to remove
end
end
def expand_options(options)
options ? " #{options}" : ""
end
# these methods are the required overrides of
# a provider that extends from Chef::Provider::Package
# so refactoring into core Chef should be easy
def load_current_resource
@current_resource = Chef::Resource::WindowsPackage.new(@new_resource.name)
@current_resource.package_name(@new_resource.package_name)
@current_resource.version(nil)
unless current_installed_version.nil?
@current_resource.version(current_installed_version)
end
@current_resource
end
def current_installed_version
@current_installed_version ||= begin
if installed_packages.include?(@new_resource.package_name)
installed_packages[@new_resource.package_name][:version]
end
end
end
def candidate_version
@candidate_version ||= begin
@new_resource.version || 'latest'
end
end
def install_package(name,version)
Chef::Log.debug("Processing #{@new_resource} as a #{installer_type} installer.")
install_args = [cached_file(@new_resource.source, @new_resource.checksum), expand_options(unattended_installation_flags), expand_options(@new_resource.options)]
Chef::Log.info("Starting installation...this could take awhile.")
Chef::Log.debug "Install command: #{ sprintf(install_command_template, *install_args) }"
shell_out!(sprintf(install_command_template, *install_args), {:timeout => @new_resource.timeout, :returns => @new_resource.success_codes})
end
def remove_package(name, version)
uninstall_string = installed_packages[@new_resource.package_name][:uninstall_string]
Chef::Log.info("Registry provided uninstall string for #{@new_resource} is '#{uninstall_string}'")
uninstall_command = begin
if uninstall_string =~ /msiexec/i
"#{uninstall_string} /qn"
else
uninstall_string.gsub!('"','')
"start \"\" /wait /d\"#{::File.dirname(uninstall_string)}\" #{::File.basename(uninstall_string)}#{expand_options(@new_resource.options)} /S"
end
end
Chef::Log.info("Removing #{@new_resource} with uninstall command '#{uninstall_command}'")
shell_out!(uninstall_command, {:returns => @new_resource.success_codes})
end
private
def install_command_template
case installer_type
when :msi
"msiexec%2$s \"%1$s\"%3$s"
else
"start \"\" /wait \"%1$s\"%2$s%3$s & exit %%%%ERRORLEVEL%%%%"
end
end
def uninstall_command_template
case installer_type
when :msi
"msiexec %2$s %1$s"
else
"start \"\" /wait /d%1$s %2$s %3$s"
end
end
# http://unattended.sourceforge.net/installers.php
def unattended_installation_flags
case installer_type
when :msi
# this is no-ui
"/qn /i"
when :installshield
"/s /sms"
when :nsis
"/S /NCRC"
when :inno
#"/sp- /silent /norestart"
"/verysilent /norestart"
when :wise
"/s"
else
end
end
def installed_packages
@installed_packages || begin
installed_packages = {}
# Computer\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE)) #rescue nil
# 64-bit registry view
# Computer\HKEY_LOCAL_MACHINE\Software\Wow6464Node\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE, (::Win32::Registry::Constants::KEY_READ | 0x0100))) #rescue nil
# 32-bit registry view
# Computer\HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE, (::Win32::Registry::Constants::KEY_READ | 0x0200))) #rescue nil
# Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_CURRENT_USER)) #rescue nil
installed_packages
end
end
def extract_installed_packages_from_key(hkey = ::Win32::Registry::HKEY_LOCAL_MACHINE, desired = ::Win32::Registry::Constants::KEY_READ)
uninstall_subkey = 'Software\Microsoft\Windows\CurrentVersion\Uninstall'
packages = {}
begin
::Win32::Registry.open(hkey, uninstall_subkey, desired) do |reg|
reg.each_key do |key, wtime|
begin
k = reg.open(key, desired)
display_name = k["DisplayName"] rescue nil
version = k["DisplayVersion"] rescue "NO VERSION"
uninstall_string = k["UninstallString"] rescue nil
if display_name
packages[display_name] = {:name => display_name,
:version => version,
:uninstall_string => uninstall_string}
end
rescue ::Win32::Registry::Error
end
end
end
rescue ::Win32::Registry::Error
end
packages
end
def installer_type
@installer_type || begin
if @new_resource.installer_type
@new_resource.installer_type
else
basename = ::File.basename(cached_file(@new_resource.source, @new_resource.checksum))
if basename.split(".").last.downcase == "msi" # Microsoft MSI
:msi
else
# search the binary file for installer type
contents = ::Kernel.open(::File.expand_path(cached_file(@new_resource.source)), "rb") {|io| io.read } # TODO limit data read in
case contents
when /inno/i # Inno Setup
:inno
when /wise/i # Wise InstallMaster
:wise
when /nsis/i # Nullsoft Scriptable Install System
:nsis
else
# if file is named 'setup.exe' assume installshield
if basename == "setup.exe"
:installshield
else
raise Chef::Exceptions::AttributeNotFound, "installer_type could not be determined, please set manually"
end
end
end
end
end
end
Making change to uninstall string to honor exit code.
#
# Author:: Seth Chisamore (<schisamo@opscode.com>)
# Cookbook Name:: windows
# Provider:: package
#
# Copyright:: 2011, Opscode, Inc.
#
# 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.
#
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require 'win32/registry'
end
require 'chef/mixin/shell_out'
require 'chef/mixin/language'
include Chef::Mixin::ShellOut
include Windows::Helper
# the logic in all action methods mirror that of
# the Chef::Provider::Package which will make
# refactoring into core chef easy
action :install do
# If we specified a version, and it's not the current version, move to the specified version
if @new_resource.version != nil && @new_resource.version != @current_resource.version
install_version = @new_resource.version
# If it's not installed at all, install it
elsif @current_resource.version == nil
install_version = candidate_version
end
if install_version
Chef::Log.info("Installing #{@new_resource} version #{install_version}")
status = install_package(@new_resource.package_name, install_version)
if status
@new_resource.updated_by_last_action(true)
end
end
end
action :upgrade do
if @current_resource.version != candidate_version
orig_version = @current_resource.version || "uninstalled"
Chef::Log.info("Upgrading #{@new_resource} version from #{orig_version} to #{candidate_version}")
status = upgrade_package(@new_resource.package_name, candidate_version)
if status
@new_resource.updated_by_last_action(true)
end
end
end
action :remove do
if removing_package?
Chef::Log.info("Removing #{@new_resource}")
remove_package(@current_resource.package_name, @new_resource.version)
@new_resource.updated_by_last_action(true)
else
end
end
def removing_package?
if @current_resource.version.nil?
false # nothing to remove
elsif @new_resource.version.nil?
true # remove any version of a package
elsif @new_resource.version == @current_resource.version
true # remove the version we have
else
false # we don't have the version we want to remove
end
end
def expand_options(options)
options ? " #{options}" : ""
end
# these methods are the required overrides of
# a provider that extends from Chef::Provider::Package
# so refactoring into core Chef should be easy
def load_current_resource
@current_resource = Chef::Resource::WindowsPackage.new(@new_resource.name)
@current_resource.package_name(@new_resource.package_name)
@current_resource.version(nil)
unless current_installed_version.nil?
@current_resource.version(current_installed_version)
end
@current_resource
end
def current_installed_version
@current_installed_version ||= begin
if installed_packages.include?(@new_resource.package_name)
installed_packages[@new_resource.package_name][:version]
end
end
end
def candidate_version
@candidate_version ||= begin
@new_resource.version || 'latest'
end
end
def install_package(name,version)
Chef::Log.debug("Processing #{@new_resource} as a #{installer_type} installer.")
install_args = [cached_file(@new_resource.source, @new_resource.checksum), expand_options(unattended_installation_flags), expand_options(@new_resource.options)]
Chef::Log.info("Starting installation...this could take awhile.")
Chef::Log.debug "Install command: #{ sprintf(install_command_template, *install_args) }"
shell_out!(sprintf(install_command_template, *install_args), {:timeout => @new_resource.timeout, :returns => @new_resource.success_codes})
end
def remove_package(name, version)
uninstall_string = installed_packages[@new_resource.package_name][:uninstall_string]
Chef::Log.info("Registry provided uninstall string for #{@new_resource} is '#{uninstall_string}'")
uninstall_command = begin
if uninstall_string =~ /msiexec/i
"#{uninstall_string} /qn"
else
uninstall_string.gsub!('"','')
"start \"\" /wait /d\"#{::File.dirname(uninstall_string)}\" #{::File.basename(uninstall_string)}#{expand_options(@new_resource.options)} /S & exit %%%%ERRORLEVEL%%%%"
end
end
Chef::Log.info("Removing #{@new_resource} with uninstall command '#{uninstall_command}'")
shell_out!(uninstall_command, {:returns => @new_resource.success_codes})
end
private
def install_command_template
case installer_type
when :msi
"msiexec%2$s \"%1$s\"%3$s"
else
"start \"\" /wait \"%1$s\"%2$s%3$s & exit %%%%ERRORLEVEL%%%%"
end
end
# http://unattended.sourceforge.net/installers.php
def unattended_installation_flags
case installer_type
when :msi
# this is no-ui
"/qn /i"
when :installshield
"/s /sms"
when :nsis
"/S /NCRC"
when :inno
#"/sp- /silent /norestart"
"/verysilent /norestart"
when :wise
"/s"
else
end
end
def installed_packages
@installed_packages || begin
installed_packages = {}
# Computer\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE)) #rescue nil
# 64-bit registry view
# Computer\HKEY_LOCAL_MACHINE\Software\Wow6464Node\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE, (::Win32::Registry::Constants::KEY_READ | 0x0100))) #rescue nil
# 32-bit registry view
# Computer\HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE, (::Win32::Registry::Constants::KEY_READ | 0x0200))) #rescue nil
# Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_CURRENT_USER)) #rescue nil
installed_packages
end
end
def extract_installed_packages_from_key(hkey = ::Win32::Registry::HKEY_LOCAL_MACHINE, desired = ::Win32::Registry::Constants::KEY_READ)
uninstall_subkey = 'Software\Microsoft\Windows\CurrentVersion\Uninstall'
packages = {}
begin
::Win32::Registry.open(hkey, uninstall_subkey, desired) do |reg|
reg.each_key do |key, wtime|
begin
k = reg.open(key, desired)
display_name = k["DisplayName"] rescue nil
version = k["DisplayVersion"] rescue "NO VERSION"
uninstall_string = k["UninstallString"] rescue nil
if display_name
packages[display_name] = {:name => display_name,
:version => version,
:uninstall_string => uninstall_string}
end
rescue ::Win32::Registry::Error
end
end
end
rescue ::Win32::Registry::Error
end
packages
end
def installer_type
@installer_type || begin
if @new_resource.installer_type
@new_resource.installer_type
else
basename = ::File.basename(cached_file(@new_resource.source, @new_resource.checksum))
if basename.split(".").last.downcase == "msi" # Microsoft MSI
:msi
else
# search the binary file for installer type
contents = ::Kernel.open(::File.expand_path(cached_file(@new_resource.source)), "rb") {|io| io.read } # TODO limit data read in
case contents
when /inno/i # Inno Setup
:inno
when /wise/i # Wise InstallMaster
:wise
when /nsis/i # Nullsoft Scriptable Install System
:nsis
else
# if file is named 'setup.exe' assume installshield
if basename == "setup.exe"
:installshield
else
raise Chef::Exceptions::AttributeNotFound, "installer_type could not be determined, please set manually"
end
end
end
end
end
end
|
#
# Cookbook Name:: newrelic
# Provider:: sysmond
#
# Author:: Kirill Kouznetsov <agon.smith@gmail.com>
#
# Copyright 2013, Kirill Kouznetsov
#
# 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.
#
action :install do
nr_repo = apt_repository "newrelic" do
distribution node['newrelic']['apt']['di
uri node['newrelic']['apt']['repo']stribution']
components node['newrelic']['apt']['components']
key node['newrelic']['apt']['keyfile']
end
nr_pack = package node['newrelic']['package_name']
if nr_repo.updated_by_last_action? or nr_pack.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
action :configure do
all_newrelic_res = run_context.resource_collection.all_resources.select do |resource|
resource.resource_name == new_resource.resource_name
end
bad_invocations = all_newrelic_res.select do |resource|
resource.key != all_newrelic_res.first.key
end.count
if bad_invocations > 0
Chef::Log.warn("Resource #{new_resource} was invoked with different license keys for #{bad_invocations+1} times. This can break your system configuration!!! Please, be careful!!!")
end
directory "/var/run/newrelic" do
owner "newrelic"
group "newrelic"
end
directory "/etc/newrelic" do
owner "root"
group "root"
mode 00755
action :create
end
nr_temp = template "/etc/newrelic/nrsysmond.cfg" do
source "nrsysmond.cfg.erb"
owner "root"
group "newrelic"
mode "640"
variables(
:license_key => new_resource.key
)
notifies :restart, "service[newrelic-sysmond]"
end
nr_serv = service "newrelic-sysmond" do
supports :status => true, :restart => true, :reload => true
action [ :enable, :start ]
end
if nr_temp.updated_by_last_action? or nr_serv.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
action :disable do
nr_serv = service "newrelic-sysmond" do
supports :status => true, :restart => true, :reload => true
action [ :disable, :stop ]
end
if nr_serv.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
action :uninstall do
nr_pack = package node['newrelic']['package_name'] do
action :uninstall
end
if nr_pack.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
# vim: ts=2 sts=2 sw=2 et sta
Fix misspelling in sysmond provider.
#
# Cookbook Name:: newrelic
# Provider:: sysmond
#
# Author:: Kirill Kouznetsov <agon.smith@gmail.com>
#
# Copyright 2013, Kirill Kouznetsov
#
# 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.
#
action :install do
nr_repo = apt_repository "newrelic" do
distribution node['newrelic']['apt']['distribution']
uri node['newrelic']['apt']['repo']
components node['newrelic']['apt']['components']
key node['newrelic']['apt']['keyfile']
end
nr_pack = package node['newrelic']['package_name']
if nr_repo.updated_by_last_action? or nr_pack.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
action :configure do
all_newrelic_res = run_context.resource_collection.all_resources.select do |resource|
resource.resource_name == new_resource.resource_name
end
bad_invocations = all_newrelic_res.select do |resource|
resource.key != all_newrelic_res.first.key
end.count
if bad_invocations > 0
Chef::Log.warn("Resource #{new_resource} was invoked with different license keys for #{bad_invocations+1} times. This can break your system configuration!!! Please, be careful!!!")
end
directory "/var/run/newrelic" do
owner "newrelic"
group "newrelic"
end
directory "/etc/newrelic" do
owner "root"
group "root"
mode 00755
action :create
end
nr_temp = template "/etc/newrelic/nrsysmond.cfg" do
source "nrsysmond.cfg.erb"
owner "root"
group "newrelic"
mode "640"
variables(
:license_key => new_resource.key
)
notifies :restart, "service[newrelic-sysmond]"
end
nr_serv = service "newrelic-sysmond" do
supports :status => true, :restart => true, :reload => true
action [ :enable, :start ]
end
if nr_temp.updated_by_last_action? or nr_serv.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
action :disable do
nr_serv = service "newrelic-sysmond" do
supports :status => true, :restart => true, :reload => true
action [ :disable, :stop ]
end
if nr_serv.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
action :uninstall do
nr_pack = package node['newrelic']['package_name'] do
action :uninstall
end
if nr_pack.updated_by_last_action?
new_resource.updated_by_last_action(true)
end
end
# vim: ts=2 sts=2 sw=2 et sta |
module Sidewalk
class UriMatch
attr_reader :parts, :parameters, :controller
def initialize parts = [], parameters = {}, controller = nil
unless parts.is_a?(Array) && parameters.is_a?(Hash)
raise ArgumentError.new(
'Sidewalk::UriMatch([parts], {parameters}, controller)'
)
end
@parts, @parameters, @controller = parts, parameters, controller
end
end
end
[ci skip] docs for UriMatch
module Sidewalk
# Information on a +URI+ +=>+ {Controller} match.
#
# These are generated by {UriMapper}.
class UriMatch
# The URL path, divided into regexp-matches.
#
# The URI map is a tree; this tells you what was matched at each level
# of the tree.
attr_reader :parts
# Any named captures from the match.
attr_reader :parameters
# What the URL maps to.
#
# This should be an instance of {Controller}, or a +Proc+.
attr_reader :controller
def initialize parts = [], parameters = {}, controller = nil
unless parts.is_a?(Array) && parameters.is_a?(Hash)
raise ArgumentError.new(
'Sidewalk::UriMatch([parts], {parameters}, controller)'
)
end
@parts, @parameters, @controller = parts, parameters, controller
end
end
end
|
module Similarweb
VERSION = "0.0.1"
end
version bump
module Similarweb
VERSION = "0.0.2"
end
|
require "simple_xlsx_reader/version"
require 'nokogiri'
require 'zip/zip'
require 'zip/zipfilesystem'
require 'date'
module SimpleXlsxReader
def self.open(file_path)
Document.new(file_path).to_hash
end
class Document
attr_reader :file_path
def initialize(file_path)
@file_path = file_path
end
def sheets
@sheets ||= Mapper.new(xml).load_sheets
end
def to_hash
sheets.inject({}) {|acc, sheet| acc[sheet.name] = sheet.rows; acc}
end
def xml
Xml.load(file_path)
end
class Xml
attr_accessor :workbook, :shared_strings, :sheets, :styles
def self.load(file_path)
self.new.tap do |xml|
Zip::ZipFile.open(file_path) do |zip|
xml.workbook = Nokogiri::XML(zip.read('xl/workbook.xml'))
xml.shared_strings = Nokogiri::XML(zip.read('xl/sharedStrings.xml'))
xml.styles = Nokogiri::XML(zip.read('xl/styles.xml'))
xml.sheets = []
i = 0
loop do
i += 1
break if !zip.file.file?("xl/worksheets/sheet#{i}.xml")
xml.sheets <<
Nokogiri::XML(zip.read("xl/worksheets/sheet#{i}.xml"))
end
end
end
end
end
class Mapper < Struct.new(:xml)
def load_sheets
sheet_toc.map do |(sheet_name, sheet_number)|
Sheet.new(sheet_name, rows_on_sheet(sheet_number))
end
end
# Table of contents for the sheets, ex. {'Authors' => 0, ...}
def sheet_toc
xml.workbook.xpath('/xmlns:workbook/xmlns:sheets/xmlns:sheet').
inject({}) do |acc, sheet|
acc[sheet.attributes['name'].value] =
sheet.attributes['sheetId'].value.to_i - 1 # keep things 0-indexed
acc
end
end
def rows_on_sheet(number)
xml.sheets[number].
xpath("/xmlns:worksheet/xmlns:sheetData/xmlns:row").map do |xrow|
xrow.children.map do |xcell|
type = xcell.attributes['t'] &&
xcell.attributes['t'].value
# If not the above, attempt to determine from a custom style
type ||= xcell.attributes['s'] &&
style_types[xcell.attributes['s'].value.to_i]
self.class.cast(xcell.text, type, shared_strings: shared_strings)
end
end
end
# Excel doesn't record types for some cells, only its display style, so
# we have to back out the type from that style.
#
# Some of these styles can be determined from a known set (see NumFmtMap),
# while others are 'custom' and we have to make a best guess.
#
# This is the array of types corresponding to the styles a spreadsheet
# uses, and includes both the known style types and the custom styles.
#
# Note that the xml sheet cells that use this don't reference the
# numFmtId, but instead the array index of a style in the stored list of
# only the styles used in the spreadsheet (which can be either known or
# custom). Hence this style types array, rather than a map of numFmtId to
# type.
def style_types
@style_types ||=
xml.styles.xpath('/xmlns:styleSheet/xmlns:cellXfs/xmlns:xf').map {|xstyle|
style_type_by_num_fmt_id(xstyle.attributes['numFmtId'].value)}
end
# Finds the type we think a style is; For example, fmtId 14 is a date
# style, so this would return :date
def style_type_by_num_fmt_id(id)
return nil if id.nil?
id = id.to_i
if id > 164 # custom style, arg!
custom_style_types[id]
else # we should know this one
NumFmtMap[id]
end
end
# Map of (numFmtId > 164) (custom styles) to our best guess at the type
# ex. {165 => :date_time}
def custom_style_types
@custom_style_types ||=
xml.styles.xpath('/xmlns:styleSheet/xmlns:numFmts/xmlns:numFmt').
inject({}) do |acc, xstyle|
acc[xstyle.attributes['numFmtId'].value.to_i] =
determine_custom_style_type(xstyle.attributes['formatCode'].value)
acc
end
end
# This is the least deterministic part of reading xlsx files. Due to
# custom styles, you can't know for sure when a date is a date other than
# looking at its format and gessing. It's not impossible to guess right,
# though.
#
# http://stackoverflow.com/questions/4948998/determining-if-an-xlsx-cell-is-date-formatted-for-excel-2007-spreadsheets
def determine_custom_style_type(string)
return :float if string[0] == '_'
return :float if string[0] == ' 0'
# Looks for one of ymdhis outside of meta-stuff like [Red]
return :date_time if string =~ /(^|\])[^\[]*[ymdhis]/i
return :unsupported
end
##
# The heart of typecasting. The ruby type is determined either explicitly
# from the cell xml or implicitly from the cell style, and this
# method expects that work to have been done already. This, then,
# takes the type we determined it to be and casts the cell value
# to that type.
#
# types:
# - s: shared string (see #shared_string)
# - n: number (cast to a float)
# - b: boolean
# - str: string
# - inlineStr: string
# - ruby symbol: for when type has been determined by style
#
# options:
# - shared_strings: needed for 's' (shared string) type
def self.cast(value, type, options = {})
return nil if value.nil? || value.empty?
case type
##
# There are few built-in types
##
when 's' # shared string
options[:shared_strings][value.to_i]
when 'n' # number
value.to_f
when 'b'
value.to_i == 1
when 'str'
value
when 'inlineStr'
value
##
# Type can also be determined by a style,
# detected earlier and cast here by its standardized symbol
##
when :string, :unsupported
value
when :fixnum
value.to_i
when :float
value.to_f
when :percentage
value.to_f / 100
# the trickiest. note that all these formats can vary on
# whether they actually contain a date, time, or datetime.
when :date, :time, :date_time
days_since_1900, fraction_of_24 = value.split('.')
# http://stackoverflow.com/questions/10559767/how-to-convert-ms-excel-date-from-float-to-date-format-in-ruby
date = Date.new(1899, 12, 30) + days_since_1900.to_i
if fraction_of_24 # there is a time associated
fraction_of_24 = "0.#{fraction_of_24}".to_f
military = fraction_of_24 * 24
hour = military.truncate
minute = ((military % 1) * 60).truncate
return Time.utc(date.year, date.month, date.day, hour, minute)
else
return date
end
when :bignum
if defined?(BigDecimal)
BigDecimal.new(value)
else
value.to_f
end
##
# Beats me
##
else
value
end
end
# Map of non-custom numFmtId to casting symbol
NumFmtMap = {
0 => :string, # General
1 => :fixnum, # 0
2 => :float, # 0.00
3 => :fixnum, # #,##0
4 => :float, # #,##0.00
5 => :unsupported, # $#,##0_);($#,##0)
6 => :unsupported, # $#,##0_);[Red]($#,##0)
7 => :unsupported, # $#,##0.00_);($#,##0.00)
8 => :unsupported, # $#,##0.00_);[Red]($#,##0.00)
9 => :percentage, # 0%
10 => :percentage, # 0.00%
11 => :bignum, # 0.00E+00
12 => :unsupported, # # ?/?
13 => :unsupported, # # ??/??
14 => :date, # mm-dd-yy
15 => :date, # d-mmm-yy
16 => :date, # d-mmm
17 => :date, # mmm-yy
18 => :time, # h:mm AM/PM
19 => :time, # h:mm:ss AM/PM
20 => :time, # h:mm
21 => :time, # h:mm:ss
22 => :date_time, # m/d/yy h:mm
37 => :unsupported, # #,##0 ;(#,##0)
38 => :unsupported, # #,##0 ;[Red](#,##0)
39 => :unsupported, # #,##0.00;(#,##0.00)
40 => :unsupported, # #,##0.00;[Red](#,##0.00)
45 => :time, # mm:ss
46 => :time, # [h]:mm:ss
47 => :time, # mmss.0
48 => :bignum, # ##0.0E+0
49 => :unsupported # @
}
# For performance reasons, excel uses an optional SpreadsheetML feature
# that puts all strings in a separate xml file, and then references
# them by their index in that file.
def shared_strings
@shared_strings ||= xml.shared_strings.
xpath('/xmlns:sst/xmlns:si/xmlns:t/text()').map(&:to_s)
end
end
class Sheet < Struct.new(:name, :rows)
def headers
rows[0]
end
def data
rows[1..-1]
end
def to_a
data
end
end
end
end
Make #open return a document rather than a hash
Since sheets can have load errors, and possibly other important
features, we should give them a document rather than a simple hash.
The advantage of using ::open now, other than functioning as a primary
interface, is that it will parse the file immediately, where
Document#new doesn't open the document until something tries to access
the sheets.
require "simple_xlsx_reader/version"
require 'nokogiri'
require 'zip/zip'
require 'zip/zipfilesystem'
require 'date'
module SimpleXlsxReader
def self.open(file_path)
Document.new(file_path).tap(&:sheets)
end
class Document
attr_reader :file_path
def initialize(file_path)
@file_path = file_path
end
def sheets
@sheets ||= Mapper.new(xml).load_sheets
end
def to_hash
sheets.inject({}) {|acc, sheet| acc[sheet.name] = sheet.rows; acc}
end
def xml
Xml.load(file_path)
end
class Xml
attr_accessor :workbook, :shared_strings, :sheets, :styles
def self.load(file_path)
self.new.tap do |xml|
Zip::ZipFile.open(file_path) do |zip|
xml.workbook = Nokogiri::XML(zip.read('xl/workbook.xml'))
xml.shared_strings = Nokogiri::XML(zip.read('xl/sharedStrings.xml'))
xml.styles = Nokogiri::XML(zip.read('xl/styles.xml'))
xml.sheets = []
i = 0
loop do
i += 1
break if !zip.file.file?("xl/worksheets/sheet#{i}.xml")
xml.sheets <<
Nokogiri::XML(zip.read("xl/worksheets/sheet#{i}.xml"))
end
end
end
end
end
class Mapper < Struct.new(:xml)
def load_sheets
sheet_toc.map do |(sheet_name, sheet_number)|
Sheet.new(sheet_name, rows_on_sheet(sheet_number))
end
end
# Table of contents for the sheets, ex. {'Authors' => 0, ...}
def sheet_toc
xml.workbook.xpath('/xmlns:workbook/xmlns:sheets/xmlns:sheet').
inject({}) do |acc, sheet|
acc[sheet.attributes['name'].value] =
sheet.attributes['sheetId'].value.to_i - 1 # keep things 0-indexed
acc
end
end
def rows_on_sheet(number)
xml.sheets[number].
xpath("/xmlns:worksheet/xmlns:sheetData/xmlns:row").map do |xrow|
xrow.children.map do |xcell|
type = xcell.attributes['t'] &&
xcell.attributes['t'].value
# If not the above, attempt to determine from a custom style
type ||= xcell.attributes['s'] &&
style_types[xcell.attributes['s'].value.to_i]
self.class.cast(xcell.text, type, shared_strings: shared_strings)
end
end
end
# Excel doesn't record types for some cells, only its display style, so
# we have to back out the type from that style.
#
# Some of these styles can be determined from a known set (see NumFmtMap),
# while others are 'custom' and we have to make a best guess.
#
# This is the array of types corresponding to the styles a spreadsheet
# uses, and includes both the known style types and the custom styles.
#
# Note that the xml sheet cells that use this don't reference the
# numFmtId, but instead the array index of a style in the stored list of
# only the styles used in the spreadsheet (which can be either known or
# custom). Hence this style types array, rather than a map of numFmtId to
# type.
def style_types
@style_types ||=
xml.styles.xpath('/xmlns:styleSheet/xmlns:cellXfs/xmlns:xf').map {|xstyle|
style_type_by_num_fmt_id(xstyle.attributes['numFmtId'].value)}
end
# Finds the type we think a style is; For example, fmtId 14 is a date
# style, so this would return :date
def style_type_by_num_fmt_id(id)
return nil if id.nil?
id = id.to_i
if id > 164 # custom style, arg!
custom_style_types[id]
else # we should know this one
NumFmtMap[id]
end
end
# Map of (numFmtId > 164) (custom styles) to our best guess at the type
# ex. {165 => :date_time}
def custom_style_types
@custom_style_types ||=
xml.styles.xpath('/xmlns:styleSheet/xmlns:numFmts/xmlns:numFmt').
inject({}) do |acc, xstyle|
acc[xstyle.attributes['numFmtId'].value.to_i] =
determine_custom_style_type(xstyle.attributes['formatCode'].value)
acc
end
end
# This is the least deterministic part of reading xlsx files. Due to
# custom styles, you can't know for sure when a date is a date other than
# looking at its format and gessing. It's not impossible to guess right,
# though.
#
# http://stackoverflow.com/questions/4948998/determining-if-an-xlsx-cell-is-date-formatted-for-excel-2007-spreadsheets
def determine_custom_style_type(string)
return :float if string[0] == '_'
return :float if string[0] == ' 0'
# Looks for one of ymdhis outside of meta-stuff like [Red]
return :date_time if string =~ /(^|\])[^\[]*[ymdhis]/i
return :unsupported
end
##
# The heart of typecasting. The ruby type is determined either explicitly
# from the cell xml or implicitly from the cell style, and this
# method expects that work to have been done already. This, then,
# takes the type we determined it to be and casts the cell value
# to that type.
#
# types:
# - s: shared string (see #shared_string)
# - n: number (cast to a float)
# - b: boolean
# - str: string
# - inlineStr: string
# - ruby symbol: for when type has been determined by style
#
# options:
# - shared_strings: needed for 's' (shared string) type
def self.cast(value, type, options = {})
return nil if value.nil? || value.empty?
case type
##
# There are few built-in types
##
when 's' # shared string
options[:shared_strings][value.to_i]
when 'n' # number
value.to_f
when 'b'
value.to_i == 1
when 'str'
value
when 'inlineStr'
value
##
# Type can also be determined by a style,
# detected earlier and cast here by its standardized symbol
##
when :string, :unsupported
value
when :fixnum
value.to_i
when :float
value.to_f
when :percentage
value.to_f / 100
# the trickiest. note that all these formats can vary on
# whether they actually contain a date, time, or datetime.
when :date, :time, :date_time
days_since_1900, fraction_of_24 = value.split('.')
# http://stackoverflow.com/questions/10559767/how-to-convert-ms-excel-date-from-float-to-date-format-in-ruby
date = Date.new(1899, 12, 30) + days_since_1900.to_i
if fraction_of_24 # there is a time associated
fraction_of_24 = "0.#{fraction_of_24}".to_f
military = fraction_of_24 * 24
hour = military.truncate
minute = ((military % 1) * 60).truncate
return Time.utc(date.year, date.month, date.day, hour, minute)
else
return date
end
when :bignum
if defined?(BigDecimal)
BigDecimal.new(value)
else
value.to_f
end
##
# Beats me
##
else
value
end
end
# Map of non-custom numFmtId to casting symbol
NumFmtMap = {
0 => :string, # General
1 => :fixnum, # 0
2 => :float, # 0.00
3 => :fixnum, # #,##0
4 => :float, # #,##0.00
5 => :unsupported, # $#,##0_);($#,##0)
6 => :unsupported, # $#,##0_);[Red]($#,##0)
7 => :unsupported, # $#,##0.00_);($#,##0.00)
8 => :unsupported, # $#,##0.00_);[Red]($#,##0.00)
9 => :percentage, # 0%
10 => :percentage, # 0.00%
11 => :bignum, # 0.00E+00
12 => :unsupported, # # ?/?
13 => :unsupported, # # ??/??
14 => :date, # mm-dd-yy
15 => :date, # d-mmm-yy
16 => :date, # d-mmm
17 => :date, # mmm-yy
18 => :time, # h:mm AM/PM
19 => :time, # h:mm:ss AM/PM
20 => :time, # h:mm
21 => :time, # h:mm:ss
22 => :date_time, # m/d/yy h:mm
37 => :unsupported, # #,##0 ;(#,##0)
38 => :unsupported, # #,##0 ;[Red](#,##0)
39 => :unsupported, # #,##0.00;(#,##0.00)
40 => :unsupported, # #,##0.00;[Red](#,##0.00)
45 => :time, # mm:ss
46 => :time, # [h]:mm:ss
47 => :time, # mmss.0
48 => :bignum, # ##0.0E+0
49 => :unsupported # @
}
# For performance reasons, excel uses an optional SpreadsheetML feature
# that puts all strings in a separate xml file, and then references
# them by their index in that file.
def shared_strings
@shared_strings ||= xml.shared_strings.
xpath('/xmlns:sst/xmlns:si/xmlns:t/text()').map(&:to_s)
end
end
class Sheet < Struct.new(:name, :rows)
def headers
rows[0]
end
def data
rows[1..-1]
end
def to_a
data
end
end
end
end
|
module Pacer
class BlockVertexFilterPipe < AbstractPipe
def initialize(back, block)
@back = back
@block = block
end
def processNextStart()
while s = starts.next
path = VertexFilterPath.new(s, back)
return s if yield path
end
end
end
class Path
include Enumerable
class << self
def vertex_path(name)
end
def edge_path(name)
end
def path(name)
end
end
def initialize(pipe, back = nil)
@back = back
@pipe = pipe
end
def back
@back
end
def root?
@back.nil?
end
def each
@pipe.to_enum(:each)
end
# bias is the chance the element will be returned from 0 to 1 (0% to 100%)
def random(bias = 0.5)
self.class.new(RandomFilterPipe.new(bias), self)
end
def uniq
self.class.new(DuplicateFilterPipe.new, self)
end
def [](prop_or_subset)
case prop_or_subset
when String, Symbol
# could use PropertyPipe but that would mean supporting objects that I don't think
# would have much purpose.
map do |element|
element[prop_or_subset]
end
when Fixnum
self.class.new(RangeFilterPipe.new(prop_or_subset, prop_or_subset), self)
when Range
end_index = prop_or_subset.end
end_index -= 1 if prop_or_subset.exclude_end?
self.class.new(RangeFilterPipe.new(prop_or_subset.begin, end_index), self)
when Array
end
end
protected
def filter_pipe(pipe, args_array, block)
return pipe if args_array.empty? and block.nil?
pipe = args_array.select { |arg| arg.is_a? Hash }.inject(pipe) do |p, hash|
hash.inject(p) do |p2, (key, value)|
new_pipe = PropertyFilterPipe.new(key.to_s, value.to_s, ComparisonFilterPipe::Filter::EQUAL)
new_pipe.set_start p2
new_pipe
end
end
if block
new_pipe = BlockFilterPipe.new(block)
new_pipe.set_start pipe
pipe = new_pipe
end
pipe
end
end
class GraphPath < Path
def vertexes(*args, &block)
pipe = GraphElementPipe.new(GraphElementPipe.ElementType.VERTEX);
VertexPath.new(filter_pipe(pipe, args, block), self)
end
def edges(*args, &block)
pipe = GraphElementPipe.new(GraphElementPipe.ElementType.EDGE);
EdgePath.new(filter_pipe(pipe, args, block), self)
end
end
class EdgePath < Path
def out_v(*args, &block)
pipe = VertexEdgePipe.new(VertexEdgePipe.Step.OUT_VERTEX)
VertexPath.new(filter_pipe(pipe, args, block), self)
end
def in_v(*args, &block)
pipe = VertexEdgePipe.new(VertexEdgePipe.Step.IN_VERTEX)
VertexPath.new(filter_pipe(pipe, args, block), self)
end
def both_v(*args, &block)
pipe = VertexEdgePipe.new(VertexEdgePipe.Step.BOTH_VERTICES)
VertexPath.new(filter_pipe(pipe, args, block), self)
end
protected
def filter_pipe(pipe, args_array, block)
labels = args_array.select { |arg| arg.is_a? Symbol or arg.is_a? String }
if labels.empty?
super
else
new_pipe = labels.inject(pipe) do |label|
p = LabelFilterPipe.new(label.to_s, ComparisonFilterPipe::Filter::EQUAL)
p.set_start pipe
p
end
super(new_pipe, args_array - labels, block)
end
end
end
class VertexPath < Path
def out_e(*args, &block)
pipe = EdgeVertexPipe.new(EdgeVertexPipe.Step.OUT_EDGES)
EdgePath.new(filter_pipe(pipe, args, block), self)
end
def in_e(*args, &block)
pipe = EdgeVertexPipe.new(EdgeVertexPipe.Step.IN_EDGES)
EdgePath.new(filter_pipe(pipe, args, block), self)
end
def both_e(*args, &block)
pipe = EdgeVertexPipe.new(EdgeVertexPipe.Step.BOTH_EDGES)
EdgePath.new(filter_pipe(pipe, args, block), self)
end
end
end
Set start for each pipe. It looks like pipes are not immutable so they need to be created later or paths will not be reusable.
module Pacer
class BlockVertexFilterPipe < AbstractPipe
def initialize(back, block)
@back = back
@block = block
end
def processNextStart()
while s = starts.next
path = VertexFilterPath.new(s, back)
return s if yield path
end
end
end
class SingleElementPipe < AbstractPipe
def initialize(element)
@element = element
end
def processNextStart()
element, @element = @element, nil
element
end
end
class Path
include Enumerable
class << self
def vertex_path(name)
end
def edge_path(name)
end
def path(name)
end
end
def initialize(pipe, back = nil)
@back = back
if pipe.is_a? Pipe
@pipe = pipe
else
end
end
def back
@back
end
def root?
@back.nil?
end
def each
@pipe.to_enum(:each)
end
# bias is the chance the element will be returned from 0 to 1 (0% to 100%)
def random(bias = 0.5)
self.class.new(RandomFilterPipe.new(bias), self)
end
def uniq
self.class.new(DuplicateFilterPipe.new, self)
end
def [](prop_or_subset)
case prop_or_subset
when String, Symbol
# could use PropertyPipe but that would mean supporting objects that I don't think
# would have much purpose.
map do |element|
element[prop_or_subset]
end
when Fixnum
self.class.new(RangeFilterPipe.new(prop_or_subset, prop_or_subset), self)
when Range
end_index = prop_or_subset.end
end_index -= 1 if prop_or_subset.exclude_end?
self.class.new(RangeFilterPipe.new(prop_or_subset.begin, end_index), self)
when Array
end
end
protected
def filter_pipe(pipe, args_array, block)
return pipe if args_array.empty? and block.nil?
pipe = args_array.select { |arg| arg.is_a? Hash }.inject(pipe) do |p, hash|
hash.inject(p) do |p2, (key, value)|
new_pipe = PropertyFilterPipe.new(key.to_s, value.to_s, ComparisonFilterPipe::Filter::EQUAL)
new_pipe.set_start p2
new_pipe
end
end
if block
new_pipe = BlockFilterPipe.new(block)
new_pipe.set_start pipe
pipe = new_pipe
end
pipe
end
end
class GraphPath < Path
def vertexes(*filters, &block)
pipe = GraphElementPipe.new(GraphElementPipe.ElementType.VERTEX);
VertexPath.new(filter_pipe(pipe, filters, block), self)
end
def edges(*filters, &block)
pipe = GraphElementPipe.new(GraphElementPipe.ElementType.EDGE);
EdgePath.new(filter_pipe(pipe, filters, block), self)
end
end
class EdgePath < Path
def out_v(*filters, &block)
pipe = VertexEdgePipe.new(VertexEdgePipe.Step.OUT_VERTEX)
pipe.set_start = @pipe
VertexPath.new(filter_pipe(pipe, filters, block), self)
end
def in_v(*filters, &block)
pipe = VertexEdgePipe.new(VertexEdgePipe.Step.IN_VERTEX)
pipe.set_start = @pipe
VertexPath.new(filter_pipe(pipe, filters, block), self)
end
def both_v(*filters, &block)
pipe = VertexEdgePipe.new(VertexEdgePipe.Step.BOTH_VERTICES)
pipe.set_start = @pipe
VertexPath.new(filter_pipe(pipe, filters, block), self)
end
def virtices(*filters)
raise "Can't call virtices for EdgePath."
end
def edges(*filters, &block)
EdgePath.new(filter_pipe(@pipe, filters, block), back)
end
protected
def filter_pipe(pipe, args_array, block)
labels = args_array.select { |arg| arg.is_a? Symbol or arg.is_a? String }
if labels.empty?
super
else
new_pipe = labels.inject(pipe) do |label|
p = LabelFilterPipe.new(label.to_s, ComparisonFilterPipe::Filter::EQUAL)
p.set_start pipe
p
end
super(new_pipe, args_array - labels, block)
end
end
end
class VertexPath < Path
def out_e(*filters, &block)
pipe = EdgeVertexPipe.new(EdgeVertexPipe.Step.OUT_EDGES)
pipe.set_start = @pipe
EdgePath.new(filter_pipe(pipe, filters, block), self)
end
def in_e(*filters, &block)
pipe = EdgeVertexPipe.new(EdgeVertexPipe.Step.IN_EDGES)
pipe.set_start = @pipe
EdgePath.new(filter_pipe(pipe, filters, block), self)
end
def both_e(*filters, &block)
pipe = EdgeVertexPipe.new(EdgeVertexPipe.Step.BOTH_EDGES)
pipe.set_start = @pipe
EdgePath.new(filter_pipe(pipe, filters, block), self)
end
def virtices(*filters, &block)
VertexPath.new(filter_pipe(@pipe, filters, block), back)
end
def edges(*filters, &block)
raise "Can't call edges for VertexPath."
end
end
end
|
# coding: utf-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_gateway'
s.version = '3.0.0.beta'
s.summary = 'Additional Payment Gateways for Spree Commerce'
s.description = s.summary
s.author = 'Spree Commerce'
s.email = 'gems@spreecommerce.com'
s.homepage = 'http://www.spreecommerce.com'
s.license = %q{BSD-3}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 3.0.0.beta'
s.add_development_dependency 'braintree'
s.add_development_dependency 'capybara'
s.add_development_dependency 'coffee-rails', '~> 4.0.0'
s.add_development_dependency 'database_cleaner', '1.2.0'
s.add_development_dependency 'factory_girl', '~> 4.4'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'guard-rspec'
s.add_development_dependency 'launchy'
s.add_development_dependency 'mysql2'
s.add_development_dependency 'pg'
s.add_development_dependency 'poltergeist', '~> 1.5.0'
s.add_development_dependency 'pry'
s.add_development_dependency 'rspec-activemodel-mocks'
s.add_development_dependency 'rspec-rails', '~> 2.99'
s.add_development_dependency 'sass-rails', '~> 4.0.2'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end
Bump spree for master branch.
# coding: utf-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'spree_gateway'
s.version = '3.0.0.beta'
s.summary = 'Additional Payment Gateways for Spree Commerce'
s.description = s.summary
s.author = 'Spree Commerce'
s.email = 'gems@spreecommerce.com'
s.homepage = 'http://www.spreecommerce.com'
s.license = %q{BSD-3}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'spree_core', '~> 3.1.0.beta'
s.add_development_dependency 'braintree'
s.add_development_dependency 'capybara'
s.add_development_dependency 'coffee-rails', '~> 4.0.0'
s.add_development_dependency 'database_cleaner', '1.2.0'
s.add_development_dependency 'factory_girl', '~> 4.4'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'guard-rspec'
s.add_development_dependency 'launchy'
s.add_development_dependency 'mysql2'
s.add_development_dependency 'pg'
s.add_development_dependency 'poltergeist', '~> 1.5.0'
s.add_development_dependency 'pry'
s.add_development_dependency 'rspec-activemodel-mocks'
s.add_development_dependency 'rspec-rails', '~> 2.99'
s.add_development_dependency 'sass-rails', '~> 4.0.2'
s.add_development_dependency 'selenium-webdriver'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'sqlite3'
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "devise_paypal/version"
Gem::Specification.new do |s|
s.name = "devise_paypal"
s.version = DevisePaypal::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["David Wilkie"]
s.email = ["dwilkie@gmail.com"]
s.homepage = "http://github.com/dwilkie/devise_paypal"
s.summary = %q{Signup or login using Paypal}
s.description = %q{Signup or login using Paypal's Authorization or Permissions api's}
s.rubyforge_project = "devise_paypal"
s.add_runtime_dependency "paypal-ipn", > "0.0.1"
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"]
end
Fixed bug in gemfile
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "devise_paypal/version"
Gem::Specification.new do |s|
s.name = "devise_paypal"
s.version = DevisePaypal::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["David Wilkie"]
s.email = ["dwilkie@gmail.com"]
s.homepage = "http://github.com/dwilkie/devise_paypal"
s.summary = %q{Signup or login using Paypal}
s.description = %q{Signup or login using Paypal's Authorization or Permissions api's}
s.rubyforge_project = "devise_paypal"
s.add_runtime_dependency "paypal-ipn", ">0.0.1"
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"]
end
|
require 'rubycas-client'
require 'sinatra/base'
require 'active_support/core_ext'
module Sinatra
module CAS
module Client
module Helpers
def authenticated?
if session[settings.username_session_key]
puts "User is already identified as #{session[settings.username_session_key]}" if settings.console_debugging
return true
end
end
def authenticate
puts "Running CAS filter for request #{request.fullpath}..." if settings.console_debugging
client = CASClient::Client.new(
cas_base_url: settings.cas_base_url,
force_ssl_verification: settings.verify_ssl
)
ticket = params[:ticket]
cas_login_url = client.add_service_to_login_url(settings.service_url)
if ticket
if ticket =~ /^PT-/
st = CASClient::ProxyTicket.new(ticket, settings.service_url, false)
puts "User has a ticket (proxy ticket)! #{st.inspect}" if settings.console_debugging
else
st = CASClient::ServiceTicket.new(ticket, settings.service_url, false)
puts "User has a ticket (service ticket)! #{st.inspect}" if settings.console_debugging
end
client.validate_service_ticket(st) unless st.has_been_validated?
if st.is_valid?
puts 'ticket is valid' if settings.console_debugging if settings.console_debugging
session[settings.username_session_key] = st.user
puts "user logged as #{session[settings.username_session_key]}" if settings.console_debugging
redirect settings.service_url
else
puts 'ticket is not valid' if settings.console_debugging
session[settings.username_session_key] = nil
redirect cas_login_url
end
else
puts 'No ticket, redirecting to login server' if settings.console_debugging
session[settings.username_session_key]
redirect cas_login_url
end
end
end
def self.registered(app)
app.helpers CAS::Client::Helpers
#TODO: setup defaults options
app.set :cas_base_url, 'https://login.example.com/cas'
app.set :service_url, 'https://localhost/'
app.set :verify_ssl, false
app.set :console_debugging, false
app.set :username_session_key, :cas_user
app.enable :sessions
end
end
end
register CAS::Client
end
check for session
require 'rubycas-client'
require 'sinatra/base'
require 'active_support/core_ext'
module Sinatra
module CAS
module Client
module Helpers
def authenticated?
if session[settings.username_session_key]
puts "User is already identified as #{session[settings.username_session_key]}" if settings.console_debugging
return true
end
end
def authenticate
puts "Running CAS filter for request #{request.fullpath}..." if settings.console_debugging
client = CASClient::Client.new(
cas_base_url: settings.cas_base_url,
force_ssl_verification: settings.verify_ssl
)
ticket = params[:ticket]
cas_login_url = client.add_service_to_login_url(settings.service_url)
if ticket
if ticket =~ /^PT-/
st = CASClient::ProxyTicket.new(ticket, settings.service_url, false)
puts "User has a ticket (proxy ticket)! #{st.inspect}" if settings.console_debugging
else
st = CASClient::ServiceTicket.new(ticket, settings.service_url, false)
puts "User has a ticket (service ticket)! #{st.inspect}" if settings.console_debugging
end
client.validate_service_ticket(st) unless st.has_been_validated?
if st.is_valid?
puts 'ticket is valid' if settings.console_debugging if settings.console_debugging
session[settings.username_session_key] = st.user
puts "user logged as #{session[settings.username_session_key]}" if settings.console_debugging
redirect settings.service_url
else
puts 'ticket is not valid' if settings.console_debugging
session[settings.username_session_key] = nil
redirect cas_login_url
end
else
puts 'No ticket, redirecting to login server' if settings.console_debugging
session[settings.username_session_key]
redirect cas_login_url
end
end
end
def self.registered(app)
app.helpers CAS::Client::Helpers
#TODO: setup defaults options
app.set :cas_base_url, 'https://login.example.com/cas'
app.set :service_url, 'https://localhost/'
app.set :verify_ssl, false
app.set :console_debugging, false
app.set :username_session_key, :cas_user
app.set :session_key, :rack.session
unless env.include?(options[:session_key]):
fail "you need to set up a session middleware *before* #{self.class}"
end
#app.enable :sessions
end
end
end
register CAS::Client
end
|
require 'nokogiri'
require 'psych'
module SippyCup
#
# A representation of a SippyCup scenario from a manifest or created in code. Allows building a scenario from a set of basic primitives, and then exporting to SIPp scenario files, including the XML scenario and PCAP audio.
#
class Scenario
USER_AGENT = "SIPp/sippy_cup"
VALID_DTMF = %w{0 1 2 3 4 5 6 7 8 9 0 * # A B C D}.freeze
MSEC = 1_000
#
# Build a scenario based on either a manifest string or a file handle. Manifests are supplied in YAML format.
# All manifest keys can be overridden by passing in a Hash of corresponding values.
#
# @param [String, File] manifest The YAML manifest
# @param [Hash] options Options to override (see #initialize)
#
# @return [SippyCup::Scenario]
#
# @example Parse a manifest string
# manifest = <<-MANIFEST
# source: 192.168.1.1
# destination: 192.168.1.2
# steps:
# - invite
# - wait_for_answer
# - ack_answer
# - sleep 3
# - wait_for_hangup
# MANIFEST
# Scenario.from_manifest(manifest)
#
# @example Parse a manifest file by path
# File.open("/my/manifest.yml") { |f| Scenario.from_manifest(f) }
# # or
# Scenario.from_manifest(File.read("/my/manifest.yml"))
#
# @example Override keys from the manifest
# Scenario.from_manifest(manifest, source: '192.168.12.1')
#
def self.from_manifest(manifest, options = {})
args = ActiveSupport::HashWithIndifferentAccess.new(Psych.safe_load(manifest)).symbolize_keys.merge options
name = args.delete :name
steps = args.delete :steps
scenario = Scenario.new name, args
scenario.build steps
scenario
end
# @return [Hash] The options the scenario was created with, either from a manifest or passed as overrides
attr_reader :scenario_options
# @return [Array<Hash>] a collection of errors encountered while building the scenario.
attr_reader :errors
#
# Create a scenario instance
#
# @param [String] name The scenario's name
# @param [Hash] args options to customise the scenario
# @option options [String] :filename The name of the files to be saved to disk
# @option options [String] :source The source IP/hostname with which to invoke SIPp
# @option options [String] :destination The target system at which to direct traffic
# @option options [String] :from_user The SIP user from which traffic should appear
# @option options [Integer] :rtcp_port The RTCP (media) port to bind to locally
# @option options [Array<String>] :steps A collection of steps
#
# @yield [scenario] Builder block to construct scenario
# @yieldparam [Scenario] scenario the initialized scenario instance
#
def initialize(name, args = {}, &block)
parse_args args
@scenario_options = args.merge name: name
@rtcp_port = args[:rtcp_port]
@filename = args[:filename] || name.downcase.gsub(/\W+/, '_')
@filename = File.expand_path @filename, Dir.pwd
@media = Media.new '127.0.0.255', 55555, '127.255.255.255', 5060
@errors = []
instance_eval &block if block_given?
end
# @return [true, false] the validity of the scenario. Will be false if errors were encountered while building the scenario from a manifest
def valid?
@errors.size.zero?
end
#
# Build the scenario steps provided
#
# @param [Array<String>] steps A collection of steps to build the scenario
#
def build(steps)
raise ArgumentError, "Must provide scenario steps" unless steps
steps.each_with_index do |step, index|
begin
instruction, arg = step.split ' ', 2
if arg && !arg.empty?
# Strip leading/trailing quotes if present
arg.gsub!(/^'|^"|'$|"$/, '')
self.__send__ instruction, arg
else
self.__send__ instruction
end
rescue => e
@errors << {step: index + 1, message: "#{step}: #{e.message}"}
end
end
end
#
# Send an invite message
#
# Uses the :rtcp_port option the Scenario was created with to specify RTCP ports in SDP, or defaults to dynamic binding
#
# @param [Hash] opts A set of options to modify the message
# @option opts [Integer] :retrans
# @option opts [String] :headers Extra headers to place into the INVITE
def invite(opts = {})
opts[:retrans] ||= 500
rtp_string = @rtcp_port ? "m=audio #{@rtcp_port.to_i - 1} RTP/AVP 0 101\na=rtcp:#{@rtcp_port}\n" : "m=audio [media_port] RTP/AVP 0 101\n"
headers = opts.delete :headers
rtp_string = @rtcp_port ? "m=audio #{@rtcp_port.to_i - 1} RTP/AVP 0 101\na=rtcp:#{@rtcp_port}\n" : "m=audio [media_port] RTP/AVP 0 101\n"
# FIXME: The DTMF mapping (101) is hard-coded. It would be better if we could
# get this from the DTMF payload generator
msg = <<-INVITE
INVITE sip:[service]@[remote_ip]:[remote_port] SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: "#{@from_user}" <sip:#{@from_user}@[local_ip]>;tag=[call_number]
To: <sip:[service]@[remote_ip]:[remote_port]>
Call-ID: [call_id]
CSeq: [cseq] INVITE
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Type: application/sdp
Content-Length: [len]
#{headers}
v=0
o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip]
s=-
c=IN IP[media_ip_type] [media_ip]
t=0 0
#{rtp_string}
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
INVITE
send msg, opts
end
#
# Send a REGISTER message with the specified credentials
#
# @param [String] user the user to register as. May be given as a full SIP URI (sip:user@domain.com), in email-address format (user@domain.com) or as a simple username ('user'). If no domain is supplied, the source IP from SIPp will be used.
# @param [optional, String, nil] password the password to authenticate with.
# @param [Hash] opts A set of options to modify the message
#
# @example Register with authentication
# s.register 'frank@there.com', 'abc123'
#
# @example Register without authentication or a domain
# s.register 'frank'
#
def register(user, password = nil, opts = {})
opts[:retrans] ||= 500
user, domain = parse_user user
msg = if password
register_auth domain, user, password
else
register_message domain, user
end
send msg, opts
end
#
# Sets an expectation for a SIP 100 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_trying(opts = {})
handle_response 100, opts
end
alias :receive_100 :receive_trying
#
# Sets an expectation for a SIP 180 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_ringing(opts = {})
handle_response 180, opts
end
alias :receive_180 :receive_ringing
#
# Sets an expectation for a SIP 183 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_progress(opts = {})
handle_response 183, opts
end
alias :receive_183 :receive_progress
#
# Sets an expectation for a SIP 200 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_answer(opts = {})
options = {
response: 200,
rrs: true, # Record Record Set: Make the Route headers available via [route] later
rtd: true # Response Time Duration: Record the response time
}
recv options.merge(opts)
end
alias :receive_200 :receive_answer
#
# Shortcut that sets expectations for optional SIP 100, 180 and 183, followed by a required 200.
#
# @param [Hash] opts A set of options to modify the expectations
#
def wait_for_answer(opts = {})
receive_trying({optional: true}.merge opts)
receive_ringing({optional: true}.merge opts)
receive_progress({optional: true}.merge opts)
receive_answer opts
end
#
# Acknowledge a received answer message (SIP 200) and start media playback
#
# @param [Hash] opts A set of options to modify the message parameters
#
def ack_answer(opts = {})
msg = <<-BODY
ACK [next_url] SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: "#{@from_user}" <sip:#{@from_user}@[local_ip]>;tag=[call_number]
[last_To:]
Call-ID: [call_id]
CSeq: [cseq] ACK
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Length: 0
[routes]
BODY
send msg, opts
start_media
end
#
# Insert a pause into the scenario and its media of the specified duration
#
# @param [Numeric] seconds The duration of the pause in seconds
#
def sleep(seconds)
milliseconds = (seconds.to_f * MSEC).to_i
pause milliseconds
@media << "silence:#{milliseconds}"
end
#
# Send DTMF digits
#
# @param [String] DTMF digits to send. Must be 0-9, *, # or A-D
#
# @example Send a single DTMF digit
# send_digits '1'
#
# @example Enter a pin number
# send_digits '1234'
#
def send_digits(digits)
delay = (0.250 * MSEC).to_i # FIXME: Need to pass this down to the media layer
digits.split('').each do |digit|
raise ArgumentError, "Invalid DTMF digit requested: #{digit}" unless VALID_DTMF.include? digit
@media << "dtmf:#{digit}"
@media << "silence:#{delay}"
end
pause delay * 2 * digits.size
end
#
# Send a BYE message
#
# @param [Hash] opts A set of options to modify the message parameters
#
def send_bye(opts = {})
msg = <<-MSG
BYE [next_url] SIP/2.0
[last_Via:]
From: "#{@from_user}" <sip:#{@from_user}@[local_ip]>;tag=[call_number]
[last_To:]
[last_Call-ID]
CSeq: [cseq] BYE
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Length: 0
[routes]
MSG
send msg, opts
end
#
# Expect to receive a BYE message
#
# @param [Hash] opts A set of options to modify the expectation
#
def receive_bye(opts = {})
recv opts.merge request: 'BYE'
end
#
# Acknowledge a received BYE message
#
# @param [Hash] opts A set of options to modify the message parameters
#
def ack_bye(opts = {})
msg = <<-ACK
SIP/2.0 200 OK
[last_Via:]
[last_From:]
[last_To:]
[last_Call-ID:]
[last_CSeq:]
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Length: 0
[routes]
ACK
send msg, opts
end
#
# Shortcut to set an expectation for a BYE and acknowledge it when received
#
# @param [Hash] opts A set of options to modify the expectation
#
def wait_for_hangup(opts = {})
receive_bye(opts)
ack_bye(opts)
end
#
# Dump the scenario to a SIPp XML string
#
# @return [String] the SIPp XML scenario
def to_xml
doc.to_xml
end
#
# Compile the scenario and its media to disk
#
# Writes the SIPp scenario file to disk at {filename}.xml, and the PCAP media to {filename}.pcap.
# {filename} is taken from the :filename option when creating the scenario, or falls back to a down-snake-cased version of the scenario name.
#
# @example Export a scenario to a specified filename
# scenario = Scenario.new 'Test Scenario', filename: 'my_scenario'
# scenario.compile! # Leaves files at my_scenario.xml and my_scenario.pcap
#
# @example Export a scenario to a calculated filename
# scenario = Scenario.new 'Test Scenario'
# scenario.compile! # Leaves files at test_scenario.xml and test_scenario.pcap
#
def compile!
print "Compiling scenario to #{@filename}.xml..."
File.open "#{@filename}.xml", 'w' do |file|
file.write doc.to_xml
end
puts "done."
print "Compiling media to #{@filename}.pcap..."
compile_media.to_file filename: "#{@filename}.pcap"
puts "done."
end
private
#TODO: SIPS support?
def parse_user(user)
user.slice! 0, 4 if user =~ /sip:/
user = user.split(":")[0]
user, domain = user.split("@")
domain ||= "[remote_ip]"
[user, domain]
end
def doc
@doc ||= begin
Nokogiri::XML::Builder.new do |xml|
xml.scenario name: @scenario_options[:name]
end.doc
end
end
def scenario_node
@scenario_node = doc.xpath('//scenario').first
end
def parse_args(args)
raise ArgumentError, "Must include source IP:PORT" unless args.keys.include? :source
raise ArgumentError, "Must include destination IP:PORT" unless args.keys.include? :destination
@from_addr, @from_port = args[:source].split ':'
@to_addr, @to_port = args[:destination].split ':'
@from_user = args[:from_user] || "sipp"
end
def compile_media
@media.compile!
end
def register_message(domain, user, opts = {})
<<-BODY
REGISTER sip:#{domain} SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: <sip:#{user}@#{domain}>;tag=[call_number]
To: <sip:#{user}@#{domain}>
Call-ID: [call_id]
CSeq: [cseq] REGISTER
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 10
Expires: 120
User-Agent: #{USER_AGENT}
Content-Length: 0
BODY
end
def register_auth(domain, user, password, opts = {})
recv response: '401', auth: true, optional: false
<<-AUTH
REGISTER sip:#{domain} SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: <sip:#{user}@#{domain}>;tag=[call_number]
To: <sip:#{user}@#{domain}>
Call-ID: [call_id]
CSeq: [cseq] REGISTER
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 20
Expires: 3600
[authentication username=#{user} password=#{password}]
User-Agent: #{USER_AGENT}
Content-Length: 0
AUTH
end
def start_media
nop = Nokogiri::XML::Node.new 'nop', doc
action = Nokogiri::XML::Node.new 'action', doc
nop << action
exec = Nokogiri::XML::Node.new 'exec', doc
exec['play_pcap_audio'] = "#{@filename}.pcap"
action << exec
scenario_node << nop
end
def pause(msec)
pause = Nokogiri::XML::Node.new 'pause', doc
pause['milliseconds'] = msec.to_i
scenario_node << pause
end
def send(msg, opts = {})
send = Nokogiri::XML::Node.new 'send', doc
opts.each do |k,v|
send[k.to_s] = v
end
send << "\n"
send << Nokogiri::XML::CDATA.new(doc, msg)
send << "\n" #Newlines are required before and after CDATA so SIPp will parse properly
scenario_node << send
end
def recv(opts = {})
raise ArgumentError, "Receive must include either a response or a request" unless opts.keys.include?(:response) || opts.keys.include?(:request)
recv = Nokogiri::XML::Node.new 'recv', doc
opts.each do |k,v|
recv[k.to_s] = v
end
scenario_node << recv
end
def optional_recv(opts)
opts[:optional] = true if opts[:optional].nil?
recv opts
end
def handle_response(code, opts)
optional_recv opts.merge(response: code)
end
end
end
Fix duplicate line and doc newline issue
require 'nokogiri'
require 'psych'
module SippyCup
#
# A representation of a SippyCup scenario from a manifest or created in code. Allows building a scenario from a set of basic primitives, and then exporting to SIPp scenario files, including the XML scenario and PCAP audio.
#
class Scenario
USER_AGENT = "SIPp/sippy_cup"
VALID_DTMF = %w{0 1 2 3 4 5 6 7 8 9 0 * # A B C D}.freeze
MSEC = 1_000
#
# Build a scenario based on either a manifest string or a file handle. Manifests are supplied in YAML format.
# All manifest keys can be overridden by passing in a Hash of corresponding values.
#
# @param [String, File] manifest The YAML manifest
# @param [Hash] options Options to override (see #initialize)
#
# @return [SippyCup::Scenario]
#
# @example Parse a manifest string
# manifest = <<-MANIFEST
# source: 192.168.1.1
# destination: 192.168.1.2
# steps:
# - invite
# - wait_for_answer
# - ack_answer
# - sleep 3
# - wait_for_hangup
# MANIFEST
# Scenario.from_manifest(manifest)
#
# @example Parse a manifest file by path
# File.open("/my/manifest.yml") { |f| Scenario.from_manifest(f) }
# # or
# Scenario.from_manifest(File.read("/my/manifest.yml"))
#
# @example Override keys from the manifest
# Scenario.from_manifest(manifest, source: '192.168.12.1')
#
def self.from_manifest(manifest, options = {})
args = ActiveSupport::HashWithIndifferentAccess.new(Psych.safe_load(manifest)).symbolize_keys.merge options
name = args.delete :name
steps = args.delete :steps
scenario = Scenario.new name, args
scenario.build steps
scenario
end
# @return [Hash] The options the scenario was created with, either from a manifest or passed as overrides
attr_reader :scenario_options
# @return [Array<Hash>] a collection of errors encountered while building the scenario.
attr_reader :errors
#
# Create a scenario instance
#
# @param [String] name The scenario's name
# @param [Hash] args options to customise the scenario
# @option options [String] :filename The name of the files to be saved to disk
# @option options [String] :source The source IP/hostname with which to invoke SIPp
# @option options [String] :destination The target system at which to direct traffic
# @option options [String] :from_user The SIP user from which traffic should appear
# @option options [Integer] :rtcp_port The RTCP (media) port to bind to locally
# @option options [Array<String>] :steps A collection of steps
#
# @yield [scenario] Builder block to construct scenario
# @yieldparam [Scenario] scenario the initialized scenario instance
#
def initialize(name, args = {}, &block)
parse_args args
@scenario_options = args.merge name: name
@rtcp_port = args[:rtcp_port]
@filename = args[:filename] || name.downcase.gsub(/\W+/, '_')
@filename = File.expand_path @filename, Dir.pwd
@media = Media.new '127.0.0.255', 55555, '127.255.255.255', 5060
@errors = []
instance_eval &block if block_given?
end
# @return [true, false] the validity of the scenario. Will be false if errors were encountered while building the scenario from a manifest
def valid?
@errors.size.zero?
end
#
# Build the scenario steps provided
#
# @param [Array<String>] steps A collection of steps to build the scenario
#
def build(steps)
raise ArgumentError, "Must provide scenario steps" unless steps
steps.each_with_index do |step, index|
begin
instruction, arg = step.split ' ', 2
if arg && !arg.empty?
# Strip leading/trailing quotes if present
arg.gsub!(/^'|^"|'$|"$/, '')
self.__send__ instruction, arg
else
self.__send__ instruction
end
rescue => e
@errors << {step: index + 1, message: "#{step}: #{e.message}"}
end
end
end
#
# Send an invite message
#
# Uses the :rtcp_port option the Scenario was created with to specify RTCP ports in SDP, or defaults to dynamic binding
#
# @param [Hash] opts A set of options to modify the message
# @option opts [Integer] :retrans
# @option opts [String] :headers Extra headers to place into the INVITE
#
def invite(opts = {})
opts[:retrans] ||= 500
rtp_string = @rtcp_port ? "m=audio #{@rtcp_port.to_i - 1} RTP/AVP 0 101\na=rtcp:#{@rtcp_port}\n" : "m=audio [media_port] RTP/AVP 0 101\n"
headers = opts.delete :headers
# FIXME: The DTMF mapping (101) is hard-coded. It would be better if we could
# get this from the DTMF payload generator
msg = <<-INVITE
INVITE sip:[service]@[remote_ip]:[remote_port] SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: "#{@from_user}" <sip:#{@from_user}@[local_ip]>;tag=[call_number]
To: <sip:[service]@[remote_ip]:[remote_port]>
Call-ID: [call_id]
CSeq: [cseq] INVITE
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Type: application/sdp
Content-Length: [len]
#{headers}
v=0
o=user1 53655765 2353687637 IN IP[local_ip_type] [local_ip]
s=-
c=IN IP[media_ip_type] [media_ip]
t=0 0
#{rtp_string}
a=rtpmap:0 PCMU/8000
a=rtpmap:101 telephone-event/8000
a=fmtp:101 0-15
INVITE
send msg, opts
end
#
# Send a REGISTER message with the specified credentials
#
# @param [String] user the user to register as. May be given as a full SIP URI (sip:user@domain.com), in email-address format (user@domain.com) or as a simple username ('user'). If no domain is supplied, the source IP from SIPp will be used.
# @param [optional, String, nil] password the password to authenticate with.
# @param [Hash] opts A set of options to modify the message
#
# @example Register with authentication
# s.register 'frank@there.com', 'abc123'
#
# @example Register without authentication or a domain
# s.register 'frank'
#
def register(user, password = nil, opts = {})
opts[:retrans] ||= 500
user, domain = parse_user user
msg = if password
register_auth domain, user, password
else
register_message domain, user
end
send msg, opts
end
#
# Sets an expectation for a SIP 100 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_trying(opts = {})
handle_response 100, opts
end
alias :receive_100 :receive_trying
#
# Sets an expectation for a SIP 180 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_ringing(opts = {})
handle_response 180, opts
end
alias :receive_180 :receive_ringing
#
# Sets an expectation for a SIP 183 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_progress(opts = {})
handle_response 183, opts
end
alias :receive_183 :receive_progress
#
# Sets an expectation for a SIP 200 message from the remote party
#
# @param [Hash] opts A set of options to modify the expectation
# @option opts [true, false] :optional Wether or not receipt of the message is optional. Defaults to true.
#
def receive_answer(opts = {})
options = {
response: 200,
rrs: true, # Record Record Set: Make the Route headers available via [route] later
rtd: true # Response Time Duration: Record the response time
}
recv options.merge(opts)
end
alias :receive_200 :receive_answer
#
# Shortcut that sets expectations for optional SIP 100, 180 and 183, followed by a required 200.
#
# @param [Hash] opts A set of options to modify the expectations
#
def wait_for_answer(opts = {})
receive_trying({optional: true}.merge opts)
receive_ringing({optional: true}.merge opts)
receive_progress({optional: true}.merge opts)
receive_answer opts
end
#
# Acknowledge a received answer message (SIP 200) and start media playback
#
# @param [Hash] opts A set of options to modify the message parameters
#
def ack_answer(opts = {})
msg = <<-BODY
ACK [next_url] SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: "#{@from_user}" <sip:#{@from_user}@[local_ip]>;tag=[call_number]
[last_To:]
Call-ID: [call_id]
CSeq: [cseq] ACK
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Length: 0
[routes]
BODY
send msg, opts
start_media
end
#
# Insert a pause into the scenario and its media of the specified duration
#
# @param [Numeric] seconds The duration of the pause in seconds
#
def sleep(seconds)
milliseconds = (seconds.to_f * MSEC).to_i
pause milliseconds
@media << "silence:#{milliseconds}"
end
#
# Send DTMF digits
#
# @param [String] DTMF digits to send. Must be 0-9, *, # or A-D
#
# @example Send a single DTMF digit
# send_digits '1'
#
# @example Enter a pin number
# send_digits '1234'
#
def send_digits(digits)
delay = (0.250 * MSEC).to_i # FIXME: Need to pass this down to the media layer
digits.split('').each do |digit|
raise ArgumentError, "Invalid DTMF digit requested: #{digit}" unless VALID_DTMF.include? digit
@media << "dtmf:#{digit}"
@media << "silence:#{delay}"
end
pause delay * 2 * digits.size
end
#
# Send a BYE message
#
# @param [Hash] opts A set of options to modify the message parameters
#
def send_bye(opts = {})
msg = <<-MSG
BYE [next_url] SIP/2.0
[last_Via:]
From: "#{@from_user}" <sip:#{@from_user}@[local_ip]>;tag=[call_number]
[last_To:]
[last_Call-ID]
CSeq: [cseq] BYE
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Length: 0
[routes]
MSG
send msg, opts
end
#
# Expect to receive a BYE message
#
# @param [Hash] opts A set of options to modify the expectation
#
def receive_bye(opts = {})
recv opts.merge request: 'BYE'
end
#
# Acknowledge a received BYE message
#
# @param [Hash] opts A set of options to modify the message parameters
#
def ack_bye(opts = {})
msg = <<-ACK
SIP/2.0 200 OK
[last_Via:]
[last_From:]
[last_To:]
[last_Call-ID:]
[last_CSeq:]
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 100
User-Agent: #{USER_AGENT}
Content-Length: 0
[routes]
ACK
send msg, opts
end
#
# Shortcut to set an expectation for a BYE and acknowledge it when received
#
# @param [Hash] opts A set of options to modify the expectation
#
def wait_for_hangup(opts = {})
receive_bye(opts)
ack_bye(opts)
end
#
# Dump the scenario to a SIPp XML string
#
# @return [String] the SIPp XML scenario
def to_xml
doc.to_xml
end
#
# Compile the scenario and its media to disk
#
# Writes the SIPp scenario file to disk at {filename}.xml, and the PCAP media to {filename}.pcap.
# {filename} is taken from the :filename option when creating the scenario, or falls back to a down-snake-cased version of the scenario name.
#
# @example Export a scenario to a specified filename
# scenario = Scenario.new 'Test Scenario', filename: 'my_scenario'
# scenario.compile! # Leaves files at my_scenario.xml and my_scenario.pcap
#
# @example Export a scenario to a calculated filename
# scenario = Scenario.new 'Test Scenario'
# scenario.compile! # Leaves files at test_scenario.xml and test_scenario.pcap
#
def compile!
print "Compiling scenario to #{@filename}.xml..."
File.open "#{@filename}.xml", 'w' do |file|
file.write doc.to_xml
end
puts "done."
print "Compiling media to #{@filename}.pcap..."
compile_media.to_file filename: "#{@filename}.pcap"
puts "done."
end
private
#TODO: SIPS support?
def parse_user(user)
user.slice! 0, 4 if user =~ /sip:/
user = user.split(":")[0]
user, domain = user.split("@")
domain ||= "[remote_ip]"
[user, domain]
end
def doc
@doc ||= begin
Nokogiri::XML::Builder.new do |xml|
xml.scenario name: @scenario_options[:name]
end.doc
end
end
def scenario_node
@scenario_node = doc.xpath('//scenario').first
end
def parse_args(args)
raise ArgumentError, "Must include source IP:PORT" unless args.keys.include? :source
raise ArgumentError, "Must include destination IP:PORT" unless args.keys.include? :destination
@from_addr, @from_port = args[:source].split ':'
@to_addr, @to_port = args[:destination].split ':'
@from_user = args[:from_user] || "sipp"
end
def compile_media
@media.compile!
end
def register_message(domain, user, opts = {})
<<-BODY
REGISTER sip:#{domain} SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: <sip:#{user}@#{domain}>;tag=[call_number]
To: <sip:#{user}@#{domain}>
Call-ID: [call_id]
CSeq: [cseq] REGISTER
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 10
Expires: 120
User-Agent: #{USER_AGENT}
Content-Length: 0
BODY
end
def register_auth(domain, user, password, opts = {})
recv response: '401', auth: true, optional: false
<<-AUTH
REGISTER sip:#{domain} SIP/2.0
Via: SIP/2.0/[transport] [local_ip]:[local_port];branch=[branch]
From: <sip:#{user}@#{domain}>;tag=[call_number]
To: <sip:#{user}@#{domain}>
Call-ID: [call_id]
CSeq: [cseq] REGISTER
Contact: <sip:#{@from_user}@[local_ip]:[local_port];transport=[transport]>
Max-Forwards: 20
Expires: 3600
[authentication username=#{user} password=#{password}]
User-Agent: #{USER_AGENT}
Content-Length: 0
AUTH
end
def start_media
nop = Nokogiri::XML::Node.new 'nop', doc
action = Nokogiri::XML::Node.new 'action', doc
nop << action
exec = Nokogiri::XML::Node.new 'exec', doc
exec['play_pcap_audio'] = "#{@filename}.pcap"
action << exec
scenario_node << nop
end
def pause(msec)
pause = Nokogiri::XML::Node.new 'pause', doc
pause['milliseconds'] = msec.to_i
scenario_node << pause
end
def send(msg, opts = {})
send = Nokogiri::XML::Node.new 'send', doc
opts.each do |k,v|
send[k.to_s] = v
end
send << "\n"
send << Nokogiri::XML::CDATA.new(doc, msg)
send << "\n" #Newlines are required before and after CDATA so SIPp will parse properly
scenario_node << send
end
def recv(opts = {})
raise ArgumentError, "Receive must include either a response or a request" unless opts.keys.include?(:response) || opts.keys.include?(:request)
recv = Nokogiri::XML::Node.new 'recv', doc
opts.each do |k,v|
recv[k.to_s] = v
end
scenario_node << recv
end
def optional_recv(opts)
opts[:optional] = true if opts[:optional].nil?
recv opts
end
def handle_response(code, opts)
optional_recv opts.merge(response: code)
end
end
end
|
module Skywriter
module Resource
def self.property(name, **options)
property_definitions << PropertyDefinition.new(name, options)
end
attr_reader :logical_name
def initialize(logical_name, **options)
@logical_name = logical_name
@options = options.freeze
end
def as_json
Thread.current[:skywriter_as_json_context] = self
{ logical_name =>
{
'Type' => type,
'Properties' => properties.as_json,
'DependsOn' => all_dependencies,
}
}
ensure
Thread.current[:skywriter_as_json_context] = nil
end
def to_json(*)
as_json.to_json
end
def type
@type ||= self.class.name.gsub("Skywriter::Resource", "AWS")
end
# @param with [:ref, :logical_name] How this pointer should be
# rendered in JSON. Use `:ref` to generate {"Ref": "foo"},
# and `:logical_name` to generate "foo"
def as_pointer(with: :ref)
case with
when :ref
Skywriter::Resource::RefPointer.new(self)
when :logical_name
Skywriter::Resource::LogicalNamePointer.new(self)
else
raise ArgumentError, "Unrecognized 'with' value '#{with}'"
end
end
def register_dependency(dependency)
magical_dependencies << dependency.logical_name
end
private
attr_reader :options
def all_dependencies
(additional_dependencies + magical_dependencies).to_a
end
def additional_dependencies
Set.new(Array(options[:additional_dependencies]))
end
def magical_dependencies
@magical_dependencies ||= Set.new
end
def properties
@properties ||= property_definitions.each_with_object({}) do |property_definition, hash|
if (value = options[property_definition.key])
hash[property_definition.name] = value
end
end
end
def self.property_definitions
@property_definitions ||= []
end
def property_definitions
self.class.property_definitions
end
end
class PropertyDefinition
attr_reader :name, :key
def initialize(name, **options)
@name = name.to_s
@key = name.to_s.underscore.to_sym
end
end
end
Refactor into a module
module Skywriter
module Resource
module DSL
def property(name, **options)
property_definitions << PropertyDefinition.new(name, options)
end
def property_definitions
@property_definitions ||= []
end
class PropertyDefinition
attr_reader :name, :key
def initialize(name, **options)
@name = name.to_s
@key = name.to_s.underscore.to_sym
end
end
end
attr_reader :logical_name
def initialize(logical_name, **options)
@logical_name = logical_name
@options = options.freeze
end
def as_json
Thread.current[:skywriter_as_json_context] = self
{ logical_name =>
{
'Type' => type,
'Properties' => properties.as_json,
'DependsOn' => all_dependencies,
}
}
ensure
Thread.current[:skywriter_as_json_context] = nil
end
def to_json(*)
as_json.to_json
end
def type
@type ||= self.class.name.gsub("Skywriter::Resource", "AWS")
end
# @param with [:ref, :logical_name] How this pointer should be
# rendered in JSON. Use `:ref` to generate {"Ref": "foo"},
# and `:logical_name` to generate "foo"
def as_pointer(with: :ref)
case with
when :ref
Skywriter::Resource::RefPointer.new(self)
when :logical_name
Skywriter::Resource::LogicalNamePointer.new(self)
else
raise ArgumentError, "Unrecognized 'with' value '#{with}'"
end
end
def register_dependency(dependency)
magical_dependencies << dependency.logical_name
end
private
attr_reader :options
def self.included(base)
base.extend(DSL)
end
def all_dependencies
(additional_dependencies + magical_dependencies).to_a
end
def additional_dependencies
Set.new(Array(options[:additional_dependencies]))
end
def magical_dependencies
@magical_dependencies ||= Set.new
end
def properties
@properties ||= property_definitions.each_with_object({}) do |property_definition, hash|
if (value = options[property_definition.key])
hash[property_definition.name] = value
end
end
end
def property_definitions
self.class.property_definitions
end
end
end
|
module SMTPMachine
module Router
def self.included(base) # :nodoc:
base.extend ClassMethods
end
module ClassMethods
attr_accessor :routes
def reset!
self.routes = {}
end
def ehlo(regex, options = {}, &block)
add_route(:ehlo, regex, options, &block)
end
def mail_from(regex, options = {}, &block)
add_route(:from, regex, options, &block)
end
def rcpt_to(regex, options = {}, &block)
add_route(:to, regex, options, &block)
end
def data(regex, options = {}, &block)
add_route(:data, regex, options, &block)
end
def map(regex, options = {}, &block)
add_route(:to, regex) { true }
add_route(:data, regex, ({:match => :to}).merge(options), &block)
end
def add_route(action, regex, options = {}, &block)
match_against = options[:match] || action
define_method "__email #{action} #{regex}", &block
unbound_method = instance_method("__email #{action} #{regex}")
block = lambda { unbound_method.bind(self).call }
(routes[action] ||= []).
push([regex, match_against, block]).last
end
end
attr_accessor :routes
def initialize
self.routes = {}
super
end
def route!
compile_routes
match = false
routes.each do |block|
catch(:pass) do
res = instance_eval(&block)
match ||= res
end
end
match
end
private
def compile_routes
self.routes =
(self.class.routes[action] || []).select { |r, m, _|
return true unless r
if action == m
r =~ payload
else
!([context.send(m)].flatten.grep(r)).empty?
end
}.map {|_,_,b| b}
end
# Pass control to the next matching route.
def pass
throw :pass
end
# Exit the current block, halts any further processing of the request
def halt
throw :halt
end
# Rejects the email immediately
def reject
throw :halt, false
end
end
end
clean up/clarify router a tad
module SMTPMachine
module Router
def self.included(base) # :nodoc:
base.extend ClassMethods
end
module ClassMethods
attr_accessor :routes
def reset!
self.routes = {}
end
def ehlo(regex, options = {}, &block)
add_route(:ehlo, regex, options, &block)
end
def mail_from(regex, options = {}, &block)
add_route(:from, regex, options, &block)
end
def rcpt_to(regex, options = {}, &block)
add_route(:to, regex, options, &block)
end
def data(regex, options = {}, &block)
add_route(:data, regex, options, &block)
end
def map(regex, options = {}, &block)
add_route(:to, regex) { true }
add_route(:data, regex, ({:match => :to}).merge(options), &block)
end
def add_route(action, regex, options = {}, &block)
match_against = options[:match] || action
define_method "__email #{action} #{regex}", &block
unbound_method = instance_method("__email #{action} #{regex}")
block = lambda { unbound_method.bind(self).call }
(routes[action] ||= []).
push([regex, match_against, block]).last
end
end
attr_accessor :routes
def initialize
self.routes = {}
super
end
def route!
compile_routes
match = false
routes.each do |block|
catch(:pass) do
res = instance_eval(&block)
match ||= res
end
end
match
end
private
def compile_routes
self.routes =
(self.class.routes[action] || []).select do |regex, match_action, _|
return true unless regex
if action == match_action
regex =~ payload
else
!([context.send(match_action)].flatten.grep(regex)).empty?
end
end.map {|_,_,b| b}
end
# Pass control to the next matching route.
def pass
throw :pass
end
# Exit the current block, halts any further processing of the request
def halt
throw :halt
end
# Rejects the email immediately
def reject
throw :halt, false
end
end
end
|
module SocmapAdf
VERSION = "0.0.4"
end
0.0.5
module SocmapAdf
VERSION = "0.0.5"
end
|
# encoding: utf-8
module Sponges
class Supervisor
attr_reader :store, :name, :options
def initialize(name, options, store, block)
@name, @options, @store, @block = name, options, store, block
store.on_fork
store.register Process.pid
@children_seen = 0
end
def start
options[:size].times do
fork_children
end
trap_signals
at_exit do
Sponges.logger.info "Supervisor exits."
end
Sponges.logger.info "Supervisor started, waiting for messages."
sleep
rescue Exception => exception
Sponges.logger.error exception
kill_them_all(:INT)
raise exception
end
private
def fork_children
name = children_name
pid = fork do
$PROGRAM_NAME = name
Sponges::Hook.after_fork
@block.call
end
Sponges.logger.info "Supervisor create a child with #{pid} pid."
store.add_children pid
end
def children_name
"#{name}_child_#{@children_seen +=1}"
end
def trap_signals
(Sponges::SIGNALS + [:HUP]).each do |signal|
trap(signal) do
handle_signal signal
end
end
trap(:TTIN) do
Sponges.logger.warn "Supervisor increment child's pool by one."
fork_children
end
trap(:TTOU) do
Sponges.logger.warn "Supervisor decrement child's pool by one."
if store.children_pids.first
kill_one(store.children_pids.first, :HUP)
store.delete_children(children_pids.first)
else
Sponges.logger.warn "No more child to kill."
end
end
trap(:CHLD) do
store.children_pids.each do |pid|
begin
dead = Process.waitpid(pid.to_i, Process::WNOHANG)
if dead
Sponges.logger.warn "Child #{dead} died. Restarting a new one..."
store.delete_children dead
Sponges::Hook.on_chld
fork_children
end
rescue Errno::ECHILD => e
# Don't panic
end
end
end
end
def handle_signal(signal)
Sponges.logger.info "Supervisor received #{signal} signal."
kill_them_all(signal)
Process.waitall
Sponges.logger.info "Children shutdown complete."
Sponges.logger.info "Supervisor shutdown. Exiting..."
pid = store.supervisor_pid
store.clear(name)
Process.kill :USR1, pid.to_i
end
def kill_them_all(signal)
store.children_pids.each do |pid|
kill_one(pid.to_i, signal)
end
end
def kill_one(pid, signal)
begin
Process.kill signal, pid
Process.waitpid pid
Sponges.logger.info "Child #{pid} receive a #{signal} signal."
rescue Errno::ESRCH => e
# Don't panic
end
end
end
end
Various fixes on decrement
Signed-off-by: chatgris <f9469d12bf3d131e7aae80be27ccfe58aa9db1f1@af83.com>
# encoding: utf-8
module Sponges
class Supervisor
attr_reader :store, :name, :options
def initialize(name, options, store, block)
@name, @options, @store, @block = name, options, store, block
store.on_fork
store.register Process.pid
@children_seen = 0
end
def start
options[:size].times do
fork_children
end
trap_signals
at_exit do
Sponges.logger.info "Supervisor exits."
end
Sponges.logger.info "Supervisor started, waiting for messages."
sleep
rescue Exception => exception
Sponges.logger.error exception
kill_them_all(:INT)
raise exception
end
private
def fork_children
name = children_name
pid = fork do
$PROGRAM_NAME = name
Sponges::Hook.after_fork
@block.call
end
Sponges.logger.info "Supervisor create a child with #{pid} pid."
store.add_children pid
end
def children_name
"#{name}_child_#{@children_seen +=1}"
end
def trap_signals
(Sponges::SIGNALS + [:HUP]).each do |signal|
trap(signal) do
handle_signal signal
end
end
trap(:TTIN) do
Sponges.logger.warn "Supervisor increment child's pool by one."
fork_children
end
trap(:TTOU) do
Sponges.logger.warn "Supervisor decrement child's pool by one."
if store.children_pids.first
kill_one(store.children_pids.first, :HUP)
store.delete_children(store.children_pids.first)
else
Sponges.logger.warn "No more child to kill."
end
end
trap(:CHLD) do
store.children_pids.each do |pid|
begin
dead = Process.waitpid(pid.to_i, Process::WNOHANG)
if dead
Sponges.logger.warn "Child #{dead} died. Restarting a new one..."
store.delete_children dead
Sponges::Hook.on_chld
fork_children
end
rescue Errno::ECHILD => e
# Don't panic
end
end
end
end
def handle_signal(signal)
Sponges.logger.info "Supervisor received #{signal} signal."
kill_them_all(signal)
Process.waitall
Sponges.logger.info "Children shutdown complete."
Sponges.logger.info "Supervisor shutdown. Exiting..."
pid = store.supervisor_pid
store.clear(name)
Process.kill :USR1, pid.to_i
end
def kill_them_all(signal)
store.children_pids.each do |pid|
kill_one(pid.to_i, signal)
end
end
def kill_one(pid, signal)
begin
Process.kill signal, pid
Process.waitpid pid
Sponges.logger.info "Child #{pid} receive a #{signal} signal."
rescue Errno::ESRCH, Errno::ECHILD, SignalException => e
# Don't panic
end
end
end
end
|
require "spring/configuration"
require "spring/application_watcher"
require "spring/commands"
require "set"
module Spring
class << self
attr_accessor :application_watcher
end
self.application_watcher = ApplicationWatcher.new
class Application
WATCH_INTERVAL = 0.2
attr_reader :manager, :watcher
def initialize(manager, watcher = Spring.application_watcher)
@manager = manager
@watcher = watcher
@setup = Set.new
end
def start
require Spring.application_root_path.join("config", "application")
# The test environment has config.cache_classes = true set by default.
# However, we don't want this to prevent us from performing class reloading,
# so this gets around that.
Rails::Application.initializer :initialize_dependency_mechanism, group: :all do
ActiveSupport::Dependencies.mechanism = :load
end
require Spring.application_root_path.join("config", "environment")
watcher.add_files $LOADED_FEATURES
watcher.add_files ["Gemfile", "Gemfile.lock"].map { |f| "#{Rails.root}/#{f}" }
watcher.add_globs Rails.application.paths["config/initializers"].map { |p| "#{Rails.root}/#{p}/*.rb" }
run
end
def run
loop do
watch_application
serve manager.recv_io(UNIXSocket)
end
end
def watch_application
until IO.select([manager], [], [], WATCH_INTERVAL)
exit if watcher.stale?
end
end
def serve(client)
streams = 3.times.map { client.recv_io }
args_length = client.gets.to_i
args = args_length.times.map { client.read(client.gets.to_i) }
command = Spring.command(args.shift)
setup command
ActionDispatch::Reloader.cleanup!
ActionDispatch::Reloader.prepare!
pid = fork {
Process.setsid
[STDOUT, STDERR, STDIN].zip(streams).each { |a, b| a.reopen(b) }
IGNORE_SIGNALS.each { |sig| trap(sig, "DEFAULT") }
invoke_after_fork_callbacks
command.call(args)
}
manager.puts pid
_, status = Process.wait2 pid
ensure
streams.each(&:close) if streams
client.puts(status ? status.exitstatus : 1)
client.close
end
# The command might need to require some files in the
# main process so that they are cached. For example a test command wants to
# load the helper file once and have it cached.
#
# FIXME: The watcher.add_files will reset the watcher, which may mean that
# previous changes to already-loaded files are missed.
def setup(command)
return if @setup.include?(command.class)
@setup << command.class
if command.respond_to?(:setup)
command.setup
watcher.add_files $LOADED_FEATURES # loaded features may have changed
end
end
def invoke_after_fork_callbacks
Spring.after_fork_callbacks.each do |callback|
callback.call
end
end
end
end
Allow multiple commands to run at once
E.g. if you have several terminals open and are running two test
commands at once.
Closes #78
require "spring/configuration"
require "spring/application_watcher"
require "spring/commands"
require "set"
module Spring
class << self
attr_accessor :application_watcher
end
self.application_watcher = ApplicationWatcher.new
class Application
WATCH_INTERVAL = 0.2
attr_reader :manager, :watcher
def initialize(manager, watcher = Spring.application_watcher)
@manager = manager
@watcher = watcher
@setup = Set.new
end
def start
require Spring.application_root_path.join("config", "application")
# The test environment has config.cache_classes = true set by default.
# However, we don't want this to prevent us from performing class reloading,
# so this gets around that.
Rails::Application.initializer :initialize_dependency_mechanism, group: :all do
ActiveSupport::Dependencies.mechanism = :load
end
require Spring.application_root_path.join("config", "environment")
watcher.add_files $LOADED_FEATURES
watcher.add_files ["Gemfile", "Gemfile.lock"].map { |f| "#{Rails.root}/#{f}" }
watcher.add_globs Rails.application.paths["config/initializers"].map { |p| "#{Rails.root}/#{p}/*.rb" }
run
end
def run
loop do
watch_application
serve manager.recv_io(UNIXSocket)
end
end
def watch_application
until IO.select([manager], [], [], WATCH_INTERVAL)
exit if watcher.stale?
end
end
def serve(client)
streams = 3.times.map { client.recv_io }
args_length = client.gets.to_i
args = args_length.times.map { client.read(client.gets.to_i) }
command = Spring.command(args.shift)
setup command
ActionDispatch::Reloader.cleanup!
ActionDispatch::Reloader.prepare!
pid = fork {
Process.setsid
[STDOUT, STDERR, STDIN].zip(streams).each { |a, b| a.reopen(b) }
IGNORE_SIGNALS.each { |sig| trap(sig, "DEFAULT") }
invoke_after_fork_callbacks
command.call(args)
}
manager.puts pid
# Wait in a separate thread so we can run multiple commands at once
Thread.new {
_, status = Process.wait2 pid
streams.each(&:close)
client.puts(status.exitstatus)
client.close
}
rescue => e
streams.each(&:close) if streams
client.puts(1)
client.close
raise
end
# The command might need to require some files in the
# main process so that they are cached. For example a test command wants to
# load the helper file once and have it cached.
#
# FIXME: The watcher.add_files will reset the watcher, which may mean that
# previous changes to already-loaded files are missed.
def setup(command)
return if @setup.include?(command.class)
@setup << command.class
if command.respond_to?(:setup)
command.setup
watcher.add_files $LOADED_FEATURES # loaded features may have changed
end
end
def invoke_after_fork_callbacks
Spring.after_fork_callbacks.each do |callback|
callback.call
end
end
end
end
|
module SQLParser
VERSION = '0.8'
end
fix(in_predicate): IN() predicate accepts a value list with one element
module SQLParser
VERSION = '0.9'
end |
require 'cli/name_version_pair'
require 'cli/client/export_release_client'
require 'json'
module Bosh::Cli::Command
module Release
class ExportRelease < Base
usage 'export release'
desc 'Export the compiled release to a tarball. Release should be in the form of {name}/{version} and stemcell should be in the form of {operating system name}/{stemcell version}'
def export(release, stemcell)
auth_required
deployment_required
manifest = Bosh::Cli::Manifest.new(deployment, director)
manifest.load
release = Bosh::Cli::NameVersionPair.parse(release)
stemcell = Bosh::Cli::NameVersionPair.parse(stemcell)
stemcell_os = stemcell.name
client = Bosh::Cli::Client::ExportReleaseClient.new(director)
status, task_id = client.export(manifest.name, release.name, release.version, stemcell_os, stemcell.version)
task_report(status, task_id)
task_result_file = director.get_task_result_log(task_id)
task_result = JSON.parse(task_result_file)
tarball_blobstore_id = task_result['blobstore_id']
tarball_sha1 = task_result['sha1']
tarball_file_name = "release-#{release.name}-#{release.version}-on-#{stemcell_os}-stemcell-#{stemcell.version}.tgz"
tarball_file_path = File.join(Dir.pwd, tarball_file_name)
nl
progress_renderer.start(tarball_file_name, "downloading...")
tmpfile = director.download_resource(tarball_blobstore_id)
File.open(tarball_file_path, "wb") do |file|
file << File.open(tmpfile).read
end
progress_renderer.finish(tarball_file_name, "downloaded")
if file_checksum(tarball_file_path) != tarball_sha1
err("Checksum mismatch for downloaded blob `#{tarball_file_path}'")
end
end
# Returns file SHA1 checksum
# @param [String] path File path
def file_checksum(path)
Digest::SHA1.file(path).hexdigest
end
end
end
end
cli should exit with error without trying to fetch compiled release tarball if director task did not succeed
[#99659682]
https://www.pivotaltracker.com/story/show/99659682
Signed-off-by: Sukhil Suresh <7738644c72471621b3fc113c0e37dedf152ad781@pivotal.io>
require 'cli/name_version_pair'
require 'cli/client/export_release_client'
require 'json'
module Bosh::Cli::Command
module Release
class ExportRelease < Base
usage 'export release'
desc 'Export the compiled release to a tarball. Release should be in the form of {name}/{version} and stemcell should be in the form of {operating system name}/{stemcell version}'
def export(release, stemcell)
auth_required
deployment_required
manifest = Bosh::Cli::Manifest.new(deployment, director)
manifest.load
release = Bosh::Cli::NameVersionPair.parse(release)
stemcell = Bosh::Cli::NameVersionPair.parse(stemcell)
stemcell_os = stemcell.name
client = Bosh::Cli::Client::ExportReleaseClient.new(director)
status, task_id = client.export(manifest.name, release.name, release.version, stemcell_os, stemcell.version)
if status != :done
task_report(status, task_id)
return
end
task_result_file = director.get_task_result_log(task_id)
task_result = JSON.parse(task_result_file)
tarball_blobstore_id = task_result['blobstore_id']
tarball_sha1 = task_result['sha1']
tarball_file_name = "release-#{release.name}-#{release.version}-on-#{stemcell_os}-stemcell-#{stemcell.version}.tgz"
tarball_file_path = File.join(Dir.pwd, tarball_file_name)
nl
progress_renderer.start(tarball_file_name, "downloading...")
tmpfile = director.download_resource(tarball_blobstore_id)
File.open(tarball_file_path, "wb") do |file|
file << File.open(tmpfile).read
end
progress_renderer.finish(tarball_file_name, "downloaded")
if file_checksum(tarball_file_path) != tarball_sha1
err("Checksum mismatch for downloaded blob `#{tarball_file_path}'")
end
task_report(status, task_id, "Exported Release `#{release.name.make_green}/#{release.version.make_green}` for `#{stemcell_os.make_green}/#{stemcell.version.make_green}`")
end
# Returns file SHA1 checksum
# @param [String] path File path
def file_checksum(path)
Digest::SHA1.file(path).hexdigest
end
end
end
end
|
#
# Cookbook Name:: docker
# Provider:: image
#
# Copyright 2013, Brian Flad
#
# 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.
#
require 'chef/mixin/shell_out'
include Chef::Mixin::ShellOut
def load_current_resource
@current_resource = Chef::Resource::DockerImage.new(new_resource)
di = shell_out("docker images -a")
if di.stdout.include?(new_resource.image_name)
di.stdout.each_line do |di_line|
next unless di_line.include?(new_resource.image_name)
image_info = di_line.split(%r{\s\s+})
@current_resource.installed(true)
@current_resource.repository(image_info[0])
@current_resource.installed_tag(image_info[1])
@current_resource.id(image_info[2])
break
end
end
@current_resource
end
action :pull do
unless installed?
pull_args = ""
pull_args += " -registry #{new_resource.registry}" if new_resource.registry
pull_args += " -t #{new_resource.tag}" if new_resource.tag
shell_out("docker pull #{new_resource.image_name} #{pull_args}")
new_resource.updated_by_last_action(true)
end
end
action :build do
unless installed?
full_image_name = new_resource.image_name
full_image_name += ":#{new_resource.tag}" if new_resource.tags
shell_out("docker build -t #{full_image_name} - < #{new_resource.dockerfile}")
new_resource.updated_by_last_action(true)
end
end
action :remove do
remove if @current_resource.installed
new_resource.updated_by_last_action(true)
end
def remove
shell_out("docker rmi #{new_resource.image_name}")
end
def installed?
@current_resource.installed && tag_match
end
def tag_match
# if the tag is specified, we need to check if it matches what
# is installed already
if new_resource.tag
@current_resource.installed_tag == new_resource.tag
else
# the tag matches otherwise because it's installed
true
end
end
syntax fix
#
# Cookbook Name:: docker
# Provider:: image
#
# Copyright 2013, Brian Flad
#
# 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.
#
require 'chef/mixin/shell_out'
include Chef::Mixin::ShellOut
def load_current_resource
@current_resource = Chef::Resource::DockerImage.new(new_resource)
di = shell_out("docker images -a")
if di.stdout.include?(new_resource.image_name)
di.stdout.each_line do |di_line|
next unless di_line.include?(new_resource.image_name)
image_info = di_line.split(%r{\s\s+})
@current_resource.installed(true)
@current_resource.repository(image_info[0])
@current_resource.installed_tag(image_info[1])
@current_resource.id(image_info[2])
break
end
end
@current_resource
end
action :pull do
unless installed?
pull_args = ""
pull_args += " -registry #{new_resource.registry}" if new_resource.registry
pull_args += " -t #{new_resource.tag}" if new_resource.tag
shell_out("docker pull #{new_resource.image_name} #{pull_args}")
new_resource.updated_by_last_action(true)
end
end
action :build do
unless installed?
full_image_name = new_resource.image_name
full_image_name += ":#{new_resource.tag}" if new_resource.tag
shell_out("docker build -t #{full_image_name} - < #{new_resource.dockerfile}")
new_resource.updated_by_last_action(true)
end
end
action :remove do
remove if @current_resource.installed
new_resource.updated_by_last_action(true)
end
def remove
shell_out("docker rmi #{new_resource.image_name}")
end
def installed?
@current_resource.installed && tag_match
end
def tag_match
# if the tag is specified, we need to check if it matches what
# is installed already
if new_resource.tag
@current_resource.installed_tag == new_resource.tag
else
# the tag matches otherwise because it's installed
true
end
end
|
ucsc-genome-browser: 278
Install a mirror of the UCSC Genome Browser.
require 'formula'
class UcscGenomeBrowser < Formula
homepage 'http://genome.ucsc.edu'
url 'http://hgdownload.cse.ucsc.edu/admin/jksrc.v278.zip'
sha1 '54bc2972ac02651dcc991b8c1e063a9d3a264568'
head 'git://genome-source.cse.ucsc.edu/kent.git'
keg_only <<-EOF.undent
The UCSC Genome Browser installs many commands, and some conflict
with other packages.
EOF
depends_on :libpng
depends_on :mysql
def install
ENV.j1
machtype = `uname -m`.chomp
user = `whoami`.chomp
mkdir prefix/"cgi-bin-#{user}"
mkdir prefix/"htdocs-#{user}"
cd 'src/lib' do
system 'make', "MACHTYPE=#{machtype}"
end
cd 'src/jkOwnLib' do
system 'make', "MACHTYPE=#{machtype}"
end
cd 'src' do
system 'make',
"MACHTYPE=#{machtype}",
"BINDIR=#{bin}",
"SCRIPTS=#{bin}/scripts",
"CGI_BIN=#{prefix}/cgi-bin",
"DOCUMENTROOT=#{prefix}/htdocs",
"PNGLIB=-L#{HOMEBREW_PREFIX}/lib -lpng",
"MYSQLLIBS=-lmysqlclient -lz",
"MYSQLINC=#{HOMEBREW_PREFIX}/include"
end
mv "#{prefix}/cgi-bin-#{user}", prefix/'cgi-bin'
mv "#{prefix}/htdocs-#{user}", prefix/'htdocs'
end
# Todo: Best would be if this formula would put a complete working
# apache virtual site into #{share} and instruct the user to just
# do a symlink.
def caveats; <<-EOF.undent
To complete the installation of the UCSC Genome Browser, follow
these instructions:
http://genomewiki.ucsc.edu/index.php/Browser_Installation
To complete a minimal installation, follow these directions:
# Configure the Apache web server.
# Warning! This command will overwrite your existing web site.
# HELP us to improve these instructions so that a new virtual site is created.
rsync -avzP rsync://hgdownload.cse.ucsc.edu/htdocs/ /Library/WebServer/Documents/
sudo cp -a #{prefix}/cgi-bin/* /Library/WebServer/CGI-Executables/
sudo mkdir /Library/WebServer/CGI-Executables/trash
sudo wget https://gist.github.com/raw/4626128 -O /Library/WebServer/CGI-Executables/hg.conf
mkdir /usr/local/apache
ln -s /Library/WebServer/Documents /usr/local/apache/htdocs
sudo apachectl start
# Configure the MySQL database.
cd #{HOMEBREW_PREFIX}/opt/mysql && mysqld_safe &
mysql -uroot -proot -e "create user 'hguser'@'localhost' identified by 'hguser';"
rsync -avzP rsync://hgdownload.cse.ucsc.edu/mysql/hgcentral/ #{HOMEBREW_PREFIX}/var/mysql/hgcentral/
mysql -uroot -proot -e "grant all privileges on hgcentral.* to 'hguser'@'localhost'"
mysql -uroot -proot -e "create database hgFixed"
mysql -uroot -proot -e "grant select on hgFixed.* to 'hguser'@'localhost'"
Point your browser to http://localhost/cgi-bin/hgGateway
EOF
end
end
|
#!/usr/local/bin/ruby18
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch
Remove the dispatch.rb file, we're not using it
|
# -*- coding: utf-8 -*-
# FDF V1.3
fdfAnalysisModule do
description {
"This is an analysis module for CopyPeste."
}
author { "Team Algo" }
usage { 'Just run it!' }
init { Fdf.new() }
impl {
require 'json'
require File.join(CopyPeste::Require::Path.base, 'algorithms')
require File.join(CopyPeste::Require::Path.copy_peste, 'DbHdlr')
require File.join(CopyPeste::Require::Path.analysis, 'fdf/config_handler/Ignored_class')
class Fdf
attr_accessor :options
attr_accessor :show
def initialize
@options = {
"e" => {
helper: "sort by extension.",
allowed: [0, 1],
value: 1
},
"s" => {
helper: "sort by size.",
allowed: [0, 1],
value: 1
},
"p" => {
helper: "minimum percentage of similarity between 2 files",
allowed: [*60..100],
value: 100
}
}
@mongo = DbHdlr.new()
@c_res = "Scoring"
@c_file = "Fichier"
@results = {
module: "FDF",
options: "List of duplicated files",
timestamp: Time.now.getutc,
type: "array",
header: ["first", "second", "score"],
references: [@c_file, @c_file, nil],
transformation: [],
rows: []
}
@ignored_conf = Ignored_class.new()
end
# Look at the different rules and chose the right way to sort files
#
# @param [Array] Array of files to sort
# @Return [Hash] return an hash of all the files sorted
def sort_files_with_rules(documents)
documents.each do |extension, files|
@show.call "\tSorting extension '#{extension}' per size."
files.sort_by {|file| file[:value]}
documents[extension] = files
end
documents
end
# Extract path and name of each files and concat them.
#
# @param [Array][Array][Hash] take an Array of Array of hash. [files by extension][one file][hash of the file]
# @Return [Array] return a file array with their full path and size
def to_doc(file)
return {
path: file["path"] + "/" + file["name"],
size: file["size"],
name: file["name"]
}
end
# Get files from the database that will be analysed
#
# @Return [Array] return a file Array with the full file path : Array[0] = /home/test/expemple.c
def get_doc_to_analyse
documents = {}
query = {name: {"$nin" => @ignored_conf.ignored_ext}}
# get all extensions
extensions = @mongo.get_data("Extension", query, nil)
# for each extension
extensions.each do |extension|
extension["_id"] = BSON::ObjectId.from_string extension["_id"]["$oid"]
@show.call "\tRetrieving files with extension: '#{extension["name"]}'."
query = {ext: extension["_id"], name: {"$nin" => @ignored_conf.ignored_files }}
# get all corresponding files
files = @mongo.get_data(@c_file, query)
documents[extension["name"]] = []
# save each file, formated, in the good extension
files.each {|file| documents[extension["name"]] << to_doc(file)}
end
documents
end
# Save pair of file compared by fdupes/levenshtein, and there result
# This Hash is saved in an Array
#
# @param [Hash] files and distance between their titles
# @param [Int] result of comparison algorim
# @return
def save_result_data(file_d, similarity)
result_data = [
file_d[:files][0], #first file
file_d[:files][1], #second file
similarity #their similarity score
]
@results[:rows] << result_data
end
# Open the two files and send there containt to fdupes algorithm
#
# @param [Array] File Array
# @param [Integer] Loop position
# @return [Integer] Return the percentage of difference between files
def open_and_send(f1, f2)
begin
file1 = IO.read f1[:path]
file2 = IO.read f2[:path]
rescue => e # file doesn't exists, db have to be updated
@show.call "\t[Error]: #{e} Please update your database"
return nil
end
begin
# if 100% similarity and files have the same size
if @options["p"][:value] == 100
return nil if f1[:size] != f2[:size]
return 100 - Algorithms.fdupes_match(file1, f1[:size], file2, f2[:size])
end
Algorithms.diff(file1, file2)
rescue => e
@show.call "\t[Not treated]: #{f1[:path]} & #{f2[:path]}: #{e}"
end
end
# Send files to the fdupes algorithms
#
# @param [Array] File array containing levenshtein's results
def check_files_similarity(documents)
duplicated_files = {}
# for each extension
documents.each do |extension, files|
next if files.length < 2
@show.call "\tSearching for duplication with extension: '#{extension}'."
# iterate all files to find duplications
(files.length - 1).times do |i|
f1 = files[i]
#@show.call "\tSearching if file #{f1[:name]} is duplicated"
((i + 1)..(files.length - 1)).each do |j|
f2 = files[j]
# stop loop if size is required but files aren't of the same size
break if @options["s"][:value] == 1 && f1[:size] != f2[:size]
# allow little differences in filenames
next if Algorithms.levenshtein(f1[:name], f2[:name]) > 1
result = open_and_send(f1, f2)
next if result == nil
f3 = f2.clone
f3[:similarity] = result
if (@options["p"][:value] == 100 && result == 100) || (result >= @options["p"][:value])
if duplicated_files.key?(f1[:path])
duplicated_files[f1[:path]] << f3
else
duplicated_files[f1[:path]] = [f3]
end
end
end
end
end
@results[:rows] = duplicated_files
end
# Function used to initialize and run the fdf
# and get the list of file to analyse.
def run(*)
@show.call "Get all files from database..."
files = get_doc_to_analyse
@show.call "Done."
@show.call "Sort files depending on options..."
sorted_file = sort_files_with_rules files
@show.call "Done."
@show.call "Searching for duplicated files..."
check_files_similarity sorted_file
@show.call "Done."
@show.call "Saving analyse results in database..."
@mongo.ins_data(@c_res, @results)
@show.call "Done, everything worked fine!"
@show.call "You can now run generate_result to extract interesting informations."
end
end
}
end
This commit ref #984 - Do not take into account 0 size files
# -*- coding: utf-8 -*-
# FDF V1.3
fdfAnalysisModule do
description {
"This is an analysis module for CopyPeste."
}
author { "Team Algo" }
usage { 'Just run it!' }
init { Fdf.new() }
impl {
require 'json'
require File.join(CopyPeste::Require::Path.base, 'algorithms')
require File.join(CopyPeste::Require::Path.copy_peste, 'DbHdlr')
require File.join(CopyPeste::Require::Path.analysis, 'fdf/config_handler/Ignored_class')
class Fdf
attr_accessor :options
attr_accessor :show
def initialize
@options = {
"e" => {
helper: "sort by extension.",
allowed: [0, 1],
value: 1
},
"s" => {
helper: "sort by size.",
allowed: [0, 1],
value: 1
},
"p" => {
helper: "minimum percentage of similarity between 2 files",
allowed: [*60..100],
value: 100
}
}
@mongo = DbHdlr.new()
@c_res = "Scoring"
@c_file = "Fichier"
@results = {
module: "FDF",
options: "List of duplicated files",
timestamp: Time.now.getutc,
type: "array",
header: ["first", "second", "score"],
references: [@c_file, @c_file, nil],
transformation: [],
rows: []
}
@ignored_conf = Ignored_class.new()
end
# Look at the different rules and chose the right way to sort files
#
# @param [Array] Array of files to sort
# @Return [Hash] return an hash of all the files sorted
def sort_files_with_rules(documents)
documents.each do |extension, files|
@show.call "\tSorting extension '#{extension}' per size."
files.sort_by {|file| file[:value]}
documents[extension] = files
end
documents
end
# Extract path and name of each files and concat them.
#
# @param [Array][Array][Hash] take an Array of Array of hash. [files by extension][one file][hash of the file]
# @Return [Array] return a file array with their full path and size
def to_doc(file)
return nil if file["size"] == 0
return {
path: file["path"] + "/" + file["name"],
size: file["size"],
name: file["name"]
}
end
# Get files from the database that will be analysed
#
# @Return [Array] return a file Array with the full file path : Array[0] = /home/test/expemple.c
def get_doc_to_analyse
documents = {}
query = {name: {"$nin" => @ignored_conf.ignored_ext}}
# get all extensions
extensions = @mongo.get_data("Extension", query, nil)
# for each extension
extensions.each do |extension|
extension["_id"] = BSON::ObjectId.from_string extension["_id"]["$oid"]
@show.call "\tRetrieving files with extension: '#{extension["name"]}'."
query = {ext: extension["_id"], name: {"$nin" => @ignored_conf.ignored_files }}
# get all corresponding files
files = @mongo.get_data(@c_file, query)
documents[extension["name"]] = []
# save each file, formated, in the good extension
files.each do |file|
doc = to_doc(file)
documents[extension["name"]] << doc if doc != nil
end
end
documents
end
# Save pair of file compared by fdupes/levenshtein, and there result
# This Hash is saved in an Array
#
# @param [Hash] files and distance between their titles
# @param [Int] result of comparison algorim
# @return
def save_result_data(file_d, similarity)
result_data = [
file_d[:files][0], #first file
file_d[:files][1], #second file
similarity #their similarity score
]
@results[:rows] << result_data
end
# Open the two files and send there containt to fdupes algorithm
#
# @param [Array] File Array
# @param [Integer] Loop position
# @return [Integer] Return the percentage of difference between files
def open_and_send(f1, f2)
begin
file1 = IO.read f1[:path]
file2 = IO.read f2[:path]
rescue => e # file doesn't exists, db have to be updated
@show.call "\t[Error]: #{e} Please update your database"
return nil
end
begin
# if 100% similarity and files have the same size
if @options["p"][:value] == 100
return nil if f1[:size] != f2[:size]
return 100 - Algorithms.fdupes_match(file1, f1[:size], file2, f2[:size])
end
Algorithms.diff(file1, file2)
rescue => e
@show.call "\t[Not treated]: #{f1[:path]} & #{f2[:path]}: #{e}"
end
end
# Send files to the fdupes algorithms
#
# @param [Array] File array containing levenshtein's results
def check_files_similarity(documents)
duplicated_files = {}
# for each extension
documents.each do |extension, files|
next if files.length < 2
@show.call "\tSearching for duplication with extension: '#{extension}'."
# iterate all files to find duplications
(files.length - 1).times do |i|
f1 = files[i]
#@show.call "\tSearching if file #{f1[:name]} is duplicated"
((i + 1)..(files.length - 1)).each do |j|
f2 = files[j]
# stop loop if size is required but files aren't of the same size
break if @options["s"][:value] == 1 && f1[:size] != f2[:size]
# allow little differences in filenames
next if Algorithms.levenshtein(f1[:name], f2[:name]) > 1
result = open_and_send(f1, f2)
next if result == nil
f3 = f2.clone
f3[:similarity] = result
if (@options["p"][:value] == 100 && result == 100) || (result >= @options["p"][:value])
if duplicated_files.key?(f1[:path])
duplicated_files[f1[:path]] << f3
else
duplicated_files[f1[:path]] = [f3]
end
end
end
end
end
@results[:rows] = duplicated_files
end
# Function used to initialize and run the fdf
# and get the list of file to analyse.
def run(*)
@show.call "Get all files from database..."
files = get_doc_to_analyse
@show.call "Done."
@show.call "Sort files depending on options..."
sorted_file = sort_files_with_rules files
@show.call "Done."
@show.call "Searching for duplicated files..."
check_files_similarity sorted_file
@show.call "Done."
@show.call "Saving analyse results in database..."
@mongo.ins_data(@c_res, @results)
@show.call "Done, everything worked fine!"
@show.call "You can now run generate_result to extract interesting informations."
end
end
}
end
|
# -*- coding: utf-8 -*-
spsAnalysisModule do
description {
"This is an analysis module for CopyPeste."
}
author { "Team Algo" }
usage { 'Just run it!' }
init { Sps.new() }
impl {
require 'json'
require 'parallel'
require 'mongo'
require File.join(CopyPeste::Require::Path.base, 'algorithms')
require File.join(CopyPeste::Require::Path.analysis, 'fdf/config_handler/Ignored_class')
class Sps
attr_accessor :options
attr_accessor :show
def initialize
@options = {
"test" => {
helper: "Option de test",
allowed: [0, 1],
value: 0
}
}
@options = options
@ignored_conf = Ignored_class.new()
end
# Function called to start the Sps module
def analyse(result)
res = {}
result_fdf = get_file_from_db
result_fdf.results.each do |data|
if data._type == "ArrayResult"
key = data.header[0].split("/")[1]
if key != nil
if !res.has_key?(key)
res[key] = {}
end
data.rows.each do |file|
key2 = file[0].split("/")[1]
if !res[key].has_key?(key2) && key != key2
res[key][key2] = []
res[key][key2] << file[1]
elsif key != key2
res[key][key2] << file[1]
end
end
end
end
end
projects = get_file_projects
compare_projects(res, projects)
end
def get_file_projects
files = []
# extensions = Extension.not_in(name: @ignored_conf.ignored_exts).to_a
# extensions.each do |extension|
# puts extension
# extension["_id"] = BSON::ObjectId.from_string extension.id
mongo_files = FileSystem.all#where(ext: extension.id).not_in(name: @ignored_conf.ignored_files)
mongo_files.each do |file|
files << file["path"]
end
# end
return get_num_files_project files
end
def get_num_files_project(files)
projects = {}
files.each do |file|
key = file.split("/")[1]
if !projects.has_key?(key)
projects[key] = 1
else
projects[key] += 1
end
end
projects
end
# This functions set the pourcent average of two projects
#
# @param [Array] Array containing all files similarities from two project
# in pourcent
def compare_projects(res, projects)
puts "\n"
res.each do |key, value|
if value.keys[0] != nil
average = 0.0
nb = 0
value[value.keys[0]].each do |num|
average = average + Integer(num)
end
if projects[key].to_i > projects[value.keys[0]].to_i
result = average/projects[key].to_f
else
result = average/projects[value.keys[0]].to_f
end
puts "average between "+key.to_s+" and "+value.keys[0].to_s+" = "+result.to_s+"%"
end
end
puts "\n"
end
# This function get the documents to analyses
def get_file_from_db
begin
ar = AnalyseResult.last
return ar
rescue
@graph_com.cmd_return(@cmd, "Collection AnalyseResult doesn't exist", true)
return nil
end
end
# Function used to initialize and run the fdf
def run(result)
result.module_name = "Sps"
result.options = @options
analyse result
@show.call "Done! Everything worked fine!"
@show.call "You can now run generate_result to extract interesting informations."
end
end
}
end
Update sps results
# -*- coding: utf-8 -*-
spsAnalysisModule do
description {
"This is an analysis module for CopyPeste."
}
author { "Team Algo" }
usage { 'Just run it!' }
init { Sps.new() }
impl {
require 'json'
require 'parallel'
require 'mongo'
require File.join(CopyPeste::Require::Path.base, 'algorithms')
require File.join(CopyPeste::Require::Path.analysis, 'fdf/config_handler/Ignored_class')
class Sps
attr_accessor :options
attr_accessor :show
def initialize
@options = {
"test" => {
helper: "Option de test",
allowed: [0, 1],
value: 0
}
}
@options = options
@results = {
module: "SPS",
options: "List of duplicated Project",
timestamp: Time.now.getutc,
data: []
}
@ignored_conf = Ignored_class.new()
end
# Function called to start the Sps module
def analyse(result)
res = {}
result_fdf = get_file_from_db
result_fdf.results.each do |data|
if data._type == "ArrayResult"
key = data.header[0].split("/")[1]
if key != nil
if !res.has_key?(key)
res[key] = {}
end
data.rows.each do |file|
key2 = file[0].split("/")[1]
if !res[key].has_key?(key2) && key != key2
res[key][key2] = []
res[key][key2] << file[1]
elsif key != key2
res[key][key2] << file[1]
end
end
end
end
end
projects = get_file_projects
compare_projects(res, projects, result)
end
def get_file_projects
files = []
# extensions = Extension.not_in(name: @ignored_conf.ignored_exts).to_a
# extensions.each do |extension|
# puts extension
# extension["_id"] = BSON::ObjectId.from_string extension.id
mongo_files = FileSystem.all#where(ext: extension.id).not_in(name: @ignored_conf.ignored_files)
mongo_files.each do |file|
files << file["path"]
end
# end
return get_num_files_project files
end
def get_num_files_project(files)
projects = {}
files.each do |file|
key = file.split("/")[1]
if !projects.has_key?(key)
projects[key] = 1
else
projects[key] += 1
end
end
projects
end
# This functions set the pourcent average of two projects
#
# @param [Array] Array containing all files similarities from two project
# in pourcent
def compare_projects(res, projects, results)
puts "\n"
res.each do |key, value|
if value.keys[0] != nil
average = 0.0
nb = 0
value[value.keys[0]].each do |num|
average = average + Integer(num)
end
if projects[key].to_i > projects[value.keys[0]].to_i
result = average/projects[key].to_f
else
result = average/projects[value.keys[0]].to_f
end
results.add_text(text: "average between #{key.to_s} and #{value.keys[0].to_s} = #{result.round(2).to_s}%")
end
end
puts "\n"
end
# This function get the documents to analyses
def get_file_from_db
begin
ar = AnalyseResult.last
return ar
rescue
@graph_com.cmd_return(@cmd, "Collection AnalyseResult doesn't exist", true)
return nil
end
end
# Function used to initialize and run the fdf
def run(result)
result.module_name = "Sps"
result.options = @options
analyse result
@show.call "Done! Everything worked fine!"
@show.call "You can now run generate_result to extract interesting informations."
end
end
}
end
|
Pod::Spec.new do |s|
s.name = "React"
s.version = "0.21.0-rc"
s.summary = "Build high quality mobile apps using React."
s.description = <<-DESC
React Native apps are built using the React JS
framework, and render directly to native UIKit
elements using a fully asynchronous architecture.
There is no browser and no HTML. We have picked what
we think is the best set of features from these and
other technologies to build what we hope to become
the best product development framework available,
with an emphasis on iteration speed, developer
delight, continuity of technology, and absolutely
beautiful and fast products with no compromises in
quality or capability.
DESC
s.homepage = "http://facebook.github.io/react-native/"
s.license = "BSD"
s.author = "Facebook"
s.source = { :git => "https://github.com/facebook/react-native.git", :tag => "v#{s.version}" }
s.default_subspec = 'Core'
s.requires_arc = true
s.platform = :ios, "7.0"
s.preserve_paths = "cli.js", "Libraries/**/*.js", "lint", "linter.js", "node_modules", "package.json", "packager", "PATENTS", "react-native-cli"
s.subspec 'Core' do |ss|
ss.source_files = "React/**/*.{c,h,m,S}"
ss.exclude_files = "**/__tests__/*", "IntegrationTests/*"
ss.frameworks = "JavaScriptCore"
end
s.subspec 'ART' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/ART/**/*.{h,m}"
ss.preserve_paths = "Libraries/ART/**/*.js"
end
s.subspec 'RCTActionSheet' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/ActionSheetIOS/*.{h,m}"
ss.preserve_paths = "Libraries/ActionSheetIOS/*.js"
end
s.subspec 'RCTAdSupport' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/AdSupport/*.{h,m}"
ss.preserve_paths = "Libraries/AdSupport/*.js"
end
s.subspec 'RCTCameraRoll' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/CameraRoll/*.{h,m}"
ss.preserve_paths = "Libraries/CameraRoll/*.js"
end
s.subspec 'RCTGeolocation' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Geolocation/*.{h,m}"
ss.preserve_paths = "Libraries/Geolocation/*.js"
end
s.subspec 'RCTImage' do |ss|
ss.dependency 'React/Core'
ss.dependency 'React/RCTNetwork'
ss.source_files = "Libraries/Image/*.{h,m}"
ss.preserve_paths = "Libraries/Image/*.js"
end
s.subspec 'RCTNetwork' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Network/*.{h,m}"
ss.preserve_paths = "Libraries/Network/*.js"
end
s.subspec 'RCTPushNotification' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/PushNotificationIOS/*.{h,m}"
ss.preserve_paths = "Libraries/PushNotificationIOS/*.js"
end
s.subspec 'RCTSettings' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Settings/*.{h,m}"
ss.preserve_paths = "Libraries/Settings/*.js"
end
s.subspec 'RCTText' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Text/*.{h,m}"
ss.preserve_paths = "Libraries/Text/*.js"
end
s.subspec 'RCTVibration' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Vibration/*.{h,m}"
ss.preserve_paths = "Libraries/Vibration/*.js"
end
s.subspec 'RCTWebSocket' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/WebSocket/*.{h,m}"
ss.preserve_paths = "Libraries/WebSocket/*.js"
end
s.subspec 'RCTLinkingIOS' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/LinkingIOS/*.{h,m}"
ss.preserve_paths = "Libraries/LinkingIOS/*.js"
end
s.subspec 'RCTTest' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/RCTTest/**/*.{h,m}"
ss.preserve_paths = "Libraries/RCTTest/**/*.js"
ss.frameworks = "XCTest"
end
end
[React] Fix RCTTest to not pull in its own vendored FBSnapshotTestCase.
https://github.com/facebook/react-native/issues/6126
Pod::Spec.new do |s|
s.name = "React"
s.version = "0.21.0-rc"
s.summary = "Build high quality mobile apps using React."
s.description = <<-DESC
React Native apps are built using the React JS
framework, and render directly to native UIKit
elements using a fully asynchronous architecture.
There is no browser and no HTML. We have picked what
we think is the best set of features from these and
other technologies to build what we hope to become
the best product development framework available,
with an emphasis on iteration speed, developer
delight, continuity of technology, and absolutely
beautiful and fast products with no compromises in
quality or capability.
DESC
s.homepage = "http://facebook.github.io/react-native/"
s.license = "BSD"
s.author = "Facebook"
s.source = { :git => "https://github.com/facebook/react-native.git", :tag => "v#{s.version}" }
s.default_subspec = 'Core'
s.requires_arc = true
s.platform = :ios, "7.0"
s.preserve_paths = "cli.js", "Libraries/**/*.js", "lint", "linter.js", "node_modules", "package.json", "packager", "PATENTS", "react-native-cli"
s.subspec 'Core' do |ss|
ss.source_files = "React/**/*.{c,h,m,S}"
ss.exclude_files = "**/__tests__/*", "IntegrationTests/*"
ss.frameworks = "JavaScriptCore"
end
s.subspec 'ART' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/ART/**/*.{h,m}"
ss.preserve_paths = "Libraries/ART/**/*.js"
end
s.subspec 'RCTActionSheet' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/ActionSheetIOS/*.{h,m}"
ss.preserve_paths = "Libraries/ActionSheetIOS/*.js"
end
s.subspec 'RCTAdSupport' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/AdSupport/*.{h,m}"
ss.preserve_paths = "Libraries/AdSupport/*.js"
end
s.subspec 'RCTCameraRoll' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/CameraRoll/*.{h,m}"
ss.preserve_paths = "Libraries/CameraRoll/*.js"
end
s.subspec 'RCTGeolocation' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Geolocation/*.{h,m}"
ss.preserve_paths = "Libraries/Geolocation/*.js"
end
s.subspec 'RCTImage' do |ss|
ss.dependency 'React/Core'
ss.dependency 'React/RCTNetwork'
ss.source_files = "Libraries/Image/*.{h,m}"
ss.preserve_paths = "Libraries/Image/*.js"
end
s.subspec 'RCTNetwork' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Network/*.{h,m}"
ss.preserve_paths = "Libraries/Network/*.js"
end
s.subspec 'RCTPushNotification' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/PushNotificationIOS/*.{h,m}"
ss.preserve_paths = "Libraries/PushNotificationIOS/*.js"
end
s.subspec 'RCTSettings' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Settings/*.{h,m}"
ss.preserve_paths = "Libraries/Settings/*.js"
end
s.subspec 'RCTText' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Text/*.{h,m}"
ss.preserve_paths = "Libraries/Text/*.js"
end
s.subspec 'RCTVibration' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/Vibration/*.{h,m}"
ss.preserve_paths = "Libraries/Vibration/*.js"
end
s.subspec 'RCTWebSocket' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/WebSocket/*.{h,m}"
ss.preserve_paths = "Libraries/WebSocket/*.js"
end
s.subspec 'RCTLinkingIOS' do |ss|
ss.dependency 'React/Core'
ss.source_files = "Libraries/LinkingIOS/*.{h,m}"
ss.preserve_paths = "Libraries/LinkingIOS/*.js"
end
s.subspec 'RCTTest' do |ss|
ss.dependency 'React/Core'
ss.dependency 'FBSnapshotTestCase'
ss.source_files = "Libraries/RCTTest/*.{h,m}"
ss.preserve_paths = "Libraries/RCTTest/*.js"
ss.frameworks = "XCTest"
end
end
|
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "punchblock/version"
Gem::Specification.new do |s|
s.name = %q{punchblock}
s.version = Punchblock::VERSION
s.platform = Gem::Platform::RUBY
s.licenses = ["MIT"]
s.authors = ["Jason Goecke", "Ben Klang", "Ben Langfeld"]
s.email = %q{punchblock@adhearsion.com}
s.homepage = %q{http://github.com/adhearsion/punchblock}
s.summary = "Punchblock is a telephony middleware library"
s.description = "Like Rack is to Rails and Sinatra, Punchblock provides a consistent API on top of several underlying third-party call control protocols."
s.rubyforge_project = "punchblock"
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.required_rubygems_version = Gem::Requirement.new(">= 1.3.7") if s.respond_to? :required_rubygems_version=
s.add_runtime_dependency %q<niceogiri>, ["~> 1.0"]
s.add_runtime_dependency %q<blather>, [">= 0.7.0"]
s.add_runtime_dependency %q<activesupport>, ["~> 3.0"]
s.add_runtime_dependency %q<state_machine>, ["~> 1.0"]
s.add_runtime_dependency %q<future-resource>, ["~> 1.0"]
s.add_runtime_dependency %q<has-guarded-handlers>, ["~> 1.3"]
s.add_runtime_dependency %q<celluloid>, [">= 0.11.1"]
s.add_runtime_dependency %q<ruby_ami>, ["~> 1.2", ">= 1.2.1"]
s.add_runtime_dependency %q<ruby_fs>, ["~> 1.0"]
s.add_runtime_dependency %q<ruby_speech>, ["~> 1.0"]
s.add_development_dependency %q<bundler>, ["~> 1.0"]
s.add_development_dependency %q<rspec>, ["~> 2.7"]
s.add_development_dependency %q<ci_reporter>, ["~> 1.6"]
s.add_development_dependency %q<yard>, ["~> 0.6"]
s.add_development_dependency %q<rake>, [">= 0"]
s.add_development_dependency %q<mocha>, [">= 0"]
s.add_development_dependency %q<i18n>, [">= 0"]
s.add_development_dependency %q<countdownlatch>, [">= 0"]
s.add_development_dependency %q<guard-rspec>
s.add_development_dependency %q<ruby_gntp>
end
[UPDATE] Temporarily hold back ruby_ami and ruby_fs dependencies
Celluloid 0.12.0 breaks everything
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "punchblock/version"
Gem::Specification.new do |s|
s.name = %q{punchblock}
s.version = Punchblock::VERSION
s.platform = Gem::Platform::RUBY
s.licenses = ["MIT"]
s.authors = ["Jason Goecke", "Ben Klang", "Ben Langfeld"]
s.email = %q{punchblock@adhearsion.com}
s.homepage = %q{http://github.com/adhearsion/punchblock}
s.summary = "Punchblock is a telephony middleware library"
s.description = "Like Rack is to Rails and Sinatra, Punchblock provides a consistent API on top of several underlying third-party call control protocols."
s.rubyforge_project = "punchblock"
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.required_rubygems_version = Gem::Requirement.new(">= 1.3.7") if s.respond_to? :required_rubygems_version=
s.add_runtime_dependency %q<niceogiri>, ["~> 1.0"]
s.add_runtime_dependency %q<blather>, [">= 0.7.0"]
s.add_runtime_dependency %q<activesupport>, ["~> 3.0"]
s.add_runtime_dependency %q<state_machine>, ["~> 1.0"]
s.add_runtime_dependency %q<future-resource>, ["~> 1.0"]
s.add_runtime_dependency %q<has-guarded-handlers>, ["~> 1.3"]
s.add_runtime_dependency %q<celluloid>, [">= 0.11.1"]
s.add_runtime_dependency %q<ruby_ami>, ["~> 1.2", ">= 1.2.1", "< 1.2.2"]
s.add_runtime_dependency %q<ruby_fs>, ["~> 1.0", "< 1.0.1"]
s.add_runtime_dependency %q<ruby_speech>, ["~> 1.0"]
s.add_development_dependency %q<bundler>, ["~> 1.0"]
s.add_development_dependency %q<rspec>, ["~> 2.7"]
s.add_development_dependency %q<ci_reporter>, ["~> 1.6"]
s.add_development_dependency %q<yard>, ["~> 0.6"]
s.add_development_dependency %q<rake>, [">= 0"]
s.add_development_dependency %q<mocha>, [">= 0"]
s.add_development_dependency %q<i18n>, [">= 0"]
s.add_development_dependency %q<countdownlatch>, [">= 0"]
s.add_development_dependency %q<guard-rspec>
s.add_development_dependency %q<ruby_gntp>
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'configurator/version'
Gem::Specification.new do |spec|
spec.name = %q{configurator}
spec.version = Configurator::VERSION
spec.license = "MIT"
spec.authors = ["Will Bryant"]
spec.description = %q{Basic configuration loading}
spec.email = ["william@tout.com"]
spec.summary = %q{Basic configuration loading}
spec.homepage = %q{http://github.com/will3216/configurator}
spec.files = Dir.glob("lib/**/*") + [
"LICENSE.txt",
"README.md",
"Rakefile",
"Gemfile",
"configurator.gemspec",
]
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = Dir.glob("spec/**/*")
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_development_dependency(%q<rails>, [">= 3.2"])
end
Added Rails as a runtime dependency
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'configurator/version'
Gem::Specification.new do |spec|
spec.name = %q{configurator}
spec.version = Configurator::VERSION
spec.license = "MIT"
spec.authors = ["Will Bryant"]
spec.description = %q{Basic configuration loading}
spec.email = ["william@tout.com"]
spec.summary = %q{Basic configuration loading}
spec.homepage = %q{http://github.com/will3216/configurator}
spec.files = Dir.glob("lib/**/*") + [
"LICENSE.txt",
"README.md",
"Rakefile",
"Gemfile",
"configurator.gemspec",
]
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = Dir.glob("spec/**/*")
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec"
spec.add_runtime_dependency(%q<rails>, [">= 3.2"])
end
|
require 'rest_client'
require 'chef/cookbook_loader'
require 'chef/cache/checksum'
require 'chef/sandbox'
require 'chef/cookbook_version'
require 'chef/cookbook/syntax_check'
require 'chef/cookbook/file_system_file_vendor'
class Chef
class CookbookUploader
class << self
def upload_cookbook(cookbook)
Chef::Log.info("Saving #{cookbook.name}")
rest = Chef::REST.new(Chef::Config[:chef_server_url])
# Syntax Check
validate_cookbook(cookbook)
# Generate metadata.json from metadata.rb
build_metadata(cookbook)
# generate checksums of cookbook files and create a sandbox
checksum_files = cookbook.checksums
checksums = checksum_files.inject({}){|memo,elt| memo[elt.first]=nil ; memo}
new_sandbox = rest.post_rest("/sandboxes", { :checksums => checksums })
Chef::Log.info("Uploading files")
# upload the new checksums and commit the sandbox
new_sandbox['checksums'].each do |checksum, info|
if info['needs_upload'] == true
Chef::Log.info("Uploading #{checksum_files[checksum]} (checksum hex = #{checksum}) to #{info['url']}")
# Checksum is the hexadecimal representation of the md5,
# but we need the base64 encoding for the content-md5
# header
checksum64 = Base64.encode64([checksum].pack("H*")).strip
timestamp = Time.now.utc.iso8601
file_contents = File.read(checksum_files[checksum])
# TODO - 5/28/2010, cw: make signing and sending the request streaming
sign_obj = Mixlib::Authentication::SignedHeaderAuth.signing_object(
:http_method => :put,
:path => URI.parse(info['url']).path,
:body => file_contents,
:timestamp => timestamp,
:user_id => rest.client_name
)
headers = { 'content-type' => 'application/x-binary', 'content-md5' => checksum64, :accept => 'application/json' }
headers.merge!(sign_obj.sign(OpenSSL::PKey::RSA.new(rest.signing_key)))
begin
RestClient::Request.execute(:method => :put, :url => info['url'], :headers => headers, :payload => file_contents)
rescue RestClient::RequestFailed => e
Chef::Log.error("Upload failed: #{e.message}\n#{e.response.body}")
raise
end
else
Chef::Log.debug("#{checksum_files[checksum]} has not changed")
end
end
sandbox_url = new_sandbox['uri']
Chef::Log.debug("Committing sandbox")
# Retry if S3 is claims a checksum doesn't exist (the eventual
# in eventual consistency)
retries = 0
begin
rest.put_rest(sandbox_url, {:is_completed => true})
rescue Net::HTTPServerException => e
if e.message =~ /^400/ && (retries += 1) <= 5
sleep 2
retry
else
raise
end
end
# files are uploaded, so save the manifest
cookbook.save
Chef::Log.info("Upload complete!")
end
def build_metadata(cookbook)
Chef::Log.debug("Generating metadata")
kcm = Chef::Knife::CookbookMetadata.new
kcm.config[:cookbook_path] = Chef::Config[:cookbook_path]
kcm.name_args = [ cookbook.name.to_s ]
kcm.run
end
def validate_cookbook(cookbook)
syntax_checker = Chef::Cookbook::SyntaxCheck.for_cookbook(cookbook.name, @user_cookbook_path)
Chef::Log.info("Validating ruby files")
exit(1) unless syntax_checker.validate_ruby_files
Chef::Log.info("Validating templates")
exit(1) unless syntax_checker.validate_templates
Chef::Log.info("Syntax OK")
true
end
end
end
end
Prevent double '/' in HTTP call to sandboxes
require 'rest_client'
require 'chef/cookbook_loader'
require 'chef/cache/checksum'
require 'chef/sandbox'
require 'chef/cookbook_version'
require 'chef/cookbook/syntax_check'
require 'chef/cookbook/file_system_file_vendor'
class Chef
class CookbookUploader
class << self
def upload_cookbook(cookbook)
Chef::Log.info("Saving #{cookbook.name}")
rest = Chef::REST.new(Chef::Config[:chef_server_url])
# Syntax Check
validate_cookbook(cookbook)
# Generate metadata.json from metadata.rb
build_metadata(cookbook)
# generate checksums of cookbook files and create a sandbox
checksum_files = cookbook.checksums
checksums = checksum_files.inject({}){|memo,elt| memo[elt.first]=nil ; memo}
new_sandbox = rest.post_rest("sandboxes", { :checksums => checksums })
Chef::Log.info("Uploading files")
# upload the new checksums and commit the sandbox
new_sandbox['checksums'].each do |checksum, info|
if info['needs_upload'] == true
Chef::Log.info("Uploading #{checksum_files[checksum]} (checksum hex = #{checksum}) to #{info['url']}")
# Checksum is the hexadecimal representation of the md5,
# but we need the base64 encoding for the content-md5
# header
checksum64 = Base64.encode64([checksum].pack("H*")).strip
timestamp = Time.now.utc.iso8601
file_contents = File.read(checksum_files[checksum])
# TODO - 5/28/2010, cw: make signing and sending the request streaming
sign_obj = Mixlib::Authentication::SignedHeaderAuth.signing_object(
:http_method => :put,
:path => URI.parse(info['url']).path,
:body => file_contents,
:timestamp => timestamp,
:user_id => rest.client_name
)
headers = { 'content-type' => 'application/x-binary', 'content-md5' => checksum64, :accept => 'application/json' }
headers.merge!(sign_obj.sign(OpenSSL::PKey::RSA.new(rest.signing_key)))
begin
RestClient::Request.execute(:method => :put, :url => info['url'], :headers => headers, :payload => file_contents)
rescue RestClient::RequestFailed => e
Chef::Log.error("Upload failed: #{e.message}\n#{e.response.body}")
raise
end
else
Chef::Log.debug("#{checksum_files[checksum]} has not changed")
end
end
sandbox_url = new_sandbox['uri']
Chef::Log.debug("Committing sandbox")
# Retry if S3 is claims a checksum doesn't exist (the eventual
# in eventual consistency)
retries = 0
begin
rest.put_rest(sandbox_url, {:is_completed => true})
rescue Net::HTTPServerException => e
if e.message =~ /^400/ && (retries += 1) <= 5
sleep 2
retry
else
raise
end
end
# files are uploaded, so save the manifest
cookbook.save
Chef::Log.info("Upload complete!")
end
def build_metadata(cookbook)
Chef::Log.debug("Generating metadata")
kcm = Chef::Knife::CookbookMetadata.new
kcm.config[:cookbook_path] = Chef::Config[:cookbook_path]
kcm.name_args = [ cookbook.name.to_s ]
kcm.run
end
def validate_cookbook(cookbook)
syntax_checker = Chef::Cookbook::SyntaxCheck.for_cookbook(cookbook.name, @user_cookbook_path)
Chef::Log.info("Validating ruby files")
exit(1) unless syntax_checker.validate_ruby_files
Chef::Log.info("Validating templates")
exit(1) unless syntax_checker.validate_templates
Chef::Log.info("Syntax OK")
true
end
end
end
end
|
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Copyright:: Copyright (c) 2008, 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require 'rubygems'
require 'json'
require 'chef'
require 'chef/role'
require 'chef/cookbook/metadata'
require 'tempfile'
require 'rake'
desc "Update your repository from source control"
task :update do
puts "** Updating your repository"
case $vcs
when :svn
sh %{svn up}
when :git
pull = false
pull = true if File.join(TOPDIR, ".git", "remotes", "origin")
IO.foreach(File.join(TOPDIR, ".git", "config")) do |line|
pull = true if line =~ /\[remote "origin"\]/
end
if pull
sh %{git pull}
else
puts "* Skipping git pull, no origin specified"
end
else
puts "* No SCM configured, skipping update"
end
end
desc "Test your cookbooks for syntax errors"
task :test_recipes do
puts "** Testing your cookbooks for syntax errors"
if File.exists?(TEST_CACHE)
cache = JSON.load(open(TEST_CACHE).read)
trap("INT") { puts "INT received, flushing test cache"; write_cache(cache) }
else
cache = {}
end
recipes = ["*cookbooks"].map { |folder|
Dir[File.join(TOPDIR, folder, "**", "*.rb")]
}.flatten
recipes.each do |recipe|
print "Testing recipe #{recipe}: "
recipe_mtime = File.stat(recipe).mtime.to_s
if cache.has_key?(recipe)
if cache[recipe]["mtime"] == recipe_mtime
puts "No modification since last test."
next
end
else
cache[recipe] = {}
end
sh %{ruby -c #{recipe}} do |ok, res|
if ok
cache[recipe]["mtime"] = recipe_mtime
else
write_cache(cache)
raise "Syntax error in #{recipe}"
end
end
end
write_cache(cache)
end
desc "Test your templates for syntax errors"
task :test_templates do
puts "** Testing your cookbooks for syntax errors"
if File.exists?(TEST_CACHE)
cache = JSON.load(open(TEST_CACHE).read)
trap("INT") { puts "INT received, flushing test cache"; write_cache(cache) }
else
cache = {}
end
templates = ["*cookbooks"].map { |folder|
Dir[File.join(TOPDIR, folder, "**", "*.erb")]
}.flatten
templates.each do |template|
print "Testing template #{template}: "
template_mtime = File.stat(template).mtime.to_s
if cache.has_key?(template)
if cache[template]["mtime"] == template_mtime
puts "No change since last test."
next
end
else
cache[template] = {}
end
sh %{erubis -x #{template} | ruby -c} do |ok, res|
if ok
cache[template]["mtime"] = template_mtime
else
write_cache(cache)
raise "Syntax error in #{template}"
end
end
end
write_cache(cache)
end
desc "Test your cookbooks for syntax errors"
task :test => [ :test_recipes , :test_templates ]
def write_cache(cache)
File.open(TEST_CACHE, "w") { |f| JSON.dump(cache, f) }
end
desc "Install the latest copy of the repository on this Chef Server"
task :install => [ :update, :test, :metadata, :roles ] do
puts "** Installing your cookbooks"
directories = [
COOKBOOK_PATH,
SITE_COOKBOOK_PATH,
CHEF_CONFIG_PATH
]
puts "* Creating Directories"
directories.each do |dir|
sh "sudo mkdir -p #{dir}"
sh "sudo chown root #{dir}"
end
puts "* Installing new Cookbooks"
sh "sudo rsync -rlP --delete --exclude '.svn' --exclude '.git*' cookbooks/ #{COOKBOOK_PATH}"
puts "* Installing new Site Cookbooks"
sh "sudo rsync -rlP --delete --exclude '.svn' --exclude '.git*' site-cookbooks/ #{SITE_COOKBOOK_PATH}"
puts "* Installing new Node Roles"
sh "sudo rsync -rlP --delete --exclude '.svn' --exclude '.git*' roles/ #{ROLE_PATH}"
if File.exists?(File.join(File.dirname(__FILE__), "config", "server.rb"))
puts "* Installing new Chef Server Config"
sh "sudo cp config/server.rb #{CHEF_SERVER_CONFIG}"
end
if File.exists?(File.join(File.dirname(__FILE__), "config", "client.rb"))
puts "* Installing new Chef Client Config"
sh "sudo cp config/client.rb #{CHEF_CLIENT_CONFIG}"
end
end
desc "By default, run rake test"
task :default => [ :test ]
desc "Create a new cookbook (with COOKBOOK=name, optional CB_PREFIX=site-)"
task :new_cookbook do
create_cookbook(File.join(TOPDIR, "#{ENV["CB_PREFIX"]}cookbooks"))
create_readme(File.join(TOPDIR, "#{ENV["CB_PREFIX"]}cookbooks"))
create_metadata(File.join(TOPDIR, "#{ENV["CB_PREFIX"]}cookbooks"))
end
def create_cookbook(dir)
raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
puts "** Creating cookbook #{ENV["COOKBOOK"]}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "attributes")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "recipes")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "definitions")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "libraries")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "files", "default")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "templates", "default")}"
unless File.exists?(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"))
open(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"), "w") do |file|
file.puts <<-EOH
#
# Cookbook Name:: #{ENV["COOKBOOK"]}
# Recipe:: default
#
# Copyright #{Time.now.year}, #{COMPANY_NAME}
#
EOH
case NEW_COOKBOOK_LICENSE
when :apachev2
file.puts <<-EOH
# 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.
#
EOH
when :none
file.puts <<-EOH
# All rights reserved - Do Not Redistribute
#
EOH
end
end
end
end
def create_readme(dir)
raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
puts "** Creating README for cookbook: #{ENV["COOKBOOK"]}"
unless File.exists?(File.join(dir, ENV["COOKBOOK"], "README.rdoc"))
open(File.join(dir, ENV["COOKBOOK"], "README.rdoc"), "w") do |file|
file.puts <<-EOH
= DESCRIPTION:
= REQUIREMENTS:
= ATTRIBUTES:
= USAGE:
EOH
end
end
end
def create_metadata(dir)
raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
puts "** Creating metadata for cookbook: #{ENV["COOKBOOK"]}"
case NEW_COOKBOOK_LICENSE
when :apachev2
license = "Apache 2.0"
when :none
license = "All rights reserved"
end
unless File.exists?(File.join(dir, ENV["COOKBOOK"], "metadata.rb"))
open(File.join(dir, ENV["COOKBOOK"], "metadata.rb"), "w") do |file|
if File.exists?(File.join(dir, ENV["COOKBOOK"], 'README.rdoc'))
long_description = "long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))"
end
file.puts <<-EOH
maintainer "#{COMPANY_NAME}"
maintainer_email "#{SSL_EMAIL_ADDRESS}"
license "#{license}"
description "Installs/Configures #{ENV["COOKBOOK"]}"
#{long_description}
version "0.1"
EOH
end
end
end
desc "Create a new self-signed SSL certificate for FQDN=foo.example.com"
task :ssl_cert do
$expect_verbose = true
fqdn = ENV["FQDN"]
fqdn =~ /^(.+?)\.(.+)$/
hostname = $1
domain = $2
raise "Must provide FQDN!" unless fqdn && hostname && domain
puts "** Creating self signed SSL Certificate for #{fqdn}"
sh("(cd #{CADIR} && openssl genrsa 2048 > #{fqdn}.key)")
sh("(cd #{CADIR} && chmod 644 #{fqdn}.key)")
puts "* Generating Self Signed Certificate Request"
tf = Tempfile.new("#{fqdn}.ssl-conf")
ssl_config = <<EOH
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
C = #{SSL_COUNTRY_NAME}
ST = #{SSL_STATE_NAME}
L = #{SSL_LOCALITY_NAME}
O = #{COMPANY_NAME}
OU = #{SSL_ORGANIZATIONAL_UNIT_NAME}
CN = #{fqdn}
emailAddress = #{SSL_EMAIL_ADDRESS}
EOH
tf.puts(ssl_config)
tf.close
sh("(cd #{CADIR} && openssl req -config '#{tf.path}' -new -x509 -nodes -sha1 -days 3650 -key #{fqdn}.key > #{fqdn}.crt)")
sh("(cd #{CADIR} && openssl x509 -noout -fingerprint -text < #{fqdn}.crt > #{fqdn}.info)")
sh("(cd #{CADIR} && cat #{fqdn}.crt #{fqdn}.key > #{fqdn}.pem)")
sh("(cd #{CADIR} && chmod 644 #{fqdn}.pem)")
end
desc "Build cookbook metadata.json from metadata.rb"
task :metadata do
Chef::Config[:cookbook_path] = [ File.join(TOPDIR, 'cookbooks'), File.join(TOPDIR, 'site-cookbooks') ]
cl = Chef::CookbookLoader.new
cl.each do |cookbook|
if ENV['COOKBOOK']
next unless cookbook.name.to_s == ENV['COOKBOOK']
end
cook_meta = Chef::Cookbook::Metadata.new(cookbook)
Chef::Config.cookbook_path.each do |cdir|
metadata_rb_file = File.join(cdir, cookbook.name.to_s, 'metadata.rb')
metadata_json_file = File.join(cdir, cookbook.name.to_s, 'metadata.json')
if File.exists?(metadata_rb_file)
puts "Generating metadata for #{cookbook.name}"
cook_meta.from_file(metadata_rb_file)
File.open(metadata_json_file, "w") do |f|
f.write(JSON.pretty_generate(cook_meta))
end
end
end
end
end
desc "Build roles from roles/role_name.json from role_name.rb"
task :roles do
Chef::Config[:role_path] = File.join(TOPDIR, 'roles')
Dir[File.join(TOPDIR, 'roles', '**', '*.rb')].each do |role_file|
short_name = File.basename(role_file, '.rb')
puts "Generating role JSON for #{short_name}"
role = Chef::Role.new
role.name(short_name)
role.from_file(role_file)
File.open(File.join(TOPDIR, 'roles', "#{short_name}.json"), "w") do |f|
f.write(JSON.pretty_generate(role))
end
end
end
Adding upload cookbook tasks
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Copyright:: Copyright (c) 2008, 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# 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.
#
require 'rubygems'
require 'json'
require 'chef'
require 'chef/role'
require 'chef/cookbook/metadata'
require 'tempfile'
require 'rake'
desc "Update your repository from source control"
task :update do
puts "** Updating your repository"
case $vcs
when :svn
sh %{svn up}
when :git
pull = false
pull = true if File.join(TOPDIR, ".git", "remotes", "origin")
IO.foreach(File.join(TOPDIR, ".git", "config")) do |line|
pull = true if line =~ /\[remote "origin"\]/
end
if pull
sh %{git pull}
else
puts "* Skipping git pull, no origin specified"
end
else
puts "* No SCM configured, skipping update"
end
end
desc "Test your cookbooks for syntax errors"
task :test_recipes do
puts "** Testing your cookbooks for syntax errors"
if File.exists?(TEST_CACHE)
cache = JSON.load(open(TEST_CACHE).read)
trap("INT") { puts "INT received, flushing test cache"; write_cache(cache) }
else
cache = {}
end
recipes = ["*cookbooks"].map { |folder|
Dir[File.join(TOPDIR, folder, "**", "*.rb")]
}.flatten
recipes.each do |recipe|
print "Testing recipe #{recipe}: "
recipe_mtime = File.stat(recipe).mtime.to_s
if cache.has_key?(recipe)
if cache[recipe]["mtime"] == recipe_mtime
puts "No modification since last test."
next
end
else
cache[recipe] = {}
end
sh %{ruby -c #{recipe}} do |ok, res|
if ok
cache[recipe]["mtime"] = recipe_mtime
else
write_cache(cache)
raise "Syntax error in #{recipe}"
end
end
end
write_cache(cache)
end
desc "Test your templates for syntax errors"
task :test_templates do
puts "** Testing your cookbooks for syntax errors"
if File.exists?(TEST_CACHE)
cache = JSON.load(open(TEST_CACHE).read)
trap("INT") { puts "INT received, flushing test cache"; write_cache(cache) }
else
cache = {}
end
templates = ["*cookbooks"].map { |folder|
Dir[File.join(TOPDIR, folder, "**", "*.erb")]
}.flatten
templates.each do |template|
print "Testing template #{template}: "
template_mtime = File.stat(template).mtime.to_s
if cache.has_key?(template)
if cache[template]["mtime"] == template_mtime
puts "No change since last test."
next
end
else
cache[template] = {}
end
sh %{erubis -x #{template} | ruby -c} do |ok, res|
if ok
cache[template]["mtime"] = template_mtime
else
write_cache(cache)
raise "Syntax error in #{template}"
end
end
end
write_cache(cache)
end
desc "Test your cookbooks for syntax errors"
task :test => [ :test_recipes , :test_templates ]
def write_cache(cache)
File.open(TEST_CACHE, "w") { |f| JSON.dump(cache, f) }
end
desc "Install the latest copy of the repository on this Chef Server"
task :install => [ :update, :test, :metadata, :roles ] do
puts "** Installing your cookbooks"
directories = [
COOKBOOK_PATH,
SITE_COOKBOOK_PATH,
CHEF_CONFIG_PATH
]
puts "* Creating Directories"
directories.each do |dir|
sh "sudo mkdir -p #{dir}"
sh "sudo chown root #{dir}"
end
puts "* Installing new Cookbooks"
sh "sudo rsync -rlP --delete --exclude '.svn' --exclude '.git*' cookbooks/ #{COOKBOOK_PATH}"
puts "* Installing new Site Cookbooks"
sh "sudo rsync -rlP --delete --exclude '.svn' --exclude '.git*' site-cookbooks/ #{SITE_COOKBOOK_PATH}"
puts "* Installing new Node Roles"
sh "sudo rsync -rlP --delete --exclude '.svn' --exclude '.git*' roles/ #{ROLE_PATH}"
if File.exists?(File.join(File.dirname(__FILE__), "config", "server.rb"))
puts "* Installing new Chef Server Config"
sh "sudo cp config/server.rb #{CHEF_SERVER_CONFIG}"
end
if File.exists?(File.join(File.dirname(__FILE__), "config", "client.rb"))
puts "* Installing new Chef Client Config"
sh "sudo cp config/client.rb #{CHEF_CLIENT_CONFIG}"
end
end
desc "By default, run rake test"
task :default => [ :test ]
desc "Create a new cookbook (with COOKBOOK=name, optional CB_PREFIX=site-)"
task :new_cookbook do
create_cookbook(File.join(TOPDIR, "#{ENV["CB_PREFIX"]}cookbooks"))
create_readme(File.join(TOPDIR, "#{ENV["CB_PREFIX"]}cookbooks"))
create_metadata(File.join(TOPDIR, "#{ENV["CB_PREFIX"]}cookbooks"))
end
def create_cookbook(dir)
raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
puts "** Creating cookbook #{ENV["COOKBOOK"]}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "attributes")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "recipes")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "definitions")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "libraries")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "files", "default")}"
sh "mkdir -p #{File.join(dir, ENV["COOKBOOK"], "templates", "default")}"
unless File.exists?(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"))
open(File.join(dir, ENV["COOKBOOK"], "recipes", "default.rb"), "w") do |file|
file.puts <<-EOH
#
# Cookbook Name:: #{ENV["COOKBOOK"]}
# Recipe:: default
#
# Copyright #{Time.now.year}, #{COMPANY_NAME}
#
EOH
case NEW_COOKBOOK_LICENSE
when :apachev2
file.puts <<-EOH
# 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.
#
EOH
when :none
file.puts <<-EOH
# All rights reserved - Do Not Redistribute
#
EOH
end
end
end
end
def create_readme(dir)
raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
puts "** Creating README for cookbook: #{ENV["COOKBOOK"]}"
unless File.exists?(File.join(dir, ENV["COOKBOOK"], "README.rdoc"))
open(File.join(dir, ENV["COOKBOOK"], "README.rdoc"), "w") do |file|
file.puts <<-EOH
= DESCRIPTION:
= REQUIREMENTS:
= ATTRIBUTES:
= USAGE:
EOH
end
end
end
def create_metadata(dir)
raise "Must provide a COOKBOOK=" unless ENV["COOKBOOK"]
puts "** Creating metadata for cookbook: #{ENV["COOKBOOK"]}"
case NEW_COOKBOOK_LICENSE
when :apachev2
license = "Apache 2.0"
when :none
license = "All rights reserved"
end
unless File.exists?(File.join(dir, ENV["COOKBOOK"], "metadata.rb"))
open(File.join(dir, ENV["COOKBOOK"], "metadata.rb"), "w") do |file|
if File.exists?(File.join(dir, ENV["COOKBOOK"], 'README.rdoc'))
long_description = "long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))"
end
file.puts <<-EOH
maintainer "#{COMPANY_NAME}"
maintainer_email "#{SSL_EMAIL_ADDRESS}"
license "#{license}"
description "Installs/Configures #{ENV["COOKBOOK"]}"
#{long_description}
version "0.1"
EOH
end
end
end
desc "Create a new self-signed SSL certificate for FQDN=foo.example.com"
task :ssl_cert do
$expect_verbose = true
fqdn = ENV["FQDN"]
fqdn =~ /^(.+?)\.(.+)$/
hostname = $1
domain = $2
raise "Must provide FQDN!" unless fqdn && hostname && domain
puts "** Creating self signed SSL Certificate for #{fqdn}"
sh("(cd #{CADIR} && openssl genrsa 2048 > #{fqdn}.key)")
sh("(cd #{CADIR} && chmod 644 #{fqdn}.key)")
puts "* Generating Self Signed Certificate Request"
tf = Tempfile.new("#{fqdn}.ssl-conf")
ssl_config = <<EOH
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
C = #{SSL_COUNTRY_NAME}
ST = #{SSL_STATE_NAME}
L = #{SSL_LOCALITY_NAME}
O = #{COMPANY_NAME}
OU = #{SSL_ORGANIZATIONAL_UNIT_NAME}
CN = #{fqdn}
emailAddress = #{SSL_EMAIL_ADDRESS}
EOH
tf.puts(ssl_config)
tf.close
sh("(cd #{CADIR} && openssl req -config '#{tf.path}' -new -x509 -nodes -sha1 -days 3650 -key #{fqdn}.key > #{fqdn}.crt)")
sh("(cd #{CADIR} && openssl x509 -noout -fingerprint -text < #{fqdn}.crt > #{fqdn}.info)")
sh("(cd #{CADIR} && cat #{fqdn}.crt #{fqdn}.key > #{fqdn}.pem)")
sh("(cd #{CADIR} && chmod 644 #{fqdn}.pem)")
end
desc "Build cookbook metadata.json from metadata.rb"
task :metadata do
Chef::Config[:cookbook_path] = [ File.join(TOPDIR, 'cookbooks'), File.join(TOPDIR, 'site-cookbooks') ]
cl = Chef::CookbookLoader.new
cl.each do |cookbook|
if ENV['COOKBOOK']
next unless cookbook.name.to_s == ENV['COOKBOOK']
end
cook_meta = Chef::Cookbook::Metadata.new(cookbook)
Chef::Config.cookbook_path.each do |cdir|
metadata_rb_file = File.join(cdir, cookbook.name.to_s, 'metadata.rb')
metadata_json_file = File.join(cdir, cookbook.name.to_s, 'metadata.json')
if File.exists?(metadata_rb_file)
puts "Generating metadata for #{cookbook.name}"
cook_meta.from_file(metadata_rb_file)
File.open(metadata_json_file, "w") do |f|
f.write(JSON.pretty_generate(cook_meta))
end
end
end
end
end
desc "Build roles from roles/role_name.json from role_name.rb"
task :roles do
Chef::Config[:role_path] = File.join(TOPDIR, 'roles')
Dir[File.join(TOPDIR, 'roles', '**', '*.rb')].each do |role_file|
short_name = File.basename(role_file, '.rb')
puts "Generating role JSON for #{short_name}"
role = Chef::Role.new
role.name(short_name)
role.from_file(role_file)
File.open(File.join(TOPDIR, 'roles', "#{short_name}.json"), "w") do |f|
f.write(JSON.pretty_generate(role))
end
end
end
desc "Upload all cookbooks"
task :upload_cookbooks => [ :metadata ]
task :upload_cookbooks do
Chef::Config[:cookbook_path] = [ File.join(TOPDIR, 'cookbooks'), File.join(TOPDIR, 'site-cookbooks') ]
cl = Chef::CookbookLoader.new
cl.each do |cookbook|
cook_meta = Chef::Cookbook::Metadata.new(cookbook)
upload_single_cookbook(cookbook.name.to_s, cook_meta.version)
puts "* Uploaded #{cookbook.name.to_s}"
end
end
desc "Upload a single cookbook"
task :upload_cookbook => [ :metadata ]
task :upload_cookbook, :cookbook do |t, args|
upload_single_cookbook(args.cookbook)
puts "* Uploaded #{args.cookbook}"
end
def upload_single_cookbook(cookbook_name, version=nil)
require 'chef/streaming_cookbook_uploader'
Chef::Log.level(:error)
Mixlib::Authentication::Log.logger = Chef::Log.logger
raise ArgumentError, "OPSCODE_KEY must be set to your API Key" unless ENV.has_key?("OPSCODE_KEY")
raise ArgumentError, "OPSCODE_USER must be set to your Username" unless ENV.has_key?("OPSCODE_USER")
Chef::Config.from_file("/etc/chef/client.rb")
tarball_name = "#{cookbook_name}.tar.gz"
temp_dir = File.join(Dir.tmpdir, "chef-upload-cookbooks")
temp_cookbook_dir = File.join(temp_dir, cookbook_name)
FileUtils.mkdir(temp_dir)
FileUtils.mkdir(temp_cookbook_dir)
child_folders = [ "cookbooks/#{cookbook_name}", "site-cookbooks/#{cookbook_name}" ]
child_folders.each do |folder|
file_path = File.join(TOPDIR, folder, ".")
FileUtils.cp_r(file_path, temp_cookbook_dir) if File.directory?(file_path)
end
system("tar", "-C", temp_dir, "-czf", File.join(temp_dir, tarball_name), "./#{cookbook_name}")
r = Chef::REST.new(Chef::Config[:chef_server_url], ENV['OPSCODE_USER'], ENV['OPSCODE_KEY'])
begin
cb = r.get_rest("cookbooks/#{cookbook_name}")
cookbook_uploaded = true
rescue Net::HTTPServerException
cookbook_uploaded = false
end
puts "* Uploading #{cookbook_name} (#{cookbook_uploaded ? 'new version' : 'first time'})"
if cookbook_uploaded
Chef::StreamingCookbookUploader.put("#{Chef::Config[:chef_server_url]}/cookbooks/#{cookbook_name}/_content", ENV["OPSCODE_USER"], ENV["OPSCODE_KEY"], {:file => File.new(File.join(temp_dir, tarball_name)), :name => cookbook_name})
else
Chef::StreamingCookbookUploader.post("#{Chef::Config[:chef_server_url]}/cookbooks", ENV["OPSCODE_USER"], ENV["OPSCODE_KEY"], {:file => File.new(File.join(temp_dir, tarball_name)), :name => cookbook_name})
end
#delete temp files (e.g. /tmp/cookbooks and /tmp/cookbooks.tgz)
FileUtils.rm_rf temp_dir
end
|
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'has_publishing/version'
Gem::Specification.new do |gem|
gem.name = "has_publishing"
gem.version = HasPublishing::VERSION
gem.authors = ["Josh McArthur @ 3months"]
gem.email = ["joshua.mcarthur@gmail.com"]
gem.description = %q{Add ability to publish/embargo models}
gem.summary = %q{Add publishing to your ActiveRecord models}
gem.homepage = "https://github.com/3months/has_publishing"
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 "activerecord"
gem.add_dependency "activesupport"
gem.add_development_dependency "debugger"
gem.add_development_dependency "rspec-rails"
gem.add_development_dependency "sqlite3"
end
Improve gem description
# -*- encoding: utf-8 -*-
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'has_publishing/version'
Gem::Specification.new do |gem|
gem.name = "has_publishing"
gem.version = HasPublishing::VERSION
gem.authors = ["Josh McArthur @ 3months"]
gem.email = ["joshua.mcarthur@gmail.com"]
gem.description = %q{Add ability to draft/publish/withdraw/embargo models}
gem.summary = %q{Add publishing to your ActiveRecord models}
gem.homepage = "https://github.com/3months/has_publishing"
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 "activerecord"
gem.add_dependency "activesupport"
gem.add_development_dependency "debugger"
gem.add_development_dependency "rspec-rails"
gem.add_development_dependency "sqlite3"
end
|
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{has_timestamps}
s.version = "1.5.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Seamus Abshere"]
s.date = %q{2009-05-14}
s.description = %q{has_timestamps is a Rails plugin that allows you to add named timestamps to ActiveRecord models without adding database columns.}
s.email = %q{seamus@abshere.net}
s.extra_rdoc_files = [
"README"
]
s.files = [
"VERSION.yml",
"examples/timestamp.rb",
"init.rb",
"lib/has_timestamps.rb",
"rails/init.rb",
"test/has_timestamps_test.rb",
"test/test_helper.rb"
]
s.homepage = %q{http://github.com/seamusabshere/has_timestamps}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.3}
s.summary = %q{Rails plugin to add named timestamps to ActiveRecord models.}
s.test_files = [
"test/has_timestamps_test.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
else
end
else
end
end
Regenerated gemspec for version 1.5.3
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{has_timestamps}
s.version = "1.5.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Seamus Abshere"]
s.date = %q{2009-05-15}
s.description = %q{has_timestamps is a Rails plugin that allows you to add named timestamps to ActiveRecord models without adding database columns.}
s.email = %q{seamus@abshere.net}
s.extra_rdoc_files = [
"README"
]
s.files = [
"VERSION.yml",
"examples/timestamp.rb",
"init.rb",
"lib/has_timestamps.rb",
"rails/init.rb",
"test/has_timestamps_test.rb",
"test/test_helper.rb"
]
s.homepage = %q{http://github.com/seamusabshere/has_timestamps}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.3}
s.summary = %q{Rails plugin to add named timestamps to ActiveRecord models.}
s.test_files = [
"test/has_timestamps_test.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
else
end
else
end
end
|
require 'grape'
module Api
class TutorialEnrolmentsApi < Grape::API
helpers AuthenticationHelpers
helpers AuthorisationHelpers
before do
authenticated?
end
desc 'Enrol project in a tutorial'
post '/units/:unit_id/tutorials/:tutorial_abbr/enrolments/:project_id' do
unit = Unit.find(params[:unit_id])
unless authorise? current_user, unit, :change_tutorial
error!({ error: 'Not authorised to change tutorial' }, 403)
end
tutorial = unit.tutorials.find_by(abbreviation: params[:tutorial_abbr])
error!({ error: "No tutorial with abbreviation #{params[:tutorial_abbr]} exists for the unit" }, 403) unless tutorial.present?
project = Project.find(params[:project_id])
result = project.enrol_in(tutorial)
if result.nil?
error!({ error: 'No enrolment added' }, 403)
else
result
end
{
enrolments: ActiveModel::ArraySerializer.new(project.tutorial_enrolments,
each_serializer: TutorialEnrolmentSerializer)
}
end
desc 'Delete an enrolment in the tutorial'
delete '/units/:unit_id/tutorials/:tutorial_abbr/enrolments/:project_id' do
unit = Unit.find(params[:unit_id])
unless authorise? current_user, unit, :change_tutorial
error!({ error: 'Not authorised to change tutorials' }, 403)
end
tutorial = unit.tutorials.find_by(abbreviation: params[:tutorial_abbr])
error!({ error: "No tutorial with abbreviation #{params[:tutorial_abbr]} exists for the unit" }, 403) unless tutorial.present?
tutorial_enrolment = tutorial.tutorial_enrolments.find_by(project_id: params[:project_id])
error!({ error: "Project not enrolled in the selected tutorial" }, 403) unless tutorial_enrolment.present?
tutorial_enrolment.destroy
{
enrolments: ActiveModel::ArraySerializer.new(Project.find(params[:project_id]).tutorial_enrolments,
each_serializer: TutorialEnrolmentSerializer)
}
end
end
end
FIX: Ensure tutorial change check uses project
require 'grape'
module Api
class TutorialEnrolmentsApi < Grape::API
helpers AuthenticationHelpers
helpers AuthorisationHelpers
before do
authenticated?
end
desc 'Enrol project in a tutorial'
post '/units/:unit_id/tutorials/:tutorial_abbr/enrolments/:project_id' do
unit = Unit.find(params[:unit_id])
project = unit.active_projects.find(params[:project_id])
unless authorise? current_user, project, :change_tutorial
error!({ error: 'Not authorised to change tutorial' }, 403)
end
tutorial = unit.tutorials.find_by(abbreviation: params[:tutorial_abbr])
error!({ error: "No tutorial with abbreviation #{params[:tutorial_abbr]} exists for the unit" }, 403) unless tutorial.present?
result = project.enrol_in(tutorial)
if result.nil?
error!({ error: 'No enrolment added' }, 403)
else
result
end
{
enrolments: ActiveModel::ArraySerializer.new(project.tutorial_enrolments,
each_serializer: TutorialEnrolmentSerializer)
}
end
desc 'Delete an enrolment in the tutorial'
delete '/units/:unit_id/tutorials/:tutorial_abbr/enrolments/:project_id' do
unit = Unit.find(params[:unit_id])
project = unit.active_projects.find(params[:project_id])
unless authorise? current_user, project, :change_tutorial
error!({ error: 'Not authorised to change tutorials' }, 403)
end
tutorial = unit.tutorials.find_by(abbreviation: params[:tutorial_abbr])
error!({ error: "No tutorial with abbreviation #{params[:tutorial_abbr]} exists for the unit" }, 403) unless tutorial.present?
tutorial_enrolment = tutorial.tutorial_enrolments.find_by(project_id: params[:project_id])
error!({ error: "Project not enrolled in the selected tutorial" }, 403) unless tutorial_enrolment.present?
tutorial_enrolment.destroy
{
enrolments: ActiveModel::ArraySerializer.new(Project.find(params[:project_id]).tutorial_enrolments,
each_serializer: TutorialEnrolmentSerializer)
}
end
end
end
|
#!/usr/bin/ruby
$outfile = {
:config => open('output/include.config.hpp', 'w'),
:config_SYSCTL => open('output/include.config_SYSCTL.cpp', 'w'),
:config_register => open('output/include.config_register.cpp', 'w'),
:config_unregister => open('output/include.config_unregister.cpp', 'w'),
:config_default => open('output/include.config.default.hpp', 'w'),
:remapcode_keyboardtype => open('output/include.remapcode_keyboardtype.hpp', 'w'),
:remapcode_func => open('output/include.remapcode_func.cpp', 'w'),
:remapcode_info => open('output/include.remapcode_info.cpp', 'w'),
:remapcode_refresh_remapfunc_key => open('output/include.remapcode_refresh_remapfunc_key.cpp', 'w'),
:remapcode_refresh_remapfunc_consumer => open('output/include.remapcode_refresh_remapfunc_consumer.cpp', 'w'),
:remapcode_refresh_remapfunc_pointing => open('output/include.remapcode_refresh_remapfunc_pointing.cpp', 'w'),
:remapcode_refresh_remapfunc_statusmessage => open('output/include.remapcode_refresh_remapfunc_statusmessage.cpp', 'w'),
:remapcode_vk_config => open('output/include.remapcode_vk_config.cpp', 'w'),
:keycode_vk_config => open('../keycode/data/include/KeyCode.VK_CONFIG.data', 'w'),
}
$func = {
:key => [],
:consumer => [],
:pointing => [],
}
# ======================================================================
def getextrakey(key)
case key
when 'HOME'
'CURSOR_LEFT'
when 'END'
'CURSOR_RIGHT'
when 'PAGEUP'
'CURSOR_UP'
when 'PAGEDOWN'
'CURSOR_DOWN'
when 'FORWARD_DELETE'
'DELETE'
else
nil
end
end
def preprocess(listAutogen)
modify = false
list = []
listAutogen.each do |autogen|
if /VK_(COMMAND|CONTROL|SHIFT|OPTION)/ =~ autogen then
key = $1
list << autogen.gsub(/VK_#{key}/, "ModifierFlag::#{key}_L")
list << autogen.gsub(/VK_#{key}/, "ModifierFlag::#{key}_R")
modify = true
elsif /VK_MOD_CCOS_L/ =~ autogen then
list << autogen.gsub(/VK_MOD_CCOS_L/, "ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_L")
modify = true
elsif /VK_MOD_CCS_L/ =~ autogen then
list << autogen.gsub(/VK_MOD_CCS_L/, "ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L")
modify = true
elsif /VK_MOD_CCO_L/ =~ autogen then
list << autogen.gsub(/VK_MOD_CCO_L/, "ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L")
modify = true
elsif /FROMKEYCODE_(HOME|END|PAGEUP|PAGEDOWN|FORWARD_DELETE)\s*,\s*ModifierFlag::/ =~ autogen then
key = $1
extrakey = getextrakey(key)
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{key},")
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{extrakey}, ModifierFlag::FN |")
modify = true
elsif /FROMKEYCODE_(HOME|END|PAGEUP|PAGEDOWN|FORWARD_DELETE)/ =~ autogen then
key = $1
extrakey = getextrakey(key)
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{key},")
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{extrakey}, ModifierFlag::FN,")
modify = true
else
list << autogen
end
end
if modify then
list = preprocess(list)
end
list
end
# ======================================================================
def parseautogen(name, lines, autogen_index)
filter = []
code_key = []
code_consumer = []
code_pointing = []
code_variable = []
while true
l = lines.shift
break if l.nil?
# --------------------------------------------------
next if /<\/?item>/ =~ l
next if /<name>.+?<\/name>/ =~ l
next if /<appendix>.+?<\/appendix>/ =~ l
next if /<sysctl>.+?<\/sysctl>/ =~ l
next if /<baseunit>.+?<\/baseunit>/ =~ l
next if /<default>.+?<\/default>/ =~ l
next if /<vk_config>.+?<\/vk_config>/ =~ l
# --------------------------------------------------
if /<block>/ =~ l then
block_code_key, block_code_consumer, block_code_pointing, block_code_variable, autogen_index = parseautogen(name, lines, autogen_index)
code_key << block_code_key unless block_code_key.empty?
code_consumer << block_code_consumer unless block_code_consumer.empty?
code_pointing << block_code_pointing unless block_code_pointing.empty?
code_variable += block_code_variable
elsif /<\/block>/ =~ l then
break
# ================================================================================
elsif /<not>(.+?)<\/not>/ =~ l then
$1.split(/,/).each do |f|
filter << "if (remapParams.workspacedata.type == KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip}) break;"
end
elsif /<only>(.+?)<\/only>/ =~ l then
tmp = []
$1.split(/,/).each do |f|
tmp << "(remapParams.workspacedata.type != KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip})"
end
filter << "if (#{tmp.join(' && ')}) break;"
elsif /<keyboardtype_not>(.+?)<\/keyboardtype_not>/ =~ l then
$1.split(/,/).each do |f|
filter << "if (remapParams.params.keyboardType == KeyboardType::#{f.strip}) break;"
end
elsif /<keyboardtype_only>(.+?)<\/keyboardtype_only>/ =~ l then
tmp = []
$1.split(/,/).each do |f|
tmp << "(remapParams.params.keyboardType != KeyboardType::#{f.strip})"
end
filter << "if (#{tmp.join(' && ')}) break;"
elsif /<(inputmode|inputmodedetail)_not>(.+?)<\/(inputmode|inputmodedetail)_not>/ =~ l then
inputmodetype = $1
$2.split(/,/).each do |f|
filter << "if (remapParams.workspacedata.#{inputmodetype} == KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip}) break;"
end
elsif /<(inputmode|inputmodedetail)_only>(.+?)<\/(inputmode|inputmodedetail)_only>/ =~ l then
inputmodetype = $1
tmp = []
$2.split(/,/).each do |f|
tmp << "(remapParams.workspacedata.#{inputmodetype} != KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip})"
end
filter << "if (#{tmp.join(' && ')}) break;"
# ================================================================================
elsif /<autogen>(.+?)<\/autogen>/ =~ l then
autogen = $1
if /^--(.+?)-- (.+)$/ =~ autogen then
type = $1
params = $2
autogen_index += 1
case type
when 'SetKeyboardType'
$outfile[:remapcode_keyboardtype] << "if (config.#{name}) {\n"
$outfile[:remapcode_keyboardtype] << " keyboardType = #{params}.get();\n"
$outfile[:remapcode_keyboardtype] << "}\n"
when 'ShowStatusMessage'
$outfile[:remapcode_refresh_remapfunc_statusmessage] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_statusmessage] << " statusmessage = #{params};\n"
$outfile[:remapcode_refresh_remapfunc_statusmessage] << " isStatusMessageVisible = true;\n"
$outfile[:remapcode_refresh_remapfunc_statusmessage] << "}\n"
when 'KeyToKey'
code_variable << ['RemapUtil::KeyToKey', "keytokey#{autogen_index}_"]
code_key << "if (keytokey#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'DoublePressModifier'
code_variable << ['DoublePressModifier', "doublepressmodifier#{autogen_index}_"]
code_key << "if (doublepressmodifier#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'IgnoreMultipleSameKeyPress'
code_variable << ['IgnoreMultipleSameKeyPress', "ignoremultiplesamekeypress#{autogen_index}_"]
code_key << "if (ignoremultiplesamekeypress#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyToConsumer'
code_variable << ['RemapUtil::KeyToConsumer', "keytoconsumer#{autogen_index}_"]
code_key << "if (keytoconsumer#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyToPointingButton'
code_variable << ['RemapUtil::KeyToPointingButton', "keytopointing#{autogen_index}_"]
code_key << "if (keytopointing#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyOverlaidModifier'
code_variable << ['KeyOverlaidModifier', "keyoverlaidmodifier#{autogen_index}_"]
code_key << "if (keyoverlaidmodifier#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyOverlaidModifierWithRepeat'
code_variable << ['KeyOverlaidModifier', "keyoverlaidmodifier#{autogen_index}_"]
code_key << "if (keyoverlaidmodifier#{autogen_index}_.remapWithRepeat(remapParams, #{params})) break;"
$func[:key] << name
when 'ModifierHoldingKeyToKey'
code_variable << ['ModifierHoldingKeyToKey', "modifierholdingkeytokey#{autogen_index}_"]
code_key << "if (modifierholdingkeytokey#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'ConsumerToKey'
code_variable << ['RemapUtil::ConsumerToKey', "consumertokey#{autogen_index}_"]
code_consumer << "if (consumertokey#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:consumer] << name
when 'ConsumerToConsumer'
code_variable << ['RemapUtil::ConsumerToConsumer', "consumertoconsumer#{autogen_index}_"]
code_consumer << "if (consumertoconsumer#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:consumer] << name
when 'PointingRelativeToScroll'
code_variable << ['RemapUtil::PointingRelativeToScroll', "pointingrelativetoscroll#{autogen_index}_"]
code_pointing << "if (pointingrelativetoscroll#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:pointing] << name
when 'PointingButtonToPointingButton'
code_variable << ['RemapUtil::PointingButtonToPointingButton', "pointingbuttontopointingbutton#{autogen_index}_"]
code_pointing << "if (pointingbuttontopointingbutton#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:pointing] << name
else
print "%%% ERROR #{type} %%%\n#{l}\n"
exit 1
end
end
elsif /<.+?>.+?<\/.+?>/ =~ l then
print "%%% ERROR unknown command %%%\n#{l}\n"
exit 1
end
end
# ======================================================================
result_code_key = ''
result_code_consumer = ''
result_code_pointing = ''
unless code_key.empty? then
result_code_key += " do {\n"
filter.each do |f|
result_code_key += " #{f}\n"
end
result_code_key += "\n" unless filter.empty?
code_key.each do |line|
result_code_key += " #{line}\n"
end
result_code_key += " } while (false);\n"
end
unless code_consumer.empty? then
result_code_consumer += " do {\n"
filter.each do |f|
result_code_consumer += " #{f}\n"
end
result_code_consumer += "\n" unless filter.empty?
code_consumer.each do |line|
result_code_consumer += " #{line}\n"
end
result_code_consumer += " } while (false);\n"
end
unless code_pointing.empty? then
result_code_pointing += " do {\n"
code_pointing.each do |line|
result_code_pointing += " #{line}\n"
end
result_code_pointing += " } while (false);\n"
end
return result_code_key, result_code_consumer, result_code_pointing, code_variable, autogen_index
end
# ----------------------------------------------------------------------
$stdin.read.scan(/<item>.+?<\/item>/m).each do |item|
if /.*(<item>.+?<\/item>)/m =~ item then
item = $1
end
name = nil
if /<sysctl>([^\.]+?)\.(.+?)<\/sysctl>/m =~ item then
name = "#{$1}_#{$2}"
$outfile[:config_SYSCTL] << "SYSCTL_PROC(_keyremap4macbook_#{$1}, OID_AUTO, #{$2}, CTLTYPE_INT|CTLFLAG_RW, &(config.#{name}), 0, refresh_remapfunc_handler, \"I\", \"\");\n"
$outfile[:config_register] << "sysctl_register_oid(&sysctl__keyremap4macbook_#{name});\n"
$outfile[:config_unregister] << "sysctl_unregister_oid(&sysctl__keyremap4macbook_#{name});\n"
end
next if name.nil?
$outfile[:config] << "int #{name};\n"
if /<default>(.+?)<\/default>/m =~ item then
$outfile[:config_default] << "#{name} = #{$1};\n"
end
# check <name> num == 1
if item.scan(/<name>(.+?)<\/name>/m).size != 1 then
print "%%% ERROR multiple <name> for #{name}\n"
exit 1
end
# ======================================================================
lines = item.split(/\n/)
lines = preprocess(lines)
code_key, code_consumer, code_pointing, code_variable, autogen_index = parseautogen(name, lines, 0)
unless lines.empty? then
print "%%% ERROR no </block> at #{name} %%%\n"
end
next if code_key.empty? &&
code_consumer.empty? &&
code_pointing.empty? &&
code_variable.empty?
$outfile[:remapcode_func] << "class RemapClass_#{name} {\n"
$outfile[:remapcode_func] << "public:\n"
unless code_key.empty? then
$outfile[:remapcode_func] << "static void remap_key(RemapParams &remapParams) {\n"
$outfile[:remapcode_func] << code_key
$outfile[:remapcode_func] << "}\n"
end
unless code_consumer.empty? then
$outfile[:remapcode_func] << "static void remap_consumer(RemapConsumerParams &remapParams) {\n"
$outfile[:remapcode_func] << code_consumer
$outfile[:remapcode_func] << "}\n"
end
unless code_pointing.empty? then
$outfile[:remapcode_func] << "static void remap_pointing(RemapPointingParams_relative &remapParams) {\n"
$outfile[:remapcode_func] << code_pointing
$outfile[:remapcode_func] << "}\n"
end
$outfile[:remapcode_func] << "\n"
$outfile[:remapcode_func] << "private:\n"
code_variable.each do |variable|
$outfile[:remapcode_func] << " static #{variable[0]} #{variable[1]};\n"
end
$outfile[:remapcode_func] << "};\n"
code_variable.each do |variable|
$outfile[:remapcode_func] << "#{variable[0]} RemapClass_#{name}::#{variable[1]};\n"
end
$outfile[:remapcode_func] << "\n\n"
if /<vk_config>true<\/vk_config>/ =~ item then
$outfile[:remapcode_vk_config] << "if (params.key == KeyCode::VK_CONFIG_TOGGLE_#{name}) {\n"
$outfile[:remapcode_vk_config] << " configitem = &(config.#{name});\n"
$outfile[:remapcode_vk_config] << " type = TYPE_TOGGLE;\n"
$outfile[:remapcode_vk_config] << "}\n"
$outfile[:remapcode_vk_config] << "if (params.key == KeyCode::VK_CONFIG_FORCE_ON_#{name}) {\n"
$outfile[:remapcode_vk_config] << " configitem = &(config.#{name});\n"
$outfile[:remapcode_vk_config] << " type = TYPE_FORCE_ON;\n"
$outfile[:remapcode_vk_config] << "}\n"
$outfile[:remapcode_vk_config] << "if (params.key == KeyCode::VK_CONFIG_FORCE_OFF_#{name}) {\n"
$outfile[:remapcode_vk_config] << " configitem = &(config.#{name});\n"
$outfile[:remapcode_vk_config] << " type = TYPE_FORCE_OFF;\n"
$outfile[:remapcode_vk_config] << "}\n"
$outfile[:keycode_vk_config] << "VK_CONFIG_TOGGLE_#{name} --AUTO--\n"
$outfile[:keycode_vk_config] << "VK_CONFIG_FORCE_ON_#{name} --AUTO--\n"
$outfile[:keycode_vk_config] << "VK_CONFIG_FORCE_OFF_#{name} --AUTO--\n"
end
end
$outfile[:remapcode_info] << "enum {\n"
$outfile[:remapcode_info] << " MAXNUM_REMAPFUNC_KEY = #{$func[:key].uniq.count},\n"
$outfile[:remapcode_info] << " MAXNUM_REMAPFUNC_CONSUMER = #{$func[:consumer].uniq.count},\n"
$outfile[:remapcode_info] << " MAXNUM_REMAPFUNC_POINTING = #{$func[:pointing].uniq.count},\n"
$outfile[:remapcode_info] << "};\n"
$func[:key].uniq.each do |name|
$outfile[:remapcode_refresh_remapfunc_key] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_key] << " listRemapFunc_key[listRemapFunc_key_size] = GeneratedCode::RemapClass_#{name}::remap_key;\n"
$outfile[:remapcode_refresh_remapfunc_key] << " ++listRemapFunc_key_size;\n"
$outfile[:remapcode_refresh_remapfunc_key] << "}\n"
end
$func[:consumer].uniq.each do |name|
$outfile[:remapcode_refresh_remapfunc_consumer] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_consumer] << " listRemapFunc_consumer[listRemapFunc_consumer_size] = GeneratedCode::RemapClass_#{name}::remap_consumer;\n"
$outfile[:remapcode_refresh_remapfunc_consumer] << " ++listRemapFunc_consumer_size;\n"
$outfile[:remapcode_refresh_remapfunc_consumer] << "}\n"
end
$func[:pointing].uniq.each do |name|
$outfile[:remapcode_refresh_remapfunc_pointing] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_pointing] << " listRemapFunc_pointing[listRemapFunc_pointing_size] = GeneratedCode::RemapClass_#{name}::remap_pointing;\n"
$outfile[:remapcode_refresh_remapfunc_pointing] << " ++listRemapFunc_pointing_size;\n"
$outfile[:remapcode_refresh_remapfunc_pointing] << "}\n"
end
$outfile.each do |name,file|
file.close
end
update config/make-code @ kext
#!/usr/bin/ruby
$outfile = {
:config => open('output/include.config.hpp', 'w'),
:config_SYSCTL => open('output/include.config_SYSCTL.cpp', 'w'),
:config_register => open('output/include.config_register.cpp', 'w'),
:config_unregister => open('output/include.config_unregister.cpp', 'w'),
:config_default => open('output/include.config.default.hpp', 'w'),
:remapcode_keyboardtype => open('output/include.remapcode_keyboardtype.hpp', 'w'),
:remapcode_func => open('output/include.remapcode_func.cpp', 'w'),
:remapcode_info => open('output/include.remapcode_info.cpp', 'w'),
:remapcode_refresh_remapfunc_key => open('output/include.remapcode_refresh_remapfunc_key.cpp', 'w'),
:remapcode_refresh_remapfunc_consumer => open('output/include.remapcode_refresh_remapfunc_consumer.cpp', 'w'),
:remapcode_refresh_remapfunc_pointing => open('output/include.remapcode_refresh_remapfunc_pointing.cpp', 'w'),
:remapcode_refresh_remapfunc_statusmessage => open('output/include.remapcode_refresh_remapfunc_statusmessage.cpp', 'w'),
:remapcode_vk_config => open('output/include.remapcode_vk_config.cpp', 'w'),
:keycode_vk_config => open('../keycode/data/include/KeyCode.VK_CONFIG.data', 'w'),
}
$func = {
:key => [],
:consumer => [],
:pointing => [],
}
# ======================================================================
def getextrakey(key)
case key
when 'HOME'
'CURSOR_LEFT'
when 'END'
'CURSOR_RIGHT'
when 'PAGEUP'
'CURSOR_UP'
when 'PAGEDOWN'
'CURSOR_DOWN'
when 'FORWARD_DELETE'
'DELETE'
else
nil
end
end
def preprocess(listAutogen)
modify = false
list = []
listAutogen.each do |autogen|
if /VK_(COMMAND|CONTROL|SHIFT|OPTION)/ =~ autogen then
key = $1
list << autogen.gsub(/VK_#{key}/, "ModifierFlag::#{key}_L")
list << autogen.gsub(/VK_#{key}/, "ModifierFlag::#{key}_R")
modify = true
elsif /VK_MOD_CCOS_L/ =~ autogen then
list << autogen.gsub(/VK_MOD_CCOS_L/, "ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L | ModifierFlag::SHIFT_L")
modify = true
elsif /VK_MOD_CCS_L/ =~ autogen then
list << autogen.gsub(/VK_MOD_CCS_L/, "ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L")
modify = true
elsif /VK_MOD_CCO_L/ =~ autogen then
list << autogen.gsub(/VK_MOD_CCO_L/, "ModifierFlag::COMMAND_L | ModifierFlag::CONTROL_L | ModifierFlag::OPTION_L")
modify = true
elsif /FROMKEYCODE_(HOME|END|PAGEUP|PAGEDOWN|FORWARD_DELETE)\s*,\s*ModifierFlag::/ =~ autogen then
key = $1
extrakey = getextrakey(key)
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{key},")
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{extrakey}, ModifierFlag::FN |")
modify = true
elsif /FROMKEYCODE_(HOME|END|PAGEUP|PAGEDOWN|FORWARD_DELETE)/ =~ autogen then
key = $1
extrakey = getextrakey(key)
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{key},")
list << autogen.gsub(/FROMKEYCODE_#{key}\s*,/, "KeyCode::#{extrakey}, ModifierFlag::FN,")
modify = true
else
list << autogen
end
end
if modify then
list = preprocess(list)
end
list
end
# ======================================================================
def parseautogen(name, lines, autogen_index)
filter = []
code_key = []
code_consumer = []
code_pointing = []
code_variable = []
while true
l = lines.shift
break if l.nil?
# --------------------------------------------------
next if /<\/?item>/ =~ l
next if /<name>.+?<\/name>/ =~ l
next if /<appendix>.+?<\/appendix>/ =~ l
next if /<sysctl>.+?<\/sysctl>/ =~ l
next if /<baseunit>.+?<\/baseunit>/ =~ l
next if /<default>.+?<\/default>/ =~ l
next if /<vk_config>.+?<\/vk_config>/ =~ l
# --------------------------------------------------
if /<block>/ =~ l then
block_code_key, block_code_consumer, block_code_pointing, block_code_variable, autogen_index = parseautogen(name, lines, autogen_index)
code_key << block_code_key unless block_code_key.empty?
code_consumer << block_code_consumer unless block_code_consumer.empty?
code_pointing << block_code_pointing unless block_code_pointing.empty?
code_variable += block_code_variable
elsif /<\/block>/ =~ l then
break
# ================================================================================
elsif /<not>(.+?)<\/not>/ =~ l then
$1.split(/,/).each do |f|
filter << "if (remapParams.workspacedata.type == KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip}) break;"
end
elsif /<only>(.+?)<\/only>/ =~ l then
tmp = []
$1.split(/,/).each do |f|
tmp << "(remapParams.workspacedata.type != KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip})"
end
filter << "if (#{tmp.join(' && ')}) break;"
elsif /<keyboardtype_not>(.+?)<\/keyboardtype_not>/ =~ l then
$1.split(/,/).each do |f|
filter << "if (remapParams.params.keyboardType == KeyboardType::#{f.strip}) break;"
end
elsif /<keyboardtype_only>(.+?)<\/keyboardtype_only>/ =~ l then
tmp = []
$1.split(/,/).each do |f|
tmp << "(remapParams.params.keyboardType != KeyboardType::#{f.strip})"
end
filter << "if (#{tmp.join(' && ')}) break;"
elsif /<(inputmode|inputmodedetail)_not>(.+?)<\/(inputmode|inputmodedetail)_not>/ =~ l then
inputmodetype = $1
$2.split(/,/).each do |f|
filter << "if (remapParams.workspacedata.#{inputmodetype} == KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip}) break;"
end
elsif /<(inputmode|inputmodedetail)_only>(.+?)<\/(inputmode|inputmodedetail)_only>/ =~ l then
inputmodetype = $1
tmp = []
$2.split(/,/).each do |f|
tmp << "(remapParams.workspacedata.#{inputmodetype} != KeyRemap4MacBook_bridge::GetWorkspaceData::#{f.strip})"
end
filter << "if (#{tmp.join(' && ')}) break;"
# ================================================================================
elsif /<autogen>(.+?)<\/autogen>/ =~ l then
autogen = $1
if /^--(.+?)-- (.+)$/ =~ autogen then
type = $1
params = $2
autogen_index += 1
case type
when 'SetKeyboardType'
$outfile[:remapcode_keyboardtype] << "if (config.#{name}) {\n"
$outfile[:remapcode_keyboardtype] << " keyboardType = #{params}.get();\n"
$outfile[:remapcode_keyboardtype] << "}\n"
when 'ShowStatusMessage'
$outfile[:remapcode_refresh_remapfunc_statusmessage] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_statusmessage] << " statusmessage = #{params};\n"
$outfile[:remapcode_refresh_remapfunc_statusmessage] << " isStatusMessageVisible = true;\n"
$outfile[:remapcode_refresh_remapfunc_statusmessage] << "}\n"
when 'KeyToKey'
code_variable << ['RemapUtil::KeyToKey', "keytokey#{autogen_index}_"]
code_key << "if (keytokey#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'DoublePressModifier'
code_variable << ['DoublePressModifier', "doublepressmodifier#{autogen_index}_"]
code_key << "if (doublepressmodifier#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'IgnoreMultipleSameKeyPress'
code_variable << ['IgnoreMultipleSameKeyPress', "ignoremultiplesamekeypress#{autogen_index}_"]
code_key << "if (ignoremultiplesamekeypress#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyToConsumer'
code_variable << ['RemapUtil::KeyToConsumer', "keytoconsumer#{autogen_index}_"]
code_key << "if (keytoconsumer#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyToPointingButton'
code_variable << ['RemapUtil::KeyToPointingButton', "keytopointing#{autogen_index}_"]
code_key << "if (keytopointing#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyOverlaidModifier'
code_variable << ['KeyOverlaidModifier', "keyoverlaidmodifier#{autogen_index}_"]
code_key << "if (keyoverlaidmodifier#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'KeyOverlaidModifierWithRepeat'
code_variable << ['KeyOverlaidModifier', "keyoverlaidmodifier#{autogen_index}_"]
code_key << "if (keyoverlaidmodifier#{autogen_index}_.remapWithRepeat(remapParams, #{params})) break;"
$func[:key] << name
when 'ModifierHoldingKeyToKey'
code_variable << ['ModifierHoldingKeyToKey', "modifierholdingkeytokey#{autogen_index}_"]
code_key << "if (modifierholdingkeytokey#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:key] << name
when 'ConsumerToKey'
code_variable << ['RemapUtil::ConsumerToKey', "consumertokey#{autogen_index}_"]
code_consumer << "if (consumertokey#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:consumer] << name
when 'ConsumerToConsumer'
code_variable << ['RemapUtil::ConsumerToConsumer', "consumertoconsumer#{autogen_index}_"]
code_consumer << "if (consumertoconsumer#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:consumer] << name
when 'PointingRelativeToScroll'
code_variable << ['RemapUtil::PointingRelativeToScroll', "pointingrelativetoscroll#{autogen_index}_"]
code_pointing << "if (pointingrelativetoscroll#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:pointing] << name
when 'PointingButtonToPointingButton'
code_variable << ['RemapUtil::PointingButtonToPointingButton', "pointingbuttontopointingbutton#{autogen_index}_"]
code_pointing << "if (pointingbuttontopointingbutton#{autogen_index}_.remap(remapParams, #{params})) break;"
$func[:pointing] << name
else
print "%%% ERROR #{type} %%%\n#{l}\n"
exit 1
end
end
elsif /<.+?>.+?<\/.+?>/ =~ l then
print "%%% ERROR unknown command %%%\n#{l}\n"
exit 1
end
end
# ======================================================================
result_code_key = ''
result_code_consumer = ''
result_code_pointing = ''
unless code_key.empty? then
result_code_key += " do {\n"
filter.each do |f|
result_code_key += " #{f}\n"
end
result_code_key += "\n" unless filter.empty?
code_key.each do |line|
result_code_key += " #{line}\n"
end
result_code_key += " } while (false);\n"
end
unless code_consumer.empty? then
result_code_consumer += " do {\n"
filter.each do |f|
result_code_consumer += " #{f}\n"
end
result_code_consumer += "\n" unless filter.empty?
code_consumer.each do |line|
result_code_consumer += " #{line}\n"
end
result_code_consumer += " } while (false);\n"
end
unless code_pointing.empty? then
result_code_pointing += " do {\n"
code_pointing.each do |line|
result_code_pointing += " #{line}\n"
end
result_code_pointing += " } while (false);\n"
end
return result_code_key, result_code_consumer, result_code_pointing, code_variable, autogen_index
end
# ----------------------------------------------------------------------
$stdin.read.scan(/<item>.+?<\/item>/m).each do |item|
if /.*(<item>.+?<\/item>)/m =~ item then
item = $1
end
name = nil
if /<sysctl>([^\.]+?)\.(.+?)<\/sysctl>/m =~ item then
name = "#{$1}_#{$2}"
$outfile[:config_SYSCTL] << "SYSCTL_PROC(_keyremap4macbook_#{$1}, OID_AUTO, #{$2}, CTLTYPE_INT|CTLFLAG_RW, &(config.#{name}), 0, refresh_remapfunc_handler, \"I\", \"\");\n"
$outfile[:config_register] << "sysctl_register_oid(&sysctl__keyremap4macbook_#{name});\n"
$outfile[:config_unregister] << "sysctl_unregister_oid(&sysctl__keyremap4macbook_#{name});\n"
end
next if name.nil?
$outfile[:config] << "int #{name};\n"
if /<default>(.+?)<\/default>/m =~ item then
$outfile[:config_default] << "#{name} = #{$1};\n"
end
# check <name> num == 1
if item.scan(/<name>(.+?)<\/name>/m).size != 1 then
print "%%% ERROR no <name> or multiple <name> for #{name}\n"
exit 1
end
# ======================================================================
lines = item.split(/\n/)
lines = preprocess(lines)
code_key, code_consumer, code_pointing, code_variable, autogen_index = parseautogen(name, lines, 0)
unless lines.empty? then
print "%%% ERROR no </block> at #{name} %%%\n"
end
next if code_key.empty? &&
code_consumer.empty? &&
code_pointing.empty? &&
code_variable.empty?
$outfile[:remapcode_func] << "class RemapClass_#{name} {\n"
$outfile[:remapcode_func] << "public:\n"
unless code_key.empty? then
$outfile[:remapcode_func] << "static void remap_key(RemapParams &remapParams) {\n"
$outfile[:remapcode_func] << code_key
$outfile[:remapcode_func] << "}\n"
end
unless code_consumer.empty? then
$outfile[:remapcode_func] << "static void remap_consumer(RemapConsumerParams &remapParams) {\n"
$outfile[:remapcode_func] << code_consumer
$outfile[:remapcode_func] << "}\n"
end
unless code_pointing.empty? then
$outfile[:remapcode_func] << "static void remap_pointing(RemapPointingParams_relative &remapParams) {\n"
$outfile[:remapcode_func] << code_pointing
$outfile[:remapcode_func] << "}\n"
end
$outfile[:remapcode_func] << "\n"
$outfile[:remapcode_func] << "private:\n"
code_variable.each do |variable|
$outfile[:remapcode_func] << " static #{variable[0]} #{variable[1]};\n"
end
$outfile[:remapcode_func] << "};\n"
code_variable.each do |variable|
$outfile[:remapcode_func] << "#{variable[0]} RemapClass_#{name}::#{variable[1]};\n"
end
$outfile[:remapcode_func] << "\n\n"
if /<vk_config>true<\/vk_config>/ =~ item then
$outfile[:remapcode_vk_config] << "if (params.key == KeyCode::VK_CONFIG_TOGGLE_#{name}) {\n"
$outfile[:remapcode_vk_config] << " configitem = &(config.#{name});\n"
$outfile[:remapcode_vk_config] << " type = TYPE_TOGGLE;\n"
$outfile[:remapcode_vk_config] << "}\n"
$outfile[:remapcode_vk_config] << "if (params.key == KeyCode::VK_CONFIG_FORCE_ON_#{name}) {\n"
$outfile[:remapcode_vk_config] << " configitem = &(config.#{name});\n"
$outfile[:remapcode_vk_config] << " type = TYPE_FORCE_ON;\n"
$outfile[:remapcode_vk_config] << "}\n"
$outfile[:remapcode_vk_config] << "if (params.key == KeyCode::VK_CONFIG_FORCE_OFF_#{name}) {\n"
$outfile[:remapcode_vk_config] << " configitem = &(config.#{name});\n"
$outfile[:remapcode_vk_config] << " type = TYPE_FORCE_OFF;\n"
$outfile[:remapcode_vk_config] << "}\n"
$outfile[:keycode_vk_config] << "VK_CONFIG_TOGGLE_#{name} --AUTO--\n"
$outfile[:keycode_vk_config] << "VK_CONFIG_FORCE_ON_#{name} --AUTO--\n"
$outfile[:keycode_vk_config] << "VK_CONFIG_FORCE_OFF_#{name} --AUTO--\n"
end
end
$outfile[:remapcode_info] << "enum {\n"
$outfile[:remapcode_info] << " MAXNUM_REMAPFUNC_KEY = #{$func[:key].uniq.count},\n"
$outfile[:remapcode_info] << " MAXNUM_REMAPFUNC_CONSUMER = #{$func[:consumer].uniq.count},\n"
$outfile[:remapcode_info] << " MAXNUM_REMAPFUNC_POINTING = #{$func[:pointing].uniq.count},\n"
$outfile[:remapcode_info] << "};\n"
$func[:key].uniq.each do |name|
$outfile[:remapcode_refresh_remapfunc_key] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_key] << " listRemapFunc_key[listRemapFunc_key_size] = GeneratedCode::RemapClass_#{name}::remap_key;\n"
$outfile[:remapcode_refresh_remapfunc_key] << " ++listRemapFunc_key_size;\n"
$outfile[:remapcode_refresh_remapfunc_key] << "}\n"
end
$func[:consumer].uniq.each do |name|
$outfile[:remapcode_refresh_remapfunc_consumer] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_consumer] << " listRemapFunc_consumer[listRemapFunc_consumer_size] = GeneratedCode::RemapClass_#{name}::remap_consumer;\n"
$outfile[:remapcode_refresh_remapfunc_consumer] << " ++listRemapFunc_consumer_size;\n"
$outfile[:remapcode_refresh_remapfunc_consumer] << "}\n"
end
$func[:pointing].uniq.each do |name|
$outfile[:remapcode_refresh_remapfunc_pointing] << "if (config.#{name}) {\n"
$outfile[:remapcode_refresh_remapfunc_pointing] << " listRemapFunc_pointing[listRemapFunc_pointing_size] = GeneratedCode::RemapClass_#{name}::remap_pointing;\n"
$outfile[:remapcode_refresh_remapfunc_pointing] << " ++listRemapFunc_pointing_size;\n"
$outfile[:remapcode_refresh_remapfunc_pointing] << "}\n"
end
$outfile.each do |name,file|
file.close
end
|
Airbrake.configure do |config|
config.api_key = 'api_key'
end
airbrake
Airbrake.configure do |config|
config.api_key = ENV["AIRBRAKE_API_KEY"]
end
|
# Airbrake is an online tool that provides robust exception tracking in your Rails
# applications. In doing so, it allows you to easily review errors, tie an error
# to an individual piece of code, and trace the cause back to recent
# changes. Airbrake enables for easy categorization, searching, and prioritization
# of exceptions so that when errors occur, your team can quickly determine the
# root cause.
#
# Configuration details:
# https://github.com/airbrake/airbrake-ruby#configuration
Airbrake.configure do |c|
# You must set both project_id & project_key. To find your project_id and
# project_key navigate to your project's General Settings and copy the values
# from the right sidebar.
# https://github.com/airbrake/airbrake-ruby#project_id--project_key
c.project_id = ENV['AIRBRAKE_PROJECT_ID']
c.project_key = ENV['AIRBRAKE_API_KEY']
# Configures the root directory of your project. Expects a String or a
# Pathname, which represents the path to your project. Providing this option
# helps us to filter out repetitive data from backtrace frames and link to
# GitHub files from our dashboard.
# https://github.com/airbrake/airbrake-ruby#root_directory
c.root_directory = Rails.root
# By default, Airbrake Ruby outputs to STDOUT. In Rails apps it makes sense to
# use the Rails' logger.
# https://github.com/airbrake/airbrake-ruby#logger
c.logger = Rails.logger
# Configures the environment the application is running in. Helps the Airbrake
# dashboard to distinguish between exceptions occurring in different
# environments. By default, it's not set.
# NOTE: This option must be set in order to make the 'ignore_environments'
# option work.
# https://github.com/airbrake/airbrake-ruby#environment
c.environment = Rails.env
# Setting this option allows Airbrake to filter exceptions occurring in
# unwanted environments such as :test. By default, it is equal to an empty
# Array, which means Airbrake Ruby sends exceptions occurring in all
# environments.
# NOTE: This option *does not* work if you don't set the 'environment' option.
# https://github.com/airbrake/airbrake-ruby#ignore_environments
c.ignore_environments = %w(test)
# A list of parameters that should be filtered out of what is sent to
# Airbrake. By default, all "password" attributes will have their contents
# replaced.
# https://github.com/airbrake/airbrake-ruby#blacklist_keys
c.blacklist_keys = [/password/i]
# Alternatively, you can integrate with Rails' filter_parameters.
# Read more: https://goo.gl/gqQ1xS
# c.blacklist_keys = Rails.application.config.filter_parameters
end
# If Airbrake doesn't send any expected exceptions, we suggest to uncomment the
# line below. It might simplify debugging of background Airbrake workers, which
# can silently die.
# Thread.abort_on_exception = ['test', 'development'].include?(Rails.env)
Configure airbrake so it ignores development
Makes it easier to work on without having to set up airbrake
environment.
# Airbrake is an online tool that provides robust exception tracking in your Rails
# applications. In doing so, it allows you to easily review errors, tie an error
# to an individual piece of code, and trace the cause back to recent
# changes. Airbrake enables for easy categorization, searching, and prioritization
# of exceptions so that when errors occur, your team can quickly determine the
# root cause.
#
# Configuration details:
# https://github.com/airbrake/airbrake-ruby#configuration
Airbrake.configure do |c|
# You must set both project_id & project_key. To find your project_id and
# project_key navigate to your project's General Settings and copy the values
# from the right sidebar.
# https://github.com/airbrake/airbrake-ruby#project_id--project_key
c.project_id = ENV['AIRBRAKE_PROJECT_ID']
c.project_key = ENV['AIRBRAKE_API_KEY']
# Configures the root directory of your project. Expects a String or a
# Pathname, which represents the path to your project. Providing this option
# helps us to filter out repetitive data from backtrace frames and link to
# GitHub files from our dashboard.
# https://github.com/airbrake/airbrake-ruby#root_directory
c.root_directory = Rails.root
# By default, Airbrake Ruby outputs to STDOUT. In Rails apps it makes sense to
# use the Rails' logger.
# https://github.com/airbrake/airbrake-ruby#logger
c.logger = Rails.logger
# Configures the environment the application is running in. Helps the Airbrake
# dashboard to distinguish between exceptions occurring in different
# environments. By default, it's not set.
# NOTE: This option must be set in order to make the 'ignore_environments'
# option work.
# https://github.com/airbrake/airbrake-ruby#environment
c.environment = Rails.env
# Setting this option allows Airbrake to filter exceptions occurring in
# unwanted environments such as :test. By default, it is equal to an empty
# Array, which means Airbrake Ruby sends exceptions occurring in all
# environments.
# NOTE: This option *does not* work if you don't set the 'environment' option.
# https://github.com/airbrake/airbrake-ruby#ignore_environments
c.ignore_environments = %w(development test)
# A list of parameters that should be filtered out of what is sent to
# Airbrake. By default, all "password" attributes will have their contents
# replaced.
# https://github.com/airbrake/airbrake-ruby#blacklist_keys
c.blacklist_keys = [/password/i]
# Alternatively, you can integrate with Rails' filter_parameters.
# Read more: https://goo.gl/gqQ1xS
# c.blacklist_keys = Rails.application.config.filter_parameters
end
# If Airbrake doesn't send any expected exceptions, we suggest to uncomment the
# line below. It might simplify debugging of background Airbrake workers, which
# can silently die.
# Thread.abort_on_exception = ['test', 'development'].include?(Rails.env)
|
module CartoDB
def self.session_domain
APP_CONFIG[:session_domain]
end
def self.secret_token
APP_CONFIG[:secret_token]
end
def self.domain
@@domain ||= if Rails.env.production?
`hostname -f`.strip
elsif Rails.env.development?
"vizzuality#{session_domain}"
else
"vizzuality#{session_domain}"
end
end
def self.hostname
@@hostname ||= if Rails.env.production?
"https://#{domain}"
elsif Rails.env.development?
"http://#{domain}:3000"
else
"http://#{domain}:53716"
end
end
def self.account_host
APP_CONFIG[:account_host]
end
def self.account_path
APP_CONFIG[:account_path]
end
module API
VERSION_1 = "v1"
end
PUBLIC_DB_USER = 'publicuser'
TILE_DB_USER = 'tileuser'
GOOGLE_SRID = 3857
SRID = 4326
USER_REQUESTS_PER_DAY = 10000
TYPES = {
"number" => ["smallint", /numeric\(\d+,\d+\)/, "integer", "bigint", "decimal", "numeric", "double precision", "serial", "big serial", "real"],
"string" => ["varchar", "character varying", "text", /character\svarying\(\d+\)/, /char\s*\(\d+\)/, /character\s*\(\d+\)/],
"date" => ["timestamp", "timestamp without time zone"],
"boolean" => ["boolean"]
}
NEXT_TYPE = {
"number" => "double precision",
"string" => "text"
}
VALID_GEOMETRY_TYPES = %W{ multipolygon point multilinestring}
POSTGRESQL_RESERVED_WORDS = %W{ ALL ANALYSE ANALYZE AND ANY ARRAY AS ASC ASYMMETRIC AUTHORIZATION BETWEEN BINARY BOTH CASE CAST
CHECK COLLATE COLUMN CONSTRAINT CREATE CROSS CURRENT_DATE CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP
CURRENT_USER DEFAULT DEFERRABLE DESC DISTINCT DO ELSE END EXCEPT FALSE FOR FOREIGN FREEZE FROM FULL
GRANT GROUP HAVING ILIKE IN INITIALLY INNER INTERSECT INTO IS ISNULL JOIN LEADING LEFT LIKE LIMIT LOCALTIME
LOCALTIMESTAMP NATURAL NEW NOT NOTNULL NULL OFF OFFSET OLD ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY
REFERENCES RIGHT SELECT SESSION_USER SIMILAR SOME SYMMETRIC TABLE THEN TO TRAILING TRUE UNION UNIQUE USER
USING VERBOSE WHEN WHERE }
LAST_BLOG_POSTS_FILE_PATH = "#{Rails.root}/public/system/last_blog_posts.html"
ERROR_CODES = {
1000 => 'File I/O error',
1001 => 'Unable to open file',
1002 => 'Unsupported file type',
1003 => 'Decompression error',
1004 => 'File encoding error',
2000 => 'File conversion errors',
3000 => 'Geometry error',
3004 => 'Unable to read SHP file',
3005 => 'SHP to PGSQL error',
3100 => 'Projection error',
3101 => 'Unsupported or missing projection',
3200 => 'Unsupported geometry type',
3201 => 'Geometry Collection not supported',
4000 => 'Raster errors',
4001 => 'Raster import error',
5000 => 'Database import error',
5001 => 'Empty table',
5002 => 'Reserved column names',
8000 => 'CartoDB account error',
8001 => 'Over account storage limit',
8002 => 'Over table limit',
99999 => 'Unknown' }
end
added the top error for OSM import errors
module CartoDB
def self.session_domain
APP_CONFIG[:session_domain]
end
def self.secret_token
APP_CONFIG[:secret_token]
end
def self.domain
@@domain ||= if Rails.env.production?
`hostname -f`.strip
elsif Rails.env.development?
"vizzuality#{session_domain}"
else
"vizzuality#{session_domain}"
end
end
def self.hostname
@@hostname ||= if Rails.env.production?
"https://#{domain}"
elsif Rails.env.development?
"http://#{domain}:3000"
else
"http://#{domain}:53716"
end
end
def self.account_host
APP_CONFIG[:account_host]
end
def self.account_path
APP_CONFIG[:account_path]
end
module API
VERSION_1 = "v1"
end
PUBLIC_DB_USER = 'publicuser'
TILE_DB_USER = 'tileuser'
GOOGLE_SRID = 3857
SRID = 4326
USER_REQUESTS_PER_DAY = 10000
TYPES = {
"number" => ["smallint", /numeric\(\d+,\d+\)/, "integer", "bigint", "decimal", "numeric", "double precision", "serial", "big serial", "real"],
"string" => ["varchar", "character varying", "text", /character\svarying\(\d+\)/, /char\s*\(\d+\)/, /character\s*\(\d+\)/],
"date" => ["timestamp", "timestamp without time zone"],
"boolean" => ["boolean"]
}
NEXT_TYPE = {
"number" => "double precision",
"string" => "text"
}
VALID_GEOMETRY_TYPES = %W{ multipolygon point multilinestring}
POSTGRESQL_RESERVED_WORDS = %W{ ALL ANALYSE ANALYZE AND ANY ARRAY AS ASC ASYMMETRIC AUTHORIZATION BETWEEN BINARY BOTH CASE CAST
CHECK COLLATE COLUMN CONSTRAINT CREATE CROSS CURRENT_DATE CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP
CURRENT_USER DEFAULT DEFERRABLE DESC DISTINCT DO ELSE END EXCEPT FALSE FOR FOREIGN FREEZE FROM FULL
GRANT GROUP HAVING ILIKE IN INITIALLY INNER INTERSECT INTO IS ISNULL JOIN LEADING LEFT LIKE LIMIT LOCALTIME
LOCALTIMESTAMP NATURAL NEW NOT NOTNULL NULL OFF OFFSET OLD ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY
REFERENCES RIGHT SELECT SESSION_USER SIMILAR SOME SYMMETRIC TABLE THEN TO TRAILING TRUE UNION UNIQUE USER
USING VERBOSE WHEN WHERE }
LAST_BLOG_POSTS_FILE_PATH = "#{Rails.root}/public/system/last_blog_posts.html"
ERROR_CODES = {
1000 => 'File I/O error',
1001 => 'Unable to open file',
1002 => 'Unsupported file type',
1003 => 'Decompression error',
1004 => 'File encoding error',
2000 => 'File conversion errors',
3000 => 'Geometry error',
3004 => 'Unable to read SHP file',
3005 => 'SHP to PGSQL error',
3100 => 'Projection error',
3101 => 'Unsupported or missing projection',
3200 => 'Unsupported geometry type',
3201 => 'Geometry Collection not supported',
4000 => 'Raster errors',
4001 => 'Raster import error',
5000 => 'Database import error',
5001 => 'Empty table',
5002 => 'Reserved column names',
6000 => 'OSM data import error',
8000 => 'CartoDB account error',
8001 => 'Over account storage limit',
8002 => 'Over table limit',
99999 => 'Unknown' }
end |
Geocoder.configure(
# Geocoding options
# timeout: 3, # geocoding service timeout (secs)
lookup: :nominatim, # name of geocoding service (symbol)
# ip_lookup: :ipinfo_io, # name of IP address geocoding service (symbol)
# language: :en, # ISO-639 language code
# use_https: false, # use HTTPS for lookup requests? (if supported)
# http_proxy: nil, # HTTP proxy server (user:pass@host:port)
# https_proxy: nil, # HTTPS proxy server (user:pass@host:port)
# api_key: nil, # API key for geocoding service
# cache: nil, # cache object (must respond to #[], #[]=, and #del)
# cache_prefix: 'geocoder:', # prefix (string) to use for all cache keys
# Exceptions that should not be rescued by default
# (if you want to implement custom error handling);
# supports SocketError and Timeout::Error
# always_raise: [],
# pickpoint: { api_key: ENV['PICKPOINT_API_KEY'] },
# bing: { api_key: ENV['BING_API_KEY'] }
# Calculation options
# units: :mi, # :km for kilometers or :mi for miles
# distances: :linear # :spherical or :linear
)
if Rails.env.test?
Geocoder.configure(lookup: :test, ip_lookup: :test)
Geocoder::Lookup::Test.set_default_stub(
[
{
'coordinates' => [51.340620, -2.301420],
'address' => 'Freshford Station',
'state' => 'Somerset',
'state_code' => '',
'country' => 'United Kingdom',
'country_code' => 'UK'
}
]
)
end
Configure postcodes.io as lookup service
Geocoder.configure(
# Geocoding options
# timeout: 3, # geocoding service timeout (secs)
# lookup: :nominatim, # name of geocoding service (symbol)
lookup: :postcodes_io,
# ip_lookup: :ipinfo_io, # name of IP address geocoding service (symbol)
# language: :en, # ISO-639 language code
# use_https: false, # use HTTPS for lookup requests? (if supported)
# http_proxy: nil, # HTTP proxy server (user:pass@host:port)
# https_proxy: nil, # HTTPS proxy server (user:pass@host:port)
# api_key: nil, # API key for geocoding service
# cache: nil, # cache object (must respond to #[], #[]=, and #del)
# cache_prefix: 'geocoder:', # prefix (string) to use for all cache keys
# Exceptions that should not be rescued by default
# (if you want to implement custom error handling);
# supports SocketError and Timeout::Error
# always_raise: [],
# pickpoint: { api_key: ENV['PICKPOINT_API_KEY'] },
# bing: { api_key: ENV['BING_API_KEY'] }
# Calculation options
# units: :mi, # :km for kilometers or :mi for miles
# distances: :linear # :spherical or :linear
)
if Rails.env.test?
Geocoder.configure(lookup: :test, ip_lookup: :test)
Geocoder::Lookup::Test.set_default_stub(
[
{
'coordinates' => [51.340620, -2.301420],
'address' => 'Freshford Station',
'state' => 'Somerset',
'state_code' => '',
'country' => 'United Kingdom',
'country_code' => 'UK'
}
]
)
end
|
IntercomRails.config do |config|
# == Intercom app_id
#
config.app_id = ENV["INTERCOM_APP_ID"] || "qvnmie0g"
# == Intercom session_duration
#
# config.session_duration = 300000
# == Intercom secret key
# This is required to enable secure mode, you can find it on your Setup
# guide in the "Secure Mode" step.
#
# config.api_secret = "..."
# == Enabled Environments
# Which environments is auto inclusion of the Javascript enabled for
#
config.enabled_environments = ["development", "production"]
# == Current user method/variable
# The method/variable that contains the logged in user in your controllers.
# If it is `current_user` or `@user`, then you can ignore this
#
# config.user.current = Proc.new { current_user }
# config.user.current = [Proc.new { current_user }]
# == Include for logged out Users
# If set to true, include the Intercom messenger on all pages, regardless of whether
# The user model class (set below) is present. Only available for Apps on the Acquire plan.
# config.include_for_logged_out_users = true
# == User model class
# The class which defines your user model
#
# config.user.model = Proc.new { User }
# == Lead/custom attributes for non-signed up users
# Pass additional attributes to for potential leads or
# non-signed up users as an an array.
# Any attribute contained in config.user.lead_attributes can be used
# as custom attribute in the application.
# config.user.lead_attributes = %w(ref_data utm_source)
# == Exclude users
# A Proc that given a user returns true if the user should be excluded
# from imports and Javascript inclusion, false otherwise.
#
# config.user.exclude_if = Proc.new { |user| user.deleted? }
# == User Custom Data
# A hash of additional data you wish to send about your users.
# You can provide either a method name which will be sent to the current
# user object, or a Proc which will be passed the current user.
#
# config.user.custom_data = {
# :plan => Proc.new { |current_user| current_user.plan.name },
# :favorite_color => :favorite_color
# }
# == Current company method/variable
# The method/variable that contains the current company for the current user,
# in your controllers. 'Companies' are generic groupings of users, so this
# could be a company, app or group.
#
# config.company.current = Proc.new { current_company }
#
# Or if you are using devise you can just use the following config
#
# config.company.current = Proc.new { current_user.company }
# == Company Custom Data
# A hash of additional data you wish to send about a company.
# This works the same as User custom data above.
#
# config.company.custom_data = {
# :number_of_messages => Proc.new { |app| app.messages.count },
# :is_interesting => :is_interesting?
# }
# == Company Plan name
# This is the name of the plan a company is currently paying (or not paying) for.
# e.g. Messaging, Free, Pro, etc.
#
# config.company.plan = Proc.new { |current_company| current_company.plan.name }
# == Company Monthly Spend
# This is the amount the company spends each month on your app. If your company
# has a plan, it will set the 'total value' of that plan appropriately.
#
# config.company.monthly_spend = Proc.new { |current_company| current_company.plan.price }
# config.company.monthly_spend = Proc.new { |current_company| (current_company.plan.price - current_company.subscription.discount) }
# == Custom Style
# By default, Intercom will add a button that opens the messenger to
# the page. If you'd like to use your own link to open the messenger,
# uncomment this line and clicks on any element with id 'Intercom' will
# open the messenger.
#
# config.inbox.style = :custom
#
# If you'd like to use your own link activator CSS selector
# uncomment this line and clicks on any element that matches the query will
# open the messenger
# config.inbox.custom_activator = '.intercom'
end
Include for logged out users
IntercomRails.config do |config|
# == Intercom app_id
#
config.app_id = ENV["INTERCOM_APP_ID"] || "qvnmie0g"
# == Intercom session_duration
#
# config.session_duration = 300000
# == Intercom secret key
# This is required to enable secure mode, you can find it on your Setup
# guide in the "Secure Mode" step.
#
# config.api_secret = "..."
# == Enabled Environments
# Which environments is auto inclusion of the Javascript enabled for
#
config.enabled_environments = ["development", "production"]
# == Current user method/variable
# The method/variable that contains the logged in user in your controllers.
# If it is `current_user` or `@user`, then you can ignore this
#
# config.user.current = Proc.new { current_user }
# config.user.current = [Proc.new { current_user }]
# == Include for logged out Users
# If set to true, include the Intercom messenger on all pages, regardless of whether
# The user model class (set below) is present. Only available for Apps on the Acquire plan.
config.include_for_logged_out_users = true
# == User model class
# The class which defines your user model
#
# config.user.model = Proc.new { User }
# == Lead/custom attributes for non-signed up users
# Pass additional attributes to for potential leads or
# non-signed up users as an an array.
# Any attribute contained in config.user.lead_attributes can be used
# as custom attribute in the application.
# config.user.lead_attributes = %w(ref_data utm_source)
# == Exclude users
# A Proc that given a user returns true if the user should be excluded
# from imports and Javascript inclusion, false otherwise.
#
# config.user.exclude_if = Proc.new { |user| user.deleted? }
# == User Custom Data
# A hash of additional data you wish to send about your users.
# You can provide either a method name which will be sent to the current
# user object, or a Proc which will be passed the current user.
#
# config.user.custom_data = {
# :plan => Proc.new { |current_user| current_user.plan.name },
# :favorite_color => :favorite_color
# }
# == Current company method/variable
# The method/variable that contains the current company for the current user,
# in your controllers. 'Companies' are generic groupings of users, so this
# could be a company, app or group.
#
# config.company.current = Proc.new { current_company }
#
# Or if you are using devise you can just use the following config
#
# config.company.current = Proc.new { current_user.company }
# == Company Custom Data
# A hash of additional data you wish to send about a company.
# This works the same as User custom data above.
#
# config.company.custom_data = {
# :number_of_messages => Proc.new { |app| app.messages.count },
# :is_interesting => :is_interesting?
# }
# == Company Plan name
# This is the name of the plan a company is currently paying (or not paying) for.
# e.g. Messaging, Free, Pro, etc.
#
# config.company.plan = Proc.new { |current_company| current_company.plan.name }
# == Company Monthly Spend
# This is the amount the company spends each month on your app. If your company
# has a plan, it will set the 'total value' of that plan appropriately.
#
# config.company.monthly_spend = Proc.new { |current_company| current_company.plan.price }
# config.company.monthly_spend = Proc.new { |current_company| (current_company.plan.price - current_company.subscription.discount) }
# == Custom Style
# By default, Intercom will add a button that opens the messenger to
# the page. If you'd like to use your own link to open the messenger,
# uncomment this line and clicks on any element with id 'Intercom' will
# open the messenger.
#
# config.inbox.style = :custom
#
# If you'd like to use your own link activator CSS selector
# uncomment this line and clicks on any element that matches the query will
# open the messenger
# config.inbox.custom_activator = '.intercom'
end
|
# frozen_string_literal: true
Mobility.configure do |config|
# Sets the default backend to use in models. This can be overridden in models
# by passing +backend: ...+ to +translates+.
config.default_backend = :jsonb
# By default, Mobility uses the +translates+ class method in models to
# describe translated attributes, but you can configure this method to be
# whatever you like. This may be useful if using Mobility alongside another
# translation gem which uses the same method name.
config.accessor_method = :translates
# To query on translated attributes, you need to append a scope to your
# model. The name of this scope is +i18n+ by default, but this can be changed
# to something else.
config.query_method = :i18n
# Uncomment and remove (or add) items to (from) this list to completely
# disable/enable plugins globally (so they cannot be used and are never even
# loaded). Note that if you remove an item from the list, you will not be
# able to use the plugin at all, and any options for the plugin will be
# ignored by models. (In most cases, you probably don't want to change this.)
#
config.plugins = %i[
cache
dirty
fallbacks
presence
default
attribute_methods
fallthrough_accessors
locale_accessors
]
# The translation cache is on by default, but you can turn it off by
# uncommenting this line. (This may be helpful in debugging.)
#
# config.default_options[:cache] = false
# Dirty tracking is disabled by default. Uncomment this line to enable it.
# If you enable this, you should also enable +locale_accessors+ by default
# (see below).
#
config.default_options[:dirty] = true
# No fallbacks are used by default. To define default fallbacks, uncomment
# and set the default fallback option value here. A "true" value will use
# whatever is defined by +I18n.fallbacks+ (if defined), or alternatively will
# fallback to your +I18n.default_locale+.
#
config.default_options[:fallbacks] = true
# The Presence plugin converts empty strings to nil when fetching and setting
# translations. By default it is on, uncomment this line to turn it off.
#
# config.default_options[:presence] = false
# Set a default value to use if the translation is nil. By default this is
# off, uncomment and set a default to use it across all models (you probably
# don't want to do that).
#
# config.default_options[:default] = ...
# Uncomment to enable locale_accessors by default on models. A true value
# will use the locales defined in I18n.available_locales. If you want
# something else, pass an array of locales instead.
#
config.default_options[:locale_accessors] = true
# Uncomment to enable fallthrough accessors by default on models. This will
# allow you to call any method with a suffix like _en or _pt_br, and Mobility
# will catch the suffix and convert it into a locale in +method_missing+. If
# you don't need this kind of open-ended fallthrough behavior, it's better
# to use locale_accessors instead (which define methods) since method_missing
# is very slow. (You can use both fallthrough and locale accessor plugins
# together without conflict.)
#
# Note: The dirty plugin enables fallthrough_accessors by default.
#
# config.default_options[:fallthrough_accessors] = true
end
Update mobility config to 1.0 style
# frozen_string_literal: true
Mobility.configure do
# PLUGINS
plugins do
# Backend
#
# Sets the default backend to use in models. This can be overridden in models
# by passing +backend: ...+ to +translates+.
#
# To default to a different backend globally, replace +:key_value+ by another
# backend name.
#
backend :jsonb
# ActiveRecord
#
# Defines ActiveRecord as ORM, and enables ActiveRecord-specific plugins.
active_record
# Accessors
#
# Define reader and writer methods for translated attributes. Remove either
# to disable globally, or pass +reader: false+ or +writer: false+ to
# +translates+ in any translated model.
#
reader
writer
# Backend Reader
#
# Defines reader to access the backend for any attribute, of the form
# +<attribute>_backend+.
#
backend_reader
#
# Or pass an interpolation string to define a different pattern:
# backend_reader "%s_translations"
# Query
#
# Defines a scope on the model class which allows querying on
# translated attributes. The default scope is named +i18n+, pass a different
# name as default to change the global default, or to +translates+ in any
# model to change it for that model alone.
#
query
# Cache
#
# Comment out to disable caching reads and writes.
#
cache
# Dirty
#
# Uncomment this line to include and enable globally:
dirty
#
# Or uncomment this line to include but disable by default, and only enable
# per model by passing +dirty: true+ to +translates+.
# dirty false
# Fallbacks
#
# Uncomment line below to enable fallbacks, using +I18n.fallbacks+.
fallbacks
#
# Or uncomment this line to enable fallbacks with a global default.
# fallbacks { :pt => :en }
# Presence
#
# Converts blank strings to nil on reads and writes. Comment out to
# disable.
#
presence
# Default
#
# Set a default translation per attributes. When enabled, passing +default:
# 'foo'+ sets a default translation string to show in case no translation is
# present. Can also be passed a proc.
#
# default 'foo'
# Fallthrough Accessors
#
# Uses method_missing to define locale-specific accessor methods like
# +title_en+, +title_en=+, +title_fr+, +title_fr=+ for each translated
# attribute. If you know what set of locales you want to support, it's
# generally better to use Locale Accessors (or both together) since
# +method_missing+ is very slow. (You can use both fallthrough and locale
# accessor plugins together without conflict.)
#
fallthrough_accessors
# Locale Accessors
#
# Uses +def+ to define accessor methods for a set of locales. By default uses
# +I18n.available_locales+, but you can pass the set of locales with
# +translates+ and/or set a global default here.
#
locale_accessors
#
# Or define specific defaults by uncommenting line below
# locale_accessors [:en, :ja]
# Attribute Methods
#
# Adds translated attributes to +attributes+ hash, and defines methods
# +translated_attributes+ and +untranslated_attributes+ which return hashes
# with translated and untranslated attributes, respectively. Be aware that
# this plugin can create conflicts with other gems.
#
attribute_methods
end
end
|
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, Rails.application.secrets.omniauth["facebook"]["app_id"], Rails.application.secrets.omniauth["facebook"]["app_secret"], scope: 'email', info_fields: 'name,email'
provider :google_oauth2, Rails.application.secrets.omniauth["google"]["client_id"], Rails.application.secrets.omniauth["google"]["client_secret"], skip_jwt: true
end
Improve oauth config readability
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook,
Rails.application.secrets.omniauth["facebook"]["app_id"],
Rails.application.secrets.omniauth["facebook"]["app_secret"],
scope: 'email',
info_fields: 'name,email'
provider :google_oauth2,
Rails.application.secrets.omniauth["google"]["client_id"],
Rails.application.secrets.omniauth["google"]["client_secret"],
skip_jwt: true
end
|
Rails.application.config.middleware.use OmniAuth::Builder do
provider :shopify,
ShopifyApp.configuration.api_key,
ShopifyApp.configuration.secret,
# Example permission scopes - see http://docs.shopify.com/api/tutorials/oauth for full listing
scope: ShopifyApp.configuration.scope,
setup: lambda {|env|
params = Rack::Utils.parse_query(env['QUERY_STRING'])
site_url = "https://#{params['shop']}"
env['omniauth.strategy'].options[:client_options][:site] = site_url
redirect_uri = "https://devlopment-store.myshopify.com/admin/apps"
}
end
commit
|
if !ENV['GITHUB_KEY'].present? || !ENV['GITHUB_SECRET'].present?
puts "*" * 80
puts "ENV['GITHUB_KEY'] is NOT SET."
puts "ENV['GITHUB_SECRET'] is NOT SET"
puts "*" * 80
else
puts "GITHUB_SECRET and GITHUB_KEY set"
end
Rails.application.config.middleware.use OmniAuth::Builder do
# provider :developer unless Rails.env.production?
require 'openid/store/filesystem'
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
provider :openid, :store => OpenID::Store::Filesystem.new('/tmp')
end
add some instructions to the startup warning
if !ENV['GITHUB_KEY'].present? || !ENV['GITHUB_SECRET'].present?
puts "*" * 80
puts "ENV['GITHUB_KEY'] is NOT SET."
puts "ENV['GITHUB_SECRET'] is NOT SET"
puts "use "
pust "$ source github.env.vars"
puts "*" * 80
else
puts "GITHUB_SECRET and GITHUB_KEY set"
end
Rails.application.config.middleware.use OmniAuth::Builder do
# provider :developer unless Rails.env.production?
require 'openid/store/filesystem'
provider :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
provider :openid, :store => OpenID::Store::Filesystem.new('/tmp')
end
|
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, '1517142275185874', 'APP-ID'
end
added app secret
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, '1517142275185874', 'b69b2474d3c149940a3c08ef83950800'
end |
module PublishingAPI
# To be set in dev mode so that this can run when the draft content store isn't running.
cattr_accessor :swallow_connection_errors
def self.register_service(name:, client:)
@services ||= {}
@services[name] = client
end
def self.service(name)
@services[name] || raise(ServiceNotRegisteredException.new(name))
end
class ServiceNotRegisteredException < RuntimeError; end
end
PublishingAPI.register_service(
name: :draft_content_store,
client: ContentStoreWriter.new(Plek.find('draft-content-store'))
)
PublishingAPI.register_service(
name: :live_content_store,
client: ContentStoreWriter.new(Plek.find('content-store'))
)
if ENV['DISABLE_QUEUE_PUBLISHER'] || (Rails.env.test? && ENV['ENABLE_QUEUE_IN_TEST_MODE'].blank?)
rabbitmq_config = { noop: true }
elsif ENV["RABBITMQ_URL"] && ENV["RABBITMQ_EXCHANGE"]
rabbitmq_config = { exchange: ENV["RABBITMQ_EXCHANGE"] }
else
rabbitmq_config = Rails.application.config_for(:rabbitmq).symbolize_keys
end
PublishingAPI.register_service(
name: :queue_publisher,
client: QueuePublisher.new(rabbitmq_config)
)
if Rails.env.development?
PublishingAPI.swallow_connection_errors = true
end
# Statsd "the process" listens on a port on the provided host for UDP
# messages. Given that it's UDP, it's fire-and-forget and will not
# block your application. You do not need to have a statsd process
# running locally on your development environment.
statsd_client = Statsd.new("localhost")
statsd_client.namespace = "govuk.app.publishing-api"
PublishingAPI.register_service(name: :statsd, client: statsd_client)
Add bearer tokens for content store authentication
module PublishingAPI
# To be set in dev mode so that this can run when the draft content store isn't running.
cattr_accessor :swallow_connection_errors
def self.register_service(name:, client:)
@services ||= {}
@services[name] = client
end
def self.service(name)
@services[name] || raise(ServiceNotRegisteredException.new(name))
end
class ServiceNotRegisteredException < RuntimeError; end
end
PublishingAPI.register_service(
name: :draft_content_store,
client: ContentStoreWriter.new(
Plek.find('draft-content-store'),
{ bearer_token: ENV['DRAFT_CONTENT_STORE_BEARER_TOKEN'] },
)
)
PublishingAPI.register_service(
name: :live_content_store,
client: ContentStoreWriter.new(
Plek.find('content-store'),
{ bearer_token: ENV['CONTENT_STORE_BEARER_TOKEN'] },
)
)
if ENV['DISABLE_QUEUE_PUBLISHER'] || (Rails.env.test? && ENV['ENABLE_QUEUE_IN_TEST_MODE'].blank?)
rabbitmq_config = { noop: true }
elsif ENV["RABBITMQ_URL"] && ENV["RABBITMQ_EXCHANGE"]
rabbitmq_config = { exchange: ENV["RABBITMQ_EXCHANGE"] }
else
rabbitmq_config = Rails.application.config_for(:rabbitmq).symbolize_keys
end
PublishingAPI.register_service(
name: :queue_publisher,
client: QueuePublisher.new(rabbitmq_config)
)
if Rails.env.development?
PublishingAPI.swallow_connection_errors = true
end
# Statsd "the process" listens on a port on the provided host for UDP
# messages. Given that it's UDP, it's fire-and-forget and will not
# block your application. You do not need to have a statsd process
# running locally on your development environment.
statsd_client = Statsd.new("localhost")
statsd_client.namespace = "govuk.app.publishing-api"
PublishingAPI.register_service(name: :statsd, client: statsd_client)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.