CombinedText stringlengths 4 3.42M |
|---|
# -*- coding: utf-8 -*-
LOG_TO_STDOUT = true unless Object.const_defined?(:LOG_TO_STDOUT)
REO_LOG_DIR = "" unless Object.const_defined?(:REO_LOG_DIR)
REO_LOG_FILE = "reo.log" unless Object.const_defined?(:REO_LOG_FILE)
File.delete REO_LOG_FILE rescue nil
module RobustExcelOle
class REOError < RuntimeError # :nodoc: #
end
class ExcelError < REOError # :nodoc: #
end
class WorkbookError < REOError # :nodoc: #
end
class FileError < REOError # :nodoc: #
end
class NamesError < REOError # :nodoc: #
end
class MiscError < REOError # :nodoc: #
end
class ExcelDamaged < ExcelError # :nodoc: #
end
class UnsavedWorkbooks < ExcelError # :nodoc: #
end
class WorkbookBlocked < WorkbookError # :nodoc: #
end
class WorkbookNotSaved < WorkbookError # :nodoc: #
end
class WorkbookReadOnly < WorkbookError # :nodoc: #
end
class WorkbookBeingUsed < WorkbookError # :nodoc: #
end
class FileNotFound < FileError # :nodoc: #
end
class FileNameNotGiven < FileError # :nodoc: #
end
class FileAlreadyExists < FileError # :nodoc: #
end
class NameNotFound < NamesError # :nodoc: #
end
class NameAlreadyExists < NamesError # :nodoc: #
end
class RangeNotEvaluatable < MiscError # :nodoc: #
end
class OptionInvalid < MiscError # :nodoc: #
end
class ObjectNotAlive < MiscError # :nodoc: #
end
class TypeErrorREO < REOError # :nodoc: #
end
class TimeOut < REOError # :nodoc: #
end
class UnexpectedError < REOError # :nodoc: #
end
class REOCommon
def excel
raise TypeErrorREO, "receiver instance is neither an Excel nor a Book"
end
def own_methods
(self.methods - Object.methods).sort
end
def self.tr1(text)
puts :text
end
def self.trace(text)
if LOG_TO_STDOUT
puts text
else
if REO_LOG_DIR.empty?
homes = ["HOME", "HOMEPATH"]
home = homes.find {|h| ENV[h] != nil}
reo_log_dir = ENV[home]
else
reo_log_dir = REO_LOG_DIR
end
File.open(reo_log_dir + "/" + REO_LOG_FILE,"a") do | file |
file.puts text
end
end
end
def self.puts_hash(hash)
hash.each do |e|
if e[1].is_a?(Hash)
puts "#{e[0]} =>"
e[1].each do |f|
puts " #{f[0]} => #{f[1]}"
end
else
puts "#{e[0]} => #{e[1]}"
end
end
end
end
class RangeOwners < REOCommon
# returns the contents of a range with given name
# evaluates formula contents of the range is a formula
# if no contents could be returned, then return default value, if provided, raise error otherwise
# Excel Bug: if a local name without a qualifier is given, then by default Excel takes the first worksheet,
# even if a different worksheet is active
# @param [String] name the name of the range
# @param [Hash] opts the options
# @option opts [Symbol] :default the default value that is provided if no contents could be returned
# @return [Variant] the contents of a range with given name
def nameval(name, opts = {:default => nil})
name_obj = name_object(name)
value = begin
name_obj.RefersToRange.Value
rescue WIN32OLERuntimeError
#begin
# self.sheet(1).Evaluate(name_obj.Name)
#rescue WIN32OLERuntimeError
return opts[:default] if opts[:default]
raise RangeNotEvaluatable, "cannot evaluate range named #{name.inspect} in #{self}"
#end
end
if value.is_a?(Bignum) #RobustExcelOle::XlErrName
return opts[:default] if opts[:default]
raise RangeNotEvaluatable, "cannot evaluate range named #{name.inspect} in #{File.basename(workbook.stored_filename).inspect rescue nil}"
end
return opts[:default] if opts[:default] && value.nil?
value
end
# sets the contents of a range
# @param [String] name the name of a range
# @param [Variant] value the contents of the range
# @param [FixNum] color the color when setting a value
# @param [Hash] opts :color [FixNum] the color when setting the contents
def set_nameval(name, value, opts = {:color => 0})
begin
cell = name_object(name).RefersToRange
cell.Interior.ColorIndex = opts[:color]
workbook.modified_cells << cell unless cell_modified?(cell)
cell.Value = value
rescue WIN32OLERuntimeError
raise RangeNotEvaluatable, "cannot assign value to range named #{name.inspect} in #{self.inspect}"
end
end
# returns the contents of a range with a locally defined name
# evaluates the formula if the contents is a formula
# if no contents could be returned, then return default value, if provided, raise error otherwise
# @param [String] name the name of a range
# @param [Hash] opts the options
# @option opts [Symbol] :default the default value that is provided if no contents could be returned
# @return [Variant] the contents of a range with given name
def rangeval(name, opts = {:default => nil})
begin
range = self.Range(name)
rescue WIN32OLERuntimeError
return opts[:default] if opts[:default]
raise NameNotFound, "name #{name.inspect} not in #{self.inspect}"
end
begin
value = range.Value
rescue WIN32OLERuntimeError
return opts[:default] if opts[:default]
raise RangeNotEvaluatable, "cannot determine value of range named #{name.inspect} in #{self.inspect}"
end
return opts[:default] if (value.nil? && opts[:default])
raise RangeNotEvaluatable, "cannot evaluate range named #{name.inspect}" if value.is_a?(Bignum)
value
end
# assigns a value to a range given a locally defined name
# @param [String] name the name of a range
# @param [Variant] value the assigned value
# @param [Hash] opts :color [FixNum] the color when setting the contents
def set_rangeval(name,value, opts = {:color => 0})
begin
return set_nameval(name, value, opts) if self.is_a?(Book)
range = self.Range(name)
rescue WIN32OLERuntimeError
raise NameNotFound, "name #{name.inspect} not in #{self.inspect}"
end
begin
range.Interior.ColorIndex = opts[:color]
workbook.modified_cells << range unless cell_modified?(range)
range.Value = value
rescue WIN32OLERuntimeError
raise RangeNotEvaluatable, "cannot assign value to range named #{name.inspect} in #{self.inspect}"
end
end
private
def name_object(name)
begin
self.Parent.Names.Item(name)
rescue WIN32OLERuntimeError
begin
self.Names.Item(name)
rescue WIN32OLERuntimeError
raise RobustExcelOle::NameNotFound, "name #{name.inspect} not in #{self.inspect}"
end
end
end
def cell_modified?(cell)
workbook.modified_cells.each{|c| return true if c.Name.Value == cell.Name.Value}
false
end
end
end
cell_modified only if workbook
# -*- coding: utf-8 -*-
LOG_TO_STDOUT = true unless Object.const_defined?(:LOG_TO_STDOUT)
REO_LOG_DIR = "" unless Object.const_defined?(:REO_LOG_DIR)
REO_LOG_FILE = "reo.log" unless Object.const_defined?(:REO_LOG_FILE)
File.delete REO_LOG_FILE rescue nil
module RobustExcelOle
class REOError < RuntimeError # :nodoc: #
end
class ExcelError < REOError # :nodoc: #
end
class WorkbookError < REOError # :nodoc: #
end
class FileError < REOError # :nodoc: #
end
class NamesError < REOError # :nodoc: #
end
class MiscError < REOError # :nodoc: #
end
class ExcelDamaged < ExcelError # :nodoc: #
end
class UnsavedWorkbooks < ExcelError # :nodoc: #
end
class WorkbookBlocked < WorkbookError # :nodoc: #
end
class WorkbookNotSaved < WorkbookError # :nodoc: #
end
class WorkbookReadOnly < WorkbookError # :nodoc: #
end
class WorkbookBeingUsed < WorkbookError # :nodoc: #
end
class FileNotFound < FileError # :nodoc: #
end
class FileNameNotGiven < FileError # :nodoc: #
end
class FileAlreadyExists < FileError # :nodoc: #
end
class NameNotFound < NamesError # :nodoc: #
end
class NameAlreadyExists < NamesError # :nodoc: #
end
class RangeNotEvaluatable < MiscError # :nodoc: #
end
class OptionInvalid < MiscError # :nodoc: #
end
class ObjectNotAlive < MiscError # :nodoc: #
end
class TypeErrorREO < REOError # :nodoc: #
end
class TimeOut < REOError # :nodoc: #
end
class UnexpectedError < REOError # :nodoc: #
end
class REOCommon
def excel
raise TypeErrorREO, "receiver instance is neither an Excel nor a Book"
end
def own_methods
(self.methods - Object.methods).sort
end
def self.tr1(text)
puts :text
end
def self.trace(text)
if LOG_TO_STDOUT
puts text
else
if REO_LOG_DIR.empty?
homes = ["HOME", "HOMEPATH"]
home = homes.find {|h| ENV[h] != nil}
reo_log_dir = ENV[home]
else
reo_log_dir = REO_LOG_DIR
end
File.open(reo_log_dir + "/" + REO_LOG_FILE,"a") do | file |
file.puts text
end
end
end
def self.puts_hash(hash)
hash.each do |e|
if e[1].is_a?(Hash)
puts "#{e[0]} =>"
e[1].each do |f|
puts " #{f[0]} => #{f[1]}"
end
else
puts "#{e[0]} => #{e[1]}"
end
end
end
end
class RangeOwners < REOCommon
# returns the contents of a range with given name
# evaluates formula contents of the range is a formula
# if no contents could be returned, then return default value, if provided, raise error otherwise
# Excel Bug: if a local name without a qualifier is given, then by default Excel takes the first worksheet,
# even if a different worksheet is active
# @param [String] name the name of the range
# @param [Hash] opts the options
# @option opts [Symbol] :default the default value that is provided if no contents could be returned
# @return [Variant] the contents of a range with given name
def nameval(name, opts = {:default => nil})
name_obj = name_object(name)
value = begin
name_obj.RefersToRange.Value
rescue WIN32OLERuntimeError
#begin
# self.sheet(1).Evaluate(name_obj.Name)
#rescue WIN32OLERuntimeError
return opts[:default] if opts[:default]
raise RangeNotEvaluatable, "cannot evaluate range named #{name.inspect} in #{self}"
#end
end
if value.is_a?(Bignum) #RobustExcelOle::XlErrName
return opts[:default] if opts[:default]
raise RangeNotEvaluatable, "cannot evaluate range named #{name.inspect} in #{File.basename(workbook.stored_filename).inspect rescue nil}"
end
return opts[:default] if opts[:default] && value.nil?
value
end
# sets the contents of a range
# @param [String] name the name of a range
# @param [Variant] value the contents of the range
# @param [FixNum] color the color when setting a value
# @param [Hash] opts :color [FixNum] the color when setting the contents
def set_nameval(name, value, opts = {:color => 0})
begin
cell = name_object(name).RefersToRange
cell.Interior.ColorIndex = opts[:color]
workbook.modified_cells << cell unless cell_modified?(cell) if workbook
cell.Value = value
rescue WIN32OLERuntimeError
raise RangeNotEvaluatable, "cannot assign value to range named #{name.inspect} in #{self.inspect}"
end
end
# returns the contents of a range with a locally defined name
# evaluates the formula if the contents is a formula
# if no contents could be returned, then return default value, if provided, raise error otherwise
# @param [String] name the name of a range
# @param [Hash] opts the options
# @option opts [Symbol] :default the default value that is provided if no contents could be returned
# @return [Variant] the contents of a range with given name
def rangeval(name, opts = {:default => nil})
begin
range = self.Range(name)
rescue WIN32OLERuntimeError
return opts[:default] if opts[:default]
raise NameNotFound, "name #{name.inspect} not in #{self.inspect}"
end
begin
value = range.Value
rescue WIN32OLERuntimeError
return opts[:default] if opts[:default]
raise RangeNotEvaluatable, "cannot determine value of range named #{name.inspect} in #{self.inspect}"
end
return opts[:default] if (value.nil? && opts[:default])
raise RangeNotEvaluatable, "cannot evaluate range named #{name.inspect}" if value.is_a?(Bignum)
value
end
# assigns a value to a range given a locally defined name
# @param [String] name the name of a range
# @param [Variant] value the assigned value
# @param [Hash] opts :color [FixNum] the color when setting the contents
def set_rangeval(name,value, opts = {:color => 0})
begin
return set_nameval(name, value, opts) if self.is_a?(Book)
range = self.Range(name)
rescue WIN32OLERuntimeError
raise NameNotFound, "name #{name.inspect} not in #{self.inspect}"
end
begin
range.Interior.ColorIndex = opts[:color]
workbook.modified_cells << range unless cell_modified?(range) if workbook
range.Value = value
rescue WIN32OLERuntimeError
raise RangeNotEvaluatable, "cannot assign value to range named #{name.inspect} in #{self.inspect}"
end
end
private
def name_object(name)
begin
self.Parent.Names.Item(name)
rescue WIN32OLERuntimeError
begin
self.Names.Item(name)
rescue WIN32OLERuntimeError
raise RobustExcelOle::NameNotFound, "name #{name.inspect} not in #{self.inspect}"
end
end
end
def cell_modified?(cell)
workbook.modified_cells.each{|c| return true if c.Name.Value == cell.Name.Value}
false
end
end
end
|
module RSpec
module Core
module MemoizedHelpers
# @note `subject` was contributed by Joe Ferris to support the one-liner
# syntax embraced by shoulda matchers:
#
# describe Widget do
# it { should validate_presence_of(:name) }
# end
#
# While the examples below demonstrate how to use `subject`
# explicitly in examples, we recommend that you define a method with
# an intention revealing name instead.
#
# @example
#
# # explicit declaration of subject
# describe Person do
# subject { Person.new(:birthdate => 19.years.ago) }
# it "should be eligible to vote" do
# subject.should be_eligible_to_vote
# # ^ ^ explicit reference to subject not recommended
# end
# end
#
# # implicit subject => { Person.new }
# describe Person do
# it "should be eligible to vote" do
# subject.should be_eligible_to_vote
# # ^ ^ explicit reference to subject not recommended
# end
# end
#
# # one-liner syntax - should is invoked on subject
# describe Person do
# it { should be_eligible_to_vote }
# end
#
# @note Because `subject` is designed to create state that is reset between
# each example, and `before(:all)` is designed to setup state that is
# shared across _all_ examples in an example group, `subject` is _not_
# intended to be used in a `before(:all)` hook. RSpec 2.13.1 prints
# a warning when you reference a `subject` from `before(:all)` and we plan
# to have it raise an error in RSpec 3.
#
# @see #should
def subject
raise NotImplementedError, 'This definition is here for documentation purposes only'
' - it is overriden anyway below when this module gets included.'
end
# When `should` is called with no explicit receiver, the call is
# delegated to the object returned by `subject`. Combined with an
# implicit subject this supports very concise expressions.
#
# @example
#
# describe Person do
# it { should be_eligible_to_vote }
# end
#
# @see #subject
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message)
end
# Just like `should`, `should_not` delegates to the subject (implicit or
# explicit) of the example group.
#
# @example
#
# describe Person do
# it { should_not be_eligible_to_vote }
# end
#
# @see #subject
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message)
end
private
# @private
def __memoized
@__memoized ||= {}
end
# Used internally to customize the behavior of the
# memoized hash when used in a `before(:all)` hook.
#
# @private
class BeforeAllMemoizedHash
def initialize(example_group_instance)
@example_group_instance = example_group_instance
@hash = {}
end
def self.isolate_for_before_all(example_group_instance)
example_group_instance.instance_eval do
@__memoized = BeforeAllMemoizedHash.new(self)
begin
yield
ensure
@__memoized.preserve_accessed_lets
@__memoized = nil
end
end
end
def fetch(key, &block)
description = if key == :subject
"subject"
else
"let declaration `#{key}`"
end
::RSpec.warn_deprecation <<-EOS
WARNING: #{description} accessed in a `before(:all)` hook at:
#{caller[1]}
This is deprecated behavior that will not be supported in RSpec 3.
`let` and `subject` declarations are not intended to be called
in a `before(:all)` hook, as they exist to define state that
is reset between each example, while `before(:all)` exists to
define state that is shared across examples in an example group.
EOS
@hash.fetch(key, &block)
end
def []=(key, value)
@hash[key] = value
end
def preserve_accessed_lets
hash = @hash
@example_group_instance.class.class_eval do
hash.each do |key, value|
undef_method(key) if method_defined?(key)
define_method(key) { value }
end
end
end
end
def self.included(mod)
mod.extend(ClassMethods)
# This logic defines an implicit subject
mod.subject do
described = described_class || self.class.description
Class === described ? described.new : described
end
end
module ClassMethods
# Generates a method whose return value is memoized after the first
# call. Useful for reducing duplication between examples that assign
# values to the same local variable.
#
# @note `let` _can_ enhance readability when used sparingly (1,2, or
# maybe 3 declarations) in any given example group, but that can
# quickly degrade with overuse. YMMV.
#
# @note `let` uses an `||=` conditional that has the potential to
# behave in surprising ways in examples that spawn separate threads,
# though we have yet to see this in practice. You've been warned.
#
# @note Because `let` is designed to create state that is reset between
# each example, and `before(:all)` is designed to setup state that is
# shared across _all_ examples in an example group, `let` is _not_
# intended to be used in a `before(:all)` hook. RSpec 2.13.1 prints
# a warning when you reference a `let` from `before(:all)` and we plan
# to have it raise an error in RSpec 3.
#
# @example
#
# describe Thing do
# let(:thing) { Thing.new }
#
# it "does something" do
# # first invocation, executes block, memoizes and returns result
# thing.do_something
#
# # second invocation, returns the memoized value
# thing.should be_something
# end
# end
def let(name, &block)
# We have to pass the block directly to `define_method` to
# allow it to use method constructs like `super` and `return`.
raise "#let or #subject called without a block" if block.nil?
MemoizedHelpers.module_for(self).send(:define_method, name, &block)
# Apply the memoization. The method has been defined in an ancestor
# module so we can use `super` here to get the value.
define_method(name) do
__memoized.fetch(name) { |k| __memoized[k] = super(&nil) }
end
end
# Just like `let`, except the block is invoked by an implicit `before`
# hook. This serves a dual purpose of setting up state and providing a
# memoized reference to that state.
#
# @example
#
# class Thing
# def self.count
# @count ||= 0
# end
#
# def self.count=(val)
# @count += val
# end
#
# def self.reset_count
# @count = 0
# end
#
# def initialize
# self.class.count += 1
# end
# end
#
# describe Thing do
# after(:each) { Thing.reset_count }
#
# context "using let" do
# let(:thing) { Thing.new }
#
# it "is not invoked implicitly" do
# Thing.count.should eq(0)
# end
#
# it "can be invoked explicitly" do
# thing
# Thing.count.should eq(1)
# end
# end
#
# context "using let!" do
# let!(:thing) { Thing.new }
#
# it "is invoked implicitly" do
# Thing.count.should eq(1)
# end
#
# it "returns memoized version on first invocation" do
# thing
# Thing.count.should eq(1)
# end
# end
# end
def let!(name, &block)
let(name, &block)
before { __send__(name) }
end
# Declares a `subject` for an example group which can then be the
# implicit receiver (through delegation) of calls to `should`.
#
# Given a `name`, defines a method with that name which returns the
# `subject`. This lets you declare the subject once and access it
# implicitly in one-liners and explicitly using an intention revealing
# name.
#
# @param [String,Symbol] name used to define an accessor with an
# intention revealing name
# @param block defines the value to be returned by `subject` in examples
#
# @example
#
# describe CheckingAccount, "with $50" do
# subject { CheckingAccount.new(Money.new(50, :USD)) }
# it { should have_a_balance_of(Money.new(50, :USD)) }
# it { should_not be_overdrawn }
# end
#
# describe CheckingAccount, "with a non-zero starting balance" do
# subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
# it { should_not be_overdrawn }
# it "has a balance equal to the starting balance" do
# account.balance.should eq(Money.new(50, :USD))
# end
# end
#
# @see MemoizedHelpers#should
def subject(name=nil, &block)
if name
let(name, &block)
alias_method :subject, name
self::NamedSubjectPreventSuper.send(:define_method, name) do
raise NotImplementedError, "`super` in named subjects is not supported"
end
else
let(:subject, &block)
end
end
# Just like `subject`, except the block is invoked by an implicit `before`
# hook. This serves a dual purpose of setting up state and providing a
# memoized reference to that state.
#
# @example
#
# class Thing
# def self.count
# @count ||= 0
# end
#
# def self.count=(val)
# @count += val
# end
#
# def self.reset_count
# @count = 0
# end
#
# def initialize
# self.class.count += 1
# end
# end
#
# describe Thing do
# after(:each) { Thing.reset_count }
#
# context "using subject" do
# subject { Thing.new }
#
# it "is not invoked implicitly" do
# Thing.count.should eq(0)
# end
#
# it "can be invoked explicitly" do
# subject
# Thing.count.should eq(1)
# end
# end
#
# context "using subject!" do
# subject!(:thing) { Thing.new }
#
# it "is invoked implicitly" do
# Thing.count.should eq(1)
# end
#
# it "returns memoized version on first invocation" do
# subject
# Thing.count.should eq(1)
# end
# end
# end
def subject!(name=nil, &block)
subject(name, &block)
before { subject }
end
# Creates a nested example group named by the submitted `attribute`,
# and then generates an example using the submitted block.
#
# @example
#
# # This ...
# describe Array do
# its(:size) { should eq(0) }
# end
#
# # ... generates the same runtime structure as this:
# describe Array do
# describe "size" do
# it "should eq(0)" do
# subject.size.should eq(0)
# end
# end
# end
#
# The attribute can be a `Symbol` or a `String`. Given a `String`
# with dots, the result is as though you concatenated that `String`
# onto the subject in an expression.
#
# @example
#
# describe Person do
# subject do
# Person.new.tap do |person|
# person.phone_numbers << "555-1212"
# end
# end
#
# its("phone_numbers.first") { should eq("555-1212") }
# end
#
# When the subject is a `Hash`, you can refer to the Hash keys by
# specifying a `Symbol` or `String` in an array.
#
# @example
#
# describe "a configuration Hash" do
# subject do
# { :max_users => 3,
# 'admin' => :all_permissions }
# end
#
# its([:max_users]) { should eq(3) }
# its(['admin']) { should eq(:all_permissions) }
#
# # You can still access to its regular methods this way:
# its(:keys) { should include(:max_users) }
# its(:count) { should eq(2) }
# end
#
# Note that this method does not modify `subject` in any way, so if you
# refer to `subject` in `let` or `before` blocks, you're still
# referring to the outer subject.
#
# @example
#
# describe Person do
# subject { Person.new }
# before { subject.age = 25 }
# its(:age) { should eq(25) }
# end
def its(attribute, &block)
describe(attribute) do
if Array === attribute
let(:__its_subject) { subject[*attribute] }
else
let(:__its_subject) do
attribute_chain = attribute.to_s.split('.')
attribute_chain.inject(subject) do |inner_subject, attr|
inner_subject.send(attr)
end
end
end
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
example(&block)
end
end
end
# @api private
#
# Gets the LetDefinitions module. The module is mixed into
# the example group and is used to hold all let definitions.
# This is done so that the block passed to `let` can be
# forwarded directly on to `define_method`, so that all method
# constructs (including `super` and `return`) can be used in
# a `let` block.
#
# The memoization is provided by a method definition on the
# example group that supers to the LetDefinitions definition
# in order to get the value to memoize.
def self.module_for(example_group)
get_constant_or_yield(example_group, :LetDefinitions) do
mod = Module.new do
include Module.new {
example_group.const_set(:NamedSubjectPreventSuper, self)
}
end
example_group.__send__(:include, mod)
example_group.const_set(:LetDefinitions, mod)
mod
end
end
if Module.method(:const_defined?).arity == 1 # for 1.8
# @api private
#
# Gets the named constant or yields.
# On 1.8, const_defined? / const_get do not take into
# account the inheritance hierarchy.
def self.get_constant_or_yield(example_group, name)
if example_group.const_defined?(name)
example_group.const_get(name)
else
yield
end
end
else
# @api private
#
# Gets the named constant or yields.
# On 1.9, const_defined? / const_get take into account the
# the inheritance by default, and accept an argument to
# disable this behavior. It's important that we don't
# consider inheritance here; each example group level that
# uses a `let` should get its own `LetDefinitions` module.
def self.get_constant_or_yield(example_group, name)
if example_group.const_defined?(name, (check_ancestors = false))
example_group.const_get(name, check_ancestors)
else
yield
end
end
end
end
end
end
Move definition of implicit subject.
This is in prep for changing when the LetDefinitions module is included.
The use of `subject` from the `included` hook was causing problems when
I was trying to do that.
module RSpec
module Core
module MemoizedHelpers
# @note `subject` was contributed by Joe Ferris to support the one-liner
# syntax embraced by shoulda matchers:
#
# describe Widget do
# it { should validate_presence_of(:name) }
# end
#
# While the examples below demonstrate how to use `subject`
# explicitly in examples, we recommend that you define a method with
# an intention revealing name instead.
#
# @example
#
# # explicit declaration of subject
# describe Person do
# subject { Person.new(:birthdate => 19.years.ago) }
# it "should be eligible to vote" do
# subject.should be_eligible_to_vote
# # ^ ^ explicit reference to subject not recommended
# end
# end
#
# # implicit subject => { Person.new }
# describe Person do
# it "should be eligible to vote" do
# subject.should be_eligible_to_vote
# # ^ ^ explicit reference to subject not recommended
# end
# end
#
# # one-liner syntax - should is invoked on subject
# describe Person do
# it { should be_eligible_to_vote }
# end
#
# @note Because `subject` is designed to create state that is reset between
# each example, and `before(:all)` is designed to setup state that is
# shared across _all_ examples in an example group, `subject` is _not_
# intended to be used in a `before(:all)` hook. RSpec 2.13.1 prints
# a warning when you reference a `subject` from `before(:all)` and we plan
# to have it raise an error in RSpec 3.
#
# @see #should
def subject
__memoized.fetch(:subject) do
__memoized[:subject] = begin
described = described_class || self.class.description
Class === described ? described.new : described
end
end
end
# When `should` is called with no explicit receiver, the call is
# delegated to the object returned by `subject`. Combined with an
# implicit subject this supports very concise expressions.
#
# @example
#
# describe Person do
# it { should be_eligible_to_vote }
# end
#
# @see #subject
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message)
end
# Just like `should`, `should_not` delegates to the subject (implicit or
# explicit) of the example group.
#
# @example
#
# describe Person do
# it { should_not be_eligible_to_vote }
# end
#
# @see #subject
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message)
end
private
# @private
def __memoized
@__memoized ||= {}
end
# Used internally to customize the behavior of the
# memoized hash when used in a `before(:all)` hook.
#
# @private
class BeforeAllMemoizedHash
def initialize(example_group_instance)
@example_group_instance = example_group_instance
@hash = {}
end
def self.isolate_for_before_all(example_group_instance)
example_group_instance.instance_eval do
@__memoized = BeforeAllMemoizedHash.new(self)
begin
yield
ensure
@__memoized.preserve_accessed_lets
@__memoized = nil
end
end
end
def fetch(key, &block)
description = if key == :subject
"subject"
else
"let declaration `#{key}`"
end
::RSpec.warn_deprecation <<-EOS
WARNING: #{description} accessed in a `before(:all)` hook at:
#{caller[1]}
This is deprecated behavior that will not be supported in RSpec 3.
`let` and `subject` declarations are not intended to be called
in a `before(:all)` hook, as they exist to define state that
is reset between each example, while `before(:all)` exists to
define state that is shared across examples in an example group.
EOS
@hash.fetch(key, &block)
end
def []=(key, value)
@hash[key] = value
end
def preserve_accessed_lets
hash = @hash
@example_group_instance.class.class_eval do
hash.each do |key, value|
undef_method(key) if method_defined?(key)
define_method(key) { value }
end
end
end
end
def self.included(mod)
mod.extend(ClassMethods)
end
module ClassMethods
# Generates a method whose return value is memoized after the first
# call. Useful for reducing duplication between examples that assign
# values to the same local variable.
#
# @note `let` _can_ enhance readability when used sparingly (1,2, or
# maybe 3 declarations) in any given example group, but that can
# quickly degrade with overuse. YMMV.
#
# @note `let` uses an `||=` conditional that has the potential to
# behave in surprising ways in examples that spawn separate threads,
# though we have yet to see this in practice. You've been warned.
#
# @note Because `let` is designed to create state that is reset between
# each example, and `before(:all)` is designed to setup state that is
# shared across _all_ examples in an example group, `let` is _not_
# intended to be used in a `before(:all)` hook. RSpec 2.13.1 prints
# a warning when you reference a `let` from `before(:all)` and we plan
# to have it raise an error in RSpec 3.
#
# @example
#
# describe Thing do
# let(:thing) { Thing.new }
#
# it "does something" do
# # first invocation, executes block, memoizes and returns result
# thing.do_something
#
# # second invocation, returns the memoized value
# thing.should be_something
# end
# end
def let(name, &block)
# We have to pass the block directly to `define_method` to
# allow it to use method constructs like `super` and `return`.
raise "#let or #subject called without a block" if block.nil?
MemoizedHelpers.module_for(self).send(:define_method, name, &block)
# Apply the memoization. The method has been defined in an ancestor
# module so we can use `super` here to get the value.
define_method(name) do
__memoized.fetch(name) { |k| __memoized[k] = super(&nil) }
end
end
# Just like `let`, except the block is invoked by an implicit `before`
# hook. This serves a dual purpose of setting up state and providing a
# memoized reference to that state.
#
# @example
#
# class Thing
# def self.count
# @count ||= 0
# end
#
# def self.count=(val)
# @count += val
# end
#
# def self.reset_count
# @count = 0
# end
#
# def initialize
# self.class.count += 1
# end
# end
#
# describe Thing do
# after(:each) { Thing.reset_count }
#
# context "using let" do
# let(:thing) { Thing.new }
#
# it "is not invoked implicitly" do
# Thing.count.should eq(0)
# end
#
# it "can be invoked explicitly" do
# thing
# Thing.count.should eq(1)
# end
# end
#
# context "using let!" do
# let!(:thing) { Thing.new }
#
# it "is invoked implicitly" do
# Thing.count.should eq(1)
# end
#
# it "returns memoized version on first invocation" do
# thing
# Thing.count.should eq(1)
# end
# end
# end
def let!(name, &block)
let(name, &block)
before { __send__(name) }
end
# Declares a `subject` for an example group which can then be the
# implicit receiver (through delegation) of calls to `should`.
#
# Given a `name`, defines a method with that name which returns the
# `subject`. This lets you declare the subject once and access it
# implicitly in one-liners and explicitly using an intention revealing
# name.
#
# @param [String,Symbol] name used to define an accessor with an
# intention revealing name
# @param block defines the value to be returned by `subject` in examples
#
# @example
#
# describe CheckingAccount, "with $50" do
# subject { CheckingAccount.new(Money.new(50, :USD)) }
# it { should have_a_balance_of(Money.new(50, :USD)) }
# it { should_not be_overdrawn }
# end
#
# describe CheckingAccount, "with a non-zero starting balance" do
# subject(:account) { CheckingAccount.new(Money.new(50, :USD)) }
# it { should_not be_overdrawn }
# it "has a balance equal to the starting balance" do
# account.balance.should eq(Money.new(50, :USD))
# end
# end
#
# @see MemoizedHelpers#should
def subject(name=nil, &block)
if name
let(name, &block)
alias_method :subject, name
self::NamedSubjectPreventSuper.send(:define_method, name) do
raise NotImplementedError, "`super` in named subjects is not supported"
end
else
let(:subject, &block)
end
end
# Just like `subject`, except the block is invoked by an implicit `before`
# hook. This serves a dual purpose of setting up state and providing a
# memoized reference to that state.
#
# @example
#
# class Thing
# def self.count
# @count ||= 0
# end
#
# def self.count=(val)
# @count += val
# end
#
# def self.reset_count
# @count = 0
# end
#
# def initialize
# self.class.count += 1
# end
# end
#
# describe Thing do
# after(:each) { Thing.reset_count }
#
# context "using subject" do
# subject { Thing.new }
#
# it "is not invoked implicitly" do
# Thing.count.should eq(0)
# end
#
# it "can be invoked explicitly" do
# subject
# Thing.count.should eq(1)
# end
# end
#
# context "using subject!" do
# subject!(:thing) { Thing.new }
#
# it "is invoked implicitly" do
# Thing.count.should eq(1)
# end
#
# it "returns memoized version on first invocation" do
# subject
# Thing.count.should eq(1)
# end
# end
# end
def subject!(name=nil, &block)
subject(name, &block)
before { subject }
end
# Creates a nested example group named by the submitted `attribute`,
# and then generates an example using the submitted block.
#
# @example
#
# # This ...
# describe Array do
# its(:size) { should eq(0) }
# end
#
# # ... generates the same runtime structure as this:
# describe Array do
# describe "size" do
# it "should eq(0)" do
# subject.size.should eq(0)
# end
# end
# end
#
# The attribute can be a `Symbol` or a `String`. Given a `String`
# with dots, the result is as though you concatenated that `String`
# onto the subject in an expression.
#
# @example
#
# describe Person do
# subject do
# Person.new.tap do |person|
# person.phone_numbers << "555-1212"
# end
# end
#
# its("phone_numbers.first") { should eq("555-1212") }
# end
#
# When the subject is a `Hash`, you can refer to the Hash keys by
# specifying a `Symbol` or `String` in an array.
#
# @example
#
# describe "a configuration Hash" do
# subject do
# { :max_users => 3,
# 'admin' => :all_permissions }
# end
#
# its([:max_users]) { should eq(3) }
# its(['admin']) { should eq(:all_permissions) }
#
# # You can still access to its regular methods this way:
# its(:keys) { should include(:max_users) }
# its(:count) { should eq(2) }
# end
#
# Note that this method does not modify `subject` in any way, so if you
# refer to `subject` in `let` or `before` blocks, you're still
# referring to the outer subject.
#
# @example
#
# describe Person do
# subject { Person.new }
# before { subject.age = 25 }
# its(:age) { should eq(25) }
# end
def its(attribute, &block)
describe(attribute) do
if Array === attribute
let(:__its_subject) { subject[*attribute] }
else
let(:__its_subject) do
attribute_chain = attribute.to_s.split('.')
attribute_chain.inject(subject) do |inner_subject, attr|
inner_subject.send(attr)
end
end
end
def should(matcher=nil, message=nil)
RSpec::Expectations::PositiveExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
def should_not(matcher=nil, message=nil)
RSpec::Expectations::NegativeExpectationHandler.handle_matcher(__its_subject, matcher, message)
end
example(&block)
end
end
end
# @api private
#
# Gets the LetDefinitions module. The module is mixed into
# the example group and is used to hold all let definitions.
# This is done so that the block passed to `let` can be
# forwarded directly on to `define_method`, so that all method
# constructs (including `super` and `return`) can be used in
# a `let` block.
#
# The memoization is provided by a method definition on the
# example group that supers to the LetDefinitions definition
# in order to get the value to memoize.
def self.module_for(example_group)
get_constant_or_yield(example_group, :LetDefinitions) do
mod = Module.new do
include Module.new {
example_group.const_set(:NamedSubjectPreventSuper, self)
}
end
example_group.__send__(:include, mod)
example_group.const_set(:LetDefinitions, mod)
mod
end
end
if Module.method(:const_defined?).arity == 1 # for 1.8
# @api private
#
# Gets the named constant or yields.
# On 1.8, const_defined? / const_get do not take into
# account the inheritance hierarchy.
def self.get_constant_or_yield(example_group, name)
if example_group.const_defined?(name)
example_group.const_get(name)
else
yield
end
end
else
# @api private
#
# Gets the named constant or yields.
# On 1.9, const_defined? / const_get take into account the
# the inheritance by default, and accept an argument to
# disable this behavior. It's important that we don't
# consider inheritance here; each example group level that
# uses a `let` should get its own `LetDefinitions` module.
def self.get_constant_or_yield(example_group, name)
if example_group.const_defined?(name, (check_ancestors = false))
example_group.const_get(name, check_ancestors)
else
yield
end
end
end
end
end
end
|
# encoding: utf-8
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for multiple expressions placed on the same line.
# It also checks for lines terminated with a semicolon.
class Semicolon < Cop
MSG = 'Do not use semicolons to terminate expressions.'.freeze
def investigate(processed_source)
return unless processed_source.ast
@processed_source = processed_source
check_for_line_terminator
end
def on_begin(node)
return if cop_config['AllowAsExpressionSeparator']
exprs = node.children
return if exprs.size < 2
# create a map matching lines to the number of expressions on them
exprs_lines = exprs.map { |e| e.source_range.line }
lines = exprs_lines.group_by { |i| i }
# every line with more than 1 expression on it is an offense
lines.each do |line, expr_on_line|
next unless expr_on_line.size > 1
# TODO: Find the correct position of the semicolon. We don't know
# if the first semicolon on the line is a separator of
# expressions. It's just a guess.
column = @processed_source[line - 1].index(';')
convention_on(line, column, !:last_on_line)
end
end
private
def check_for_line_terminator
tokens_for_lines = @processed_source.tokens.group_by do |token|
token.pos.line
end
tokens_for_lines.each do |line, tokens|
next unless tokens.last.type == :tSEMI
convention_on(line, tokens.last.pos.column, :last_on_line)
end
end
def convention_on(line, column, last_on_line)
range = source_range(@processed_source.buffer, line, column)
add_offense(last_on_line ? range : nil, range)
end
def autocorrect(range)
return unless range
->(corrector) { corrector.remove(range) }
end
end
end
end
end
Add comment to Style/Semicolon#convention_on
# encoding: utf-8
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for multiple expressions placed on the same line.
# It also checks for lines terminated with a semicolon.
class Semicolon < Cop
MSG = 'Do not use semicolons to terminate expressions.'.freeze
def investigate(processed_source)
return unless processed_source.ast
@processed_source = processed_source
check_for_line_terminator
end
def on_begin(node)
return if cop_config['AllowAsExpressionSeparator']
exprs = node.children
return if exprs.size < 2
# create a map matching lines to the number of expressions on them
exprs_lines = exprs.map { |e| e.source_range.line }
lines = exprs_lines.group_by { |i| i }
# every line with more than 1 expression on it is an offense
lines.each do |line, expr_on_line|
next unless expr_on_line.size > 1
# TODO: Find the correct position of the semicolon. We don't know
# if the first semicolon on the line is a separator of
# expressions. It's just a guess.
column = @processed_source[line - 1].index(';')
convention_on(line, column, !:last_on_line)
end
end
private
def check_for_line_terminator
tokens_for_lines = @processed_source.tokens.group_by do |token|
token.pos.line
end
tokens_for_lines.each do |line, tokens|
next unless tokens.last.type == :tSEMI
convention_on(line, tokens.last.pos.column, :last_on_line)
end
end
def convention_on(line, column, last_on_line)
range = source_range(@processed_source.buffer, line, column)
# Don't attempt to autocorrect if semicolon is separating statements
# on the same line
add_offense(last_on_line ? range : nil, range)
end
def autocorrect(range)
return unless range
->(corrector) { corrector.remove(range) }
end
end
end
end
end
|
class EnginesCore
require "/opt/engines/lib/ruby/system/SystemUtils.rb"
require "/opt/engines/lib/ruby/system/DNSHosting.rb"
require_relative 'DockerApi.rb'
require_relative 'SystemApi.rb'
require_relative 'SystemPreferences.rb'
def initialize
@docker_api = DockerApi.new
@system_api = SystemApi.new(self) #will change to to docker_api and not self
@system_preferences = SystemPreferences.new
@last_error = String.new
end
attr_reader :last_error
def software_service_definition(params)
sm = loadServiceManager
return sm.software_service_definition(params)
end
#@return an [Array] of service_hashes regsitered against the Service params[:publisher_namespace] params[:type_path]
def get_registered_against_service(params)
sm = loadServiceManager
return sm.get_registered_against_service(params)
end
def add_domain(params)
return @system_api.add_domain(params)
end
#
# def remove_containers_cron_list(container_name)
# p :remove_containers_cron
# if @system_api.remove_containers_cron_list(container_name)
# cron_service = loadManagedService("cron")
# return @system_api.rebuild_crontab(cron_service)
# else
# return false
# end
# end
#
# def rebuild_crontab(cron_service)
# #acutally a rebuild (or resave) as hadh already removed from consumer list
# p :rebuild_crontab
# return @system_api.rebuild_crontab(cron_service)
# end
def remove_domain(params)
return @system_api.rm_domain(params[:domain_name],@system_api)
end
def update_domain(old_domain,params)
return @system_api.update_domain(old_domain,params,@system_api)
end
def signal_service_process(pid,sig,name)
container = loadManagedService(name)
return @docker_api.signal_container_process(pid,sig,container)
end
def start_container(container)
return @docker_api.start_container(container)
end
def inspect_container(container)
return @docker_api.inspect_container(container)
end
def stop_container(container)
return @docker_api.stop_container(container)
end
def pause_container(container)
return @docker_api.pause_container(container)
end
def unpause_container(container)
return @docker_api.unpause_container(container)
end
def ps_container(container)
return @docker_api.ps_container(container)
end
def logs_container(container)
return @docker_api.logs_container(container)
end
# def add_monitor(site_hash)
# return @system_api.add_monitor(site_hash)
# end
#
# def rm_monitor(site_hash)
# return @system_api.rm_monitor(site_hash)
# end
def get_build_report(engine_name)
return @system_api.get_build_report(engine_name)
end
def save_build_report(container,build_report)
return @system_api.save_build_report(container,build_report)
end
def save_container(container)
return @system_api.save_container(container)
end
def save_blueprint(blueprint,container)
return @system_api.save_blueprint(blueprint,container)
end
def load_blueprint(container)
return @system_api.load_blueprint(container)
end
def add_volume(site_hash)
return @system_api.add_volume(site_hash)
end
def rm_volume(site_hash)
return @system_api.rm_volume(site_hash)
end
def remove_self_hosted_domain(domain_name)
return @system_api.remove_self_hosted_domain(domain_name)
end
def add_self_hosted_domain(params)
return @system_api.add_self_hosted_domain(params)
end
def list_self_hosted_domains()
return @system_api.list_self_hosted_domains()
end
def update_self_hosted_domain(old_domain_name, params)
@system_api.update_self_hosted_domain(old_domain_name, params)
end
# def load_system_preferences
# return @system_api.load_system_preferences
# end
#
# def save_system_preferences(preferences)
# return @system_api.save_system_preferences(preferences)
# end
def get_container_memory_stats(container)
return @system_api.get_container_memory_stats(container)
end
def set_engine_hostname_details(container,params)
return @system_api.set_engine_hostname_details(container,params)
end
def image_exists?(container_name)
imageName = container_name
return @docker_api.image_exists?(imageName)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
def list_attached_services_for(objectName,identifier)
sm = loadServiceManager()
return sm.list_attached_services_for(objectName,identifier)
rescue Exception=>e
SystemUtils.log_exception e
end
def list_avail_services_for(object)
objectname = object.class.name.split('::').last
# p :load_vail_services_for
# p objectname
services = load_avail_services_for(objectname)
subservices = load_avail_component_services_for(object)
retval = Hash.new
retval[:services] = services
retval[:subservices] = subservices
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def load_software_service(params)
sm = loadServiceManager()
# p :load_software_service
# p params
service_container = sm.get_software_service_container_name(params)
params[:service_container_name] = service_container
# p :service_container_name
# p service_container
service = loadManagedService(service_container)
if service == nil
return nil
end
return service
rescue Exception=>e
SystemUtils.log_exception e
end
def setup_email_params(params)
arg="smarthost_hostname=" + params[:smarthost_hostname] \
+ ":smarthost_username=" + params[:smarthost_username]\
+ ":smarthost_password=" + params[:smarthost_password]\
+ ":mail_name=smtp." + params[:default_domain]
container=loadManagedService("smtp")
return @docker_api.docker_exec(container,SysConfig.SetupParamsScript,arg)
rescue Exception=>e
SystemUtils.log_exception(e)
end
def set_engines_ssh_pw(params)
pass = params[:ssh_password]
cmd = "echo -e " + pass + "\n" + pass + " | passwd engines"
SystemUtils.debug_output( "ssh_pw",cmd)
SystemUtils.run_system(cmd)
end
def set_default_domain(params)
@system_preferences.set_default_domain(params)
end
def set_default_site(params)
@system_preferences.set_default_site(params)
end
def get_default_site()
@system_preferences.get_default_site
end
def get_default_domain()
@system_preferences.get_default_domain
end
def set_database_password(container_name,params)
arg = "mysql_password=" + params[:mysql_password] +":" \
+ "server=" + container_name + ":" \
+ "psql_password=" + params[:psql_password] #Need two args
if container_name
server_container = loadManagedService(container_name)
return @docker_api.docker_exec(server_container,SysConfig.SetupParamsScript,arg)
end
return true
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
#Attach the service defined in service_hash [Hash]
#@return boolean indicating sucess
def attach_service(service_hash)
p :attach_Service
p service_hash
SystemUtils.symbolize_keys(service_hash[:variables])
p service_hash
if service_hash == nil
log_error_mesg("Attach Service passed a nil","")
return false
elsif service_hash.is_a?(Hash) == false
log_error_mesg("Attached Service passed a non Hash",service_hash)
return false
end
if service_hash.has_key?(:service_handle) == false || service_hash[:service_handle] == nil
service_handle_field = SoftwareServiceDefinition.service_handle_field(service_hash)
p :service_handle_field
p service_handle_field
p service_hash[:variables][service_handle_field.to_sym]
service_hash[:service_handle] = service_hash[:variables][service_handle_field.to_sym]
end
if service_hash.has_key?(:variables) == false
log_error_mesg("Attached Service passed no variables",service_hash)
return false
end
sm = loadServiceManager()
return sm.add_service(service_hash)
rescue Exception=>e
SystemUtils.log_exception e
end
def remove_orphaned_service(params)
sm = loadServiceManager()
return sm.remove_orphaned_service(params)
rescue Exception=>e
SystemUtils.log_exception e
end
def dettach_service(params)
sm = loadServiceManager()
return sm.remove_service(params)
# if service !=nil && service != false
# return service.remove_consumer(params)
# end
# @last_error = "Failed to dettach Service: " + @last_error
rescue Exception=>e
SystemUtils.log_exception e
return false
end
def list_providers_in_use
sm = loadServiceManager()
return sm.list_providers_in_use
end
def loadServiceManager()
if @service_manager == nil
@service_manager = ServiceManager.new(self)
return @service_manager
end
return @service_manager
end
def match_orphan_service(service_hash)
sm = loadServiceManager()
if sm.retrieve_orphan(service_hash) == false
return false
end
return true
end
#returns
def find_service_consumers(params)
sm = loadServiceManager()
return sm.find_service_consumers(params)
end
def service_is_registered?(service_hash)
sm = loadServiceManager()
return sm.service_is_registered?(service_hash)
end
def get_engine_persistant_services(params)
sm = loadServiceManager()
return sm.get_engine_persistant_services(params)
end
def managed_service_tree
sm = loadServiceManager()
return sm.managed_service_tree
end
def get_managed_engine_tree
sm = loadServiceManager()
return sm.get_managed_engine_tree
end
def find_engine_services(params)
sm = loadServiceManager()
return sm.find_engine_services(params)
end
def load_service_definition(filename)
yaml_file = File.open(filename)
# p :open
# p filename
return SoftwareServiceDefinition.from_yaml(yaml_file)
rescue
rescue Exception=>e
SystemUtils.log_exception e
end
def load_avail_services_for_type(typename)
# p :load_avail_services_for_by_type
# p typename
retval = Array.new
dir = SysConfig.ServiceMapTemplateDir + "/" + typename
# p :dir
# p dir
if Dir.exists?(dir)
Dir.foreach(dir) do |service_dir_entry|
begin
if service_dir_entry.start_with?(".") == true
next
end
# p :service_dir_entry
# p service_dir_entry
if service_dir_entry.end_with?(".yaml")
service = load_service_definition(dir + "/" + service_dir_entry)
if service != nil
# p :service_as_serivce
# p service
# p :as_hash
# p service.to_h
# p :as_yaml
# p service.to_yaml()
retval.push(service.to_h)
end
end
rescue Exception=>e
SystemUtils.log_exception e
next
end
end
end
# p typename
# p retval
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def load_avail_services_for(typename)
# p :load_avail_services_for
# p typename
retval = Array.new
dir = SysConfig.ServiceMapTemplateDir + "/" + typename
# p :dir
# p dir
if Dir.exists?(dir)
Dir.foreach(dir) do |service_dir_entry|
begin
if service_dir_entry.start_with?(".") == true
next
end
# p :service_dir_entry
# p service_dir_entry
if service_dir_entry.end_with?(".yaml")
service = load_service_definition(dir + "/" + service_dir_entry)
if service != nil
retval.push(service.to_h)
end
end
rescue Exception=>e
SystemUtils.log_exception e
next
end
end
end
# p typename
# p retval
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def load_avail_component_services_for(engine)
retval = Hash.new
if engine.is_a?(ManagedEngine)
params = Hash.new
params[:engine_name]=engine.container_name
persistant_services = get_engine_persistant_services(params)
persistant_services.each do |service|
type_path = service[:type_path]
retval[type_path] = load_avail_services_for_type(type_path)
# p retval[type_path]
end
else
# p :load_avail_component_services_for_engine_got_a
# p engine.to_s
return nil
end
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def set_engine_runtime_properties(params)
#FIX ME also need to deal with Env Variables
engine_name = params[:engine_name]
engine = loadManagedEngine(engine_name)
if engine.is_a?(EnginesOSapiResult) == true
last_error = engine.result_mesg
return false
end
if engine.is_active == true
last_error="Container is active"
return false
end
if params.has_key?(:memory)
if params[:memory] == engine.memory
last_error="No Change in Memory Value"
return false
end
if engine.update_memory(params[:memory]) == false
last_error= engine.last_error
return false
end
end
if engine.has_container? == true
if destroy_container(engine) == false
last_error= engine.last_error
return false
end
end
if create_container(engine) == false
last_error= engine.last_error
return false
end
return true
end
def set_engine_network_properties (engine, params)
return @system_api.set_engine_network_properties(engine,params)
end
def get_system_load_info
return @system_api.get_system_load_info
end
def get_system_memory_info
return @system_api.get_system_memory_info
end
def getManagedEngines
return @system_api.getManagedEngines
end
def loadManagedEngine(engine_name)
return @system_api.loadManagedEngine(engine_name)
end
def get_orphaned_services_tree
return loadServiceManager.get_orphaned_services_tree
end
def loadManagedService(service_name)
return @system_api.loadManagedService(service_name)
end
def getManagedServices
return @system_api.getManagedServices
end
def list_domains
return @system_api.list_domains
end
def list_managed_engines
return @system_api.list_managed_engines
end
def list_managed_services
return @system_api.list_managed_services
end
def destroy_container(container)
clear_error
begin
if @docker_api.destroy_container(container) != false
@system_api.destroy_container(container) #removes cid file
return true
else
return false
end
rescue Exception=>e
container.last_error=( "Failed To Destroy " + e.to_s)
SystemUtils.log_exception(e)
return false
end
end
def generate_engines_user_ssh_key
return @system_api.regen_system_ssh_key
end
def system_update
return @system_api.system_update
end
def delete_image(container)
begin
clear_error
if @docker_api.delete_image(container) == true
#only delete if del all otherwise backup
return @system_api.delete_container_configs(container)
end
return false
rescue Exception=>e
@last_error=( "Failed To Delete " + e.to_s)
SystemUtils.log_exception(e)
return false
end
end
#@return boolean indicating sucess
#@params [Hash] :engine_name
#Retrieves all persistant service registered to :engine_name and destroys the underlying service (fs db etc)
# They are removed from the tree if delete is sucessful
def delete_engine_persistant_services(params)
sm = loadServiceManager()
services = sm.get_engine_persistant_services(params)
services.each do |service_hash|
service_hash[:remove_all_application_data] = params[:remove_all_application_data]
if service_hash.has_key?(:service_container_name) == false
log_error_mesg("Missing :service_container_name in service_hash",service_hash)
return false
end
service = loadManagedService(service_hash[:service_container_name])
if service == nil
log_error_mesg("Failed to load container name keyed by :service_container_name ",service_hash)
return false
end
if service.is_running == false
log_error_mesg("Cannot remove service consumer if service is not running ",service_hash)
return false
end
if service.remove_consumer(service_hash) == false
log_error_mesg("Failed to remove service ",service_hash)
return false
end
#REMOVE THE SERVICE HERE AND NOW
if sm.remove_from_engine_registery(service_hash) ==true
if sm.remove_from_services_registry(service_hash) == false
log_error_mesg("Cannot remove from Service Registry",service_hash)
return false
end
else
log_error_mesg("Cannot remove from Engine Registry",service_hash)
return false
end
end
return true
rescue Exception=>e
@last_error=( "Failed To Delete " + e.to_s)
SystemUtils.log_exception(e)
return false
end
def delete_image_dependancies(params)
sm = loadServiceManager()
if sm.rm_remove_engine(params) == false
log_error_mesg("Failed to remove deleted Service",params)
return false
end
return true
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
def run_system(cmd)
clear_error
begin
cmd = cmd + " 2>&1"
res= %x<#{cmd}>
SystemUtils.debug_output("run system",res)
#FIXME should be case insensitive The last one is a pure kludge
#really need to get stderr and stdout separately
if $? == 0 && res.downcase.include?("error") == false && res.downcase.include?("fail") == false && res.downcase.include?("could not resolve hostname") == false && res.downcase.include?("unsuccessful") == false
return true
else
@last_error = res
SystemUtils.debug_output("run system result",res)
return false
end
rescue Exception=>e
SystemUtils.log_exception(e)
return ret_val
end
end
def run_volume_builder(container,username)
clear_error
begin
if File.exists?(SysConfig.CidDir + "/volbuilder.cid") == true
command = "docker stop volbuilder"
run_system(command)
command = "docker rm volbuilder"
run_system(command)
File.delete(SysConfig.CidDir + "/volbuilder.cid")
end
mapped_vols = get_volbuild_volmaps container
command = "docker run --name volbuilder --memory=20m -e fw_user=" + username + " --cidfile /opt/engines/run/volbuilder.cid " + mapped_vols + " -t engines/volbuilder:" + SystemUtils.system_release + " /bin/sh /home/setup_vols.sh "
SystemUtils.debug_output("Run volumen builder",command)
run_system(command)
#Note no -d so process will not return until setup.sh completes
command = "docker rm volbuilder"
if File.exists?(SysConfig.CidDir + "/volbuilder.cid") == true
File.delete(SysConfig.CidDir + "/volbuilder.cid")
end
res = run_system(command)
if res != true
SystemUtils.log_error(res)
#don't return false as
end
return true
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
def create_container(container)
clear_error
begin
if @system_api.clear_cid(container) != false
@system_api.clear_container_var_run(container)
if @docker_api.create_container(container) == true
return @system_api.create_container(container)
end
else
return false
end
rescue Exception=>e
container.last_error=("Failed To Create " + e.to_s)
SystemUtils.log_exception(e)
return false
end
end
def load_and_attach_persistant_services(container)
dirname = get_container_dir(container) + "/persistant/"
sm = loadServiceManager()
return sm.load_and_attach_services(dirname,container )
end
def load_and_attach_nonpersistant_services(container)
dirname = get_container_dir(container) + "/nonpersistant/"
sm = loadServiceManager()
return sm.load_and_attach_services(dirname,container)
end
def get_container_dir(container)
return @system_api.container_state_dir(container) +"/services/"
end
#install from fresh copy of blueprint in repositor
def reinstall_engine(engine)
clear_error
EngineBuilder.re_install_engine(engine,self)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
#rebuilds image from current blueprint
def rebuild_image(container)
clear_error
begin
params=Hash.new
params[:engine_name] = container.container_name
params[:domain_name] = container.domain_name
params[:host_name] = container.hostname
params[:env_variables] = container.environments
params[:http_protocol] = container.protocol
params[:repository_url] = container.repo
params[:software_environment_variables] = container.environments
# custom_env=params
# @http_protocol = params[:http_protocol] = container.
builder = EngineBuilder.new(params, self)
return builder.rebuild_managed_container(container)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
#FIXME Kludge
def get_container_network_metrics(container_name)
begin
ret_val = Hash.new
clear_error
cmd = "docker exec " + container_name + " netstat --interfaces -e | grep bytes |head -1 | awk '{ print $2 " " $6}' 2>&1"
res= %x<#{cmd}>
vals = res.split("bytes:")
if vals.count < 2
if vals[1] != nil && vals[2] != nil
ret_val[:in] = vals[1].chop
ret_val[:out] = vals[2].chop
else
ret_val[:in] ="-1"
ret_val[:out] ="-1"
end
else
ret_val[:in] ="-1"
ret_val[:out] ="-1"
end
return ret_val
rescue Exception=>e
SystemUtils.log_exception(e)
ret_val[:in] = -1
ret_val[:out] = -1
return ret_val
end
end
def is_startup_complete container
clear_error
begin
return @system_api.is_startup_complete(container)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
def log_error_mesg(msg,object)
obj_str = object.to_s.slice(0,256)
@last_error = msg +":" + obj_str
SystemUtils.log_error_mesg(msg,object)
end
def register_non_persistant_services(engine_name)
sm = loadServiceManager()
return sm.register_non_persistant_services(engine_name)
end
def deregister_non_persistant_services(engine_name)
sm = loadServiceManager()
return sm.deregister_non_persistant_services(engine_name)
end
#@return an [Array] of service_hashs of Orphaned persistant services match @params [Hash]
#:path_type :publisher_namespace
def get_orphaned_services(params)
return loadServiceManager.get_orphaned_services(params)
end
def clean_up_dangling_images
@docker_api.clean_up_dangling_images
end
#@ return [Boolean] indicating sucess
#For Maintanence ONLY
def delete_service_from_service_registry(service_hash)
sm = loadServiceManager()
return sm.remove_from_services_registry(service_hash)
end
def delete_service_from_engine_registry(service_hash)
sm = loadServiceManager()
return sm.remove_from_engine_registery(service_hash)
end
protected
def get_volbuild_volmaps container
begin
clear_error
state_dir = SysConfig.CidDir + "/containers/" + container.container_name + "/run/"
log_dir = SysConfig.SystemLogRoot + "/containers/" + container.container_name
volume_option = " -v " + state_dir + ":/client/state:rw "
volume_option += " -v " + log_dir + ":/client/log:rw "
if container.volumes != nil
container.volumes.each_value do |vol|
SystemUtils.debug_output("build vol maps",vol)
volume_option += " -v " + vol.localpath.to_s + ":/dest/fs:rw"
end
end
volume_option += " --volumes-from " + container.container_name
return volume_option
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
def clear_error
@last_error = ""
end
#@return an [Array] of service_hashs of Active persistant services match @params [Hash]
#:path_type :publisher_namespace
def get_active_persistant_services(params)
return loadServiceManager.get_active_persistant_services(params)
end
end
need symbols not strings
class EnginesCore
require "/opt/engines/lib/ruby/system/SystemUtils.rb"
require "/opt/engines/lib/ruby/system/DNSHosting.rb"
require_relative 'DockerApi.rb'
require_relative 'SystemApi.rb'
require_relative 'SystemPreferences.rb'
def initialize
@docker_api = DockerApi.new
@system_api = SystemApi.new(self) #will change to to docker_api and not self
@system_preferences = SystemPreferences.new
@last_error = String.new
end
attr_reader :last_error
def software_service_definition(params)
sm = loadServiceManager
return sm.software_service_definition(params)
end
#@return an [Array] of service_hashes regsitered against the Service params[:publisher_namespace] params[:type_path]
def get_registered_against_service(params)
sm = loadServiceManager
return sm.get_registered_against_service(params)
end
def add_domain(params)
return @system_api.add_domain(params)
end
#
# def remove_containers_cron_list(container_name)
# p :remove_containers_cron
# if @system_api.remove_containers_cron_list(container_name)
# cron_service = loadManagedService("cron")
# return @system_api.rebuild_crontab(cron_service)
# else
# return false
# end
# end
#
# def rebuild_crontab(cron_service)
# #acutally a rebuild (or resave) as hadh already removed from consumer list
# p :rebuild_crontab
# return @system_api.rebuild_crontab(cron_service)
# end
def remove_domain(params)
return @system_api.rm_domain(params[:domain_name],@system_api)
end
def update_domain(old_domain,params)
return @system_api.update_domain(old_domain,params,@system_api)
end
def signal_service_process(pid,sig,name)
container = loadManagedService(name)
return @docker_api.signal_container_process(pid,sig,container)
end
def start_container(container)
return @docker_api.start_container(container)
end
def inspect_container(container)
return @docker_api.inspect_container(container)
end
def stop_container(container)
return @docker_api.stop_container(container)
end
def pause_container(container)
return @docker_api.pause_container(container)
end
def unpause_container(container)
return @docker_api.unpause_container(container)
end
def ps_container(container)
return @docker_api.ps_container(container)
end
def logs_container(container)
return @docker_api.logs_container(container)
end
# def add_monitor(site_hash)
# return @system_api.add_monitor(site_hash)
# end
#
# def rm_monitor(site_hash)
# return @system_api.rm_monitor(site_hash)
# end
def get_build_report(engine_name)
return @system_api.get_build_report(engine_name)
end
def save_build_report(container,build_report)
return @system_api.save_build_report(container,build_report)
end
def save_container(container)
return @system_api.save_container(container)
end
def save_blueprint(blueprint,container)
return @system_api.save_blueprint(blueprint,container)
end
def load_blueprint(container)
return @system_api.load_blueprint(container)
end
def add_volume(site_hash)
return @system_api.add_volume(site_hash)
end
def rm_volume(site_hash)
return @system_api.rm_volume(site_hash)
end
def remove_self_hosted_domain(domain_name)
return @system_api.remove_self_hosted_domain(domain_name)
end
def add_self_hosted_domain(params)
return @system_api.add_self_hosted_domain(params)
end
def list_self_hosted_domains()
return @system_api.list_self_hosted_domains()
end
def update_self_hosted_domain(old_domain_name, params)
@system_api.update_self_hosted_domain(old_domain_name, params)
end
# def load_system_preferences
# return @system_api.load_system_preferences
# end
#
# def save_system_preferences(preferences)
# return @system_api.save_system_preferences(preferences)
# end
def get_container_memory_stats(container)
return @system_api.get_container_memory_stats(container)
end
def set_engine_hostname_details(container,params)
return @system_api.set_engine_hostname_details(container,params)
end
def image_exists?(container_name)
imageName = container_name
return @docker_api.image_exists?(imageName)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
def list_attached_services_for(objectName,identifier)
sm = loadServiceManager()
return sm.list_attached_services_for(objectName,identifier)
rescue Exception=>e
SystemUtils.log_exception e
end
def list_avail_services_for(object)
objectname = object.class.name.split('::').last
# p :load_vail_services_for
# p objectname
services = load_avail_services_for(objectname)
subservices = load_avail_component_services_for(object)
retval = Hash.new
retval[:services] = services
retval[:subservices] = subservices
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def load_software_service(params)
sm = loadServiceManager()
# p :load_software_service
# p params
service_container = sm.get_software_service_container_name(params)
params[:service_container_name] = service_container
# p :service_container_name
# p service_container
service = loadManagedService(service_container)
if service == nil
return nil
end
return service
rescue Exception=>e
SystemUtils.log_exception e
end
def setup_email_params(params)
arg="smarthost_hostname=" + params[:smarthost_hostname] \
+ ":smarthost_username=" + params[:smarthost_username]\
+ ":smarthost_password=" + params[:smarthost_password]\
+ ":mail_name=smtp." + params[:default_domain]
container=loadManagedService("smtp")
return @docker_api.docker_exec(container,SysConfig.SetupParamsScript,arg)
rescue Exception=>e
SystemUtils.log_exception(e)
end
def set_engines_ssh_pw(params)
pass = params[:ssh_password]
cmd = "echo -e " + pass + "\n" + pass + " | passwd engines"
SystemUtils.debug_output( "ssh_pw",cmd)
SystemUtils.run_system(cmd)
end
def set_default_domain(params)
@system_preferences.set_default_domain(params)
end
def set_default_site(params)
@system_preferences.set_default_site(params)
end
def get_default_site()
@system_preferences.get_default_site
end
def get_default_domain()
@system_preferences.get_default_domain
end
def set_database_password(container_name,params)
arg = "mysql_password=" + params[:mysql_password] +":" \
+ "server=" + container_name + ":" \
+ "psql_password=" + params[:psql_password] #Need two args
if container_name
server_container = loadManagedService(container_name)
return @docker_api.docker_exec(server_container,SysConfig.SetupParamsScript,arg)
end
return true
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
#Attach the service defined in service_hash [Hash]
#@return boolean indicating sucess
def attach_service(service_hash)
p :attach_Service
p service_hash
service_hash = SystemUtils.symbolize_keys(service_hash[:variables])
p service_hash
if service_hash == nil
log_error_mesg("Attach Service passed a nil","")
return false
elsif service_hash.is_a?(Hash) == false
log_error_mesg("Attached Service passed a non Hash",service_hash)
return false
end
if service_hash.has_key?(:service_handle) == false || service_hash[:service_handle] == nil
service_handle_field = SoftwareServiceDefinition.service_handle_field(service_hash)
p :service_handle_field
p service_handle_field
p service_hash[:variables][service_handle_field.to_sym]
service_hash[:service_handle] = service_hash[:variables][service_handle_field.to_sym]
end
if service_hash.has_key?(:variables) == false
log_error_mesg("Attached Service passed no variables",service_hash)
return false
end
sm = loadServiceManager()
return sm.add_service(service_hash)
rescue Exception=>e
SystemUtils.log_exception e
end
def remove_orphaned_service(params)
sm = loadServiceManager()
return sm.remove_orphaned_service(params)
rescue Exception=>e
SystemUtils.log_exception e
end
def dettach_service(params)
sm = loadServiceManager()
return sm.remove_service(params)
# if service !=nil && service != false
# return service.remove_consumer(params)
# end
# @last_error = "Failed to dettach Service: " + @last_error
rescue Exception=>e
SystemUtils.log_exception e
return false
end
def list_providers_in_use
sm = loadServiceManager()
return sm.list_providers_in_use
end
def loadServiceManager()
if @service_manager == nil
@service_manager = ServiceManager.new(self)
return @service_manager
end
return @service_manager
end
def match_orphan_service(service_hash)
sm = loadServiceManager()
if sm.retrieve_orphan(service_hash) == false
return false
end
return true
end
#returns
def find_service_consumers(params)
sm = loadServiceManager()
return sm.find_service_consumers(params)
end
def service_is_registered?(service_hash)
sm = loadServiceManager()
return sm.service_is_registered?(service_hash)
end
def get_engine_persistant_services(params)
sm = loadServiceManager()
return sm.get_engine_persistant_services(params)
end
def managed_service_tree
sm = loadServiceManager()
return sm.managed_service_tree
end
def get_managed_engine_tree
sm = loadServiceManager()
return sm.get_managed_engine_tree
end
def find_engine_services(params)
sm = loadServiceManager()
return sm.find_engine_services(params)
end
def load_service_definition(filename)
yaml_file = File.open(filename)
# p :open
# p filename
return SoftwareServiceDefinition.from_yaml(yaml_file)
rescue
rescue Exception=>e
SystemUtils.log_exception e
end
def load_avail_services_for_type(typename)
# p :load_avail_services_for_by_type
# p typename
retval = Array.new
dir = SysConfig.ServiceMapTemplateDir + "/" + typename
# p :dir
# p dir
if Dir.exists?(dir)
Dir.foreach(dir) do |service_dir_entry|
begin
if service_dir_entry.start_with?(".") == true
next
end
# p :service_dir_entry
# p service_dir_entry
if service_dir_entry.end_with?(".yaml")
service = load_service_definition(dir + "/" + service_dir_entry)
if service != nil
# p :service_as_serivce
# p service
# p :as_hash
# p service.to_h
# p :as_yaml
# p service.to_yaml()
retval.push(service.to_h)
end
end
rescue Exception=>e
SystemUtils.log_exception e
next
end
end
end
# p typename
# p retval
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def load_avail_services_for(typename)
# p :load_avail_services_for
# p typename
retval = Array.new
dir = SysConfig.ServiceMapTemplateDir + "/" + typename
# p :dir
# p dir
if Dir.exists?(dir)
Dir.foreach(dir) do |service_dir_entry|
begin
if service_dir_entry.start_with?(".") == true
next
end
# p :service_dir_entry
# p service_dir_entry
if service_dir_entry.end_with?(".yaml")
service = load_service_definition(dir + "/" + service_dir_entry)
if service != nil
retval.push(service.to_h)
end
end
rescue Exception=>e
SystemUtils.log_exception e
next
end
end
end
# p typename
# p retval
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def load_avail_component_services_for(engine)
retval = Hash.new
if engine.is_a?(ManagedEngine)
params = Hash.new
params[:engine_name]=engine.container_name
persistant_services = get_engine_persistant_services(params)
persistant_services.each do |service|
type_path = service[:type_path]
retval[type_path] = load_avail_services_for_type(type_path)
# p retval[type_path]
end
else
# p :load_avail_component_services_for_engine_got_a
# p engine.to_s
return nil
end
return retval
rescue Exception=>e
SystemUtils.log_exception e
end
def set_engine_runtime_properties(params)
#FIX ME also need to deal with Env Variables
engine_name = params[:engine_name]
engine = loadManagedEngine(engine_name)
if engine.is_a?(EnginesOSapiResult) == true
last_error = engine.result_mesg
return false
end
if engine.is_active == true
last_error="Container is active"
return false
end
if params.has_key?(:memory)
if params[:memory] == engine.memory
last_error="No Change in Memory Value"
return false
end
if engine.update_memory(params[:memory]) == false
last_error= engine.last_error
return false
end
end
if engine.has_container? == true
if destroy_container(engine) == false
last_error= engine.last_error
return false
end
end
if create_container(engine) == false
last_error= engine.last_error
return false
end
return true
end
def set_engine_network_properties (engine, params)
return @system_api.set_engine_network_properties(engine,params)
end
def get_system_load_info
return @system_api.get_system_load_info
end
def get_system_memory_info
return @system_api.get_system_memory_info
end
def getManagedEngines
return @system_api.getManagedEngines
end
def loadManagedEngine(engine_name)
return @system_api.loadManagedEngine(engine_name)
end
def get_orphaned_services_tree
return loadServiceManager.get_orphaned_services_tree
end
def loadManagedService(service_name)
return @system_api.loadManagedService(service_name)
end
def getManagedServices
return @system_api.getManagedServices
end
def list_domains
return @system_api.list_domains
end
def list_managed_engines
return @system_api.list_managed_engines
end
def list_managed_services
return @system_api.list_managed_services
end
def destroy_container(container)
clear_error
begin
if @docker_api.destroy_container(container) != false
@system_api.destroy_container(container) #removes cid file
return true
else
return false
end
rescue Exception=>e
container.last_error=( "Failed To Destroy " + e.to_s)
SystemUtils.log_exception(e)
return false
end
end
def generate_engines_user_ssh_key
return @system_api.regen_system_ssh_key
end
def system_update
return @system_api.system_update
end
def delete_image(container)
begin
clear_error
if @docker_api.delete_image(container) == true
#only delete if del all otherwise backup
return @system_api.delete_container_configs(container)
end
return false
rescue Exception=>e
@last_error=( "Failed To Delete " + e.to_s)
SystemUtils.log_exception(e)
return false
end
end
#@return boolean indicating sucess
#@params [Hash] :engine_name
#Retrieves all persistant service registered to :engine_name and destroys the underlying service (fs db etc)
# They are removed from the tree if delete is sucessful
def delete_engine_persistant_services(params)
sm = loadServiceManager()
services = sm.get_engine_persistant_services(params)
services.each do |service_hash|
service_hash[:remove_all_application_data] = params[:remove_all_application_data]
if service_hash.has_key?(:service_container_name) == false
log_error_mesg("Missing :service_container_name in service_hash",service_hash)
return false
end
service = loadManagedService(service_hash[:service_container_name])
if service == nil
log_error_mesg("Failed to load container name keyed by :service_container_name ",service_hash)
return false
end
if service.is_running == false
log_error_mesg("Cannot remove service consumer if service is not running ",service_hash)
return false
end
if service.remove_consumer(service_hash) == false
log_error_mesg("Failed to remove service ",service_hash)
return false
end
#REMOVE THE SERVICE HERE AND NOW
if sm.remove_from_engine_registery(service_hash) ==true
if sm.remove_from_services_registry(service_hash) == false
log_error_mesg("Cannot remove from Service Registry",service_hash)
return false
end
else
log_error_mesg("Cannot remove from Engine Registry",service_hash)
return false
end
end
return true
rescue Exception=>e
@last_error=( "Failed To Delete " + e.to_s)
SystemUtils.log_exception(e)
return false
end
def delete_image_dependancies(params)
sm = loadServiceManager()
if sm.rm_remove_engine(params) == false
log_error_mesg("Failed to remove deleted Service",params)
return false
end
return true
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
def run_system(cmd)
clear_error
begin
cmd = cmd + " 2>&1"
res= %x<#{cmd}>
SystemUtils.debug_output("run system",res)
#FIXME should be case insensitive The last one is a pure kludge
#really need to get stderr and stdout separately
if $? == 0 && res.downcase.include?("error") == false && res.downcase.include?("fail") == false && res.downcase.include?("could not resolve hostname") == false && res.downcase.include?("unsuccessful") == false
return true
else
@last_error = res
SystemUtils.debug_output("run system result",res)
return false
end
rescue Exception=>e
SystemUtils.log_exception(e)
return ret_val
end
end
def run_volume_builder(container,username)
clear_error
begin
if File.exists?(SysConfig.CidDir + "/volbuilder.cid") == true
command = "docker stop volbuilder"
run_system(command)
command = "docker rm volbuilder"
run_system(command)
File.delete(SysConfig.CidDir + "/volbuilder.cid")
end
mapped_vols = get_volbuild_volmaps container
command = "docker run --name volbuilder --memory=20m -e fw_user=" + username + " --cidfile /opt/engines/run/volbuilder.cid " + mapped_vols + " -t engines/volbuilder:" + SystemUtils.system_release + " /bin/sh /home/setup_vols.sh "
SystemUtils.debug_output("Run volumen builder",command)
run_system(command)
#Note no -d so process will not return until setup.sh completes
command = "docker rm volbuilder"
if File.exists?(SysConfig.CidDir + "/volbuilder.cid") == true
File.delete(SysConfig.CidDir + "/volbuilder.cid")
end
res = run_system(command)
if res != true
SystemUtils.log_error(res)
#don't return false as
end
return true
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
def create_container(container)
clear_error
begin
if @system_api.clear_cid(container) != false
@system_api.clear_container_var_run(container)
if @docker_api.create_container(container) == true
return @system_api.create_container(container)
end
else
return false
end
rescue Exception=>e
container.last_error=("Failed To Create " + e.to_s)
SystemUtils.log_exception(e)
return false
end
end
def load_and_attach_persistant_services(container)
dirname = get_container_dir(container) + "/persistant/"
sm = loadServiceManager()
return sm.load_and_attach_services(dirname,container )
end
def load_and_attach_nonpersistant_services(container)
dirname = get_container_dir(container) + "/nonpersistant/"
sm = loadServiceManager()
return sm.load_and_attach_services(dirname,container)
end
def get_container_dir(container)
return @system_api.container_state_dir(container) +"/services/"
end
#install from fresh copy of blueprint in repositor
def reinstall_engine(engine)
clear_error
EngineBuilder.re_install_engine(engine,self)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
#rebuilds image from current blueprint
def rebuild_image(container)
clear_error
begin
params=Hash.new
params[:engine_name] = container.container_name
params[:domain_name] = container.domain_name
params[:host_name] = container.hostname
params[:env_variables] = container.environments
params[:http_protocol] = container.protocol
params[:repository_url] = container.repo
params[:software_environment_variables] = container.environments
# custom_env=params
# @http_protocol = params[:http_protocol] = container.
builder = EngineBuilder.new(params, self)
return builder.rebuild_managed_container(container)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
#FIXME Kludge
def get_container_network_metrics(container_name)
begin
ret_val = Hash.new
clear_error
cmd = "docker exec " + container_name + " netstat --interfaces -e | grep bytes |head -1 | awk '{ print $2 " " $6}' 2>&1"
res= %x<#{cmd}>
vals = res.split("bytes:")
if vals.count < 2
if vals[1] != nil && vals[2] != nil
ret_val[:in] = vals[1].chop
ret_val[:out] = vals[2].chop
else
ret_val[:in] ="-1"
ret_val[:out] ="-1"
end
else
ret_val[:in] ="-1"
ret_val[:out] ="-1"
end
return ret_val
rescue Exception=>e
SystemUtils.log_exception(e)
ret_val[:in] = -1
ret_val[:out] = -1
return ret_val
end
end
def is_startup_complete container
clear_error
begin
return @system_api.is_startup_complete(container)
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
def log_error_mesg(msg,object)
obj_str = object.to_s.slice(0,256)
@last_error = msg +":" + obj_str
SystemUtils.log_error_mesg(msg,object)
end
def register_non_persistant_services(engine_name)
sm = loadServiceManager()
return sm.register_non_persistant_services(engine_name)
end
def deregister_non_persistant_services(engine_name)
sm = loadServiceManager()
return sm.deregister_non_persistant_services(engine_name)
end
#@return an [Array] of service_hashs of Orphaned persistant services match @params [Hash]
#:path_type :publisher_namespace
def get_orphaned_services(params)
return loadServiceManager.get_orphaned_services(params)
end
def clean_up_dangling_images
@docker_api.clean_up_dangling_images
end
#@ return [Boolean] indicating sucess
#For Maintanence ONLY
def delete_service_from_service_registry(service_hash)
sm = loadServiceManager()
return sm.remove_from_services_registry(service_hash)
end
def delete_service_from_engine_registry(service_hash)
sm = loadServiceManager()
return sm.remove_from_engine_registery(service_hash)
end
protected
def get_volbuild_volmaps container
begin
clear_error
state_dir = SysConfig.CidDir + "/containers/" + container.container_name + "/run/"
log_dir = SysConfig.SystemLogRoot + "/containers/" + container.container_name
volume_option = " -v " + state_dir + ":/client/state:rw "
volume_option += " -v " + log_dir + ":/client/log:rw "
if container.volumes != nil
container.volumes.each_value do |vol|
SystemUtils.debug_output("build vol maps",vol)
volume_option += " -v " + vol.localpath.to_s + ":/dest/fs:rw"
end
end
volume_option += " --volumes-from " + container.container_name
return volume_option
rescue Exception=>e
SystemUtils.log_exception(e)
return false
end
end
def clear_error
@last_error = ""
end
#@return an [Array] of service_hashs of Active persistant services match @params [Hash]
#:path_type :publisher_namespace
def get_active_persistant_services(params)
return loadServiceManager.get_active_persistant_services(params)
end
end
|
#--
# Copyright (c) 2005-2009, John Mettraux, jmettraux@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Made in Japan.
#++
require 'dm-core'
require 'ruote/engine/context'
require 'ruote/queue/subscriber'
require 'ruote/storage/base'
require 'ruote/dm/ticket'
module Ruote
module Dm
#
# The datamapper resource class for Ruote expressions.
#
class DmExpression
include DataMapper::Resource
property :fei, String, :key => true
property :wfid, String, :index => :wfid
property :expclass, String, :index => :expclass
property :svalue, Object, :length => 2**32 - 1, :lazy => false
def as_ruote_expression (context)
fe = svalue
fe.context = context
fe
end
# Saves the expression as a DataMapper record.
#
# Returns false if the exact same expression is already stored.
# Returns true if the record got created or updated (exp modified).
#
def self.from_ruote_expression (fexp)
e = DmExpression.first(:fei => fexp.fei.to_s) || DmExpression.new
e.fei = fexp.fei.to_s
e.wfid = fexp.fei.parent_wfid
e.expclass = fexp.class.name
e.svalue = fexp
e.save
end
# Sets the table name for expressions to 'dm_expressions'.
#
def self.storage_name (repository_name=default_repository_name)
'dm_expressions'
end
end
#
# DataMapper persistence for Ruote expressions.
#
# == Ruote::Dm::DmExpression.auto_upgrade!
#
# You might want to run
#
# Ruote::Dm::DmExpression.auto_upgrade!
#
# before your first run for Ruote::Dm::DmStorage (usually
# Ruote::Dm::DmPersistedEngine)
#
class DmStorage
include EngineContext
include StorageBase
include Subscriber
def context= (c)
@context = c
@dm_repository =
c[:expstorage_dm_repository] || c[:dm_repository] || :default
#DataMapper.repository(@dm_repository) do
# DmExpression.auto_upgrade!
#end
# this is costly, and it's now left to the integrator
subscribe(:expressions)
end
def find_expressions (query={})
conditions = {}
# TODO: Update to use DM.repository.adapter.query since there is
# guarantee dm-aggregates is around.
if m = query[:responding_to]
expclass_list = DmExpression.aggregate(:expclass).select do |expclass_name|
::Object.const_get(expclass_name).instance_methods.include?(m.to_s) rescue nil
end
return [] if expclass_list.empty?
conditions[:expclass] = expclass_list
end
if i = query[:wfid]
conditions[:wfid] = i
end
if c = query[:class]
conditions[:expclass] = c.to_s
end
DataMapper.repository(@dm_repository) {
DmExpression.all(conditions)
}.collect { |e|
e.as_ruote_expression(@context)
}
end
def []= (fei, fexp)
DataMapper.repository(@dm_repository) do
DmExpression.from_ruote_expression(fexp)
end
end
def [] (fei)
if fexp = find(fei)
fexp.as_ruote_expression(@context)
else
nil
end
end
def delete (fei)
if e = find(fei)
e.destroy
end
end
def size
DataMapper.repository(@dm_repository) do
#DmExpression.count
# dm-aggregates is in dm-core and dm-core is no ruby 1.9.1 friend
# jpr5: 10/16/09: Actually, dm-aggregates is in dm-more.
# This may have been rectified by now..
DmExpression.all.size
end
end
# A dangerous method, deletes all the expressions and all the tickets.
# Mostly used for tearing down test sets.
#
def purge!
DataMapper.repository(@dm_repository) do
DmExpression.all.destroy!
Ticket.all.destroy!
end
end
def to_s
find_expressions.inject('') do |s, fexp|
s << "#{fexp.fei.to_s} => #{fexp.class}\n"
s
end
end
#--
# ticket methods
#++
def draw_ticket (fexp)
Ruote::Dm::Ticket.draw(self.object_id.to_s, fexp.fei.to_s)
end
def discard_all_tickets (fei)
Ruote::Dm::Ticket.discard_all(fei.to_s)
end
protected
def find (fei)
DataMapper.repository(@dm_repository) do
DmExpression.first(:fei => fei.to_s)
end
end
end
end
end
Provide alternate field aggregation mechanism in case dm-aggregates is not installed (resolves TODO).
#--
# Copyright (c) 2005-2009, John Mettraux, jmettraux@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Made in Japan.
#++
require 'dm-core'
require 'ruote/engine/context'
require 'ruote/queue/subscriber'
require 'ruote/storage/base'
require 'ruote/dm/ticket'
module Ruote
module Dm
#
# The datamapper resource class for Ruote expressions.
#
class DmExpression
include DataMapper::Resource
property :fei, String, :key => true
property :wfid, String, :index => :wfid
property :expclass, String, :index => :expclass
property :svalue, Object, :length => 2**32 - 1, :lazy => false
def as_ruote_expression (context)
fe = svalue
fe.context = context
fe
end
# Saves the expression as a DataMapper record.
#
# Returns false if the exact same expression is already stored.
# Returns true if the record got created or updated (exp modified).
#
def self.from_ruote_expression (fexp)
e = DmExpression.first(:fei => fexp.fei.to_s) || DmExpression.new
e.fei = fexp.fei.to_s
e.wfid = fexp.fei.parent_wfid
e.expclass = fexp.class.name
e.svalue = fexp
e.save
end
# Sets the table name for expressions to 'dm_expressions'.
#
def self.storage_name (repository_name=default_repository_name)
'dm_expressions'
end
end
#
# DataMapper persistence for Ruote expressions.
#
# == Ruote::Dm::DmExpression.auto_upgrade!
#
# You might want to run
#
# Ruote::Dm::DmExpression.auto_upgrade!
#
# before your first run for Ruote::Dm::DmStorage (usually
# Ruote::Dm::DmPersistedEngine)
#
class DmStorage
include EngineContext
include StorageBase
include Subscriber
def context= (c)
@context = c
@dm_repository =
c[:expstorage_dm_repository] || c[:dm_repository] || :default
#DataMapper.repository(@dm_repository) do
# DmExpression.auto_upgrade!
#end
# this is costly, and it's now left to the integrator
subscribe(:expressions)
end
def find_expressions (query={})
conditions = {}
if m = query[:responding_to]
# NOTE: Using dm-aggregates would be cleaner, but if it's not
# available then using this SQL directly will be equivalent.
# It should run on any of DM's adapters, and will work within
# any defined repositories or field naming conventions.
expclass_list = if DmExpression.respond_to?(:aggregate)
DmExpression.aggregate(:expclass)
else
table = DmExpression.storage_name(@dm_repository)
field = DmExpression.properties(@dm_repository)[:expclass].field
DmExpression.repository.adapter.query("select #{field} from #{table} group by #{field}")
end.select do |expclass_name|
::Object.const_get(expclass_name).instance_methods.include?(m.to_s) rescue false
end
return [] if expclass_list.empty?
conditions[:expclass] = expclass_list
end
if i = query[:wfid]
conditions[:wfid] = i
end
if c = query[:class]
conditions[:expclass] = c.to_s
end
DataMapper.repository(@dm_repository) {
DmExpression.all(conditions)
}.collect { |e|
e.as_ruote_expression(@context)
}
end
def []= (fei, fexp)
DataMapper.repository(@dm_repository) do
DmExpression.from_ruote_expression(fexp)
end
end
def [] (fei)
if fexp = find(fei)
fexp.as_ruote_expression(@context)
else
nil
end
end
def delete (fei)
if e = find(fei)
e.destroy
end
end
def size
DataMapper.repository(@dm_repository) do
#DmExpression.count
# dm-aggregates is in dm-core and dm-core is no ruby 1.9.1 friend
# jpr5: 10/16/09: Actually, dm-aggregates is in dm-more.
# This may have been rectified by now..
DmExpression.all.size
end
end
# A dangerous method, deletes all the expressions and all the tickets.
# Mostly used for tearing down test sets.
#
def purge!
DataMapper.repository(@dm_repository) do
DmExpression.all.destroy!
Ticket.all.destroy!
end
end
def to_s
find_expressions.inject('') do |s, fexp|
s << "#{fexp.fei.to_s} => #{fexp.class}\n"
s
end
end
#--
# ticket methods
#++
def draw_ticket (fexp)
Ruote::Dm::Ticket.draw(self.object_id.to_s, fexp.fei.to_s)
end
def discard_all_tickets (fei)
Ruote::Dm::Ticket.discard_all(fei.to_s)
end
protected
def find (fei)
DataMapper.repository(@dm_repository) do
DmExpression.first(:fei => fei.to_s)
end
end
end
end
end
|
module SchemaPlus::Columns
VERSION = "0.1.0"
end
module fixup
module SchemaPlus
module Columns
VERSION = "0.1.0"
end
end
|
module ScopedSearch
# The QueryBuilder class builds an SQL query based on aquery string that is
# provided to the search_for named scope. It uses a SearchDefinition instance
# to shape the query.
class QueryBuilder
attr_reader :ast, :definition
# Creates a find parameter hash that can be passed to ActiveRecord::Base#find,
# given a search definition and query string. This method is called from the
# search_for named scope.
#
# This method will parse the query string and build an SQL query using the search
# query. It will return an ampty hash if the search query is empty, in which case
# the scope call will simply return all records.
def self.build_query(definition, *args)
query = args[0]
options = args[1] || {}
query_builder_class = self.class_for(definition)
if query.kind_of?(ScopedSearch::QueryLanguage::AST::Node)
return query_builder_class.new(definition, query, options[:profile]).build_find_params
elsif query.kind_of?(String)
return query_builder_class.new(definition, ScopedSearch::QueryLanguage::Compiler.parse(query), options[:profile]).build_find_params
elsif query.nil?
return { }
else
raise "Unsupported query object: #{query.inspect}!"
end
end
# Loads the QueryBuilder class for the connection of the given definition.
# If no specific adapter is found, the default QueryBuilder class is returned.
def self.class_for(definition)
self.const_get(definition.klass.connection.class.name.split('::').last)
rescue
self
end
# Initializes the instance by setting the relevant parameters
def initialize(definition, ast, profile)
@definition, @ast, @definition.profile = definition, ast, profile
end
# Actually builds the find parameters hash that should be used in the search_for
# named scope.
def build_find_params
parameters = []
includes = []
# Build SQL WHERE clause using the AST
sql = @ast.to_sql(self, definition) do |notification, value|
# Handle the notifications encountered during the SQL generation:
# Store the parameters, includes, etc so that they can be added to
# the find-hash later on.
case notification
when :parameter then parameters << value
when :include then includes << value
else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}"
end
end
# Build hash for ActiveRecord::Base#find for the named scope
find_attributes = {}
find_attributes[:conditions] = [sql] + parameters unless sql.nil?
find_attributes[:include] = includes.uniq unless includes.empty?
find_attributes # Uncomment for debugging
return find_attributes
end
# A hash that maps the operators of the query language with the corresponding SQL operator.
SQL_OPERATORS = { :eq =>'=', :ne => '<>', :like => 'LIKE', :unlike => 'NOT LIKE',
:gt => '>', :lt =>'<', :lte => '<=', :gte => '>=' }
# Return the SQL operator to use given an operator symbol and field definition.
#
# By default, it will simply look up the correct SQL operator in the SQL_OPERATORS
# hash, but this can be overrided by a database adapter.
def sql_operator(operator, field)
SQL_OPERATORS[operator]
end
# Perform a comparison between a field and a Date(Time) value.
#
# This function makes sure the date is valid and adjust the comparison in
# some cases to return more logical results.
#
# This function needs a block that can be used to pass other information about the query
# (parameters that should be escaped, includes) to the query builder.
#
# <tt>field</tt>:: The field to test.
# <tt>operator</tt>:: The operator used for comparison.
# <tt>value</tt>:: The value to compare the field with.
def datetime_test(field, operator, value, &block) # :yields: finder_option_type, value
# Parse the value as a date/time and ignore invalid timestamps
timestamp = parse_temporal(value)
return nil unless timestamp
timestamp = Date.parse(timestamp.strftime('%Y-%m-%d')) if field.date?
# Check for the case that a date-only value is given as search keyword,
# but the field is of datetime type. Change the comparison to return
# more logical results.
if timestamp.day_fraction == 0 && field.datetime?
if [:eq, :ne].include?(operator)
# Instead of looking for an exact (non-)match, look for dates that
# fall inside/outside the range of timestamps of that day.
yield(:parameter, timestamp)
yield(:parameter, timestamp + 1)
negate = (operator == :ne) ? 'NOT' : ''
field_sql = field.to_sql(operator, &block)
return "#{negate}(#{field_sql} >= ? AND #{field_sql} < ?)"
elsif operator == :gt
# Make sure timestamps on the given date are not included in the results
# by moving the date to the next day.
timestamp += 1
operator = :gte
elsif operator == :lte
# Make sure the timestamps of the given date are included by moving the
# date to the next date.
timestamp += 1
operator = :lt
end
end
# Yield the timestamp and return the SQL test
yield(:parameter, timestamp)
"#{field.to_sql(operator, &block)} #{sql_operator(operator, field)} ?"
end
# Generates a simple SQL test expression, for a field and value using an operator.
#
# This function needs a block that can be used to pass other information about the query
# (parameters that should be escaped, includes) to the query builder.
#
# <tt>field</tt>:: The field to test.
# <tt>operator</tt>:: The operator used for comparison.
# <tt>value</tt>:: The value to compare the field with.
def sql_test(field, operator, value, &block) # :yields: finder_option_type, value
if [:like, :unlike].include?(operator) && value !~ /^\%/ && value !~ /\%$/
yield(:parameter, "%#{value}%")
return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?"
elsif field.temporal?
return datetime_test(field, operator, value, &block)
else
yield(:parameter, value)
return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?"
end
end
# Try to parse a string as a datetime.
def parse_temporal(value)
DateTime.parse(value, true) rescue nil
end
# This module gets included into the Field class to add SQL generation.
module Field
# Return an SQL representation for this field. Also make sure that
# the relation which includes the search field is included in the
# SQL query.
#
# This function may yield an :include that should be used in the
# ActiveRecord::Base#find call, to make sure that the field is avalable
# for the SQL query.
def to_sql(builder, operator = nil, &block) # :yields: finder_option_type, value
yield(:include, relation) if relation
definition.klass.connection.quote_table_name(klass.table_name) + "." +
definition.klass.connection.quote_column_name(field)
end
end
# This module contains modules for every AST::Node class to add SQL generation.
module AST
# Defines the to_sql method for AST LeadNodes
module LeafNode
def to_sql(builder, definition, &block)
# Search keywords found without context, just search on all the default fields
fragments = definition.default_fields_for(value).map do |field|
builder.sql_test(field, field.default_operator, value, &block)
end
"(#{fragments.join(' OR ')})"
end
end
# Defines the to_sql method for AST operator nodes
module OperatorNode
# Returns a NOT(...) SQL fragment that negates the current AST node's children
def to_not_sql(builder, definition, &block)
"(NOT(#{rhs.to_sql(builder, definition, &block)}) OR #{rhs.to_sql(builder, definition, &block)} IS NULL)"
end
# Returns an IS (NOT) NULL SQL fragment
def to_null_sql(builder, definition, &block)
field = definition.fields[rhs.value.to_sym]
raise ScopedSearch::QueryNotSupported, "Field '#{rhs.value}' not recognized for searching!" unless field
case operator
when :null then "#{field.to_sql(builder, &block)} IS NULL"
when :notnull then "#{field.to_sql(builder, &block)} IS NOT NULL"
end
end
# No explicit field name given, run the operator on all default fields
def to_default_fields_sql(builder, definition, &block)
raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode)
# Search keywords found without context, just search on all the default fields
fragments = definition.default_fields_for(rhs.value, operator).map { |field|
builder.sql_test(field, operator, rhs.value, &block) }.compact
fragments.empty? ? nil : "(#{fragments.join(' OR ')})"
end
# Explicit field name given, run the operator on the specified field only
def to_single_field_sql(builder, definition, &block)
raise ScopedSearch::QueryNotSupported, "Field name not a leaf node" unless lhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode)
raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode)
# Search only on the given field.
field = definition.fields[lhs.value.to_sym]
raise ScopedSearch::QueryNotSupported, "Field '#{lhs.value}' not recognized for searching!" unless field
builder.sql_test(field, operator, rhs.value, &block)
end
# Convert this AST node to an SQL fragment.
def to_sql(builder, definition, &block)
if operator == :not && children.length == 1
to_not_sql(builder, definition, &block)
elsif [:null, :notnull].include?(operator)
to_null_sql(builder, definition, &block)
elsif children.length == 1
to_default_fields_sql(builder, definition, &block)
elsif children.length == 2
to_single_field_sql(builder, definition, &block)
else
raise ScopedSearch::QueryNotSupported, "Don't know how to handle this operator node: #{operator.inspect} with #{children.inspect}!"
end
end
end
# Defines the to_sql method for AST AND/OR operators
module LogicalOperatorNode
def to_sql(builder, definition, &block)
fragments = children.map { |c| c.to_sql(builder, definition, &block) }.compact
fragments.empty? ? nil : "(#{fragments.join(" #{operator.to_s.upcase} ")})"
end
end
end
# The MysqlAdapter makes sure that case sensitive comparisons are used
# when using the (not) equals operator, regardless of the field's
# collation setting.
class MysqlAdapter < ScopedSearch::QueryBuilder
# Patches the default <tt>sql_operator</tt> method to add
# <tt>BINARY</tt> after the equals and not equals operator to force
# case-sensitive comparisons.
def sql_operator(operator, field)
if [:ne, :eq].include?(operator) && field.textual?
"#{SQL_OPERATORS[operator]} BINARY"
else
super(operator, field)
end
end
end
# The PostgreSQLAdapter make sure that searches are case sensitive when
# using the like/unlike operators, by using the PostrgeSQL-specific
# <tt>ILIKE operator</tt> instead of <tt>LIKE</tt>.
class PostgreSQLAdapter < ScopedSearch::QueryBuilder
# Switches out the default LIKE operator for ILIKE in the default
# <tt>sql_operator</tt> method.
def sql_operator(operator, field)
case operator
when :like then 'ILIKE'
when :unlike then 'NOT ILIKE'
else super(operator, field)
end
end
end
# The Oracle adapter also requires some tweaks to make the case insensitive LIKE work.
class OracleEnhancedAdapter < ScopedSearch::QueryBuilder
# Use REGEXP_LIKE for case insensitive comparisons
def sql_operator(operator, field)
case operator
when :like then 'REGEXP_LIKE'
when :unlike then 'NOT REGEXP_LIKE'
else super(operator, field)
end
end
def sql_test(field, operator, value, &block) # :yields: finder_option_type, value
if field.textual? && [:like, :unlike].include?(operator)
wildcard_value = (value !~ /^\%/ && value !~ /\%$/) ? "%#{value}%" : value
yield(:parameter, wildcard_value)
return "#{self.sql_operator(operator, field)}(#{field.to_sql(operator, &block)}, ?, 'i')"
else
super(field, operator, &block)
end
end
end
end
# Include the modules into the corresponding classes
# to add SQL generation capabilities to them.
Definition::Field.send(:include, QueryBuilder::Field)
QueryLanguage::AST::LeafNode.send(:include, QueryBuilder::AST::LeafNode)
QueryLanguage::AST::OperatorNode.send(:include, QueryBuilder::AST::OperatorNode)
QueryLanguage::AST::LogicalOperatorNode.send(:include, QueryBuilder::AST::LogicalOperatorNode)
end
Fixed some issues in the Oracle adapter. Hopefully it is working!
module ScopedSearch
# The QueryBuilder class builds an SQL query based on aquery string that is
# provided to the search_for named scope. It uses a SearchDefinition instance
# to shape the query.
class QueryBuilder
attr_reader :ast, :definition
# Creates a find parameter hash that can be passed to ActiveRecord::Base#find,
# given a search definition and query string. This method is called from the
# search_for named scope.
#
# This method will parse the query string and build an SQL query using the search
# query. It will return an ampty hash if the search query is empty, in which case
# the scope call will simply return all records.
def self.build_query(definition, *args)
query = args[0]
options = args[1] || {}
query_builder_class = self.class_for(definition)
if query.kind_of?(ScopedSearch::QueryLanguage::AST::Node)
return query_builder_class.new(definition, query, options[:profile]).build_find_params
elsif query.kind_of?(String)
return query_builder_class.new(definition, ScopedSearch::QueryLanguage::Compiler.parse(query), options[:profile]).build_find_params
elsif query.nil?
return { }
else
raise "Unsupported query object: #{query.inspect}!"
end
end
# Loads the QueryBuilder class for the connection of the given definition.
# If no specific adapter is found, the default QueryBuilder class is returned.
def self.class_for(definition)
self.const_get(definition.klass.connection.class.name.split('::').last)
rescue
self
end
# Initializes the instance by setting the relevant parameters
def initialize(definition, ast, profile)
@definition, @ast, @definition.profile = definition, ast, profile
end
# Actually builds the find parameters hash that should be used in the search_for
# named scope.
def build_find_params
parameters = []
includes = []
# Build SQL WHERE clause using the AST
sql = @ast.to_sql(self, definition) do |notification, value|
# Handle the notifications encountered during the SQL generation:
# Store the parameters, includes, etc so that they can be added to
# the find-hash later on.
case notification
when :parameter then parameters << value
when :include then includes << value
else raise ScopedSearch::QueryNotSupported, "Cannot handle #{notification.inspect}: #{value.inspect}"
end
end
# Build hash for ActiveRecord::Base#find for the named scope
find_attributes = {}
find_attributes[:conditions] = [sql] + parameters unless sql.nil?
find_attributes[:include] = includes.uniq unless includes.empty?
# p find_attributes # Uncomment for debugging
return find_attributes
end
# A hash that maps the operators of the query language with the corresponding SQL operator.
SQL_OPERATORS = { :eq =>'=', :ne => '<>', :like => 'LIKE', :unlike => 'NOT LIKE',
:gt => '>', :lt =>'<', :lte => '<=', :gte => '>=' }
# Return the SQL operator to use given an operator symbol and field definition.
#
# By default, it will simply look up the correct SQL operator in the SQL_OPERATORS
# hash, but this can be overrided by a database adapter.
def sql_operator(operator, field)
SQL_OPERATORS[operator]
end
# Perform a comparison between a field and a Date(Time) value.
#
# This function makes sure the date is valid and adjust the comparison in
# some cases to return more logical results.
#
# This function needs a block that can be used to pass other information about the query
# (parameters that should be escaped, includes) to the query builder.
#
# <tt>field</tt>:: The field to test.
# <tt>operator</tt>:: The operator used for comparison.
# <tt>value</tt>:: The value to compare the field with.
def datetime_test(field, operator, value, &block) # :yields: finder_option_type, value
# Parse the value as a date/time and ignore invalid timestamps
timestamp = parse_temporal(value)
return nil unless timestamp
timestamp = Date.parse(timestamp.strftime('%Y-%m-%d')) if field.date?
# Check for the case that a date-only value is given as search keyword,
# but the field is of datetime type. Change the comparison to return
# more logical results.
if timestamp.day_fraction == 0 && field.datetime?
if [:eq, :ne].include?(operator)
# Instead of looking for an exact (non-)match, look for dates that
# fall inside/outside the range of timestamps of that day.
yield(:parameter, timestamp)
yield(:parameter, timestamp + 1)
negate = (operator == :ne) ? 'NOT' : ''
field_sql = field.to_sql(operator, &block)
return "#{negate}(#{field_sql} >= ? AND #{field_sql} < ?)"
elsif operator == :gt
# Make sure timestamps on the given date are not included in the results
# by moving the date to the next day.
timestamp += 1
operator = :gte
elsif operator == :lte
# Make sure the timestamps of the given date are included by moving the
# date to the next date.
timestamp += 1
operator = :lt
end
end
# Yield the timestamp and return the SQL test
yield(:parameter, timestamp)
"#{field.to_sql(operator, &block)} #{sql_operator(operator, field)} ?"
end
# Generates a simple SQL test expression, for a field and value using an operator.
#
# This function needs a block that can be used to pass other information about the query
# (parameters that should be escaped, includes) to the query builder.
#
# <tt>field</tt>:: The field to test.
# <tt>operator</tt>:: The operator used for comparison.
# <tt>value</tt>:: The value to compare the field with.
def sql_test(field, operator, value, &block) # :yields: finder_option_type, value
if [:like, :unlike].include?(operator) && value !~ /^\%/ && value !~ /\%$/
yield(:parameter, "%#{value}%")
return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?"
elsif field.temporal?
return datetime_test(field, operator, value, &block)
else
yield(:parameter, value)
return "#{field.to_sql(operator, &block)} #{self.sql_operator(operator, field)} ?"
end
end
# Try to parse a string as a datetime.
def parse_temporal(value)
DateTime.parse(value, true) rescue nil
end
# This module gets included into the Field class to add SQL generation.
module Field
# Return an SQL representation for this field. Also make sure that
# the relation which includes the search field is included in the
# SQL query.
#
# This function may yield an :include that should be used in the
# ActiveRecord::Base#find call, to make sure that the field is avalable
# for the SQL query.
def to_sql(builder, operator = nil, &block) # :yields: finder_option_type, value
yield(:include, relation) if relation
definition.klass.connection.quote_table_name(klass.table_name) + "." +
definition.klass.connection.quote_column_name(field)
end
end
# This module contains modules for every AST::Node class to add SQL generation.
module AST
# Defines the to_sql method for AST LeadNodes
module LeafNode
def to_sql(builder, definition, &block)
# Search keywords found without context, just search on all the default fields
fragments = definition.default_fields_for(value).map do |field|
builder.sql_test(field, field.default_operator, value, &block)
end
"(#{fragments.join(' OR ')})"
end
end
# Defines the to_sql method for AST operator nodes
module OperatorNode
# Returns a NOT(...) SQL fragment that negates the current AST node's children
def to_not_sql(builder, definition, &block)
"(NOT(#{rhs.to_sql(builder, definition, &block)}) OR #{rhs.to_sql(builder, definition, &block)} IS NULL)"
end
# Returns an IS (NOT) NULL SQL fragment
def to_null_sql(builder, definition, &block)
field = definition.fields[rhs.value.to_sym]
raise ScopedSearch::QueryNotSupported, "Field '#{rhs.value}' not recognized for searching!" unless field
case operator
when :null then "#{field.to_sql(builder, &block)} IS NULL"
when :notnull then "#{field.to_sql(builder, &block)} IS NOT NULL"
end
end
# No explicit field name given, run the operator on all default fields
def to_default_fields_sql(builder, definition, &block)
raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode)
# Search keywords found without context, just search on all the default fields
fragments = definition.default_fields_for(rhs.value, operator).map { |field|
builder.sql_test(field, operator, rhs.value, &block) }.compact
fragments.empty? ? nil : "(#{fragments.join(' OR ')})"
end
# Explicit field name given, run the operator on the specified field only
def to_single_field_sql(builder, definition, &block)
raise ScopedSearch::QueryNotSupported, "Field name not a leaf node" unless lhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode)
raise ScopedSearch::QueryNotSupported, "Value not a leaf node" unless rhs.kind_of?(ScopedSearch::QueryLanguage::AST::LeafNode)
# Search only on the given field.
field = definition.fields[lhs.value.to_sym]
raise ScopedSearch::QueryNotSupported, "Field '#{lhs.value}' not recognized for searching!" unless field
builder.sql_test(field, operator, rhs.value, &block)
end
# Convert this AST node to an SQL fragment.
def to_sql(builder, definition, &block)
if operator == :not && children.length == 1
to_not_sql(builder, definition, &block)
elsif [:null, :notnull].include?(operator)
to_null_sql(builder, definition, &block)
elsif children.length == 1
to_default_fields_sql(builder, definition, &block)
elsif children.length == 2
to_single_field_sql(builder, definition, &block)
else
raise ScopedSearch::QueryNotSupported, "Don't know how to handle this operator node: #{operator.inspect} with #{children.inspect}!"
end
end
end
# Defines the to_sql method for AST AND/OR operators
module LogicalOperatorNode
def to_sql(builder, definition, &block)
fragments = children.map { |c| c.to_sql(builder, definition, &block) }.compact
fragments.empty? ? nil : "(#{fragments.join(" #{operator.to_s.upcase} ")})"
end
end
end
# The MysqlAdapter makes sure that case sensitive comparisons are used
# when using the (not) equals operator, regardless of the field's
# collation setting.
class MysqlAdapter < ScopedSearch::QueryBuilder
# Patches the default <tt>sql_operator</tt> method to add
# <tt>BINARY</tt> after the equals and not equals operator to force
# case-sensitive comparisons.
def sql_operator(operator, field)
if [:ne, :eq].include?(operator) && field.textual?
"#{SQL_OPERATORS[operator]} BINARY"
else
super(operator, field)
end
end
end
# The PostgreSQLAdapter make sure that searches are case sensitive when
# using the like/unlike operators, by using the PostrgeSQL-specific
# <tt>ILIKE operator</tt> instead of <tt>LIKE</tt>.
class PostgreSQLAdapter < ScopedSearch::QueryBuilder
# Switches out the default LIKE operator for ILIKE in the default
# <tt>sql_operator</tt> method.
def sql_operator(operator, field)
case operator
when :like then 'ILIKE'
when :unlike then 'NOT ILIKE'
else super(operator, field)
end
end
end
# The Oracle adapter also requires some tweaks to make the case insensitive LIKE work.
class OracleEnhancedAdapter < ScopedSearch::QueryBuilder
# Use REGEXP_LIKE for case insensitive comparisons
def sql_operator(operator, field)
case operator
when :like then 'REGEXP_LIKE'
when :unlike then 'NOT REGEXP_LIKE'
else super(operator, field)
end
end
def sql_test(field, operator, value, &block) # :yields: finder_option_type, value
if field.textual? && [:like, :unlike].include?(operator)
regexp_value = if value !~ /^\%/ && value !~ /\%$/
Regexp.quote(value)
else
"^#{Regexp.quote(value)}$".sub(/^\^%/, '').sub(/%\$$/, '')
end
yield(:parameter, regexp_value)
return "#{self.sql_operator(operator, field)}(#{field.to_sql(operator, &block)}, ?, 'i')"
else
super(field, operator, value, &block)
end
end
end
end
# Include the modules into the corresponding classes
# to add SQL generation capabilities to them.
Definition::Field.send(:include, QueryBuilder::Field)
QueryLanguage::AST::LeafNode.send(:include, QueryBuilder::AST::LeafNode)
QueryLanguage::AST::OperatorNode.send(:include, QueryBuilder::AST::OperatorNode)
QueryLanguage::AST::LogicalOperatorNode.send(:include, QueryBuilder::AST::LogicalOperatorNode)
end
|
require_relative './noko_doc'
# Scrapes data for Repositories and Users on Github.com
class GithubRepoScraper
@github_doc = NokoDoc.new
@current_repo = nil
@SECONDS_BETWEEN_REQUESTS = 0
# TODO: repo_stars, repo_description etc. are common methods but aren't valid unless we are on a repo
class << self
attr_reader :github_doc # TODO: is this needed?
# Gets the following:
# - number of stars the project has
# - raw README.md file
#
# Example project's Github url vs raw url
# - Github: https://github.com/rspec/rspec/blob/master/README.md
# - Raw: https://raw.githubusercontent.com/rspec/rspec/master/README.md
#
# repos: repos whose repo data will be updated
def update_repo_data(repos = Repository.all)
repos.each do |repo|
begin
@current_repo = repo
break unless @github_doc.new_doc(@current_repo.url)
puts "Updated repo #{@current_repo.name}"
# TODO: add to update_repo_data to get repo name and owner name
# owner, repo_name = @current_repo.url[/\/\w+\/\w+/].split('/)
# Parse the page and update repo
repo.update(stars: repo_stars, watchers: repo_watchers, forks: repo_forks, description: repo_description)
rescue OpenURI::HTTPError => e
repo.destroy
puts "DESTROYED #{@current_repo.name} : its Github URL #{@current_repo.url} resulted in #{e.message}"
end
end
end
# Retrieves the commits for each Repository
#
# NOTE: you can use all options together, but whichever one ends first
# will be the one that stops the scraper
#
# Options
# repositories: repos to be scraped for data
# page_limit: maximum number of pages to iterate
# user_limit: max number of users to add
# TODO: expand rake task to pass in these options
def commits(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
catch :scrape_limit_reached do
@repositories.each do |repo|
@current_repo = repo
commits_path = @current_repo.url + '/commits/master'
puts "Scraping #{repo.name} commits"
break unless @github_doc.new_doc(commits_path)
# TODO: test forks
repo.update(watchers: repo_watchers, stars: repo_stars, forks: repo_forks) if get_repo_meta
catch :recent_commits_finished do
traverse_commit_pagination
end
# TODO: why is this here?
@page_limit
end
end
end
private
# this can be added to the other scraper
def handle_scrape_limits(opts={})
@repositories = opts[:repositories] || Repository.all
@page_limit = opts[:page_limit] || Float::INFINITY
@user_limit = opts[:user_limit] || Float::INFINITY
end
def traverse_commit_pagination
page_count = 1
loop do
fetch_commit_data
throw :scrape_limit_reached if page_count >= @page_limit
break unless @github_doc.doc.css('.pagination').any?
page_count += 1
next_path = @github_doc.doc.css('.pagination a')[0]['href']
sleep SECONDS_BETWEEN_REQUESTS
break unless @github_doc.new_doc('https://github.com' + next_path)
end
end
def fetch_commit_data
@github_doc.doc.css('.commit').each do |commit_info|
commit_date = Time.parse(commit_info.css('relative-time')[0][:datetime])
throw :recent_commits_finished unless commit_date.today?
# Not all avatars are users
user_anchor = commit_info.css('.commit-avatar-cell a')[0]
github_username = user_anchor['href'][1..-1] if user_anchor
if !github_username.nil? && !User.exists?(github_username: github_username)
user = User.create(github_username: github_username)
puts "User CREATE github_username:#{user.github_username}"
elsif !github_username.nil?
user = User.find_by(github_username: github_username)
end
if user
message = commit_info.css("a.message").text
github_identifier = commit_info.css("a.sha").text.strip
unless Commit.exists?(github_identifier: github_identifier)
Commit.create(
message: message,
user: user,
repository: @current_repo,
github_identifier: github_identifier
)
puts "Commit CREATE identifier:#{github_identifier} by #{user.github_username}"
end
end
throw :scrape_limit_reached if User.count >= @user_limit
end
end
def repo_readme_content
# NOTE: Only available on the code subpage of the repo
if @github_doc.doc.at('td span:contains("README")')
raw_file_url = @current_repo.url.gsub('github', 'raw.githubusercontent') \
+ '/master/README.md'
NokoDoc.new_temp_doc(raw_file_url).css('body p').text
else
"Empty"
end
end
def select_social_count(child=nil)
@github_doc.doc.css("ul.pagehead-actions li:nth-child(#{child}) .social-count")
.text.strip.gsub(',', '').to_i
end
def repo_watchers
select_social_count(1)
end
def repo_stars
select_social_count(2)
end
def repo_forks
select_social_count(3)
end
end
end
went through todos and removed depracated code
require_relative './noko_doc'
# Scrapes data for Repositories and Users on Github.com
class GithubRepoScraper
@github_doc = NokoDoc.new
@current_repo = nil
@SECONDS_BETWEEN_REQUESTS = 0
class << self
# Gets the following:
# - number of stars the project has
# - raw README.md file
#
# Example project's Github url vs raw url
# - Github: https://github.com/rspec/rspec/blob/master/README.md
# - Raw: https://raw.githubusercontent.com/rspec/rspec/master/README.md
#
# repos: repos whose repo data will be updated
def update_repo_data(repos = Repository.all)
repos.each do |repo|
begin
@current_repo = repo
break unless @github_doc.new_doc(@current_repo.url)
puts "Updated repo #{@current_repo.name}"
# TODO: add to update_repo_data to get repo name and owner name
# owner, repo_name = @current_repo.url[/\/\w+\/\w+/].split('/)
# Parse the page and update repo
repo.update(stars: repo_stars, watchers: repo_watchers, forks: repo_forks, description: repo_description)
rescue OpenURI::HTTPError => e
repo.destroy
puts "DESTROYED #{@current_repo.name} : its Github URL #{@current_repo.url} resulted in #{e.message}"
end
end
end
# Retrieves the commits for each Repository
#
# NOTE: you can use all options together, but whichever one ends first
# will be the one that stops the scraper
#
# Options
# repositories: repos to be scraped for data
# page_limit: maximum number of pages to iterate
# user_limit: max number of users to add
def commits(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
catch :scrape_limit_reached do
@repositories.each do |repo|
@current_repo = repo
commits_path = @current_repo.url + '/commits/master'
puts "Scraping #{repo.name} commits"
break unless @github_doc.new_doc(commits_path)
repo.update(watchers: repo_watchers, stars: repo_stars, forks: repo_forks) if get_repo_meta
catch :recent_commits_finished do
traverse_commit_pagination
end
end
end
end
private
# this can be added to the other scraper
def handle_scrape_limits(opts={})
@repositories = opts[:repositories] || Repository.all
@page_limit = opts[:page_limit] || Float::INFINITY
@user_limit = opts[:user_limit] || Float::INFINITY
end
def traverse_commit_pagination
page_count = 1
loop do
fetch_commit_data
throw :scrape_limit_reached if page_count >= @page_limit
break unless @github_doc.doc.css('.pagination').any?
page_count += 1
next_path = @github_doc.doc.css('.pagination a')[0]['href']
sleep SECONDS_BETWEEN_REQUESTS
break unless @github_doc.new_doc('https://github.com' + next_path)
end
end
def fetch_commit_data
@github_doc.doc.css('.commit').each do |commit_info|
commit_date = Time.parse(commit_info.css('relative-time')[0][:datetime])
throw :recent_commits_finished unless commit_date.today?
# Not all avatars are users
user_anchor = commit_info.css('.commit-avatar-cell a')[0]
github_username = user_anchor['href'][1..-1] if user_anchor
if !github_username.nil? && !User.exists?(github_username: github_username)
user = User.create(github_username: github_username)
puts "User CREATE github_username:#{user.github_username}"
elsif !github_username.nil?
user = User.find_by(github_username: github_username)
end
if user
message = commit_info.css("a.message").text
github_identifier = commit_info.css("a.sha").text.strip
unless Commit.exists?(github_identifier: github_identifier)
Commit.create(
message: message,
user: user,
repository: @current_repo,
github_identifier: github_identifier
)
puts "Commit CREATE identifier:#{github_identifier} by #{user.github_username}"
end
end
throw :scrape_limit_reached if User.count >= @user_limit
end
end
def repo_readme_content
# NOTE: Only available on the code subpage of the repo
if @github_doc.doc.at('td span:contains("README")')
raw_file_url = @current_repo.url.gsub('github', 'raw.githubusercontent') \
+ '/master/README.md'
NokoDoc.new_temp_doc(raw_file_url).css('body p').text
else
"Empty"
end
end
def select_social_count(child=nil)
@github_doc.doc.css("ul.pagehead-actions li:nth-child(#{child}) .social-count")
.text.strip.gsub(',', '').to_i
end
def repo_watchers
select_social_count(1)
end
def repo_stars
select_social_count(2)
end
def repo_forks
select_social_count(3)
end
end
end
|
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 'set'
require 'thread'
module Seahorse
class Client
# @api private
class PluginList
include Enumerable
# @param [Array, Set] plugins
# @option options [Mutex] :mutex
def initialize(plugins = [], options = {})
@mutex = options[:mutex] || Mutex.new
@plugins = {}
if plugins.is_a?(PluginList)
plugins.send(:each_plugin) { |plugin| add(plugin) }
else
plugins.each { |plugin| add(plugin) }
end
end
# Adds and returns the `plugin`.
# @param [Plugin] plugin
# @return [void]
def add(plugin)
plugin = PluginDetails.new(plugin)
@mutex.synchronize do
@plugins[plugin.canonical_name] = plugin
end
nil
end
# Removes and returns the `plugin`.
# @param [Plugin] plugin
# @return [void]
def remove(plugin)
plugin = PluginDetails.new(plugin)
@mutex.synchronize do
@plugins.delete(plugin.canonical_name)
end
nil
end
# Enumerates the plugins.
# @return [Enumerator]
def each(&block)
each_plugin do |plugin|
yield(plugin.klass)
end
end
private
# Yield each PluginDetail behind the mutex
def each_plugin(&block)
@mutex.synchronize do
@plugins.values.each(&block)
end
end
# A utility class that computes the canonical name for a plugin
# and defers requiring the plugin until the plugin class is
# required.
# @api private
class PluginDetails
# @param [String, Symbol, Class] plugin
def initialize(plugin)
if plugin.is_a?(Class)
@canonical_name = plugin.name
@klass = plugin
else
@canonical_name, @gem_name = plugin.to_s.split('.').reverse
@klass = nil
end
end
# @return [String]
attr_reader :canonical_name
# @return [Class]
def klass
@klass ||= require_plugin
end
# Returns the given plugin if it is already a PluginDetails object.
def self.new(plugin)
if plugin.is_a?(self)
plugin
else
super
end
end
private
# @return [Class]
def require_plugin
require(@gem_name) if @gem_name
plugin_class = Kernel
@canonical_name.split('::').each do |const_name|
plugin_class = plugin_class.const_get(const_name)
end
plugin_class
end
end
end
end
end
Renamed an inner utility class for clarity.
# Copyright 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 'set'
require 'thread'
module Seahorse
class Client
# @api private
class PluginList
include Enumerable
# @param [Array, Set] plugins
# @option options [Mutex] :mutex
def initialize(plugins = [], options = {})
@mutex = options[:mutex] || Mutex.new
@plugins = {}
if plugins.is_a?(PluginList)
plugins.send(:each_plugin) { |plugin| add(plugin) }
else
plugins.each { |plugin| add(plugin) }
end
end
# Adds and returns the `plugin`.
# @param [Plugin] plugin
# @return [void]
def add(plugin)
plugin = PluginWrapper.new(plugin)
@mutex.synchronize do
@plugins[plugin.canonical_name] = plugin
end
nil
end
# Removes and returns the `plugin`.
# @param [Plugin] plugin
# @return [void]
def remove(plugin)
plugin = PluginWrapper.new(plugin)
@mutex.synchronize do
@plugins.delete(plugin.canonical_name)
end
nil
end
# Enumerates the plugins.
# @return [Enumerator]
def each(&block)
each_plugin do |plugin|
yield(plugin.klass)
end
end
private
# Yield each PluginDetail behind the mutex
def each_plugin(&block)
@mutex.synchronize do
@plugins.values.each(&block)
end
end
# A utility class that computes the canonical name for a plugin
# and defers requiring the plugin until the plugin class is
# required.
# @api private
class PluginWrapper
# @param [String, Symbol, Class] plugin
def initialize(plugin)
if plugin.is_a?(Class)
@canonical_name = plugin.name
@klass = plugin
else
@canonical_name, @gem_name = plugin.to_s.split('.').reverse
@klass = nil
end
end
# @return [String]
attr_reader :canonical_name
# @return [Class]
def klass
@klass ||= require_plugin
end
# Returns the given plugin if it is already a PluginWrapper.
def self.new(plugin)
if plugin.is_a?(self)
plugin
else
super
end
end
private
# @return [Class]
def require_plugin
require(@gem_name) if @gem_name
plugin_class = Kernel
@canonical_name.split('::').each do |const_name|
plugin_class = plugin_class.const_get(const_name)
end
plugin_class
end
end
end
end
end
|
module Served
module Resource
module Requestable
extend ActiveSupport::Concern
# raised when a handler is defined if the method doesn't exist or if a proc isn't supplied
class HandlerRequired < StandardError
def initialize
super 'a handler is required, it must be a proc or a valid method'
end
end
HEADERS = { 'Content-type' => 'application/json', 'Accept' => 'application/json' }
included do
include Configurable
class_configurable :resource_name do
name.split('::').last.tableize
end
class_configurable :host do
Served.config[:hosts][parent.name.underscore.split('/')[-1]] || Served.config[:hosts][:default]
end
class_configurable :timeout do
Served.config.timeout
end
class_configurable :_headers do
HEADERS
end
class_configurable :handlers, default: {}
class_configurable :template do
'{/resource*}{/id}.json{?query*}'
end
class_configurable :raise_on_exceptions do
true
end
handle((200..201), :load)
handle([204, 202]) { attributes }
# 400 level errors
handle(301) { Resource::MovedPermanently }
handle(400) { Resource::BadRequest }
handle(401) { Resource::Unauthorized }
handle(403) { Resource::Forbidden }
handle(404) { Resource::NotFound }
handle(405) { Resource::MethodNotAllowed }
handle(406) { Resource::NotAcceptable }
handle(408) { Resource::RequestTimeout }
handle(422) { Resource::UnprocessableEntity }
# 500 level errors
handle(500) { Resource::InternalServerError }
handle(503) { Resource::BadGateway }
end
module ClassMethods
def handle_response(response)
if raise_on_exceptions
handler = handlers[response.code]
if handler.is_a? Proc
result = handler.call(response)
else
result = send(handler, response)
end
if result.is_a?(HttpError)
raise result.new(self, response)
result = Served::JsonApiError::Errors.new(response)
end
result
else
serializer.load(self, response)
end
end
# Sets individual handlers for response codes, accepts a proc or a symbol representing a method
#
# @param code [Integer|Range] the response code(s) the handler is to be assigned to
# @param symbol_or_proc [Symbol|Proc] a symbol representing the method to call, or a proc to be called when
# the specific response code has been called. The method or proc should return a hash of attributes, if an
# error class is returned it will be raised
# @yieldreturn [Hash] a hash of attributes, if an error class is returned it will be raised
def handle(code_or_range, symbol_or_proc=nil, &block)
raise HandlerRequired unless symbol_or_proc || block_given?
if code_or_range.is_a?(Range) || code_or_range.is_a?(Array)
code_or_range.each { |c|
handlers[c] = symbol_or_proc || block
}
else
handlers[code_or_range] = symbol_or_proc || block
end
end
# Defines the default headers that should be used for the request.
#
# @param headers [Hash] the headers to send with each requesat
# @return headers [Hash] the default headers for the class
def headers(h={})
headers ||= _headers
_headers(headers.merge!(h)) unless h.empty?
_headers
end
# Looks up a resource on the service by id. For example `SomeResource.find(5)` would call `/some_resources/5`
#
# @param id [Integer] the id of the resource
# @return [Resource::Base] the resource object.
def find(id, params = {})
instance = new(id: id)
instance.reload(params)
end
def all(params = {})
get(nil, params).map { |resource| new(resource) }
end
# @return [Served::HTTPClient] the HTTPClient using the configured backend
def client
@client ||= Served::HTTPClient.new(self)
end
def get(id, params = {})
handle_response(client.get(resource_name, id, params))
end
end
# Saves the record to the service. Will call POST if the record does not have an id, otherwise will call PUT
# to update the record
#
# @return [Boolean] returns true or false depending on save success
def save
if id
reload_with_attributes(put)
else
reload_with_attributes(post)
end
true
end
# Reloads the resource using attributes from the service
#
# @return [self] self
def reload(params = {})
reload_with_attributes(self.class.get(id, params))
self
end
# Destroys the record on the service. Acts on status code
# If code is a 204 (no content) it will simply return true
# otherwise it will parse the response and reloads the instance
#
# @return [Boolean|self] Returns true or instance
def destroy(params = {})
result = delete(params)
return result if result.is_a?(TrueClass)
reload_with_attributes(result)
true
end
private
def get(params = {})
self.class.get(id, params)
end
def put(params={})
handle_response(client.put(resource_name, id, dump, params))
end
def post(params={})
handle_response(client.post(resource_name, dump, params))
end
def delete(params={})
response = client.delete(resource_name, id, params)
return true if response.code == 204
handle_response(response)
end
def client
self.class.client
end
def handle_response(response)
self.class.handle_response(response)
end
end
end
end
do not default to true, but return result of #reload_with_attributes
module Served
module Resource
module Requestable
extend ActiveSupport::Concern
# raised when a handler is defined if the method doesn't exist or if a proc isn't supplied
class HandlerRequired < StandardError
def initialize
super 'a handler is required, it must be a proc or a valid method'
end
end
HEADERS = { 'Content-type' => 'application/json', 'Accept' => 'application/json' }
included do
include Configurable
class_configurable :resource_name do
name.split('::').last.tableize
end
class_configurable :host do
Served.config[:hosts][parent.name.underscore.split('/')[-1]] || Served.config[:hosts][:default]
end
class_configurable :timeout do
Served.config.timeout
end
class_configurable :_headers do
HEADERS
end
class_configurable :handlers, default: {}
class_configurable :template do
'{/resource*}{/id}.json{?query*}'
end
class_configurable :raise_on_exceptions do
true
end
handle((200..201), :load)
handle([204, 202]) { attributes }
# 400 level errors
handle(301) { Resource::MovedPermanently }
handle(400) { Resource::BadRequest }
handle(401) { Resource::Unauthorized }
handle(403) { Resource::Forbidden }
handle(404) { Resource::NotFound }
handle(405) { Resource::MethodNotAllowed }
handle(406) { Resource::NotAcceptable }
handle(408) { Resource::RequestTimeout }
handle(422) { Resource::UnprocessableEntity }
# 500 level errors
handle(500) { Resource::InternalServerError }
handle(503) { Resource::BadGateway }
end
module ClassMethods
def handle_response(response)
if raise_on_exceptions
handler = handlers[response.code]
if handler.is_a? Proc
result = handler.call(response)
else
result = send(handler, response)
end
if result.is_a?(HttpError)
raise result.new(self, response)
result = Served::JsonApiError::Errors.new(response)
end
result
else
serializer.load(self, response)
end
end
# Sets individual handlers for response codes, accepts a proc or a symbol representing a method
#
# @param code [Integer|Range] the response code(s) the handler is to be assigned to
# @param symbol_or_proc [Symbol|Proc] a symbol representing the method to call, or a proc to be called when
# the specific response code has been called. The method or proc should return a hash of attributes, if an
# error class is returned it will be raised
# @yieldreturn [Hash] a hash of attributes, if an error class is returned it will be raised
def handle(code_or_range, symbol_or_proc=nil, &block)
raise HandlerRequired unless symbol_or_proc || block_given?
if code_or_range.is_a?(Range) || code_or_range.is_a?(Array)
code_or_range.each { |c|
handlers[c] = symbol_or_proc || block
}
else
handlers[code_or_range] = symbol_or_proc || block
end
end
# Defines the default headers that should be used for the request.
#
# @param headers [Hash] the headers to send with each requesat
# @return headers [Hash] the default headers for the class
def headers(h={})
headers ||= _headers
_headers(headers.merge!(h)) unless h.empty?
_headers
end
# Looks up a resource on the service by id. For example `SomeResource.find(5)` would call `/some_resources/5`
#
# @param id [Integer] the id of the resource
# @return [Resource::Base] the resource object.
def find(id, params = {})
instance = new(id: id)
instance.reload(params)
end
def all(params = {})
get(nil, params).map { |resource| new(resource) }
end
# @return [Served::HTTPClient] the HTTPClient using the configured backend
def client
@client ||= Served::HTTPClient.new(self)
end
def get(id, params = {})
handle_response(client.get(resource_name, id, params))
end
end
# Saves the record to the service. Will call POST if the record does not have an id, otherwise will call PUT
# to update the record
#
# @return [Boolean] returns true or false depending on save success
def save
if id
reload_with_attributes(put)
else
reload_with_attributes(post)
end
true
end
# Reloads the resource using attributes from the service
#
# @return [self] self
def reload(params = {})
reload_with_attributes(self.class.get(id, params))
self
end
# Destroys the record on the service. Acts on status code
# If code is a 204 (no content) it will simply return true
# otherwise it will parse the response and reloads the instance
#
# @return [Boolean|self] Returns true or instance
def destroy(params = {})
result = delete(params)
return result if result.is_a?(TrueClass)
reload_with_attributes(result)
end
private
def get(params = {})
self.class.get(id, params)
end
def put(params={})
handle_response(client.put(resource_name, id, dump, params))
end
def post(params={})
handle_response(client.post(resource_name, dump, params))
end
def delete(params={})
response = client.delete(resource_name, id, params)
return true if response.code == 204
handle_response(response)
end
def client
self.class.client
end
def handle_response(response)
self.class.handle_response(response)
end
end
end
end
|
#
# ServerEngine
#
# Copyright (C) 2012-2013 Sadayuki Furuhashi
#
# 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 'socket'
require 'ipaddr'
module ServerEngine
module SocketManager
class Client
def initialize(path)
@path = path
end
def listen_tcp(bind, port)
peer = connect_peer(@path)
begin
SocketManager.send_peer(peer, [Process.pid, :listen_tcp, bind, port])
res = SocketManager.recv_peer(peer)
if res.is_a?(Exception)
raise res
else
return recv_tcp(peer, res)
end
ensure
peer.close
end
end
def listen_udp(bind, port)
peer = connect_peer(@path)
begin
SocketManager.send_peer(peer, [Process.pid, :listen_udp, bind, port])
res = SocketManager.recv_peer(peer)
if res.is_a?(Exception)
raise res
else
return recv_udp(peer, res)
end
ensure
peer.close
end
end
end
class Server
def self.generate_path
if ServerEngine.windows?
for port in 10000..65535
if `netstat -na | find "#{port}"`.length == 0
return port
end
end
else
'/tmp/SERVERENGINE_SOCKETMANAGER_' + Time.now.to_s.gsub(' ', '') + '_' + Process.pid.to_s
end
end
def self.open(path)
new(path)
end
def initialize(path)
@tcp_sockets = {}
@udp_sockets = {}
@mutex = Mutex.new
@path = start_server(path)
end
attr_reader :path
def new_client
Client.new(@path)
end
def close
stop_server
nil
end
private
def listen_tcp(bind, port)
key, bind_ip = resolve_bind_key(bind, port)
@mutex.synchronize do
if @tcp_sockets.has_key?(key)
return @tcp_sockets[key]
else
return @tcp_sockets[key] = listen_tcp_new(bind_ip, port)
end
end
end
def listen_udp(bind, port)
key, bind_ip = resolve_bind_key(bind, port)
@mutex.synchronize do
if @udp_sockets.has_key?(key)
return @udp_sockets[key]
else
return @udp_sockets[key] = listen_udp_new(bind_ip, port)
end
end
end
def resolve_bind_key(bind, port)
bind_ip = IPAddr.new(IPSocket.getaddress(bind))
if bind_ip.ipv6?
return "[#{bind_ip}]:#{port}", bind_ip
else
# assuming ipv4
if bind_ip == "127.0.0.1" or bind_ip == "0.0.0.0"
return "localhost:#{port}", bind_ip
end
return "#{bind_ip}:#{port}", bind_ip
end
end
def process_peer(peer)
while true
pid, method, bind, port = *SocketManager.recv_peer(peer)
begin
send_socket(peer, pid, method, bind, port)
rescue => e
SocketManager.send_peer(peer, e)
end
end
ensure
peer.close
end
end
def self.send_peer(peer, obj)
data = Marshal.dump(obj)
peer.write [data.bytesize].pack('N')
peer.write data
end
def self.recv_peer(peer)
len = peer.read(4).unpack('N').first
data = peer.read(len)
Marshal.load(data)
end
if ServerEngine.windows?
require_relative 'socket_manager_win'
Client.include(SocketManagerWin::ClientModule)
Server.include(SocketManagerWin::ServerModule)
else
require_relative 'socket_manager_unix'
Client.include(SocketManagerUnix::ClientModule)
Server.include(SocketManagerUnix::ServerModule)
end
end
end
Use findstr instead of find, not to use "find.exe"
Executing just "find" possibly invokes "find.exe", which is introduced by MSYS or any others (unix like something, or ...).
#
# ServerEngine
#
# Copyright (C) 2012-2013 Sadayuki Furuhashi
#
# 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 'socket'
require 'ipaddr'
module ServerEngine
module SocketManager
class Client
def initialize(path)
@path = path
end
def listen_tcp(bind, port)
peer = connect_peer(@path)
begin
SocketManager.send_peer(peer, [Process.pid, :listen_tcp, bind, port])
res = SocketManager.recv_peer(peer)
if res.is_a?(Exception)
raise res
else
return recv_tcp(peer, res)
end
ensure
peer.close
end
end
def listen_udp(bind, port)
peer = connect_peer(@path)
begin
SocketManager.send_peer(peer, [Process.pid, :listen_udp, bind, port])
res = SocketManager.recv_peer(peer)
if res.is_a?(Exception)
raise res
else
return recv_udp(peer, res)
end
ensure
peer.close
end
end
end
class Server
def self.generate_path
if ServerEngine.windows?
for port in 10000..65535
if `netstat -na | findstr "#{port}"`.length == 0
return port
end
end
else
'/tmp/SERVERENGINE_SOCKETMANAGER_' + Time.now.to_s.gsub(' ', '') + '_' + Process.pid.to_s
end
end
def self.open(path)
new(path)
end
def initialize(path)
@tcp_sockets = {}
@udp_sockets = {}
@mutex = Mutex.new
@path = start_server(path)
end
attr_reader :path
def new_client
Client.new(@path)
end
def close
stop_server
nil
end
private
def listen_tcp(bind, port)
key, bind_ip = resolve_bind_key(bind, port)
@mutex.synchronize do
if @tcp_sockets.has_key?(key)
return @tcp_sockets[key]
else
return @tcp_sockets[key] = listen_tcp_new(bind_ip, port)
end
end
end
def listen_udp(bind, port)
key, bind_ip = resolve_bind_key(bind, port)
@mutex.synchronize do
if @udp_sockets.has_key?(key)
return @udp_sockets[key]
else
return @udp_sockets[key] = listen_udp_new(bind_ip, port)
end
end
end
def resolve_bind_key(bind, port)
bind_ip = IPAddr.new(IPSocket.getaddress(bind))
if bind_ip.ipv6?
return "[#{bind_ip}]:#{port}", bind_ip
else
# assuming ipv4
if bind_ip == "127.0.0.1" or bind_ip == "0.0.0.0"
return "localhost:#{port}", bind_ip
end
return "#{bind_ip}:#{port}", bind_ip
end
end
def process_peer(peer)
while true
pid, method, bind, port = *SocketManager.recv_peer(peer)
begin
send_socket(peer, pid, method, bind, port)
rescue => e
SocketManager.send_peer(peer, e)
end
end
ensure
peer.close
end
end
def self.send_peer(peer, obj)
data = Marshal.dump(obj)
peer.write [data.bytesize].pack('N')
peer.write data
end
def self.recv_peer(peer)
len = peer.read(4).unpack('N').first
data = peer.read(len)
Marshal.load(data)
end
if ServerEngine.windows?
require_relative 'socket_manager_win'
Client.include(SocketManagerWin::ClientModule)
Server.include(SocketManagerWin::ServerModule)
else
require_relative 'socket_manager_unix'
Client.include(SocketManagerUnix::ClientModule)
Server.include(SocketManagerUnix::ServerModule)
end
end
end
|
module ShippingMaterials
require 'mustache'
class Template < Mustache
attr_reader :header, :footer
def initialize(objects, filename)
@objects = objects
@filename = filename
@rendered = ''
@header =''
@footer = ''
end
def layout_file=(name)
layout = File.read("#{template_path}/#{name}")
@header, @footer = layout.split(/{{yield}}/)
end
def render!
@rendered += @header
@objects.each do |o|
add_methods(o)
@rendered << render
end
@rendered += @footer
end
def object=(object)
add_methods(object)
end
def to_s
@rendered
end
def to_pdf
base = "#{Config.save_path}/#{File.basename(@filename)}"
html, pdf = base + '.html', base + '.pdf'
File.open(html, 'w') {|f| f.write(@rendered) }
%x( wkhtmltopdf #{html} #{pdf} )
end
private
def add_methods(object)
@public_methods ||= object.public_methods(false).grep(/[^=]$/)
@public_methods.each do |meth|
self.class.send(:define_method, meth) do
object.send(meth)
end
end
end
end
end
Add comment
module ShippingMaterials
require 'mustache'
class Template < Mustache
attr_reader :header, :footer
def initialize(objects, filename)
@objects = objects
@filename = filename
@rendered = ''
@header =''
@footer = ''
end
# Gotta refactor this to use Mustache partials
# This is embarrassing yet I am moving on
def layout_file=(name)
layout = File.read("#{template_path}/#{name}")
@header, @footer = layout.split(/{{yield}}/)
end
def render!
@rendered += @header
@objects.each do |o|
add_methods(o)
@rendered << render
end
@rendered += @footer
end
def object=(object)
add_methods(object)
end
def to_s
@rendered
end
def to_pdf
base = "#{Config.save_path}/#{File.basename(@filename)}"
html, pdf = base + '.html', base + '.pdf'
File.open(html, 'w') {|f| f.write(@rendered) }
%x( wkhtmltopdf #{html} #{pdf} )
end
private
def add_methods(object)
@public_methods ||= object.public_methods(false).grep(/[^=]$/)
@public_methods.each do |meth|
self.class.send(:define_method, meth) do
object.send(meth)
end
end
end
end
end
|
# frozen_string_literal: true
module SidekiqUniqueJobs
#
# @return [String] the current SidekiqUniqueJobs version
VERSION = "7.0.0.beta25"
end
Bump version
# frozen_string_literal: true
module SidekiqUniqueJobs
#
# @return [String] the current SidekiqUniqueJobs version
VERSION = "7.0.0.beta26"
end
|
require 'skype/communication/protocol'
require 'skype/communication/windows/win32'
class Skype
module Communication
# Utilises the Windows API to send and receive Window Messages to/from Skype.
#
# This protocol is only available on Windows and Cygwin.
class Windows
include Skype::Communication::Protocol
# Sets up access to Skype
#
# @see http://msdn.microsoft.com/en-us/library/bb384843.aspx Creating Win32-Based Applications
def initialize(application_name)
@application_name = application_name
# Get the message id's for the Skype Control messages
@api_discover_message_id = Win32::RegisterWindowMessage('SkypeControlAPIDiscover')
@api_attach_message_id = Win32::RegisterWindowMessage('SkypeControlAPIAttach')
instance = Win32::GetModuleHandle(nil)
@window_class = Win32::WNDCLASSEX.new
@window_class[:style] = Win32::CS_HREDRAW | Win32::CS_VREDRAW
@window_class[:lpfnWndProc] = method(:message_pump)
@window_class[:hInstance] = instance
@window_class[:hbrBackground] = Win32::COLOR_WINDOW
@window_class[:lpszClassName] = FFI::MemoryPointer.from_string 'ruby-skype'
@window = Win32::CreateWindowEx(Win32::WS_EX_LEFT, ::FFI::Pointer.new(@window_class.handle), 'ruby-skype', Win32::WS_OVERLAPPEDWINDOW,
0, 0, 0, 0, Win32::NULL, Win32::NULL, instance, nil)
end
# Connects to Skype.
#
# @return [void]
def connect
Win32::SendMessage(Win32::HWND_BROADCAST, @api_discover_message_id, @window, 0)
# Setup a message for use by #tick. Do this just once so we're not setting up and tearing down local variables
# all the time.
@msg = Win32::MSG.new
@authorized = nil
end
# Update processing.
#
# This executes a Windows event loop while there are messages still pending, then dumps back out to let other
# things take over and do their thing.
#
# @return [void]
def tick
while Win32::PeekMessage(@msg, Win32::NULL, 0, 0, Win32::PM_REMOVE) > 0
Win32::TranslateMessage(@msg)
Win32::DispatchMessage(@msg)
end
# Don't simplify this as we rely on false != nil for tribool values
#noinspection RubySimplifyBooleanInspection
Skype::Errors::ExceptionFactory.generate_exception("ERROR 68") if @authorized == false
end
# This is our message pump that receives messages from Windows.
#
# The return value from DefWindowProc is important and must be returned somehow.
#
# @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573.aspx MSDN
def message_pump(window_handle, message_id, wParam, lParam)
case message_id
when @api_attach_message_id
# Drop API_ATTACH messages on the floor
when @api_discover_message_id
case lParam
when API_ATTACH_SUCCESS
@skype_window = wParam
when API_ATTACH_REFUSED
# Signal to the message pump that we were deauthorised
@authorized = false
else
# Ignore pending signal
"WM: Ignoring API_DISCOVER response: #{lParam}"
end
when Win32::WM_COPYDATA
unless wParam == @skype_window
puts "WARNING: Dropping WM_COPYDATA on the floor from HWND #{wParam} (not Skype [#{@skype_window}])"
return 0
end
puts "Incoming data from Skype: #{lParam}"
# Let Windows know we got it successfully
1
else
puts "WM: #{sprintf("0x%04x", message_id)}" if Skype.DEBUG
Win32::DefWindowProc(window_handle, message_id, wParam, lParam)
end
end
# Attached to Skype successfully.
API_ATTACH_SUCCESS = 0
# Skype indicated that we should hold on.
API_ATTACH_PENDING = 1
# Attachment to Skype was refused.
API_ATTACH_REFUSED = 2
# Attachment to Skype isn't available currently. Typically there is no user logged in.
API_ATTACH_NOT_AVAILABLE = 3
end
end
end
Minor change to log message
require 'skype/communication/protocol'
require 'skype/communication/windows/win32'
class Skype
module Communication
# Utilises the Windows API to send and receive Window Messages to/from Skype.
#
# This protocol is only available on Windows and Cygwin.
class Windows
include Skype::Communication::Protocol
# Sets up access to Skype
#
# @see http://msdn.microsoft.com/en-us/library/bb384843.aspx Creating Win32-Based Applications
def initialize(application_name)
@application_name = application_name
# Get the message id's for the Skype Control messages
@api_discover_message_id = Win32::RegisterWindowMessage('SkypeControlAPIDiscover')
@api_attach_message_id = Win32::RegisterWindowMessage('SkypeControlAPIAttach')
instance = Win32::GetModuleHandle(nil)
@window_class = Win32::WNDCLASSEX.new
@window_class[:style] = Win32::CS_HREDRAW | Win32::CS_VREDRAW
@window_class[:lpfnWndProc] = method(:message_pump)
@window_class[:hInstance] = instance
@window_class[:hbrBackground] = Win32::COLOR_WINDOW
@window_class[:lpszClassName] = FFI::MemoryPointer.from_string 'ruby-skype'
@window = Win32::CreateWindowEx(Win32::WS_EX_LEFT, ::FFI::Pointer.new(@window_class.handle), 'ruby-skype', Win32::WS_OVERLAPPEDWINDOW,
0, 0, 0, 0, Win32::NULL, Win32::NULL, instance, nil)
end
# Connects to Skype.
#
# @return [void]
def connect
Win32::SendMessage(Win32::HWND_BROADCAST, @api_discover_message_id, @window, 0)
# Setup a message for use by #tick. Do this just once so we're not setting up and tearing down local variables
# all the time.
@msg = Win32::MSG.new
@authorized = nil
end
# Update processing.
#
# This executes a Windows event loop while there are messages still pending, then dumps back out to let other
# things take over and do their thing.
#
# @return [void]
def tick
while Win32::PeekMessage(@msg, Win32::NULL, 0, 0, Win32::PM_REMOVE) > 0
Win32::TranslateMessage(@msg)
Win32::DispatchMessage(@msg)
end
# Don't simplify this as we rely on false != nil for tribool values
#noinspection RubySimplifyBooleanInspection
Skype::Errors::ExceptionFactory.generate_exception("ERROR 68") if @authorized == false
end
# This is our message pump that receives messages from Windows.
#
# The return value from DefWindowProc is important and must be returned somehow.
#
# @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms633573.aspx MSDN
def message_pump(window_handle, message_id, wParam, lParam)
case message_id
when @api_attach_message_id
# Drop API_ATTACH messages on the floor
when @api_discover_message_id
case lParam
when API_ATTACH_SUCCESS
@skype_window = wParam
when API_ATTACH_REFUSED
# Signal to the message pump that we were deauthorised
@authorized = false
else
# Ignore pending signal
"WM: Ignoring API_DISCOVER response: #{lParam}"
end
when Win32::WM_COPYDATA
unless wParam == @skype_window
puts "WARNING: Dropping WM_COPYDATA on the floor from HWND #{wParam} (not Skype [#{@skype_window}])"
return 0
end
puts "Incoming data from Skype: #{lParam}"
# Let Windows know we got it successfully
1
else
puts "Unhandled WM: #{sprintf("0x%04x", message_id)}" if Skype.DEBUG
Win32::DefWindowProc(window_handle, message_id, wParam, lParam)
end
end
# Attached to Skype successfully.
API_ATTACH_SUCCESS = 0
# Skype indicated that we should hold on.
API_ATTACH_PENDING = 1
# Attachment to Skype was refused.
API_ATTACH_REFUSED = 2
# Attachment to Skype isn't available currently. Typically there is no user logged in.
API_ATTACH_NOT_AVAILABLE = 3
end
end
end
|
require 'securerandom'
require 'active_record'
module SpaceCadetPostgresqlHack
def set_auto_increment conn, table_name, id
primary_id_seq = table_name + '_id_seq'
conn.execute("select setval('#{primary_id_seq}', #{id - 1});")
end
def new_uuid conn
SecureRandom.uuid
end
end
postgresql's uuid_generate_v4() instead of SecureRandom.uuid
# require 'securerandom'
require 'active_record'
module SpaceCadetPostgresqlHack
def set_auto_increment conn, table_name, id
primary_id_seq = table_name + '_id_seq'
conn.execute("select setval('#{primary_id_seq}', #{id - 1});")
end
# create extension "uuid-ossp"
def new_uuid conn
conn.execute("select uuid_generate_v4() as u")[0]['u']
# SecureRandom.uuid
end
end
|
require 'json'
require 'http'
module Spacebunny
module LiveStream
# Proxy to Base.new
def self.new(*args)
Amqp.new *args
end
class Base
attr_accessor :api_endpoint, :raise_on_error, :client, :secret, :host, :vhost, :live_streams
attr_reader :log_to, :log_level, :logger, :custom_connection_configs, :auto_connection_configs,
:connection_configs, :auto_configs, :tls, :tls_cert, :tls_key, :tls_ca_certificates, :verify_peer
def initialize(protocol, *args)
@protocol = protocol
@custom_connection_configs = {}
@auto_connection_configs = {}
options = args.extract_options.deep_symbolize_keys
@client = options[:client] || raise(ClientRequired)
@secret = options[:secret] || raise(SecretRequired)
@api_endpoint = options[:api_endpoint] || {}
@raise_on_error = options[:raise_on_error]
@log_to = options[:log_to] || STDOUT
@log_level = options[:log_level] || ::Logger::ERROR
@logger = options[:logger] || build_logger
extract_custom_connection_configs_from options
set_live_streams options[:live_streams]
end
def api_endpoint=(options)
unless options.is_a? Hash
raise ArgumentError, 'api_endpoint must be an Hash. See doc for further info'
end
@api_endpoint = options.deep_symbolize_keys
end
# Retrieve configs from APIs endpoint
def auto_configs(force_reload = false)
if force_reload || !@auto_configs
@auto_configs = EndpointConnection.new(
@api_endpoint.merge(client: @client, secret: @secret, logger: logger)
).configs
end
@auto_configs
end
def connection_configs
return @connection_configs if @connection_configs
if auto_configure?
# If key is specified, retrieve configs from APIs endpoint
check_and_add_live_streams auto_configs[:live_streams]
@auto_connection_configs = normalize_auto_connection_configs
end
# Build final connection_configs
@connection_configs = merge_connection_configs
# Check for required params presence
check_connection_configs
@connection_configs
end
alias_method :auto_configure, :connection_configs
def connect
logger.warn "connect method must be implemented on class responsibile to handle protocol '#{@protocol}'"
end
def connection_options=(options)
unless options.is_a? Hash
raise ArgumentError, 'connection_options must be an Hash. See doc for further info'
end
extract_custom_connection_configs_from options.with_indifferent_access
end
def disconnect
@connection_configs = nil
end
# Stub method: must be implemented on the class responsible to handle the protocol
def on_receive(options = {})
logger.warn "on_receive method must be implemented on class responsibile to handle protocol '#{@protocol}'"
end
def auto_configure?
@client && @secret
end
def host
connection_configs[:host]
end
def host=(host)
@connection_configs[:host] = host
end
def secret
connection_configs[:secret]
end
def secret=(secret)
@connection_configs[:secret] = secret
end
def vhost
connection_configs[:vhost]
end
alias_method :organization_id, :vhost
def vhost=(vhost)
@connection_configs[:secret] = secret
end
private
# @private
# Check if live_streams are an array
def set_live_streams(live_streams)
if live_streams && !live_streams.is_a?(Array)
raise StreamsMustBeAnArray
end
check_and_add_live_streams(live_streams)
end
# @private
# Check for required params presence
def check_connection_configs
# Do nothing ATM
end
# @private
# Merge auto_connection_configs and custom_connection_configs
def merge_connection_configs
auto_connection_configs.merge(custom_connection_configs) do |key, old_val, new_val|
if new_val.nil?
old_val
else
new_val
end
end
end
# @private
def build_logger
logger = ::Logger.new(@log_to)
logger.level = normalize_log_level
logger.progname = 'Spacebunny'
Spacebunny.logger = logger
end
# @private
def extract_custom_connection_configs_from(options)
@custom_connection_configs = options
# Auto_recover from connection.close by default
@custom_connection_configs[:host] = @custom_connection_configs.delete :host
if @custom_connection_configs[:protocols] && custom_connection_configs[:protocols][@protocol]
@custom_connection_configs[:port] = @custom_connection_configs[:protocols][@protocol].delete :port
@custom_connection_configs[:tls_port] = @custom_connection_configs[:protocols][@protocol].delete :tls_port
end
@custom_connection_configs[:vhost] = @custom_connection_configs.delete :vhost
@custom_connection_configs[:client] = @custom_connection_configs.delete :client
@custom_connection_configs[:secret] = @custom_connection_configs.delete :secret
@custom_connection_configs[:logger] = @custom_connection_configs.delete(:logger) || @logger
end
# @private
def check_and_add_live_streams(chs)
@live_streams = [] unless @live_streams
return unless chs
chs.each do |ch|
case ch
when Hash
ch.symbolize_keys!
# Check for required attributes
[:id, :name].each do |attr|
unless ch[attr]
raise LiveStreamParamError(ch[:name], attr)
end
end
@live_streams << ch
else
raise LiveStreamFormatError
end
end
end
# @private
# Translate from auto configs given by APIs endpoint to a common format
def normalize_auto_connection_configs
{
host: auto_configs[:connection][:host],
port: auto_configs[:connection][:protocols][@protocol][:port],
tls_port: auto_configs[:connection][:protocols][@protocol][:tls_port],
vhost: auto_configs[:connection][:vhost],
client: auto_configs[:connection][:client],
secret: auto_configs[:connection][:secret]
}
end
# @private
def normalize_log_level
case @log_level
when :debug, ::Logger::DEBUG, 'debug' then ::Logger::DEBUG
when :info, ::Logger::INFO, 'info' then ::Logger::INFO
when :warn, ::Logger::WARN, 'warn' then ::Logger::WARN
when :error, ::Logger::ERROR, 'error' then ::Logger::ERROR
when :fatal, ::Logger::FATAL, 'fatal' then ::Logger::FATAL
else
Logger::ERROR
end
end
end
end
end
Fix custom connection config extraction for live_stream
require 'json'
require 'http'
module Spacebunny
module LiveStream
# Proxy to Base.new
def self.new(*args)
Amqp.new *args
end
class Base
attr_accessor :api_endpoint, :raise_on_error, :client, :secret, :host, :vhost, :live_streams
attr_reader :log_to, :log_level, :logger, :custom_connection_configs, :auto_connection_configs,
:connection_configs, :auto_configs, :tls, :tls_cert, :tls_key, :tls_ca_certificates, :verify_peer
def initialize(protocol, *args)
@protocol = protocol
@custom_connection_configs = {}
@auto_connection_configs = {}
options = args.extract_options.deep_symbolize_keys
@client = options[:client] || raise(ClientRequired)
@secret = options[:secret] || raise(SecretRequired)
@api_endpoint = options[:api_endpoint] || {}
@raise_on_error = options[:raise_on_error]
@log_to = options[:log_to] || STDOUT
@log_level = options[:log_level] || ::Logger::ERROR
@logger = options[:logger] || build_logger
extract_and_normalize_custom_connection_configs_from options
set_live_streams options[:live_streams]
end
def api_endpoint=(options)
unless options.is_a? Hash
raise ArgumentError, 'api_endpoint must be an Hash. See doc for further info'
end
@api_endpoint = options.deep_symbolize_keys
end
# Retrieve configs from APIs endpoint
def auto_configs(force_reload = false)
if force_reload || !@auto_configs
@auto_configs = EndpointConnection.new(
@api_endpoint.merge(client: @client, secret: @secret, logger: logger)
).configs
end
@auto_configs
end
def connection_configs
return @connection_configs if @connection_configs
if auto_configure?
# If key is specified, retrieve configs from APIs endpoint
check_and_add_live_streams auto_configs[:live_streams]
@auto_connection_configs = normalize_auto_connection_configs
end
# Build final connection_configs
@connection_configs = merge_connection_configs
# Check for required params presence
check_connection_configs
@connection_configs
end
alias_method :auto_configure, :connection_configs
def connect
logger.warn "connect method must be implemented on class responsibile to handle protocol '#{@protocol}'"
end
def connection_options=(options)
unless options.is_a? Hash
raise ArgumentError, 'connection_options must be an Hash. See doc for further info'
end
extract_and_normalize_custom_connection_configs_from options.with_indifferent_access
end
def disconnect
@connection_configs = nil
end
# Stub method: must be implemented on the class responsible to handle the protocol
def on_receive(options = {})
logger.warn "on_receive method must be implemented on class responsibile to handle protocol '#{@protocol}'"
end
def auto_configure?
@client && @secret
end
def host
connection_configs[:host]
end
def host=(host)
@connection_configs[:host] = host
end
def secret
connection_configs[:secret]
end
def secret=(secret)
@connection_configs[:secret] = secret
end
def vhost
connection_configs[:vhost]
end
alias_method :organization_id, :vhost
def vhost=(vhost)
@connection_configs[:secret] = secret
end
private
# @private
# Check if live_streams are an array
def set_live_streams(live_streams)
if live_streams && !live_streams.is_a?(Array)
raise StreamsMustBeAnArray
end
check_and_add_live_streams(live_streams)
end
# @private
# Check for required params presence
def check_connection_configs
# Do nothing ATM
end
# @private
# Merge auto_connection_configs and custom_connection_configs
def merge_connection_configs
auto_connection_configs.merge(custom_connection_configs) do |key, old_val, new_val|
if new_val.nil?
old_val
else
new_val
end
end
end
# @private
def build_logger
logger = ::Logger.new(@log_to)
logger.level = normalize_log_level
logger.progname = 'Spacebunny'
Spacebunny.logger = logger
end
# @private
def extract_and_normalize_custom_connection_configs_from(options)
@custom_connection_configs = options
@custom_connection_configs[:logger] = @custom_connection_configs.delete(:logger) || @logger
if conn_options = @custom_connection_configs[:connection]
@custom_connection_configs[:host] = conn_options.delete :host
if conn_options[:protocols] && conn_options[:protocols][@protocol]
@custom_connection_configs[:port] = conn_options[:protocols][@protocol].delete :port
@custom_connection_configs[:tls_port] = conn_options[:protocols][@protocol].delete :tls_port
end
@custom_connection_configs[:vhost] = conn_options.delete :vhost
@custom_connection_configs[:client] = conn_options.delete :client
@custom_connection_configs[:secret] = conn_options.delete :secret
end
end
# @private
def check_and_add_live_streams(chs)
@live_streams = [] unless @live_streams
return unless chs
chs.each do |ch|
case ch
when Hash
ch.symbolize_keys!
# Check for required attributes
[:id, :name].each do |attr|
unless ch[attr]
raise LiveStreamParamError(ch[:name], attr)
end
end
@live_streams << ch
else
raise LiveStreamFormatError
end
end
end
# @private
# Translate from auto configs given by APIs endpoint to a common format
def normalize_auto_connection_configs
{
host: auto_configs[:connection][:host],
port: auto_configs[:connection][:protocols][@protocol][:port],
tls_port: auto_configs[:connection][:protocols][@protocol][:tls_port],
vhost: auto_configs[:connection][:vhost],
client: auto_configs[:connection][:client],
secret: auto_configs[:connection][:secret]
}
end
# @private
def normalize_log_level
case @log_level
when :debug, ::Logger::DEBUG, 'debug' then ::Logger::DEBUG
when :info, ::Logger::INFO, 'info' then ::Logger::INFO
when :warn, ::Logger::WARN, 'warn' then ::Logger::WARN
when :error, ::Logger::ERROR, 'error' then ::Logger::ERROR
when :fatal, ::Logger::FATAL, 'fatal' then ::Logger::FATAL
else
Logger::ERROR
end
end
end
end
end
|
module SpatialFeatures
module Validation
# SHP file must come first
REQUIRED_SHAPEFILE_COMPONENT_EXTENSIONS = %w[shp shx dbf prj].freeze
# Check if a shapefile archive includes the required component files, otherwise
# raise an exception.
#
# @param [Zip::File] zip_file A Zip::File object
# @param [String] default_proj4_projection Optional, if supplied we don't raise an exception when we're missing a .PRJ file
# @param [Boolean] allow_generic_zip_files When true, we skip validation entirely if the archive does not contain a .SHP file
def self.validate_shapefile_archive!(zip_file, default_proj4_projection: nil, allow_generic_zip_files: false)
zip_file_entries = zip_file.entries.each_with_object({}) do |f, obj|
ext = File.extname(f.name).downcase[1..-1]
next unless ext
# TODO: we can do better here
# if ext.casecmp?("shp") && obj.key?(ext)
# raise ::SpatialFeatures::Importers::InvalidShapefileArchive, "Zip files that contain multiple Shapefiles are not supported. Please separate each Shapefile into its own zip file."
# end
obj[ext] = File.basename(f.name, '.*')
end
shapefile_basename = zip_file_entries["shp"]
unless shapefile_basename
# not a shapefile archive but we don't care
return if allow_generic_zip_files
raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "Shapefile archive is missing a SHP file"
end
REQUIRED_SHAPEFILE_COMPONENT_EXTENSIONS[1..-1].each do |ext|
ext_basename = zip_file_entries[ext]
next if ext_basename&.casecmp?(shapefile_basename)
case ext
when "prj"
# special case for missing projection files to allow using default_proj4_projection
next if default_proj4_projection
raise ::SpatialFeatures::Importers::IndeterminateShapefileProjection, "Shapefile archive is missing a projection file: #{expected_component_path(shapefile_basename, ext)}"
else
# for all un-handled cases of missing files raise the more generic error
raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "Shapefile archive is missing a required file: #{expected_component_path(shapefile_basename, ext)}"
end
end
true
end
def self.expected_component_path(basename, ext)
"#{basename}.#{ext}"
end
end
end
Refactor validation to support multiple SHP files per archive
module SpatialFeatures
module Validation
REQUIRED_SHAPEFILE_COMPONENT_EXTENSIONS = %w[shp shx dbf prj].freeze
class << self
# Check if a shapefile archive includes the required component files, otherwise
# raise an exception.
#
# @param [Zip::File] zip_file A Zip::File object
# @param [String] default_proj4_projection Optional, if supplied we don't raise an exception when we're missing a .PRJ file
# @param [Boolean] allow_generic_zip_files When true, we skip validation entirely if the archive does not contain a .SHP file
def validate_shapefile_archive!(zip_file, default_proj4_projection: nil, allow_generic_zip_files: false)
contains_shp_file = false
zip_file_basenames = shapefiles_with_components(zip_file)
if zip_file_basenames.empty?
return if allow_generic_zip_files
raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "Shapefile archive is missing a SHP file"
end
zip_file_basenames.each do |basename, extensions|
validate_components_for_basename(basename, extensions, default_proj4_projection)
end
true
end
def shapefiles_with_components(zip_file)
zip_file.entries.each_with_object({}) do |f, obj|
filename = f.name
basename = File.basename(filename, '.*')
ext = File.extname(filename).downcase[1..-1]
next unless ext
obj[basename] ||= []
obj[basename] << ext
end.delete_if { |basename, exts| !exts.include?("shp") }
end
def validate_components_for_basename(basename, extensions, has_default_proj4_projection)
required_extensions = REQUIRED_SHAPEFILE_COMPONENT_EXTENSIONS
required_extensions -= ['prj'] if has_default_proj4_projection
missing_extensions = required_extensions - extensions
missing_extensions.each do |ext|
case ext
when "prj"
raise ::SpatialFeatures::Importers::IndeterminateShapefileProjection, "Shapefile archive is missing a projection file: #{expected_component_path(basename, ext)}"
else
raise ::SpatialFeatures::Importers::IncompleteShapefileArchive, "Shapefile archive is missing a required file: #{expected_component_path(basename, ext)}"
end
end
end
def expected_component_path(basename, ext)
"#{basename}.#{ext}"
end
end
end
end
|
Add command/base/cron.rb
class Specinfra::Command::Base::Cron < Specinfra::Command::Base
def check_has_entry(user, entry)
entry_escaped = entry.gsub(/\*/, '\\*').gsub(/\[/, '\\[').gsub(/\]/, '\\]')
if user.nil?
"crontab -l | grep -v \"#\" -- | grep -- #{escape(entry_escaped)}"
else
"crontab -u #{escape(user)} -l | grep -v \"#\" | grep -- #{escape(entry_escaped)}"
end
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bumbleworks/gui/version'
Gem::Specification.new do |spec|
spec.name = "bumbleworks-gui"
spec.version = Bumbleworks::Gui::VERSION
spec.authors = ["Ravi Gadad"]
spec.email = ["ravi@renewfund.com"]
spec.description = %q{Bumbleworks web GUI for viewing/administering processes}
spec.summary = %q{This gem enables a Rory application (mountable in your own app)
to make it easier to administer your Bumbleworks instance.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "bumbleworks", ">= 0.0.72"
spec.add_runtime_dependency "rory", ">= 0.3.9"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency 'shotgun'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'capybara'
spec.add_development_dependency 'simplecov'
end
Update Rory for base_url bug fix
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'bumbleworks/gui/version'
Gem::Specification.new do |spec|
spec.name = "bumbleworks-gui"
spec.version = Bumbleworks::Gui::VERSION
spec.authors = ["Ravi Gadad"]
spec.email = ["ravi@renewfund.com"]
spec.description = %q{Bumbleworks web GUI for viewing/administering processes}
spec.summary = %q{This gem enables a Rory application (mountable in your own app)
to make it easier to administer your Bumbleworks instance.}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "bumbleworks", ">= 0.0.72"
spec.add_runtime_dependency "rory", ">= 0.3.10"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency 'shotgun'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'capybara'
spec.add_development_dependency 'simplecov'
end
|
class Speck
##
# These methods, when mixed into their respective classes, provide some
# conveniences when it comes to creating `Check`s.
module Mixins
##
# This method will quickly mix all of our `Mixins` into their respective
# targets.
def self.mixin!
Speck::Mixins.constants
.map {|mod| Speck::Mixins.const_get(mod) }
.each {|mod| mod::Target.send :include, mod }
end
module Object; Target = ::Object
##
# This method is responsible for running some sort of test on the
# receiver.
#
# It expects a block (returning true or false) to be passed. The block
# will be passed the receiver, so you can run comparators on it, or
# whatever else you like.
#
# `#check` can also be called without block on truthy objects (`true`,
# `false`, or `nil`, any other object will be treated as `true`)
def check &check
check = ->(_){self} unless block_given?
file, line, _ = Kernel::caller.first.split(':')
source = File.open(file).readlines[line.to_i - 1]
source.strip!
source = source.partition(".check").first
# TODO: Should we allow specks in the root environment? Could be useful
# for quick checks…
raise Exception::NoEnvironment unless Speck.current
Speck.current.checks <<
Speck::Check.new(->(){ check[self] }, source)
end
end
end
end
Moved the exception checking in #check
class Speck
##
# These methods, when mixed into their respective classes, provide some
# conveniences when it comes to creating `Check`s.
module Mixins
##
# This method will quickly mix all of our `Mixins` into their respective
# targets.
def self.mixin!
Speck::Mixins.constants
.map {|mod| Speck::Mixins.const_get(mod) }
.each {|mod| mod::Target.send :include, mod }
end
module Object; Target = ::Object
##
# This method is responsible for running some sort of test on the
# receiver.
#
# It expects a block (returning true or false) to be passed. The block
# will be passed the receiver, so you can run comparators on it, or
# whatever else you like.
#
# `#check` can also be called without block on truthy objects (`true`,
# `false`, or `nil`, any other object will be treated as `true`)
def check &check
check = ->(_){self} unless block_given?
# TODO: Should we allow specks in the root environment? Could be useful
# for quick checks…
raise Exception::NoEnvironment unless Speck.current
file, line, _ = Kernel::caller.first.split(':')
source = File.open(file).readlines[line.to_i - 1]
source.strip!
source = source.partition(".check").first
Speck.current.checks <<
Speck::Check.new(->(){ check[self] }, source)
end
end
end
end
|
require 'tsort'
module Spider; module Model
class UnitOfWork
include TSort
def initialize(&proc)
@objects = {}
@actions = {}
@to_delete = {}
@new_objects = []
if (proc)
start
yield self
stop
end
end
def start
Spider.current[:unit_of_work] = self
end
def stop
Spider.current[:unit_of_work] = nil
end
def run #(&proc)
#proc.call
@tasks = {}
@processed_tasks = {}
while objs = new_objects
objs.each do |obj|
@actions[obj.object_id].each do |action, params|
if action == :save
next unless obj.mapper && obj.mapper.class.write?
next unless obj.modified?
obj.save_mode do
obj.before_save
end
elsif action == :delete
obj.before_delete
end
end
end
end
@running = true
@objects.each do |obj_id, obj|
@actions[obj_id].each do |action, params|
if action == :save
next unless obj.mapper && obj.mapper.class.write?
next unless obj.modified?
end
task = Spider::Model::MapperTask.new(obj, action, params)
@tasks[task] = task
find_dependencies(task)
end
end
tasks = tsort()
Spider.logger.debug("Tasks:")
tasks.each do |task|
Spider.logger.debug "-- #{task.action} on #{task.object.class} #{task.object.primary_keys}"
end
tasks.each do |task|
#Spider::Logger.debug("Executing task #{task.inspect}")
task.execute()
end
@objects = {}
@new_objects = []
@running = false
end
def running?
@running
end
alias :commit :run
def find_dependencies(model_task)
return if (@processed_tasks[model_task])
@processed_tasks[model_task] = true
dependencies = model_task.object.mapper.get_dependencies(model_task.object, model_task.action).uniq
dependencies.each do |dep|
had0 = @tasks[dep[0]]
@tasks[dep[0]] ||= dep[0]
had1 = @tasks[dep[1]]
@tasks[dep[1]] ||= dep[1]
@tasks[dep[0]] << @tasks[dep[1]]
find_dependencies(dep[0]) unless had0
find_dependencies(dep[1]) unless had1
end
end
def add(obj, action = :save, params = {})
raise "Objects can't be added to the UnitOfWork while it is running" if @running
if (obj.class == QuerySet)
obj.each do |item|
add(item, action, params)
end
return
end
curr = @actions[obj.object_id]
if curr && (curr_act = curr.select{ |c| c[0] == action }).length > 0
curr_act.each{ |c| c[1] = params}
return
end
if action == :delete # FIXME: abstract
@actions[obj.object_id] = []
end
@actions[obj.object_id] ||= []
@actions[obj.object_id] << [action, params]
@objects[obj.object_id] = obj
@new_objects << obj unless curr
traverse(obj, action, params) if action == :save
end
def traverse(obj, action, params)
obj.class.elements_array.each do |el|
next unless obj.element_has_value?(el)
next unless el.model?
add(obj.get(el), action, params)
end
end
def to_delete(obj)
end
def new_objects
objects = @new_objects.clone
@new_objects = []
objects.length > 0 ? objects : nil
end
def tsort_each_node(&block)
@tasks.values.each(&block)
end
def tsort_each_child(node, &block)
node.dependencies.each(&block)
end
end
end; end
Process dependencies after filling the @tasks array, to ensure newly added tasks have their dependencies resolved
require 'tsort'
module Spider; module Model
class UnitOfWork
include TSort
def initialize(&proc)
@objects = {}
@actions = {}
@to_delete = {}
@new_objects = []
if (proc)
start
yield self
stop
end
end
def start
Spider.current[:unit_of_work] = self
end
def stop
Spider.current[:unit_of_work] = nil
end
def run #(&proc)
#proc.call
@tasks = {}
@processed_tasks = {}
while objs = new_objects
objs.each do |obj|
@actions[obj.object_id].each do |action, params|
if action == :save
next unless obj.mapper && obj.mapper.class.write?
next unless obj.modified?
obj.save_mode do
obj.before_save
end
elsif action == :delete
obj.before_delete
end
end
end
end
@running = true
@objects.each do |obj_id, obj|
@actions[obj_id].each do |action, params|
if action == :save
next unless obj.mapper && obj.mapper.class.write?
next unless obj.modified?
end
task = Spider::Model::MapperTask.new(obj, action, params)
@tasks[task] = task
end
end
@tasks.clone.each do |k, task|
find_dependencies(task)
end
tasks = tsort()
Spider.logger.debug("Tasks:")
tasks.each do |task|
Spider.logger.debug "-- #{task.action} on #{task.object.class} #{task.object.primary_keys}"
end
tasks.each do |task|
#Spider::Logger.debug("Executing task #{task.inspect}")
task.execute()
end
@objects = {}
@new_objects = []
@running = false
end
def running?
@running
end
alias :commit :run
def find_dependencies(model_task)
return if (@processed_tasks[model_task])
@processed_tasks[model_task] = true
dependencies = model_task.object.mapper.get_dependencies(model_task.object, model_task.action).uniq
dependencies.each do |dep|
had0 = @tasks[dep[0]]
@tasks[dep[0]] ||= dep[0]
had1 = @tasks[dep[1]]
@tasks[dep[1]] ||= dep[1]
@tasks[dep[0]] << @tasks[dep[1]]
find_dependencies(dep[0]) unless had0
find_dependencies(dep[1]) unless had1
end
end
def add(obj, action = :save, params = {})
raise "Objects can't be added to the UnitOfWork while it is running" if @running
if (obj.class == QuerySet)
obj.each do |item|
add(item, action, params)
end
return
end
curr = @actions[obj.object_id]
if curr && (curr_act = curr.select{ |c| c[0] == action }).length > 0
curr_act.each{ |c| c[1] = params}
return
end
if action == :delete # FIXME: abstract
@actions[obj.object_id] = []
end
@actions[obj.object_id] ||= []
@actions[obj.object_id] << [action, params]
@objects[obj.object_id] = obj
@new_objects << obj unless curr
traverse(obj, action, params) if action == :save
end
def traverse(obj, action, params)
obj.class.elements_array.each do |el|
next unless obj.element_has_value?(el)
next unless el.model?
add(obj.get(el), action, params)
end
end
def to_delete(obj)
end
def new_objects
objects = @new_objects.clone
@new_objects = []
objects.length > 0 ? objects : nil
end
def tsort_each_node(&block)
@tasks.values.each(&block)
end
def tsort_each_child(node, &block)
node.dependencies.each(&block)
end
end
end; end |
# 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 = %q{cantango-config}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = [%q{Kristian Mandrup}]
s.date = %q{2011-11-25}
s.description = %q{Configuration DSL for configuring CanTango}
s.email = %q{kmandrup@gmail.com}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.mdown"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.mdown",
"Rakefile",
"VERSION",
"cantango-config.gemspec",
"lib/cantango/adapter/compiler.rb",
"lib/cantango/adapter/moneta.rb",
"lib/cantango/class_methods.rb",
"lib/cantango/config.rb",
"lib/cantango/configuration.rb",
"lib/cantango/configuration/ability.rb",
"lib/cantango/configuration/account.rb",
"lib/cantango/configuration/accounts.rb",
"lib/cantango/configuration/adapters.rb",
"lib/cantango/configuration/autoload.rb",
"lib/cantango/configuration/categories.rb",
"lib/cantango/configuration/debug.rb",
"lib/cantango/configuration/engine.rb",
"lib/cantango/configuration/engines.rb",
"lib/cantango/configuration/factory.rb",
"lib/cantango/configuration/guest.rb",
"lib/cantango/configuration/hooks.rb",
"lib/cantango/configuration/localhosts.rb",
"lib/cantango/configuration/models.rb",
"lib/cantango/configuration/models/actions.rb",
"lib/cantango/configuration/models/active_record.rb",
"lib/cantango/configuration/models/data_mapper.rb",
"lib/cantango/configuration/models/generic.rb",
"lib/cantango/configuration/models/mongo.rb",
"lib/cantango/configuration/models/mongo_mapper.rb",
"lib/cantango/configuration/models/mongoid.rb",
"lib/cantango/configuration/modes.rb",
"lib/cantango/configuration/orms.rb",
"lib/cantango/configuration/registry.rb",
"lib/cantango/configuration/registry/base.rb",
"lib/cantango/configuration/registry/candidate.rb",
"lib/cantango/configuration/registry/hash.rb",
"lib/cantango/configuration/user.rb",
"lib/cantango/configuration/users.rb",
"spec/cantango/config_spec.rb",
"spec/cantango/configuration/ability_spec.rb",
"spec/cantango/configuration/account_spec.rb",
"spec/cantango/configuration/accounts_spec.rb",
"spec/cantango/configuration/adapters_spec.rb",
"spec/cantango/configuration/autoload_spec.rb",
"spec/cantango/configuration/categories_spec.rb",
"spec/cantango/configuration/debug_spec.rb",
"spec/cantango/configuration/engines/engine_shared.rb",
"spec/cantango/configuration/engines_spec.rb",
"spec/cantango/configuration/factory_spec.rb",
"spec/cantango/configuration/guest/find_guest_default_way_spec.rb",
"spec/cantango/configuration/guest_spec.rb",
"spec/cantango/configuration/localhosts_spec.rb",
"spec/cantango/configuration/models_spec.rb",
"spec/cantango/configuration/orms_spec.rb",
"spec/cantango/configuration/registry/base_spec.rb",
"spec/cantango/configuration/registry/candidate_spec.rb",
"spec/cantango/configuration/registry/hash_spec.rb",
"spec/cantango/configuration/shared/factory_ex.rb",
"spec/cantango/configuration/shared/modes_ex.rb",
"spec/cantango/configuration/shared/registry/base_ex.rb",
"spec/cantango/configuration/shared/registry/candidate_ex.rb",
"spec/cantango/configuration/shared/registry/hash_ex.rb",
"spec/cantango/configuration/user_spec.rb",
"spec/cantango/configuration/users_spec.rb",
"spec/cantango/configuration_spec.rb",
"spec/db/database.yml",
"spec/factories/project.rb",
"spec/fixtures/models.rb",
"spec/fixtures/models/admin.rb",
"spec/fixtures/models/admin_account.rb",
"spec/fixtures/models/items.rb",
"spec/fixtures/models/permission.rb",
"spec/fixtures/models/project.rb",
"spec/fixtures/models/simple_roles.rb",
"spec/fixtures/models/user.rb",
"spec/fixtures/models/user_account.rb",
"spec/migrations/001_create_projects.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/kristianmandrup/cantango-config}
s.licenses = [%q{MIT}]
s.require_paths = [%q{lib}]
s.rubygems_version = %q{1.8.6}
s.summary = %q{Configuration for Cantango}
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_runtime_dependency(%q<rails>, [">= 3.1"])
s.add_runtime_dependency(%q<sugar-high>, [">= 0.6.0"])
s.add_runtime_dependency(%q<sweetloader>, ["~> 0.1.0"])
s.add_runtime_dependency(%q<hashie>, [">= 0"])
s.add_runtime_dependency(%q<cantango-core>, [">= 0"])
s.add_development_dependency(%q<bundler>, [">= 1.1.rc"])
s.add_development_dependency(%q<jeweler>, [">= 1.6.4"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 2.6.0"])
else
s.add_dependency(%q<rails>, [">= 3.1"])
s.add_dependency(%q<sugar-high>, [">= 0.6.0"])
s.add_dependency(%q<sweetloader>, ["~> 0.1.0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<cantango-core>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.1.rc"])
s.add_dependency(%q<jeweler>, [">= 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.6.0"])
end
else
s.add_dependency(%q<rails>, [">= 3.1"])
s.add_dependency(%q<sugar-high>, [">= 0.6.0"])
s.add_dependency(%q<sweetloader>, ["~> 0.1.0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<cantango-core>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.1.rc"])
s.add_dependency(%q<jeweler>, [">= 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.6.0"])
end
end
Regenerate gemspec for version 0.1.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 = %q{cantango-config}
s.version = "0.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = [%q{Kristian Mandrup}]
s.date = %q{2011-11-25}
s.description = %q{Configuration DSL for configuring CanTango}
s.email = %q{kmandrup@gmail.com}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.mdown"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.mdown",
"Rakefile",
"VERSION",
"cantango-config.gemspec",
"lib/cantango/adapter/compiler.rb",
"lib/cantango/adapter/moneta.rb",
"lib/cantango/class_methods.rb",
"lib/cantango/config.rb",
"lib/cantango/configuration.rb",
"lib/cantango/configuration/ability.rb",
"lib/cantango/configuration/account.rb",
"lib/cantango/configuration/accounts.rb",
"lib/cantango/configuration/adapters.rb",
"lib/cantango/configuration/autoload.rb",
"lib/cantango/configuration/categories.rb",
"lib/cantango/configuration/debug.rb",
"lib/cantango/configuration/engine.rb",
"lib/cantango/configuration/engines.rb",
"lib/cantango/configuration/factory.rb",
"lib/cantango/configuration/guest.rb",
"lib/cantango/configuration/hooks.rb",
"lib/cantango/configuration/localhosts.rb",
"lib/cantango/configuration/models.rb",
"lib/cantango/configuration/models/actions.rb",
"lib/cantango/configuration/models/active_record.rb",
"lib/cantango/configuration/models/data_mapper.rb",
"lib/cantango/configuration/models/generic.rb",
"lib/cantango/configuration/models/mongo.rb",
"lib/cantango/configuration/models/mongo_mapper.rb",
"lib/cantango/configuration/models/mongoid.rb",
"lib/cantango/configuration/modes.rb",
"lib/cantango/configuration/orms.rb",
"lib/cantango/configuration/registry.rb",
"lib/cantango/configuration/registry/base.rb",
"lib/cantango/configuration/registry/candidate.rb",
"lib/cantango/configuration/registry/hash.rb",
"lib/cantango/configuration/user.rb",
"lib/cantango/configuration/users.rb",
"spec/cantango/config_spec.rb",
"spec/cantango/configuration/ability_spec.rb",
"spec/cantango/configuration/account_spec.rb",
"spec/cantango/configuration/accounts_spec.rb",
"spec/cantango/configuration/adapters_spec.rb",
"spec/cantango/configuration/autoload_spec.rb",
"spec/cantango/configuration/categories_spec.rb",
"spec/cantango/configuration/debug_spec.rb",
"spec/cantango/configuration/engines/engine_shared.rb",
"spec/cantango/configuration/engines_spec.rb",
"spec/cantango/configuration/factory_spec.rb",
"spec/cantango/configuration/guest/find_guest_default_way_spec.rb",
"spec/cantango/configuration/guest_spec.rb",
"spec/cantango/configuration/localhosts_spec.rb",
"spec/cantango/configuration/models_spec.rb",
"spec/cantango/configuration/orms_spec.rb",
"spec/cantango/configuration/registry/base_spec.rb",
"spec/cantango/configuration/registry/candidate_spec.rb",
"spec/cantango/configuration/registry/hash_spec.rb",
"spec/cantango/configuration/shared/factory_ex.rb",
"spec/cantango/configuration/shared/modes_ex.rb",
"spec/cantango/configuration/shared/registry/base_ex.rb",
"spec/cantango/configuration/shared/registry/candidate_ex.rb",
"spec/cantango/configuration/shared/registry/hash_ex.rb",
"spec/cantango/configuration/user_spec.rb",
"spec/cantango/configuration/users_spec.rb",
"spec/cantango/configuration_spec.rb",
"spec/db/database.yml",
"spec/factories/project.rb",
"spec/fixtures/models.rb",
"spec/fixtures/models/admin.rb",
"spec/fixtures/models/admin_account.rb",
"spec/fixtures/models/items.rb",
"spec/fixtures/models/permission.rb",
"spec/fixtures/models/project.rb",
"spec/fixtures/models/simple_roles.rb",
"spec/fixtures/models/user.rb",
"spec/fixtures/models/user_account.rb",
"spec/migrations/001_create_projects.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/kristianmandrup/cantango-config}
s.licenses = [%q{MIT}]
s.require_paths = [%q{lib}]
s.rubygems_version = %q{1.8.6}
s.summary = %q{Configuration for Cantango}
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_runtime_dependency(%q<rails>, [">= 3.1"])
s.add_runtime_dependency(%q<sugar-high>, [">= 0.6.0"])
s.add_runtime_dependency(%q<sweetloader>, ["~> 0.1.0"])
s.add_runtime_dependency(%q<hashie>, [">= 0"])
s.add_runtime_dependency(%q<cantango-core>, [">= 0"])
s.add_development_dependency(%q<bundler>, [">= 1.1.rc"])
s.add_development_dependency(%q<jeweler>, [">= 1.6.4"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 2.6.0"])
else
s.add_dependency(%q<rails>, [">= 3.1"])
s.add_dependency(%q<sugar-high>, [">= 0.6.0"])
s.add_dependency(%q<sweetloader>, ["~> 0.1.0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<cantango-core>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.1.rc"])
s.add_dependency(%q<jeweler>, [">= 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.6.0"])
end
else
s.add_dependency(%q<rails>, [">= 3.1"])
s.add_dependency(%q<sugar-high>, [">= 0.6.0"])
s.add_dependency(%q<sweetloader>, ["~> 0.1.0"])
s.add_dependency(%q<hashie>, [">= 0"])
s.add_dependency(%q<cantango-core>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.1.rc"])
s.add_dependency(%q<jeweler>, [">= 1.6.4"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.6.0"])
end
end
|
class KubernetesCli < Formula
desc "Kubernetes command-line interface"
homepage "http://kubernetes.io/"
head "https://github.com/kubernetes/kubernetes.git"
stable do
url "https://github.com/kubernetes/kubernetes/archive/v1.1.2.tar.gz"
sha256 "ffbbf62d7fa324b6f4c3dcdb229e028204ec458f7f78fbf87856a72ab29ec942"
end
bottle do
cellar :any_skip_relocation
sha256 "9c8d0f91dc6e9978d51e655ea177b8beb9af9fc6df3eaf804efef6f566f5b59c" => :el_capitan
sha256 "253a47d08e635d4e2ff5b767afe807fdcc0427dedcc105f397893df8b433e76b" => :yosemite
sha256 "ff8685eede53a1c4a5a6ec00ea16df39dca651202c888318845414cb745756de" => :mavericks
end
devel do
url "https://github.com/kubernetes/kubernetes/archive/v1.2.0-alpha.4.tar.gz"
sha256 "0c1d1a57ceb5beffcc7f8852d0d680ee37fc8e21814c74a0ea09e711e2c8aa44"
version "1.2.0-alpha.4"
end
depends_on "go" => :build
def install
arch = MacOS.prefer_64_bit? ? "amd64" : "x86"
system "make", "all", "WHAT=cmd/kubectl", "GOFLAGS=-v"
dir = "_output/local/bin/darwin/#{arch}"
bin.install "#{dir}/kubectl"
end
test do
assert_match /^kubectl controls the Kubernetes cluster manager./, shell_output("#{bin}/kubectl 2>&1", 0)
end
end
kubectl 1.1.3
Closes #46842.
Signed-off-by: Dominyk Tiller <53e438f55903875d07efdd98a8aaf887e7208dd3@gmail.com>
class KubernetesCli < Formula
desc "Kubernetes command-line interface"
homepage "http://kubernetes.io/"
head "https://github.com/kubernetes/kubernetes.git"
stable do
url "https://github.com/kubernetes/kubernetes/archive/v1.1.3.tar.gz"
sha256 "b844e82fad688f62ed29ede1c61677d45d1a4c4c52ac08958e3ad1e650c10756"
end
bottle do
cellar :any_skip_relocation
sha256 "9c8d0f91dc6e9978d51e655ea177b8beb9af9fc6df3eaf804efef6f566f5b59c" => :el_capitan
sha256 "253a47d08e635d4e2ff5b767afe807fdcc0427dedcc105f397893df8b433e76b" => :yosemite
sha256 "ff8685eede53a1c4a5a6ec00ea16df39dca651202c888318845414cb745756de" => :mavericks
end
devel do
url "https://github.com/kubernetes/kubernetes/archive/v1.2.0-alpha.4.tar.gz"
sha256 "0c1d1a57ceb5beffcc7f8852d0d680ee37fc8e21814c74a0ea09e711e2c8aa44"
version "1.2.0-alpha.4"
end
depends_on "go" => :build
def install
arch = MacOS.prefer_64_bit? ? "amd64" : "x86"
system "make", "all", "WHAT=cmd/kubectl", "GOFLAGS=-v"
dir = "_output/local/bin/darwin/#{arch}"
bin.install "#{dir}/kubectl"
end
test do
assert_match /^kubectl controls the Kubernetes cluster manager./, shell_output("#{bin}/kubectl 2>&1", 0)
end
end
|
module Sportradar
module Nba
module Models
class Event
def initialize(quarter:, attributes:)
@quarter = quarter
@attributes = attributes
build_statistics
end
def to_s
[].tap do |sentence_parts|
sentence_parts << quarter_number
sentence_parts << clock
sentence_parts << team_name if has_team?
sentence_parts << team_basket if has_team?
sentence_parts << event_type
sentence_parts << description
sentence_parts << free_throw_attempt
sentence_parts << free_throw_attempt_of
sentence_parts << turnover_type
sentence_parts << "[#{coordinate_x}, #{coordinate_y}]" if coordinates?
end.compact.
join(' - ')
end
def id
@attributes['id']
end
def game_id
quarter.game_id
end
def possession?
possession.present?
end
def possession
@attributes['possession'] || {}
end
def possession_team_id
possession_team.dig('id')
end
def possession_team_name
possession.dig('name')
end
def team
@attributes['attribution'] || {}
end
def team_id
team.dig('id')
end
def team_name
team.dig('name')
end
def team_basket
team.dig('team_basket')
end
def has_team?
!team_id.nil?
end
def quarter
@quarter
end
def quarter_id
@quarter.id
end
def quarter_number
@quarter.number
end
def time_code
min, sec = clock.split(':').map(&:to_i)
"PT#{min}M#{sec}S"
end
def clock
@attributes['clock'] || '0'
end
def clock_secs
begin
if clock && clock.include?(':')
mins, secs = clock.split(':').map(&:to_i)
Time.parse("00:#{mins}:#{secs}").
seconds_since_midnight.to_i
end
rescue => e
return 0
end
end
alias_method :quarter_seconds, :clock_secs
def id
@attributes['id']
end
def attempt_in_words
@attributes['attempt']
end
def attempt_matches
/(\d) of (\d)/.match(attempt_in_words)
end
def free_throw_attempt
if matches = attempt_matches
matches[0].to_i
end
end
def free_throw_attempt_of
if matches = attempt_matches
matches[1].to_i
end
end
def description
@attributes['description'] || 0
end
def event_type
@attributes['event_type']
end
def coordinates
@attributes['location'] || {}
end
def coordinates?
@attributes['location'].present?
end
def coordinate_x
coordinates['coord_x']
end
def coordinate_y
coordinates['coord_y']
end
def turnover_type
@attributes['turnover_type']
end
def updated_at
@attributes['updated']
end
def statistics
@attributes['statistics'] || []
end
def field_goal?
event_type.include?('field_goal')
end
def field_goal
self if field_goal?
end
def foul?
event_type.include?('foul') || event_type.include?('flagrant')
end
def foul
self if foul?
end
def free_throw?
event_type.include?('free_throw')
end
def free_throw
self if free_throw?
end
def made?
event_type.include?('made')
end
def miss?
event_type.include?('miss')
end
def scoring_play?
event_type.include?('made')
end
def scoring_play
self if scoring_play?
end
def stoppage?
%w(endperiod delay officialtimeout review teamtimeout tvtimeout).include?(event_type)
end
def stoppage
self if stoppage?
end
def turnover?
event_type.include?('turnover')
end
def turnover
self if turnover?
end
def play_player_stats
@play_player_stats ||= []
end
def scoring_players
@scoring_players ||= []
end
def on_court_players
@on_court_players ||= on_court_away_players + on_court_home_players
end
def on_court_away_team_id
@on_court_away_team_id ||= @attributes.dig('on_court', 'away', 'id')
end
def on_court_away_team_name
@on_court_away_team_name ||= @attributes.dig('on_court', 'away', 'name')
end
def on_court_away_players
(@attributes.dig('on_court', 'away', 'players') || {}).map do |player|
Models::OnCourtPlayer.new(
player.reverse_merge({
'event_id' => id,
'player_id' => player['id'],
'team_id' => on_court_away_team_id,
'team_name' => on_court_away_team_name,
})
)
end
end
def on_court_home_team_id
@on_court_home_team_id ||= @attributes.dig('on_court', 'home', 'id')
end
def on_court_home_team_name
@on_court_home_team_name ||= @attributes.dig('on_court', 'home', 'name')
end
def on_court_home_players
(@attributes.dig('on_court', 'home', 'players') || {}).map do |player|
Models::OnCourtPlayer.new(
player.reverse_merge({
'event_id' => id,
'player_id' => player['id'],
'team_id' => on_court_home_team_id,
'team_name' => on_court_home_team_name,
})
)
end
end
private
def build_statistics
statistics.each do |statistic|
play_player_stats << Models::PlayPlayerStat.new(event: self, attributes: statistic)
scoring_players << Models::ScoringPlayer.new(event: self, attributes: statistic) if scoring_play?
end
end
end
end
end
end
Change rule for determining if a basketball field goal in the event
module Sportradar
module Nba
module Models
class Event
def initialize(quarter:, attributes:)
@quarter = quarter
@attributes = attributes
build_statistics
end
def to_s
[].tap do |sentence_parts|
sentence_parts << quarter_number
sentence_parts << clock
sentence_parts << team_name if has_team?
sentence_parts << team_basket if has_team?
sentence_parts << event_type
sentence_parts << description
sentence_parts << free_throw_attempt
sentence_parts << free_throw_attempt_of
sentence_parts << turnover_type
sentence_parts << "[#{coordinate_x}, #{coordinate_y}]" if coordinates?
end.compact.
join(' - ')
end
def id
@attributes['id']
end
def game_id
quarter.game_id
end
def possession?
possession.present?
end
def possession
@attributes['possession'] || {}
end
def possession_team_id
possession.dig('id')
end
def possession_team_name
possession.dig('name')
end
def team
@attributes['attribution'] || {}
end
def team_id
team.dig('id')
end
def team_name
team.dig('name')
end
def team_basket
team.dig('team_basket')
end
def has_team?
!team_id.nil?
end
def quarter
@quarter
end
def quarter_id
@quarter.id
end
def quarter_number
@quarter.number
end
def time_code
min, sec = clock.split(':').map(&:to_i)
"PT#{min}M#{sec}S"
end
def clock
@attributes['clock'] || '0'
end
def clock_secs
begin
if clock && clock.include?(':')
mins, secs = clock.split(':').map(&:to_i)
Time.parse("00:#{mins}:#{secs}").
seconds_since_midnight.to_i
end
rescue => e
return 0
end
end
alias_method :quarter_seconds, :clock_secs
def id
@attributes['id']
end
def attempt_in_words
@attributes['attempt']
end
def attempt_matches
/(\d) of (\d)/.match(attempt_in_words)
end
def free_throw_attempt
if matches = attempt_matches
matches[0].to_i
end
end
def free_throw_attempt_of
if matches = attempt_matches
matches[1].to_i
end
end
def description
@attributes['description'] || 0
end
def event_type
@attributes['event_type']
end
def coordinates
@attributes['location'] || {}
end
def coordinates?
@attributes['location'].present?
end
def coordinate_x
coordinates['coord_x']
end
def coordinate_y
coordinates['coord_y']
end
def turnover_type
@attributes['turnover_type']
end
def updated_at
@attributes['updated']
end
def statistics
@attributes['statistics'] || []
end
def field_goal?
two_pointer? || three_pointer?
end
def field_goal
self if field_goal?
end
def three_pointer?
event_type.include?('threepoint')
end
def three_pointer
self if three_pointer?
end
def two_pointer?
event_type.include?('twopoint')
end
def two_pointer
self if two_pointer?
end
def foul?
event_type.include?('foul') || event_type.include?('flagrant')
end
def foul
self if foul?
end
def free_throw?
event_type.include?('free_throw')
end
def free_throw
self if free_throw?
end
def made?
event_type.include?('made')
end
def miss?
event_type.include?('miss')
end
def scoring_play?
event_type.include?('made')
end
def scoring_play
self if scoring_play?
end
def stoppage?
%w(endperiod delay officialtimeout review teamtimeout tvtimeout).include?(event_type)
end
def stoppage
self if stoppage?
end
def turnover?
event_type.include?('turnover')
end
def turnover
self if turnover?
end
def play_player_stats
@play_player_stats ||= []
end
def scoring_players
@scoring_players ||= []
end
def on_court_players
@on_court_players ||= on_court_away_players + on_court_home_players
end
def on_court_away_team_id
@on_court_away_team_id ||= @attributes.dig('on_court', 'away', 'id')
end
def on_court_away_team_name
@on_court_away_team_name ||= @attributes.dig('on_court', 'away', 'name')
end
def on_court_away_players
(@attributes.dig('on_court', 'away', 'players') || {}).map do |player|
Models::OnCourtPlayer.new(
player.reverse_merge({
'event_id' => id,
'player_id' => player['id'],
'team_id' => on_court_away_team_id,
'team_name' => on_court_away_team_name,
})
)
end
end
def on_court_home_team_id
@on_court_home_team_id ||= @attributes.dig('on_court', 'home', 'id')
end
def on_court_home_team_name
@on_court_home_team_name ||= @attributes.dig('on_court', 'home', 'name')
end
def on_court_home_players
(@attributes.dig('on_court', 'home', 'players') || {}).map do |player|
Models::OnCourtPlayer.new(
player.reverse_merge({
'event_id' => id,
'player_id' => player['id'],
'team_id' => on_court_home_team_id,
'team_name' => on_court_home_team_name,
})
)
end
end
private
def build_statistics
statistics.each do |statistic|
play_player_stats << Models::PlayPlayerStat.new(event: self, attributes: statistic)
scoring_players << Models::ScoringPlayer.new(event: self, attributes: statistic) if scoring_play?
end
end
end
end
end
end
|
require 'formula'
class PerconaServer < Formula
homepage 'http://www.percona.com'
url 'http://www.percona.com/redir/downloads/Percona-Server-5.6/LATEST/source/Percona-Server-5.6.14-rel62.0.tar.gz'
version '5.6.14-rel62.0'
sha1 '6d9ddd92338c70ec13bdeb9a23568a990a5766f9'
depends_on 'cmake' => :build
depends_on 'pidof' unless MacOS.version >= :mountain_lion
option :universal
option 'with-tests', 'Build with unit tests'
option 'with-embedded', 'Build the embedded server'
option 'with-memcached', 'Build with InnoDB Memcached plugin'
option 'enable-local-infile', 'Build with local infile loading support'
conflicts_with 'mysql-connector-c',
:because => 'both install `mysql_config`'
conflicts_with 'mariadb', 'mysql', 'mysql-cluster',
:because => "percona, mariadb, and mysql install the same binaries."
conflicts_with 'mysql-connector-c',
:because => 'both install MySQL client libraries'
env :std if build.universal?
fails_with :llvm do
build 2334
cause "https://github.com/Homebrew/homebrew/issues/issue/144"
end
# Where the database files should be located. Existing installs have them
# under var/percona, but going forward they will be under var/msyql to be
# shared with the mysql and mariadb formulae.
def datadir
@datadir ||= (var/'percona').directory? ? var/'percona' : var/'mysql'
end
def patches
# Fixes percona server 5.6 compilation on OS X 10.9, based on
# https://github.com/Homebrew/homebrew/commit/aad5d93f4fabbf69766deb83780d3a6eeab7061a
# for mysql 5.6
"https://gist.github.com/israelshirk/7cc640498cf264ebfce3/raw/846839c84647c4190ad683e4cbf0fabcd8931f97/gistfile1.txt"
end
def install
# Don't hard-code the libtool path. See:
# https://github.com/Homebrew/homebrew/issues/20185
inreplace "cmake/libutils.cmake",
"COMMAND /usr/bin/libtool -static -o ${TARGET_LOCATION}",
"COMMAND libtool -static -o ${TARGET_LOCATION}"
# Build without compiler or CPU specific optimization flags to facilitate
# compilation of gems and other software that queries `mysql-config`.
ENV.minimal_optimization
args = %W[
-DCMAKE_INSTALL_PREFIX=#{prefix}
-DCMAKE_FIND_FRAMEWORK=LAST
-DCMAKE_VERBOSE_MAKEFILE=ON
-DMYSQL_DATADIR=#{datadir}
-DINSTALL_INCLUDEDIR=include/mysql
-DINSTALL_MANDIR=share/man
-DINSTALL_DOCDIR=share/doc/#{name}
-DINSTALL_INFODIR=share/info
-DINSTALL_MYSQLSHAREDIR=share/mysql
-DWITH_SSL=yes
-DDEFAULT_CHARSET=utf8
-DDEFAULT_COLLATION=utf8_general_ci
-DSYSCONFDIR=#{etc}
-DCOMPILATION_COMMENT=Homebrew
-DWITH_EDITLINE=system
-DCMAKE_BUILD_TYPE=RelWithDebInfo
]
# PAM plugin is Linux-only at the moment
args.concat %W[
-DWITHOUT_AUTH_PAM=1
-DWITHOUT_AUTH_PAM_COMPAT=1
-DWITHOUT_DIALOG=1
]
# To enable unit testing at build, we need to download the unit testing suite
if build.with? 'tests'
args << "-DENABLE_DOWNLOADS=ON"
else
args << "-DWITH_UNIT_TESTS=OFF"
end
# Build the embedded server
args << "-DWITH_EMBEDDED_SERVER=ON" if build.with? 'embedded'
# Build with InnoDB Memcached plugin
args << "-DWITH_INNODB_MEMCACHED=ON" if build.with? 'memcached'
# Make universal for binding to universal applications
args << "-DCMAKE_OSX_ARCHITECTURES='#{Hardware::CPU.universal_archs.as_cmake_arch_flags}'" if build.universal?
# Build with local infile loading support
args << "-DENABLED_LOCAL_INFILE=1" if build.include? 'enable-local-infile'
system "cmake", *args
system "make"
# Reported upstream:
# http://bugs.mysql.com/bug.php?id=69645
inreplace "scripts/mysql_config", / +-Wno[\w-]+/, ""
system "make install"
# Don't create databases inside of the prefix!
# See: https://github.com/Homebrew/homebrew/issues/4975
rm_rf prefix+'data'
# Link the setup script into bin
ln_s prefix+'scripts/mysql_install_db', bin+'mysql_install_db'
# Fix up the control script and link into bin
inreplace "#{prefix}/support-files/mysql.server" do |s|
s.gsub!(/^(PATH=".*)(")/, "\\1:#{HOMEBREW_PREFIX}/bin\\2")
# pidof can be replaced with pgrep from proctools on Mountain Lion
s.gsub!(/pidof/, 'pgrep') if MacOS.version >= :mountain_lion
end
ln_s "#{prefix}/support-files/mysql.server", bin
# Move mysqlaccess to libexec
mv "#{bin}/mysqlaccess", libexec
mv "#{bin}/mysqlaccess.conf", libexec
# Make sure that data directory exists
datadir.mkpath
end
def post_install
unless File.exist? "#{datadir}/mysql/user.frm"
ENV['TMPDIR'] = nil
system "#{bin}/mysql_install_db", "--verbose", "--user=#{ENV["USER"]}",
"--basedir=#{prefix}", "--datadir=#{datadir}", "--tmpdir=/tmp"
end
end
def caveats; <<-EOS.undent
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
To connect:
mysql -uroot
EOS
end
plist_options :manual => 'mysql.server start'
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>#{plist_name}</string>
<key>Program</key>
<string>#{opt_prefix}/bin/mysqld_safe</string>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
</dict>
</plist>
EOS
end
end
percona-server: fix url.
Closes #25351.
require 'formula'
class PerconaServer < Formula
homepage 'http://www.percona.com'
url 'http://www.percona.com/redir/downloads/Percona-Server-5.6/Percona-Server-5.6.14-rel62.0/source/Percona-Server-5.6.14-rel62.0.tar.gz'
version '5.6.14-rel62.0'
sha1 '6d9ddd92338c70ec13bdeb9a23568a990a5766f9'
depends_on 'cmake' => :build
depends_on 'pidof' unless MacOS.version >= :mountain_lion
option :universal
option 'with-tests', 'Build with unit tests'
option 'with-embedded', 'Build the embedded server'
option 'with-memcached', 'Build with InnoDB Memcached plugin'
option 'enable-local-infile', 'Build with local infile loading support'
conflicts_with 'mysql-connector-c',
:because => 'both install `mysql_config`'
conflicts_with 'mariadb', 'mysql', 'mysql-cluster',
:because => "percona, mariadb, and mysql install the same binaries."
conflicts_with 'mysql-connector-c',
:because => 'both install MySQL client libraries'
env :std if build.universal?
fails_with :llvm do
build 2334
cause "https://github.com/Homebrew/homebrew/issues/issue/144"
end
# Where the database files should be located. Existing installs have them
# under var/percona, but going forward they will be under var/msyql to be
# shared with the mysql and mariadb formulae.
def datadir
@datadir ||= (var/'percona').directory? ? var/'percona' : var/'mysql'
end
def patches
# Fixes percona server 5.6 compilation on OS X 10.9, based on
# https://github.com/Homebrew/homebrew/commit/aad5d93f4fabbf69766deb83780d3a6eeab7061a
# for mysql 5.6
"https://gist.github.com/israelshirk/7cc640498cf264ebfce3/raw/846839c84647c4190ad683e4cbf0fabcd8931f97/gistfile1.txt"
end
def install
# Don't hard-code the libtool path. See:
# https://github.com/Homebrew/homebrew/issues/20185
inreplace "cmake/libutils.cmake",
"COMMAND /usr/bin/libtool -static -o ${TARGET_LOCATION}",
"COMMAND libtool -static -o ${TARGET_LOCATION}"
# Build without compiler or CPU specific optimization flags to facilitate
# compilation of gems and other software that queries `mysql-config`.
ENV.minimal_optimization
args = %W[
-DCMAKE_INSTALL_PREFIX=#{prefix}
-DCMAKE_FIND_FRAMEWORK=LAST
-DCMAKE_VERBOSE_MAKEFILE=ON
-DMYSQL_DATADIR=#{datadir}
-DINSTALL_INCLUDEDIR=include/mysql
-DINSTALL_MANDIR=share/man
-DINSTALL_DOCDIR=share/doc/#{name}
-DINSTALL_INFODIR=share/info
-DINSTALL_MYSQLSHAREDIR=share/mysql
-DWITH_SSL=yes
-DDEFAULT_CHARSET=utf8
-DDEFAULT_COLLATION=utf8_general_ci
-DSYSCONFDIR=#{etc}
-DCOMPILATION_COMMENT=Homebrew
-DWITH_EDITLINE=system
-DCMAKE_BUILD_TYPE=RelWithDebInfo
]
# PAM plugin is Linux-only at the moment
args.concat %W[
-DWITHOUT_AUTH_PAM=1
-DWITHOUT_AUTH_PAM_COMPAT=1
-DWITHOUT_DIALOG=1
]
# To enable unit testing at build, we need to download the unit testing suite
if build.with? 'tests'
args << "-DENABLE_DOWNLOADS=ON"
else
args << "-DWITH_UNIT_TESTS=OFF"
end
# Build the embedded server
args << "-DWITH_EMBEDDED_SERVER=ON" if build.with? 'embedded'
# Build with InnoDB Memcached plugin
args << "-DWITH_INNODB_MEMCACHED=ON" if build.with? 'memcached'
# Make universal for binding to universal applications
args << "-DCMAKE_OSX_ARCHITECTURES='#{Hardware::CPU.universal_archs.as_cmake_arch_flags}'" if build.universal?
# Build with local infile loading support
args << "-DENABLED_LOCAL_INFILE=1" if build.include? 'enable-local-infile'
system "cmake", *args
system "make"
# Reported upstream:
# http://bugs.mysql.com/bug.php?id=69645
inreplace "scripts/mysql_config", / +-Wno[\w-]+/, ""
system "make install"
# Don't create databases inside of the prefix!
# See: https://github.com/Homebrew/homebrew/issues/4975
rm_rf prefix+'data'
# Link the setup script into bin
ln_s prefix+'scripts/mysql_install_db', bin+'mysql_install_db'
# Fix up the control script and link into bin
inreplace "#{prefix}/support-files/mysql.server" do |s|
s.gsub!(/^(PATH=".*)(")/, "\\1:#{HOMEBREW_PREFIX}/bin\\2")
# pidof can be replaced with pgrep from proctools on Mountain Lion
s.gsub!(/pidof/, 'pgrep') if MacOS.version >= :mountain_lion
end
ln_s "#{prefix}/support-files/mysql.server", bin
# Move mysqlaccess to libexec
mv "#{bin}/mysqlaccess", libexec
mv "#{bin}/mysqlaccess.conf", libexec
# Make sure that data directory exists
datadir.mkpath
end
def post_install
unless File.exist? "#{datadir}/mysql/user.frm"
ENV['TMPDIR'] = nil
system "#{bin}/mysql_install_db", "--verbose", "--user=#{ENV["USER"]}",
"--basedir=#{prefix}", "--datadir=#{datadir}", "--tmpdir=/tmp"
end
end
def caveats; <<-EOS.undent
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
To connect:
mysql -uroot
EOS
end
plist_options :manual => 'mysql.server start'
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>#{plist_name}</string>
<key>Program</key>
<string>#{opt_prefix}/bin/mysqld_safe</string>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
</dict>
</plist>
EOS
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "capistrano-thin"
spec.version = '1.0.0'
spec.authors = ["Alessandro Lepore"]
spec.email = ["a.lepore@freegoweb.it"]
spec.summary = %q{Thin support for Capistrano 3.x}
spec.description = %q{Thin support for Capistrano 3.x}
spec.homepage = "https://github.com/freego/capistrano-thin"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = []
spec.test_files = []
spec.require_paths = ["lib"]
spec.add_dependency 'capistrano', '~> 3.0'
spec.add_dependency 'thin', '~> 1.6'
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
end
bump version
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
Gem::Specification.new do |spec|
spec.name = "capistrano-thin"
spec.version = '1.1.0'
spec.authors = ["Alessandro Lepore"]
spec.email = ["a.lepore@freegoweb.it"]
spec.summary = %q{Thin support for Capistrano 3.x}
spec.description = %q{Thin support for Capistrano 3.x}
spec.homepage = "https://github.com/freego/capistrano-thin"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = []
spec.test_files = []
spec.require_paths = ["lib"]
spec.add_dependency 'capistrano', '~> 3.0'
spec.add_dependency 'thin', '~> 1.6'
spec.add_development_dependency "bundler", "~> 1.5"
spec.add_development_dependency "rake"
end
|
require 'formula'
class ProxychainsNg < Formula
homepage 'https://sourceforge.net/projects/proxychains-ng'
url 'http://downloads.sourceforge.net/project/proxychains-ng/proxychains-4.6.tar.bz2'
sha1 '8f1fb3fa4c391cd2e07f0a7dd0bc4cc55550cb6b'
head 'https://github.com/rofl0r/proxychains-ng.git'
def install
system "./configure", "--prefix=#{prefix}", "--sysconfdir=#{prefix}/etc"
system "make"
system "make install"
system "make install-config"
end
end
proxychains 4.7
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
require 'formula'
class ProxychainsNg < Formula
homepage 'https://sourceforge.net/projects/proxychains-ng'
url 'http://downloads.sourceforge.net/project/proxychains-ng/proxychains-4.7.tar.bz2'
sha1 '5e5b10009f785434ebdbd7ede5a79efee4e59c5a'
head 'https://github.com/rofl0r/proxychains-ng.git'
def install
system "./configure", "--prefix=#{prefix}", "--sysconfdir=#{prefix}/etc"
system "make"
system "make install"
system "make install-config"
end
end
|
require 'options'
# This class holds the build-time options defined for a Formula,
# and provides named access to those options during install.
class BuildOptions
attr_accessor :args
include Enumerable
def initialize args
@args = Options.coerce(args)
@options = Options.new
end
def add name, description=nil
description ||= case name.to_s
when "universal" then "Build a universal binary"
when "32-bit" then "Build 32-bit only"
end.to_s
@options << Option.new(name, description)
end
def has_option? name
any? { |opt| opt.name == name }
end
def empty?
@options.empty?
end
def each(*args, &block)
@options.each(*args, &block)
end
def as_flags
@options.as_flags
end
def include? name
args.include? '--' + name
end
def with? name
if has_option? "with-#{name}"
include? "with-#{name}"
elsif has_option? "without-#{name}"
not include? "without-#{name}"
else
false
end
end
def without? name
not with? name
end
def head?
args.include? '--HEAD'
end
def devel?
args.include? '--devel'
end
def stable?
not (head? or devel?)
end
# True if the user requested a universal build.
def universal?
args.include?('--universal') && has_option?('universal')
end
# Request a 32-bit only build.
# This is needed for some use-cases though we prefer to build Universal
# when a 32-bit version is needed.
def build_32_bit?
args.include?('--32-bit') && has_option?('32-bit')
end
def used_options
Options.new(@options & @args)
end
def unused_options
Options.new(@options - @args)
end
# Some options are implicitly ON because they are not explictly turned off
# by their counterpart option. This applies only to with-/without- options.
# implicit_options are needed because `depends_on 'spam' => 'with-stuff'`
# complains if 'spam' has stuff as default and only defines `--without-stuff`.
def implicit_options
implicit = unused_options.map do |o|
if o.name =~ /^with-(.+)$/ && without?($1)
Option.new("without-#{$1}") # we loose the description, but that's ok
elsif o.name =~ /^without-(.+)$/ && with?($1)
Option.new("with-#{$1}")
end
end.compact
Options.new(implicit)
end
end
fix comment typo
require 'options'
# This class holds the build-time options defined for a Formula,
# and provides named access to those options during install.
class BuildOptions
attr_accessor :args
include Enumerable
def initialize args
@args = Options.coerce(args)
@options = Options.new
end
def add name, description=nil
description ||= case name.to_s
when "universal" then "Build a universal binary"
when "32-bit" then "Build 32-bit only"
end.to_s
@options << Option.new(name, description)
end
def has_option? name
any? { |opt| opt.name == name }
end
def empty?
@options.empty?
end
def each(*args, &block)
@options.each(*args, &block)
end
def as_flags
@options.as_flags
end
def include? name
args.include? '--' + name
end
def with? name
if has_option? "with-#{name}"
include? "with-#{name}"
elsif has_option? "without-#{name}"
not include? "without-#{name}"
else
false
end
end
def without? name
not with? name
end
def head?
args.include? '--HEAD'
end
def devel?
args.include? '--devel'
end
def stable?
not (head? or devel?)
end
# True if the user requested a universal build.
def universal?
args.include?('--universal') && has_option?('universal')
end
# Request a 32-bit only build.
# This is needed for some use-cases though we prefer to build Universal
# when a 32-bit version is needed.
def build_32_bit?
args.include?('--32-bit') && has_option?('32-bit')
end
def used_options
Options.new(@options & @args)
end
def unused_options
Options.new(@options - @args)
end
# Some options are implicitly ON because they are not explictly turned off
# by their counterpart option. This applies only to with-/without- options.
# implicit_options are needed because `depends_on 'spam' => 'with-stuff'`
# complains if 'spam' has stuff as default and only defines `--without-stuff`.
def implicit_options
implicit = unused_options.map do |o|
if o.name =~ /^with-(.+)$/ && without?($1)
Option.new("without-#{$1}") # we lose the description, but that's ok
elsif o.name =~ /^without-(.+)$/ && with?($1)
Option.new("with-#{$1}")
end
end.compact
Options.new(implicit)
end
end
|
# 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 = %q{carrierwave_dav}
s.version = "0.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["miros"]
s.date = %q{2011-06-01}
s.description = %q{Web Dav adapter for carrierwave}
s.email = %q{mirosm@mirosm.ru}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
".rspec",
".rvmrc",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"carrierwave_dav.gemspec",
"lib/carrierwave_dav.rb",
"lib/carrierwave_dav/file.rb",
"lib/carrierwave_dav/storage.rb",
"spec/carrierwave_dav/file_spec.rb",
"spec/carrierwave_dav/storage_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/miros/carrierwave_dav}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{Web Dav adapter for carrierwave}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<i18n>, [">= 0"])
s.add_runtime_dependency(%q<activesupport>, [">= 0"])
s.add_runtime_dependency(%q<carrierwave>, [">= 0"])
s.add_runtime_dependency(%q<net_dav>, [">= 0"])
s.add_development_dependency(%q<rspec-core>, ["~> 2.6.3"])
s.add_development_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_development_dependency(%q<yard>, [">= 0"])
s.add_development_dependency(%q<bundler>, [">= 0"])
s.add_development_dependency(%q<jeweler>, [">= 0"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<addressable>, ["= 2.2.4"])
s.add_development_dependency(%q<webmock>, [">= 0"])
s.add_development_dependency(%q<awesome_print>, [">= 0"])
else
s.add_dependency(%q<i18n>, [">= 0"])
s.add_dependency(%q<activesupport>, [">= 0"])
s.add_dependency(%q<carrierwave>, [">= 0"])
s.add_dependency(%q<net_dav>, [">= 0"])
s.add_dependency(%q<rspec-core>, ["~> 2.6.3"])
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<yard>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, [">= 0"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<addressable>, ["= 2.2.4"])
s.add_dependency(%q<webmock>, [">= 0"])
s.add_dependency(%q<awesome_print>, [">= 0"])
end
else
s.add_dependency(%q<i18n>, [">= 0"])
s.add_dependency(%q<activesupport>, [">= 0"])
s.add_dependency(%q<carrierwave>, [">= 0"])
s.add_dependency(%q<net_dav>, [">= 0"])
s.add_dependency(%q<rspec-core>, ["~> 2.6.3"])
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<yard>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, [">= 0"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<addressable>, ["= 2.2.4"])
s.add_dependency(%q<webmock>, [">= 0"])
s.add_dependency(%q<awesome_print>, [">= 0"])
end
end
removed another rcov duplication from dependencies
# 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 = %q{carrierwave_dav}
s.version = "0.1.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["miros"]
s.date = %q{2011-06-01}
s.description = %q{Web Dav adapter for carrierwave}
s.email = %q{mirosm@mirosm.ru}
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
".rspec",
".rvmrc",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"carrierwave_dav.gemspec",
"lib/carrierwave_dav.rb",
"lib/carrierwave_dav/file.rb",
"lib/carrierwave_dav/storage.rb",
"spec/carrierwave_dav/file_spec.rb",
"spec/carrierwave_dav/storage_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/miros/carrierwave_dav}
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{Web Dav adapter for carrierwave}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<i18n>, [">= 0"])
s.add_runtime_dependency(%q<activesupport>, [">= 0"])
s.add_runtime_dependency(%q<carrierwave>, [">= 0"])
s.add_runtime_dependency(%q<net_dav>, [">= 0"])
s.add_development_dependency(%q<rspec-core>, ["~> 2.6.3"])
s.add_development_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_development_dependency(%q<yard>, [">= 0"])
s.add_development_dependency(%q<bundler>, [">= 0"])
s.add_development_dependency(%q<jeweler>, [">= 0"])
s.add_development_dependency(%q<rcov>, [">= 0"])
s.add_development_dependency(%q<addressable>, ["= 2.2.4"])
s.add_development_dependency(%q<webmock>, [">= 0"])
s.add_development_dependency(%q<awesome_print>, [">= 0"])
else
s.add_dependency(%q<i18n>, [">= 0"])
s.add_dependency(%q<activesupport>, [">= 0"])
s.add_dependency(%q<carrierwave>, [">= 0"])
s.add_dependency(%q<net_dav>, [">= 0"])
s.add_dependency(%q<rspec-core>, ["~> 2.6.3"])
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<yard>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, [">= 0"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<addressable>, ["= 2.2.4"])
s.add_dependency(%q<webmock>, [">= 0"])
s.add_dependency(%q<awesome_print>, [">= 0"])
end
else
s.add_dependency(%q<i18n>, [">= 0"])
s.add_dependency(%q<activesupport>, [">= 0"])
s.add_dependency(%q<carrierwave>, [">= 0"])
s.add_dependency(%q<net_dav>, [">= 0"])
s.add_dependency(%q<rspec-core>, ["~> 2.6.3"])
s.add_dependency(%q<rspec>, ["~> 2.6.0"])
s.add_dependency(%q<yard>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 0"])
s.add_dependency(%q<jeweler>, [">= 0"])
s.add_dependency(%q<rcov>, [">= 0"])
s.add_dependency(%q<addressable>, ["= 2.2.4"])
s.add_dependency(%q<webmock>, [">= 0"])
s.add_dependency(%q<awesome_print>, [">= 0"])
end
end
|
require 'stash/harvester'
require 'stash/indexer'
module Stash
class HarvestAndIndexJob # rubocop:disable Metrics/ClassLength:
HARVEST_JOB_LOG_FORMAT = 'harvest job %d: %s'.freeze
INDEX_JOB_LOG_FORMAT = ' index job %d: %s'.freeze
HARVESTED_RECORD_LOG_FORMAT = 'harvested %s (timestamp: %s, deleted: %s) (harvest job: %d)'.freeze
INDEXED_RECORD_LOG_FORMAT = ' indexed %s (timestamp: %s, deleted: %s; database id: %d): %s (index job: %d)'.freeze
attr_reader :harvest_task
attr_reader :indexer
attr_reader :index_uri
attr_reader :persistence_mgr
def initialize(source_config:, index_config:, metadata_mapper:, persistence_manager:, from_time: nil, until_time: nil) # rubocop:disable Metrics/ParameterLists
@harvest_task = source_config.create_harvest_task(from_time: from_time, until_time: until_time)
@indexer = index_config.create_indexer(metadata_mapper)
@index_uri = index_config.uri
@persistence_mgr = persistence_manager
end
def harvest_and_index(&block)
harvest_job_id = begin_harvest_job(harvest_task)
harvested_records = harvest(harvest_job_id)
index(harvested_records, harvest_job_id, &block)
end
def log
Harvester.log
end
private
def harvest(job_id)
status = Indexer::IndexStatus::COMPLETED
begin
harvest_task.harvest_records
rescue Exception => e # rubocop:disable Lint/RescueException
status = Indexer::IndexStatus::FAILED
log.warn("harvest job #{job_id}: #{e}")
raise e
ensure
end_harvest_job(job_id, status)
end
end
def index(harvested_records, harvest_job_id, &block) # rubocop:disable Metrics/MethodLength
index_job_id = begin_index_job(harvest_job_id)
status = Indexer::IndexStatus::COMPLETED
begin
do_index(harvested_records, harvest_job_id, index_job_id, &block)
rescue Exception => e # rubocop:disable Lint/RescueException
status = Indexer::IndexStatus::FAILED
log.warn(" index job #{index_job_id}: #{e}")
raise e
ensure
end_index_job(index_job_id, status)
end
end
def do_index(harvested_records, harvest_job_id, index_job_id)
indexer.index(harvested_records) do |result|
harvested_record = result.record
harvested_record_id = record_harvested(harvested_record, harvest_job_id)
record_indexed(index_job_id, harvested_record, harvested_record_id, result.status)
yield result if block_given?
end
end
def begin_harvest_job(task)
log.info("Beginning harvest job for query URI #{task.query_uri}")
persistence_mgr.begin_harvest_job(
from_time: task.from_time,
until_time: task.until_time,
query_url: task.query_uri
)
end
def record_harvested(harvested_record, harvest_job_id)
log_harvested(harvest_job_id, harvested_record)
@persistence_mgr.record_harvested_record(
harvest_job_id: harvest_job_id,
identifier: harvested_record.identifier,
timestamp: harvested_record.timestamp,
deleted: harvested_record.deleted?
)
end
def log_harvested(harvest_job_id, harvested_record)
msg = format(
HARVESTED_RECORD_LOG_FORMAT,
harvested_record.identifier,
harvested_record.timestamp.xmlschema,
harvested_record.deleted?,
harvest_job_id
)
log.debug(msg)
end
def end_harvest_job(job_id, status)
msg = format(HARVEST_JOB_LOG_FORMAT, job_id, status.value)
status == Indexer::IndexStatus::COMPLETED ? log.info(msg) : log.warn(msg)
persistence_mgr.end_harvest_job(harvest_job_id: job_id, status: status)
end
def begin_index_job(harvest_job_id)
persistence_mgr.begin_index_job(
harvest_job_id: harvest_job_id,
solr_url: index_uri
)
end
def record_indexed(index_job_id, harvested_record, harvested_record_id, status)
log_indexed(index_job_id, harvested_record, harvested_record_id, status)
@persistence_mgr.record_indexed_record(
index_job_id: index_job_id,
harvested_record_id: harvested_record_id,
status: status
)
end
def log_indexed(index_job_id, harvested_record, harvested_record_id, status)
msg = format(
INDEXED_RECORD_LOG_FORMAT,
harvested_record.identifier,
harvested_record.timestamp.xmlschema,
harvested_record.deleted?,
harvested_record_id,
status.value,
index_job_id
)
status == Indexer::IndexStatus::COMPLETED ? log.debug(msg) : log.warn(msg)
end
def end_index_job(job_id, status)
msg = format(INDEX_JOB_LOG_FORMAT, job_id, status.value)
status == Indexer::IndexStatus::COMPLETED ? log.info(msg) : log.warn(msg)
persistence_mgr.end_index_job(index_job_id: job_id, status: status)
end
end
end
Add log of record count
require 'stash/harvester'
require 'stash/indexer'
module Stash
class HarvestAndIndexJob # rubocop:disable Metrics/ClassLength:
HARVEST_JOB_LOG_FORMAT = 'harvest job %d: %s'.freeze
INDEX_JOB_LOG_FORMAT = ' index job %d: %s'.freeze
HARVESTED_RECORD_LOG_FORMAT = 'harvested %s (timestamp: %s, deleted: %s) (harvest job: %d)'.freeze
INDEXED_RECORD_LOG_FORMAT = ' indexed %s (timestamp: %s, deleted: %s; database id: %d): %s (index job: %d)'.freeze
attr_reader :harvest_task
attr_reader :indexer
attr_reader :index_uri
attr_reader :persistence_mgr
def initialize(source_config:, index_config:, metadata_mapper:, persistence_manager:, from_time: nil, until_time: nil) # rubocop:disable Metrics/ParameterLists
@harvest_task = source_config.create_harvest_task(from_time: from_time, until_time: until_time)
@indexer = index_config.create_indexer(metadata_mapper)
@index_uri = index_config.uri
@persistence_mgr = persistence_manager
end
def harvest_and_index(&block)
harvest_job_id = begin_harvest_job(harvest_task)
harvested_records = harvest(harvest_job_id)
index(harvested_records, harvest_job_id, &block)
end
def log
Harvester.log
end
private
def harvest(job_id)
status = Indexer::IndexStatus::COMPLETED
begin
harvest_task.harvest_records
rescue Exception => e # rubocop:disable Lint/RescueException
status = Indexer::IndexStatus::FAILED
log.warn("harvest job #{job_id}: #{e}")
raise e
ensure
end_harvest_job(job_id, status)
end
end
def index(harvested_records, harvest_job_id, &block) # rubocop:disable Metrics/MethodLength
index_job_id = begin_index_job(harvest_job_id)
status = Indexer::IndexStatus::COMPLETED
begin
do_index(harvested_records, harvest_job_id, index_job_id, &block)
rescue Exception => e # rubocop:disable Lint/RescueException
status = Indexer::IndexStatus::FAILED
log.warn(" index job #{index_job_id}: #{e}")
raise e
ensure
end_index_job(index_job_id, status)
end
end
def do_index(harvested_records, harvest_job_id, index_job_id)
count = 0
indexer.index(harvested_records) do |result|
harvested_record = result.record
harvested_record_id = record_harvested(harvested_record, harvest_job_id)
record_indexed(index_job_id, harvested_record, harvested_record_id, result.status)
count += 1
yield result if block_given?
end
log.info(" indexed #{count} records")
end
def begin_harvest_job(task)
log.info("Beginning harvest job for query URI #{task.query_uri}")
persistence_mgr.begin_harvest_job(
from_time: task.from_time,
until_time: task.until_time,
query_url: task.query_uri
)
end
def record_harvested(harvested_record, harvest_job_id)
log_harvested(harvest_job_id, harvested_record)
@persistence_mgr.record_harvested_record(
harvest_job_id: harvest_job_id,
identifier: harvested_record.identifier,
timestamp: harvested_record.timestamp,
deleted: harvested_record.deleted?
)
end
def log_harvested(harvest_job_id, harvested_record)
msg = format(
HARVESTED_RECORD_LOG_FORMAT,
harvested_record.identifier,
harvested_record.timestamp.xmlschema,
harvested_record.deleted?,
harvest_job_id
)
log.debug(msg)
end
def end_harvest_job(job_id, status)
msg = format(HARVEST_JOB_LOG_FORMAT, job_id, status.value)
status == Indexer::IndexStatus::COMPLETED ? log.info(msg) : log.warn(msg)
persistence_mgr.end_harvest_job(harvest_job_id: job_id, status: status)
end
def begin_index_job(harvest_job_id)
persistence_mgr.begin_index_job(
harvest_job_id: harvest_job_id,
solr_url: index_uri
)
end
def record_indexed(index_job_id, harvested_record, harvested_record_id, status)
log_indexed(index_job_id, harvested_record, harvested_record_id, status)
@persistence_mgr.record_indexed_record(
index_job_id: index_job_id,
harvested_record_id: harvested_record_id,
status: status
)
end
def log_indexed(index_job_id, harvested_record, harvested_record_id, status)
msg = format(
INDEXED_RECORD_LOG_FORMAT,
harvested_record.identifier,
harvested_record.timestamp.xmlschema,
harvested_record.deleted?,
harvested_record_id,
status.value,
index_job_id
)
status == Indexer::IndexStatus::COMPLETED ? log.debug(msg) : log.warn(msg)
end
def end_index_job(job_id, status)
msg = format(INDEX_JOB_LOG_FORMAT, job_id, status.value)
status == Indexer::IndexStatus::COMPLETED ? log.info(msg) : log.warn(msg)
persistence_mgr.end_index_job(index_job_id: job_id, status: status)
end
end
end
|
#: * `audit` [`--strict`] [`--fix`] [`--online`] [`--new-formula`] [`--display-cop-names`] [`--display-filename`] [`--only=`<method>|`--except=`<method>] [`--only-cops=`[COP1,COP2..]|`--except-cops=`[COP1,COP2..]] [<formulae>]:
#: Check <formulae> for Homebrew coding style violations. This should be
#: run before submitting a new formula.
#:
#: If no <formulae> are provided, all of them are checked.
#:
#: If `--strict` is passed, additional checks are run, including RuboCop
#: style checks.
#:
#: If `--fix` is passed, style violations will be
#: automatically fixed using RuboCop's `--auto-correct` feature.
#:
#: If `--online` is passed, additional slower checks that require a network
#: connection are run.
#:
#: If `--new-formula` is passed, various additional checks are run that check
#: if a new formula is eligible for Homebrew. This should be used when creating
#: new formulae and implies `--strict` and `--online`.
#:
#: If `--display-cop-names` is passed, the RuboCop cop name for each violation
#: is included in the output.
#:
#: If `--display-filename` is passed, every line of output is prefixed with the
#: name of the file or formula being audited, to make the output easy to grep.
#:
#: If `--only` is passed, only the methods named `audit_<method>` will be run.
#:
#: If `--except` is passed, the methods named `audit_<method>` will not be run.
#:
#: If `--only-cops` is passed, only the given Rubocop cop(s)' violations would be checked.
#:
#: If `--except-cops` is passed, the given Rubocop cop(s)' checks would be skipped.
#:
#: `audit` exits with a non-zero status if any errors are found. This is useful,
#: for instance, for implementing pre-commit hooks.
# Undocumented options:
# -D activates debugging and profiling of the audit methods (not the same as --debug)
require "formula"
require "formula_versions"
require "utils"
require "extend/ENV"
require "formula_cellar_checks"
require "official_taps"
require "cmd/search"
require "cmd/style"
require "date"
require "missing_formula"
require "digest"
module Homebrew
module_function
def audit
Homebrew.inject_dump_stats!(FormulaAuditor, /^audit_/) if ARGV.switch? "D"
formula_count = 0
problem_count = 0
new_formula = ARGV.include? "--new-formula"
strict = new_formula || ARGV.include?("--strict")
online = new_formula || ARGV.include?("--online")
ENV.activate_extensions!
ENV.setup_build_environment
if ARGV.named.empty?
ff = Formula
files = Tap.map(&:formula_dir)
else
ff = ARGV.resolved_formulae
files = ARGV.resolved_formulae.map(&:path)
end
only_cops = ARGV.value("only-cops").to_s.split(",")
except_cops = ARGV.value("except-cops").to_s.split(",")
if !only_cops.empty? && !except_cops.empty?
odie "--only-cops and --except-cops cannot be used simultaneously!"
elsif (!only_cops.empty? || !except_cops.empty?) && strict
odie "--only-cops/--except-cops and --strict cannot be used simultaneously"
end
options = { fix: ARGV.flag?("--fix"), realpath: true }
if !only_cops.empty?
options[:only_cops] = only_cops
elsif !except_cops.empty?
options[:except_cops] = except_cops
elsif !strict
options[:except_cops] = [:FormulaAuditStrict]
end
# Check style in a single batch run up front for performance
style_results = check_style_json(files, options)
ff.each do |f|
options = { new_formula: new_formula, strict: strict, online: online }
options[:style_offenses] = style_results.file_offenses(f.path)
fa = FormulaAuditor.new(f, options)
fa.audit
next if fa.problems.empty?
fa.problems
formula_count += 1
problem_count += fa.problems.size
problem_lines = fa.problems.map { |p| "* #{p.chomp.gsub("\n", "\n ")}" }
if ARGV.include? "--display-filename"
puts problem_lines.map { |s| "#{f.path}: #{s}" }
else
puts "#{f.full_name}:", problem_lines.map { |s| " #{s}" }
end
end
return if problem_count.zero?
ofail "#{Formatter.pluralize(problem_count, "problem")} in #{Formatter.pluralize(formula_count, "formula")}"
end
end
class FormulaText
def initialize(path)
@text = path.open("rb", &:read)
@lines = @text.lines.to_a
end
def without_patch
@text.split("\n__END__").first
end
def data?
/^[^#]*\bDATA\b/ =~ @text
end
def end?
/^__END__$/ =~ @text
end
def trailing_newline?
/\Z\n/ =~ @text
end
def =~(other)
other =~ @text
end
def include?(s)
@text.include? s
end
def line_number(regex, skip = 0)
index = @lines.drop(skip).index { |line| line =~ regex }
index ? index + 1 : nil
end
def reverse_line_number(regex)
index = @lines.reverse.index { |line| line =~ regex }
index ? @lines.count - index : nil
end
end
class FormulaAuditor
include FormulaCellarChecks
attr_reader :formula, :text, :problems
BUILD_TIME_DEPS = %w[
autoconf
automake
boost-build
bsdmake
cmake
godep
imake
intltool
libtool
pkg-config
scons
smake
sphinx-doc
swig
].freeze
FILEUTILS_METHODS = FileUtils.singleton_methods(false).map { |m| Regexp.escape(m) }.join "|"
def initialize(formula, options = {})
@formula = formula
@new_formula = options[:new_formula]
@strict = options[:strict]
@online = options[:online]
# Accept precomputed style offense results, for efficiency
@style_offenses = options[:style_offenses]
@problems = []
@text = FormulaText.new(formula.path)
@specs = %w[stable devel head].map { |s| formula.send(s) }.compact
end
def self.check_http_content(url, user_agents: [:default])
return unless url.start_with? "http"
details = nil
user_agent = nil
hash_needed = url.start_with?("http:")
user_agents.each do |ua|
details = http_content_headers_and_checksum(url, hash_needed: hash_needed, user_agent: ua)
user_agent = ua
break if details[:status].to_s.start_with?("2")
end
return "The URL #{url} is not reachable" unless details[:status]
unless details[:status].start_with? "2"
return "The URL #{url} is not reachable (HTTP status code #{details[:status]})"
end
return unless hash_needed
secure_url = url.sub "http", "https"
secure_details =
http_content_headers_and_checksum(secure_url, hash_needed: true, user_agent: user_agent)
if !details[:status].to_s.start_with?("2") ||
!secure_details[:status].to_s.start_with?("2")
return
end
etag_match = details[:etag] &&
details[:etag] == secure_details[:etag]
content_length_match =
details[:content_length] &&
details[:content_length] == secure_details[:content_length]
file_match = details[:file_hash] == secure_details[:file_hash]
return if !etag_match && !content_length_match && !file_match
"The URL #{url} could use HTTPS rather than HTTP"
end
def self.http_content_headers_and_checksum(url, hash_needed: false, user_agent: :default)
max_time = hash_needed ? "600" : "25"
args = curl_args(
extra_args: ["--connect-timeout", "15", "--include", "--max-time", max_time, url],
show_output: true,
user_agent: user_agent,
)
output = Open3.popen3(*args) { |_, stdout, _, _| stdout.read }
status_code = :unknown
while status_code == :unknown || status_code.to_s.start_with?("3")
headers, _, output = output.partition("\r\n\r\n")
status_code = headers[%r{HTTP\/.* (\d+)}, 1]
end
output_hash = Digest::SHA256.digest(output) if hash_needed
{
status: status_code,
etag: headers[%r{ETag: ([wW]\/)?"(([^"]|\\")*)"}, 2],
content_length: headers[/Content-Length: (\d+)/, 1],
file_hash: output_hash,
}
end
def audit_style
return unless @style_offenses
display_cop_names = ARGV.include?("--display-cop-names")
@style_offenses.each do |offense|
problem offense.to_s(display_cop_name: display_cop_names)
end
end
def audit_file
# Under normal circumstances (umask 0022), we expect a file mode of 644. If
# the user's umask is more restrictive, respect that by masking out the
# corresponding bits. (The also included 0100000 flag means regular file.)
wanted_mode = 0100644 & ~File.umask
actual_mode = formula.path.stat.mode
unless actual_mode == wanted_mode
problem format("Incorrect file permissions (%03o): chmod %03o %s",
actual_mode & 0777, wanted_mode & 0777, formula.path)
end
problem "'DATA' was found, but no '__END__'" if text.data? && !text.end?
if text.end? && !text.data?
problem "'__END__' was found, but 'DATA' is not used"
end
if text =~ /inreplace [^\n]* do [^\n]*\n[^\n]*\.gsub![^\n]*\n\ *end/m
problem "'inreplace ... do' was used for a single substitution (use the non-block form instead)."
end
problem "File should end with a newline" unless text.trailing_newline?
if formula.versioned_formula?
unversioned_formula = begin
# build this ourselves as we want e.g. homebrew/core to be present
full_name = if formula.tap
"#{formula.tap}/#{formula.name}"
else
formula.name
end
Formulary.factory(full_name.gsub(/@.*$/, "")).path
rescue FormulaUnavailableError, TapFormulaAmbiguityError,
TapFormulaWithOldnameAmbiguityError
Pathname.new formula.path.to_s.gsub(/@.*\.rb$/, ".rb")
end
unless unversioned_formula.exist?
unversioned_name = unversioned_formula.basename(".rb")
problem "#{formula} is versioned but no #{unversioned_name} formula exists"
end
elsif ARGV.build_stable? &&
!(versioned_formulae = Dir[formula.path.to_s.gsub(/\.rb$/, "@*.rb")]).empty?
versioned_aliases = formula.aliases.grep(/.@\d/)
_, last_alias_version =
File.basename(versioned_formulae.sort.reverse.first)
.gsub(/\.rb$/, "").split("@")
major, minor, = formula.version.to_s.split(".")
alias_name_major = "#{formula.name}@#{major}"
alias_name_major_minor = "#{alias_name_major}.#{minor}"
alias_name = if last_alias_version.split(".").length == 1
alias_name_major
else
alias_name_major_minor
end
valid_alias_names = [alias_name_major, alias_name_major_minor]
if formula.tap && !formula.tap.core_tap?
valid_alias_names.map! { |a| "#{formula.tap}/#{a}" }
end
valid_versioned_aliases = versioned_aliases & valid_alias_names
invalid_versioned_aliases = versioned_aliases - valid_alias_names
if valid_versioned_aliases.empty?
if formula.tap
problem <<-EOS.undent
Formula has other versions so create a versioned alias:
cd #{formula.tap.alias_dir}
ln -s #{formula.path.to_s.gsub(formula.tap.path, "..")} #{alias_name}
EOS
else
problem "Formula has other versions so create an alias named #{alias_name}."
end
end
unless invalid_versioned_aliases.empty?
problem <<-EOS.undent
Formula has invalid versioned aliases:
#{invalid_versioned_aliases.join("\n ")}
EOS
end
end
end
def audit_class
if @strict
unless formula.test_defined?
problem "A `test do` test block should be added"
end
end
classes = %w[GithubGistFormula ScriptFileFormula AmazonWebServicesFormula]
klass = classes.find do |c|
Object.const_defined?(c) && formula.class < Object.const_get(c)
end
problem "#{klass} is deprecated, use Formula instead" if klass
end
# core aliases + tap alias names + tap alias full name
@@aliases ||= Formula.aliases + Formula.tap_aliases
def audit_formula_name
return unless @strict
# skip for non-official taps
return if formula.tap.nil? || !formula.tap.official?
name = formula.name
full_name = formula.full_name
if Homebrew::MissingFormula.blacklisted_reason(name)
problem "'#{name}' is blacklisted."
end
if Formula.aliases.include? name
problem "Formula name conflicts with existing aliases."
return
end
if oldname = CoreTap.instance.formula_renames[name]
problem "'#{name}' is reserved as the old name of #{oldname}"
return
end
if !formula.core_formula? && Formula.core_names.include?(name)
problem "Formula name conflicts with existing core formula."
return
end
@@local_official_taps_name_map ||= Tap.select(&:official?).flat_map(&:formula_names)
.each_with_object({}) do |tap_formula_full_name, name_map|
tap_formula_name = tap_formula_full_name.split("/").last
name_map[tap_formula_name] ||= []
name_map[tap_formula_name] << tap_formula_full_name
name_map
end
same_name_tap_formulae = @@local_official_taps_name_map[name] || []
if @online
Homebrew.search_taps(name).each do |tap_formula_full_name|
tap_formula_name = tap_formula_full_name.split("/").last
next if tap_formula_name != name
same_name_tap_formulae << tap_formula_full_name
end
end
same_name_tap_formulae.delete(full_name)
return if same_name_tap_formulae.empty?
problem "Formula name conflicts with #{same_name_tap_formulae.join ", "}"
end
def audit_deps
@specs.each do |spec|
# Check for things we don't like to depend on.
# We allow non-Homebrew installs whenever possible.
spec.deps.each do |dep|
begin
dep_f = dep.to_formula
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap dependencies
next
rescue FormulaUnavailableError
problem "Can't find dependency #{dep.name.inspect}."
next
rescue TapFormulaAmbiguityError
problem "Ambiguous dependency #{dep.name.inspect}."
next
rescue TapFormulaWithOldnameAmbiguityError
problem "Ambiguous oldname dependency #{dep.name.inspect}."
next
end
if dep_f.oldname && dep.name.split("/").last == dep_f.oldname
problem "Dependency '#{dep.name}' was renamed; use new name '#{dep_f.name}'."
end
if @@aliases.include?(dep.name) &&
(dep_f.core_formula? || !dep_f.versioned_formula?)
problem "Dependency '#{dep.name}' is an alias; use the canonical name '#{dep.to_formula.full_name}'."
end
if @new_formula && dep_f.keg_only_reason &&
!["openssl", "apr", "apr-util"].include?(dep.name) &&
[:provided_by_macos, :provided_by_osx].include?(dep_f.keg_only_reason.reason)
problem "Dependency '#{dep.name}' may be unnecessary as it is provided by macOS; try to build this formula without it."
end
dep.options.reject do |opt|
next true if dep_f.option_defined?(opt)
dep_f.requirements.detect do |r|
if r.recommended?
opt.name == "with-#{r.name}"
elsif r.optional?
opt.name == "without-#{r.name}"
end
end
end.each do |opt|
problem "Dependency #{dep} does not define option #{opt.name.inspect}"
end
case dep.name
when "git"
problem "Don't use git as a dependency"
when "mercurial"
problem "Use `depends_on :hg` instead of `depends_on 'mercurial'`"
when "gfortran"
problem "Use `depends_on :fortran` instead of `depends_on 'gfortran'`"
when "ruby"
problem <<-EOS.undent
Don't use "ruby" as a dependency. If this formula requires a
minimum Ruby version not provided by the system you should
use the RubyRequirement:
depends_on :ruby => "1.8"
where "1.8" is the minimum version of Ruby required.
EOS
when "open-mpi", "mpich"
problem <<-EOS.undent
There are multiple conflicting ways to install MPI. Use an MPIRequirement:
depends_on :mpi => [<lang list>]
Where <lang list> is a comma delimited list that can include:
:cc, :cxx, :f77, :f90
EOS
when *BUILD_TIME_DEPS
next if dep.build? || dep.run?
problem <<-EOS.undent
#{dep} dependency should be
depends_on "#{dep}" => :build
Or if it is indeed a runtime dependency
depends_on "#{dep}" => :run
EOS
end
end
end
end
def audit_conflicts
formula.conflicts.each do |c|
begin
Formulary.factory(c.name)
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap conflicts.
next
rescue FormulaUnavailableError
problem "Can't find conflicting formula #{c.name.inspect}."
rescue TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
problem "Ambiguous conflicting formula #{c.name.inspect}."
end
end
versioned_conflicts_whitelist = %w[node@ bash-completion@].freeze
return unless formula.conflicts.any? && formula.versioned_formula?
return if formula.name.start_with?(*versioned_conflicts_whitelist)
problem <<-EOS
Versioned formulae should not use `conflicts_with`.
Use `keg_only :versioned_formula` instead.
EOS
end
def audit_keg_only_style
return unless @strict
return unless formula.keg_only?
whitelist = %w[
Apple
macOS
OS
Homebrew
Xcode
GPG
GNOME
BSD
Firefox
].freeze
reason = formula.keg_only_reason.to_s
# Formulae names can legitimately be uppercase/lowercase/both.
name = Regexp.new(formula.name, Regexp::IGNORECASE)
reason.sub!(name, "")
first_word = reason.split[0]
if reason =~ /\A[A-Z]/ && !reason.start_with?(*whitelist)
problem <<-EOS.undent
'#{first_word}' from the keg_only reason should be '#{first_word.downcase}'.
EOS
end
return unless reason.end_with?(".")
problem "keg_only reason should not end with a period."
end
def audit_options
formula.options.each do |o|
if o.name == "32-bit"
problem "macOS has been 64-bit only since 10.6 so 32-bit options are deprecated."
end
next unless @strict
if o.name == "universal"
problem "macOS has been 64-bit only since 10.6 so universal options are deprecated."
end
if o.name !~ /with(out)?-/ && o.name != "c++11" && o.name != "universal"
problem "Options should begin with with/without. Migrate '--#{o.name}' with `deprecated_option`."
end
next unless o.name =~ /^with(out)?-(?:checks?|tests)$/
unless formula.deps.any? { |d| d.name == "check" && (d.optional? || d.recommended?) }
problem "Use '--with#{$1}-test' instead of '--#{o.name}'. Migrate '--#{o.name}' with `deprecated_option`."
end
end
return unless @new_formula
return if formula.deprecated_options.empty?
return if formula.versioned_formula?
problem "New formulae should not use `deprecated_option`."
end
def audit_homepage
homepage = formula.homepage
return if homepage.nil? || homepage.empty?
return unless @online
return unless DevelopmentTools.curl_handles_most_https_homepages?
if http_content_problem = FormulaAuditor.check_http_content(homepage,
user_agents: [:browser, :default])
problem http_content_problem
end
end
def audit_bottle_spec
return unless formula.bottle_disabled?
return if formula.bottle_disable_reason.valid?
problem "Unrecognized bottle modifier"
end
def audit_github_repository
return unless @online
return unless @new_formula
regex = %r{https?://github\.com/([^/]+)/([^/]+)/?.*}
_, user, repo = *regex.match(formula.stable.url) if formula.stable
_, user, repo = *regex.match(formula.homepage) unless user
return if !user || !repo
repo.gsub!(/.git$/, "")
begin
metadata = GitHub.repository(user, repo)
rescue GitHub::HTTPNotFoundError
return
end
return if metadata.nil?
problem "GitHub fork (not canonical repository)" if metadata["fork"]
if (metadata["forks_count"] < 20) && (metadata["subscribers_count"] < 20) &&
(metadata["stargazers_count"] < 50)
problem "GitHub repository not notable enough (<20 forks, <20 watchers and <50 stars)"
end
return if Date.parse(metadata["created_at"]) <= (Date.today - 30)
problem "GitHub repository too new (<30 days old)"
end
def audit_specs
if head_only?(formula) && formula.tap.to_s.downcase !~ %r{[-/]head-only$}
problem "Head-only (no stable download)"
end
if devel_only?(formula) && formula.tap.to_s.downcase !~ %r{[-/]devel-only$}
problem "Devel-only (no stable download)"
end
%w[Stable Devel HEAD].each do |name|
next unless spec = formula.send(name.downcase)
ra = ResourceAuditor.new(spec, online: @online, strict: @strict).audit
problems.concat ra.problems.map { |problem| "#{name}: #{problem}" }
spec.resources.each_value do |resource|
ra = ResourceAuditor.new(resource, online: @online, strict: @strict).audit
problems.concat ra.problems.map { |problem|
"#{name} resource #{resource.name.inspect}: #{problem}"
}
end
next if spec.patches.empty?
spec.patches.each { |p| patch_problems(p) if p.external? }
next unless @new_formula
problem "New formulae should not require patches to build. Patches should be submitted and accepted upstream first."
end
%w[Stable Devel].each do |name|
next unless spec = formula.send(name.downcase)
version = spec.version
if version.to_s !~ /\d/
problem "#{name}: version (#{version}) is set to a string without a digit"
end
if version.to_s.start_with?("HEAD")
problem "#{name}: non-HEAD version name (#{version}) should not begin with HEAD"
end
end
if formula.stable && formula.devel
if formula.devel.version < formula.stable.version
problem "devel version #{formula.devel.version} is older than stable version #{formula.stable.version}"
elsif formula.devel.version == formula.stable.version
problem "stable and devel versions are identical"
end
end
unstable_whitelist = %w[
aalib 1.4rc5
angolmois 2.0.0alpha2
automysqlbackup 3.0-rc6
aview 1.3.0rc1
distcc 3.2rc1
elm-format 0.6.0-alpha
ftgl 2.1.3-rc5
hidapi 0.8.0-rc1
libcaca 0.99b19
nethack4 4.3.0-beta2
opensyobon 1.0rc2
premake 4.4-beta5
pwnat 0.3-beta
pxz 4.999.9
recode 3.7-beta2
speexdsp 1.2rc3
sqoop 1.4.6
tcptraceroute 1.5beta7
testssl 2.8rc3
tiny-fugue 5.0b8
vbindiff 3.0_beta4
].each_slice(2).to_a.map do |formula, version|
[formula, version.sub(/\d+$/, "")]
end
gnome_devel_whitelist = %w[
gtk-doc 1.25
libart 2.3.21
pygtkglext 1.1.0
].each_slice(2).to_a.map do |formula, version|
[formula, version.split(".")[0..1].join(".")]
end
stable = formula.stable
case stable && stable.url
when /[\d\._-](alpha|beta|rc\d)/
matched = $1
version_prefix = stable.version.to_s.sub(/\d+$/, "")
return if unstable_whitelist.include?([formula.name, version_prefix])
problem "Stable version URLs should not contain #{matched}"
when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i
version_prefix = stable.version.to_s.split(".")[0..1].join(".")
return if gnome_devel_whitelist.include?([formula.name, version_prefix])
version = Version.parse(stable.url)
if version >= Version.create("1.0")
minor_version = version.to_s.split(".", 3)[1].to_i
if minor_version.odd?
problem "#{stable.version} is a development release"
end
end
end
end
def audit_revision_and_version_scheme
return unless formula.tap # skip formula not from core or any taps
return unless formula.tap.git? # git log is required
return if @new_formula
fv = FormulaVersions.new(formula)
previous_version_and_checksum = fv.previous_version_and_checksum("origin/master")
[:stable, :devel].each do |spec_sym|
next unless spec = formula.send(spec_sym)
next unless previous_version_and_checksum[spec_sym][:version] == spec.version
next if previous_version_and_checksum[spec_sym][:checksum] == spec.checksum
problem "#{spec_sym}: sha256 changed without the version also changing; please create an issue upstream to rule out malicious circumstances and to find out why the file changed."
end
attributes = [:revision, :version_scheme]
attributes_map = fv.version_attributes_map(attributes, "origin/master")
current_version_scheme = formula.version_scheme
[:stable, :devel].each do |spec|
spec_version_scheme_map = attributes_map[:version_scheme][spec]
next if spec_version_scheme_map.empty?
version_schemes = spec_version_scheme_map.values.flatten
max_version_scheme = version_schemes.max
max_version = spec_version_scheme_map.select do |_, version_scheme|
version_scheme.first == max_version_scheme
end.keys.max
if max_version_scheme && current_version_scheme < max_version_scheme
problem "version_scheme should not decrease (from #{max_version_scheme} to #{current_version_scheme})"
end
if max_version_scheme && current_version_scheme >= max_version_scheme &&
current_version_scheme > 1 &&
!version_schemes.include?(current_version_scheme - 1)
problem "version_schemes should only increment by 1"
end
formula_spec = formula.send(spec)
next unless formula_spec
spec_version = formula_spec.version
next unless max_version
next if spec_version >= max_version
above_max_version_scheme = current_version_scheme > max_version_scheme
map_includes_version = spec_version_scheme_map.keys.include?(spec_version)
next if !current_version_scheme.zero? &&
(above_max_version_scheme || map_includes_version)
problem "#{spec} version should not decrease (from #{max_version} to #{spec_version})"
end
current_revision = formula.revision
revision_map = attributes_map[:revision][:stable]
if formula.stable && !revision_map.empty?
stable_revisions = revision_map[formula.stable.version]
stable_revisions ||= []
max_revision = stable_revisions.max || 0
if current_revision < max_revision
problem "revision should not decrease (from #{max_revision} to #{current_revision})"
end
stable_revisions -= [formula.revision]
if !current_revision.zero? && stable_revisions.empty? &&
revision_map.keys.length > 1
problem "'revision #{formula.revision}' should be removed"
elsif current_revision > 1 &&
current_revision != max_revision &&
!stable_revisions.include?(current_revision - 1)
problem "revisions should only increment by 1"
end
elsif !current_revision.zero? # head/devel-only formula
problem "'revision #{current_revision}' should be removed"
end
end
def audit_legacy_patches
return unless formula.respond_to?(:patches)
legacy_patches = Patch.normalize_legacy_patches(formula.patches).grep(LegacyPatch)
return if legacy_patches.empty?
problem "Use the patch DSL instead of defining a 'patches' method"
legacy_patches.each { |p| patch_problems(p) }
end
def patch_problems(patch)
case patch.url
when /raw\.github\.com/, %r{gist\.github\.com/raw}, %r{gist\.github\.com/.+/raw},
%r{gist\.githubusercontent\.com/.+/raw}
unless patch.url =~ /[a-fA-F0-9]{40}/
problem "GitHub/Gist patches should specify a revision:\n#{patch.url}"
end
when %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)}
problem <<-EOS.undent
use GitHub pull request URLs:
https://github.com/#{$1}/#{$2}/pull/#{$3}.patch
Rather than patch-diff:
#{patch.url}
EOS
when %r{macports/trunk}
problem "MacPorts patches should specify a revision instead of trunk:\n#{patch.url}"
when %r{^http://trac\.macports\.org}
problem "Patches from MacPorts Trac should be https://, not http:\n#{patch.url}"
when %r{^http://bugs\.debian\.org}
problem "Patches from Debian should be https://, not http:\n#{patch.url}"
end
end
def audit_text
bin_names = Set.new
bin_names << formula.name
bin_names += formula.aliases
[formula.bin, formula.sbin].each do |dir|
next unless dir.exist?
bin_names += dir.children.map(&:basename).map(&:to_s)
end
bin_names.each do |name|
["system", "shell_output", "pipe_output"].each do |cmd|
if text =~ %r{(def test|test do).*(#{Regexp.escape(HOMEBREW_PREFIX)}/bin/)?#{cmd}[\(\s]+['"]#{Regexp.escape(name)}[\s'"]}m
problem %Q(fully scope test #{cmd} calls e.g. #{cmd} "\#{bin}/#{name}")
end
end
end
end
def audit_lines
text.without_patch.split("\n").each_with_index do |line, lineno|
line_problems(line, lineno+1)
end
end
def line_problems(line, _lineno)
if line =~ /<(Formula|AmazonWebServicesFormula|ScriptFileFormula|GithubGistFormula)/
problem "Use a space in class inheritance: class Foo < #{$1}"
end
# Commented-out cmake support from default template
problem "Commented cmake call found" if line.include?('# system "cmake')
# Comments from default template
[
"# PLEASE REMOVE",
"# Documentation:",
"# if this fails, try separate make/make install steps",
"# The URL of the archive",
"## Naming --",
"# if your formula requires any X11/XQuartz components",
"# if your formula fails when building in parallel",
"# Remove unrecognized options if warned by configure",
].each do |comment|
next unless line.include?(comment)
problem "Please remove default template comments"
end
# FileUtils is included in Formula
# encfs modifies a file with this name, so check for some leading characters
if line =~ %r{[^'"/]FileUtils\.(\w+)}
problem "Don't need 'FileUtils.' before #{$1}."
end
# Check for long inreplace block vars
if line =~ /inreplace .* do \|(.{2,})\|/
problem "\"inreplace <filenames> do |s|\" is preferred over \"|#{$1}|\"."
end
# Check for string interpolation of single values.
if line =~ /(system|inreplace|gsub!|change_make_var!).*[ ,]"#\{([\w.]+)\}"/
problem "Don't need to interpolate \"#{$2}\" with #{$1}"
end
# Check for string concatenation; prefer interpolation
if line =~ /(#\{\w+\s*\+\s*['"][^}]+\})/
problem "Try not to concatenate paths in string interpolation:\n #{$1}"
end
# Prefer formula path shortcuts in Pathname+
if line =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|libexec|lib|sbin|share|Frameworks)[/'"])}
problem "\"(#{$1}...#{$2})\" should be \"(#{$3.downcase}+...)\""
end
if line =~ /((man)\s*\+\s*(['"])(man[1-8])(['"]))/
problem "\"#{$1}\" should be \"#{$4}\""
end
# Prefer formula path shortcuts in strings
if line =~ %r[(\#\{prefix\}/(bin|include|libexec|lib|sbin|share|Frameworks))]
problem "\"#{$1}\" should be \"\#{#{$2.downcase}}\""
end
if line =~ %r[((\#\{prefix\}/share/man/|\#\{man\}/)(man[1-8]))]
problem "\"#{$1}\" should be \"\#{#{$3}}\""
end
if line =~ %r[((\#\{share\}/(man)))[/'"]]
problem "\"#{$1}\" should be \"\#{#{$3}}\""
end
if line =~ %r[(\#\{prefix\}/share/(info|man))]
problem "\"#{$1}\" should be \"\#{#{$2}}\""
end
if line =~ /depends_on :(automake|autoconf|libtool)/
problem ":#{$1} is deprecated. Usage should be \"#{$1}\""
end
if line =~ /depends_on :apr/
problem ":apr is deprecated. Usage should be \"apr-util\""
end
problem ":tex is deprecated" if line =~ /depends_on :tex/
if line =~ /depends_on\s+['"](.+)['"]\s+=>\s+:(lua|perl|python|ruby)(\d*)/
problem "#{$2} modules should be vendored rather than use deprecated `depends_on \"#{$1}\" => :#{$2}#{$3}`"
end
if line =~ /depends_on\s+['"](.+)['"]\s+=>\s+(.*)/
dep = $1
$2.split(" ").map do |o|
next unless o =~ /^\[?['"](.*)['"]/
problem "Dependency #{dep} should not use option #{$1}"
end
end
# Commented-out depends_on
problem "Commented-out dep #{$1}" if line =~ /#\s*depends_on\s+(.+)\s*$/
if line =~ /if\s+ARGV\.include\?\s+'--(HEAD|devel)'/
problem "Use \"if build.#{$1.downcase}?\" instead"
end
problem "Use separate make calls" if line.include?("make && make")
problem "Use spaces instead of tabs for indentation" if line =~ /^[ ]*\t/
if line.include?("ENV.x11")
problem "Use \"depends_on :x11\" instead of \"ENV.x11\""
end
# Avoid hard-coding compilers
if line =~ %r{(system|ENV\[.+\]\s?=)\s?['"](/usr/bin/)?(gcc|llvm-gcc|clang)['" ]}
problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{$3}\""
end
if line =~ %r{(system|ENV\[.+\]\s?=)\s?['"](/usr/bin/)?((g|llvm-g|clang)\+\+)['" ]}
problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{$3}\""
end
if line =~ /system\s+['"](env|export)(\s+|['"])/
problem "Use ENV instead of invoking '#{$1}' to modify the environment"
end
if formula.name != "wine" && line =~ /ENV\.universal_binary/
problem "macOS has been 64-bit only since 10.6 so ENV.universal_binary is deprecated."
end
if line =~ /build\.universal\?/
problem "macOS has been 64-bit only so build.universal? is deprecated."
end
if line =~ /version == ['"]HEAD['"]/
problem "Use 'build.head?' instead of inspecting 'version'"
end
if line =~ /build\.include\?[\s\(]+['"]\-\-(.*)['"]/
problem "Reference '#{$1}' without dashes"
end
if line =~ /build\.include\?[\s\(]+['"]with(out)?-(.*)['"]/
problem "Use build.with#{$1}? \"#{$2}\" instead of build.include? 'with#{$1}-#{$2}'"
end
if line =~ /build\.with\?[\s\(]+['"]-?-?with-(.*)['"]/
problem "Don't duplicate 'with': Use `build.with? \"#{$1}\"` to check for \"--with-#{$1}\""
end
if line =~ /build\.without\?[\s\(]+['"]-?-?without-(.*)['"]/
problem "Don't duplicate 'without': Use `build.without? \"#{$1}\"` to check for \"--without-#{$1}\""
end
if line =~ /unless build\.with\?(.*)/
problem "Use if build.without?#{$1} instead of unless build.with?#{$1}"
end
if line =~ /unless build\.without\?(.*)/
problem "Use if build.with?#{$1} instead of unless build.without?#{$1}"
end
if line =~ /(not\s|!)\s*build\.with?\?/
problem "Don't negate 'build.with?': use 'build.without?'"
end
if line =~ /(not\s|!)\s*build\.without?\?/
problem "Don't negate 'build.without?': use 'build.with?'"
end
if line =~ /ARGV\.(?!(debug\?|verbose\?|value[\(\s]))/
problem "Use build instead of ARGV to check options"
end
problem "Use new-style option definitions" if line.include?("def options")
if line.end_with?("def test")
problem "Use new-style test definitions (test do)"
end
if line.include?("MACOS_VERSION")
problem "Use MacOS.version instead of MACOS_VERSION"
end
if line.include?("MACOS_FULL_VERSION")
problem "Use MacOS.full_version instead of MACOS_FULL_VERSION"
end
cats = %w[leopard snow_leopard lion mountain_lion].join("|")
if line =~ /MacOS\.(?:#{cats})\?/
problem "\"#{$&}\" is deprecated, use a comparison to MacOS.version instead"
end
if line =~ /skip_clean\s+:all/
problem "`skip_clean :all` is deprecated; brew no longer strips symbols\n" \
"\tPass explicit paths to prevent Homebrew from removing empty folders."
end
if line =~ /depends_on [A-Z][\w:]+\.new$/
problem "`depends_on` can take requirement classes instead of instances"
end
if line =~ /^def (\w+).*$/
problem "Define method #{$1.inspect} in the class body, not at the top-level"
end
if line.include?("ENV.fortran") && !formula.requirements.map(&:class).include?(FortranRequirement)
problem "Use `depends_on :fortran` instead of `ENV.fortran`"
end
if line =~ /JAVA_HOME/i && !formula.requirements.map(&:class).include?(JavaRequirement)
problem "Use `depends_on :java` to set JAVA_HOME"
end
if line =~ /depends_on :(.+) (if.+|unless.+)$/
conditional_dep_problems($1.to_sym, $2, $&)
end
if line =~ /depends_on ['"](.+)['"] (if.+|unless.+)$/
conditional_dep_problems($1, $2, $&)
end
if line =~ /(Dir\[("[^\*{},]+")\])/
problem "#{$1} is unnecessary; just use #{$2}"
end
if line =~ /system (["'](#{FILEUTILS_METHODS})["' ])/o
system = $1
method = $2
problem "Use the `#{method}` Ruby method instead of `system #{system}`"
end
if line =~ /assert [^!]+\.include?/
problem "Use `assert_match` instead of `assert ...include?`"
end
if line.include?('system "npm", "install"') && !line.include?("Language::Node") &&
formula.name !~ /^kibana(\@\d+(\.\d+)?)?$/
problem "Use Language::Node for npm install args"
end
if line.include?("fails_with :llvm")
problem "'fails_with :llvm' is now a no-op so should be removed"
end
if line =~ /system\s+['"](otool|install_name_tool|lipo)/ && formula.name != "cctools"
problem "Use ruby-macho instead of calling #{$1}"
end
if formula.tap.to_s == "homebrew/core"
["OS.mac?", "OS.linux?"].each do |check|
next unless line.include?(check)
problem "Don't use #{check}; Homebrew/core only supports macOS"
end
end
if line =~ /((revision|version_scheme)\s+0)/
problem "'#{$1}' should be removed"
end
return unless @strict
problem "`#{$1}` in formulae is deprecated" if line =~ /(env :(std|userpaths))/
if line =~ /system ((["'])[^"' ]*(?:\s[^"' ]*)+\2)/
bad_system = $1
unless %w[| < > & ; *].any? { |c| bad_system.include? c }
good_system = bad_system.gsub(" ", "\", \"")
problem "Use `system #{good_system}` instead of `system #{bad_system}` "
end
end
problem "`#{$1}` is now unnecessary" if line =~ /(require ["']formula["'])/
if line =~ %r{#\{share\}/#{Regexp.escape(formula.name)}[/'"]}
problem "Use \#{pkgshare} instead of \#{share}/#{formula.name}"
end
return unless line =~ %r{share(\s*[/+]\s*)(['"])#{Regexp.escape(formula.name)}(?:\2|/)}
problem "Use pkgshare instead of (share#{$1}\"#{formula.name}\")"
end
def audit_reverse_migration
# Only enforce for new formula being re-added to core and official taps
return unless @strict
return unless formula.tap && formula.tap.official?
return unless formula.tap.tap_migrations.key?(formula.name)
problem <<-EOS.undent
#{formula.name} seems to be listed in tap_migrations.json!
Please remove #{formula.name} from present tap & tap_migrations.json
before submitting it to Homebrew/homebrew-#{formula.tap.repo}.
EOS
end
def audit_prefix_has_contents
return unless formula.prefix.directory?
return unless Keg.new(formula.prefix).empty_installation?
problem <<-EOS.undent
The installation seems to be empty. Please ensure the prefix
is set correctly and expected files are installed.
The prefix configure/make argument may be case-sensitive.
EOS
end
def conditional_dep_problems(dep, condition, line)
quoted_dep = quote_dep(dep)
dep = Regexp.escape(dep.to_s)
case condition
when /if build\.include\? ['"]with-#{dep}['"]$/, /if build\.with\? ['"]#{dep}['"]$/
problem %Q(Replace #{line.inspect} with "depends_on #{quoted_dep} => :optional")
when /unless build\.include\? ['"]without-#{dep}['"]$/, /unless build\.without\? ['"]#{dep}['"]$/
problem %Q(Replace #{line.inspect} with "depends_on #{quoted_dep} => :recommended")
end
end
def quote_dep(dep)
dep.is_a?(Symbol) ? dep.inspect : "'#{dep}'"
end
def problem_if_output(output)
problem(output) if output
end
def audit
only_audits = ARGV.value("only").to_s.split(",")
except_audits = ARGV.value("except").to_s.split(",")
if !only_audits.empty? && !except_audits.empty?
odie "--only and --except cannot be used simultaneously!"
end
methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name|
name = audit_method_name.gsub(/^audit_/, "")
if !only_audits.empty?
next unless only_audits.include?(name)
elsif !except_audits.empty?
next if except_audits.include?(name)
end
send(audit_method_name)
end
end
private
def problem(p)
@problems << p
end
def head_only?(formula)
formula.head && formula.devel.nil? && formula.stable.nil?
end
def devel_only?(formula)
formula.devel && formula.stable.nil?
end
end
class ResourceAuditor
attr_reader :problems
attr_reader :version, :checksum, :using, :specs, :url, :mirrors, :name
def initialize(resource, options = {})
@name = resource.name
@version = resource.version
@checksum = resource.checksum
@url = resource.url
@mirrors = resource.mirrors
@using = resource.using
@specs = resource.specs
@online = options[:online]
@strict = options[:strict]
@problems = []
end
def audit
audit_version
audit_checksum
audit_download_strategy
audit_urls
self
end
def audit_version
if version.nil?
problem "missing version"
elsif version.to_s.empty?
problem "version is set to an empty string"
elsif !version.detected_from_url?
version_text = version
version_url = Version.detect(url, specs)
if version_url.to_s == version_text.to_s && version.instance_of?(Version)
problem "version #{version_text} is redundant with version scanned from URL"
end
end
if version.to_s.start_with?("v")
problem "version #{version} should not have a leading 'v'"
end
return unless version.to_s =~ /_\d+$/
problem "version #{version} should not end with an underline and a number"
end
def audit_checksum
return unless checksum
case checksum.hash_type
when :md5
problem "MD5 checksums are deprecated, please use SHA256"
return
when :sha1
problem "SHA1 checksums are deprecated, please use SHA256"
return
when :sha256 then len = 64
end
if checksum.empty?
problem "#{checksum.hash_type} is empty"
else
problem "#{checksum.hash_type} should be #{len} characters" unless checksum.hexdigest.length == len
problem "#{checksum.hash_type} contains invalid characters" unless checksum.hexdigest =~ /^[a-fA-F0-9]+$/
problem "#{checksum.hash_type} should be lowercase" unless checksum.hexdigest == checksum.hexdigest.downcase
end
end
def audit_download_strategy
if url =~ %r{^(cvs|bzr|hg|fossil)://} || url =~ %r{^(svn)\+http://}
problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{$1}` instead"
end
url_strategy = DownloadStrategyDetector.detect(url)
if using == :git || url_strategy == GitDownloadStrategy
if specs[:tag] && !specs[:revision]
problem "Git should specify :revision when a :tag is specified."
end
end
return unless using
if using == :ssl3 || \
(Object.const_defined?("CurlSSL3DownloadStrategy") && using == CurlSSL3DownloadStrategy)
problem "The SSL3 download strategy is deprecated, please choose a different URL"
elsif (Object.const_defined?("CurlUnsafeDownloadStrategy") && using == CurlUnsafeDownloadStrategy) || \
(Object.const_defined?("UnsafeSubversionDownloadStrategy") && using == UnsafeSubversionDownloadStrategy)
problem "#{using.name} is deprecated, please choose a different URL"
end
if using == :cvs
mod = specs[:module]
problem "Redundant :module value in URL" if mod == name
if url =~ %r{:[^/]+$}
mod = url.split(":").last
if mod == name
problem "Redundant CVS module appended to URL"
else
problem "Specify CVS module as `:module => \"#{mod}\"` instead of appending it to the URL"
end
end
end
return unless url_strategy == DownloadStrategyDetector.detect("", using)
problem "Redundant :using value in URL"
end
def audit_urls
# Check GNU urls; doesn't apply to mirrors
if url =~ %r{^(?:https?|ftp)://ftpmirror.gnu.org/(.*)}
problem "Please use \"https://ftp.gnu.org/gnu/#{$1}\" instead of #{url}."
end
if mirrors.include?(url)
problem "URL should not be duplicated as a mirror: #{url}"
end
urls = [url] + mirrors
# Check a variety of SSL/TLS URLs that don't consistently auto-redirect
# or are overly common errors that need to be reduced & fixed over time.
urls.each do |p|
case p
when %r{^http://ftp\.gnu\.org/},
%r{^http://ftpmirror\.gnu\.org/},
%r{^http://download\.savannah\.gnu\.org/},
%r{^http://download-mirror\.savannah\.gnu\.org/},
%r{^http://[^/]*\.apache\.org/},
%r{^http://code\.google\.com/},
%r{^http://fossies\.org/},
%r{^http://mirrors\.kernel\.org/},
%r{^http://(?:[^/]*\.)?bintray\.com/},
%r{^http://tools\.ietf\.org/},
%r{^http://launchpad\.net/},
%r{^http://github\.com/},
%r{^http://bitbucket\.org/},
%r{^http://anonscm\.debian\.org/},
%r{^http://cpan\.metacpan\.org/},
%r{^http://hackage\.haskell\.org/},
%r{^http://(?:[^/]*\.)?archive\.org},
%r{^http://(?:[^/]*\.)?freedesktop\.org},
%r{^http://(?:[^/]*\.)?mirrorservice\.org/}
problem "Please use https:// for #{p}"
when %r{^http://search\.mcpan\.org/CPAN/(.*)}i
problem "#{p} should be `https://cpan.metacpan.org/#{$1}`"
when %r{^(http|ftp)://ftp\.gnome\.org/pub/gnome/(.*)}i
problem "#{p} should be `https://download.gnome.org/#{$2}`"
when %r{^git://anonscm\.debian\.org/users/(.*)}i
problem "#{p} should be `https://anonscm.debian.org/git/users/#{$1}`"
end
end
# Prefer HTTP/S when possible over FTP protocol due to possible firewalls.
urls.each do |p|
case p
when %r{^ftp://ftp\.mirrorservice\.org}
problem "Please use https:// for #{p}"
when %r{^ftp://ftp\.cpan\.org/pub/CPAN(.*)}i
problem "#{p} should be `http://search.cpan.org/CPAN#{$1}`"
end
end
# Check SourceForge urls
urls.each do |p|
# Skip if the URL looks like a SVN repo
next if p.include? "/svnroot/"
next if p.include? "svn.sourceforge"
# Is it a sourceforge http(s) URL?
next unless p =~ %r{^https?://.*\b(sourceforge|sf)\.(com|net)}
if p =~ /(\?|&)use_mirror=/
problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})."
end
if p.end_with?("/download")
problem "Don't use /download in SourceForge urls (url is #{p})."
end
if p =~ %r{^https?://sourceforge\.}
problem "Use https://downloads.sourceforge.net to get geolocation (url is #{p})."
end
if p =~ %r{^https?://prdownloads\.}
problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" \
"\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/"
end
if p =~ %r{^http://\w+\.dl\.}
problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})."
end
problem "Please use https:// for #{p}" if p.start_with? "http://downloads"
end
# Debian has an abundance of secure mirrors. Let's not pluck the insecure
# one out of the grab bag.
urls.each do |u|
next unless u =~ %r{^http://http\.debian\.net/debian/(.*)}i
problem <<-EOS.undent
Please use a secure mirror for Debian URLs.
We recommend:
https://mirrors.ocf.berkeley.edu/debian/#{$1}
EOS
end
# Check for Google Code download urls, https:// is preferred
# Intentionally not extending this to SVN repositories due to certificate
# issues.
urls.grep(%r{^http://.*\.googlecode\.com/files.*}) do |u|
problem "Please use https:// for #{u}"
end
# Check for new-url Google Code download urls, https:// is preferred
urls.grep(%r{^http://code\.google\.com/}) do |u|
problem "Please use https:// for #{u}"
end
# Check for git:// GitHub repo urls, https:// is preferred.
urls.grep(%r{^git://[^/]*github\.com/}) do |u|
problem "Please use https:// for #{u}"
end
# Check for git:// Gitorious repo urls, https:// is preferred.
urls.grep(%r{^git://[^/]*gitorious\.org/}) do |u|
problem "Please use https:// for #{u}"
end
# Check for http:// GitHub repo urls, https:// is preferred.
urls.grep(%r{^http://github\.com/.*\.git$}) do |u|
problem "Please use https:// for #{u}"
end
# Check for master branch GitHub archives.
urls.grep(%r{^https://github\.com/.*archive/master\.(tar\.gz|zip)$}) do
problem "Use versioned rather than branch tarballs for stable checksums."
end
# Use new-style archive downloads
urls.each do |u|
next unless u =~ %r{https://.*github.*/(?:tar|zip)ball/} && u !~ /\.git$/
problem "Use /archive/ URLs for GitHub tarballs (url is #{u})."
end
# Don't use GitHub .zip files
urls.each do |u|
next unless u =~ %r{https://.*github.*/(archive|releases)/.*\.zip$} && u !~ %r{releases/download}
problem "Use GitHub tarballs rather than zipballs (url is #{u})."
end
# Don't use GitHub codeload URLs
urls.each do |u|
next unless u =~ %r{https?://codeload\.github\.com/(.+)/(.+)/(?:tar\.gz|zip)/(.+)}
problem <<-EOS.undent
use GitHub archive URLs:
https://github.com/#{$1}/#{$2}/archive/#{$3}.tar.gz
Rather than codeload:
#{u}
EOS
end
# Check for Maven Central urls, prefer HTTPS redirector over specific host
urls.each do |u|
next unless u =~ %r{https?://(?:central|repo\d+)\.maven\.org/maven2/(.+)$}
problem "#{u} should be `https://search.maven.org/remotecontent?filepath=#{$1}`"
end
return unless @online
urls.each do |url|
next if !@strict && mirrors.include?(url)
strategy = DownloadStrategyDetector.detect(url, using)
if strategy <= CurlDownloadStrategy && !url.start_with?("file")
# A `brew mirror`'ed URL is usually not yet reachable at the time of
# pull request.
next if url =~ %r{^https://dl.bintray.com/homebrew/mirror/}
if http_content_problem = FormulaAuditor.check_http_content(url)
problem http_content_problem
end
elsif strategy <= GitDownloadStrategy
unless Utils.git_remote_exists url
problem "The URL #{url} is not a valid git URL"
end
elsif strategy <= SubversionDownloadStrategy
next unless DevelopmentTools.subversion_handles_most_https_certificates?
unless Utils.svn_remote_exists url
problem "The URL #{url} is not a valid svn URL"
end
end
end
end
def problem(text)
@problems << text
end
end
audit: fix false negative for formulae options.
Handle the case where an if/unless is detected and then write off this
line for option handling.
#: * `audit` [`--strict`] [`--fix`] [`--online`] [`--new-formula`] [`--display-cop-names`] [`--display-filename`] [`--only=`<method>|`--except=`<method>] [`--only-cops=`[COP1,COP2..]|`--except-cops=`[COP1,COP2..]] [<formulae>]:
#: Check <formulae> for Homebrew coding style violations. This should be
#: run before submitting a new formula.
#:
#: If no <formulae> are provided, all of them are checked.
#:
#: If `--strict` is passed, additional checks are run, including RuboCop
#: style checks.
#:
#: If `--fix` is passed, style violations will be
#: automatically fixed using RuboCop's `--auto-correct` feature.
#:
#: If `--online` is passed, additional slower checks that require a network
#: connection are run.
#:
#: If `--new-formula` is passed, various additional checks are run that check
#: if a new formula is eligible for Homebrew. This should be used when creating
#: new formulae and implies `--strict` and `--online`.
#:
#: If `--display-cop-names` is passed, the RuboCop cop name for each violation
#: is included in the output.
#:
#: If `--display-filename` is passed, every line of output is prefixed with the
#: name of the file or formula being audited, to make the output easy to grep.
#:
#: If `--only` is passed, only the methods named `audit_<method>` will be run.
#:
#: If `--except` is passed, the methods named `audit_<method>` will not be run.
#:
#: If `--only-cops` is passed, only the given Rubocop cop(s)' violations would be checked.
#:
#: If `--except-cops` is passed, the given Rubocop cop(s)' checks would be skipped.
#:
#: `audit` exits with a non-zero status if any errors are found. This is useful,
#: for instance, for implementing pre-commit hooks.
# Undocumented options:
# -D activates debugging and profiling of the audit methods (not the same as --debug)
require "formula"
require "formula_versions"
require "utils"
require "extend/ENV"
require "formula_cellar_checks"
require "official_taps"
require "cmd/search"
require "cmd/style"
require "date"
require "missing_formula"
require "digest"
module Homebrew
module_function
def audit
Homebrew.inject_dump_stats!(FormulaAuditor, /^audit_/) if ARGV.switch? "D"
formula_count = 0
problem_count = 0
new_formula = ARGV.include? "--new-formula"
strict = new_formula || ARGV.include?("--strict")
online = new_formula || ARGV.include?("--online")
ENV.activate_extensions!
ENV.setup_build_environment
if ARGV.named.empty?
ff = Formula
files = Tap.map(&:formula_dir)
else
ff = ARGV.resolved_formulae
files = ARGV.resolved_formulae.map(&:path)
end
only_cops = ARGV.value("only-cops").to_s.split(",")
except_cops = ARGV.value("except-cops").to_s.split(",")
if !only_cops.empty? && !except_cops.empty?
odie "--only-cops and --except-cops cannot be used simultaneously!"
elsif (!only_cops.empty? || !except_cops.empty?) && strict
odie "--only-cops/--except-cops and --strict cannot be used simultaneously"
end
options = { fix: ARGV.flag?("--fix"), realpath: true }
if !only_cops.empty?
options[:only_cops] = only_cops
elsif !except_cops.empty?
options[:except_cops] = except_cops
elsif !strict
options[:except_cops] = [:FormulaAuditStrict]
end
# Check style in a single batch run up front for performance
style_results = check_style_json(files, options)
ff.each do |f|
options = { new_formula: new_formula, strict: strict, online: online }
options[:style_offenses] = style_results.file_offenses(f.path)
fa = FormulaAuditor.new(f, options)
fa.audit
next if fa.problems.empty?
fa.problems
formula_count += 1
problem_count += fa.problems.size
problem_lines = fa.problems.map { |p| "* #{p.chomp.gsub("\n", "\n ")}" }
if ARGV.include? "--display-filename"
puts problem_lines.map { |s| "#{f.path}: #{s}" }
else
puts "#{f.full_name}:", problem_lines.map { |s| " #{s}" }
end
end
return if problem_count.zero?
ofail "#{Formatter.pluralize(problem_count, "problem")} in #{Formatter.pluralize(formula_count, "formula")}"
end
end
class FormulaText
def initialize(path)
@text = path.open("rb", &:read)
@lines = @text.lines.to_a
end
def without_patch
@text.split("\n__END__").first
end
def data?
/^[^#]*\bDATA\b/ =~ @text
end
def end?
/^__END__$/ =~ @text
end
def trailing_newline?
/\Z\n/ =~ @text
end
def =~(other)
other =~ @text
end
def include?(s)
@text.include? s
end
def line_number(regex, skip = 0)
index = @lines.drop(skip).index { |line| line =~ regex }
index ? index + 1 : nil
end
def reverse_line_number(regex)
index = @lines.reverse.index { |line| line =~ regex }
index ? @lines.count - index : nil
end
end
class FormulaAuditor
include FormulaCellarChecks
attr_reader :formula, :text, :problems
BUILD_TIME_DEPS = %w[
autoconf
automake
boost-build
bsdmake
cmake
godep
imake
intltool
libtool
pkg-config
scons
smake
sphinx-doc
swig
].freeze
FILEUTILS_METHODS = FileUtils.singleton_methods(false).map { |m| Regexp.escape(m) }.join "|"
def initialize(formula, options = {})
@formula = formula
@new_formula = options[:new_formula]
@strict = options[:strict]
@online = options[:online]
# Accept precomputed style offense results, for efficiency
@style_offenses = options[:style_offenses]
@problems = []
@text = FormulaText.new(formula.path)
@specs = %w[stable devel head].map { |s| formula.send(s) }.compact
end
def self.check_http_content(url, user_agents: [:default])
return unless url.start_with? "http"
details = nil
user_agent = nil
hash_needed = url.start_with?("http:")
user_agents.each do |ua|
details = http_content_headers_and_checksum(url, hash_needed: hash_needed, user_agent: ua)
user_agent = ua
break if details[:status].to_s.start_with?("2")
end
return "The URL #{url} is not reachable" unless details[:status]
unless details[:status].start_with? "2"
return "The URL #{url} is not reachable (HTTP status code #{details[:status]})"
end
return unless hash_needed
secure_url = url.sub "http", "https"
secure_details =
http_content_headers_and_checksum(secure_url, hash_needed: true, user_agent: user_agent)
if !details[:status].to_s.start_with?("2") ||
!secure_details[:status].to_s.start_with?("2")
return
end
etag_match = details[:etag] &&
details[:etag] == secure_details[:etag]
content_length_match =
details[:content_length] &&
details[:content_length] == secure_details[:content_length]
file_match = details[:file_hash] == secure_details[:file_hash]
return if !etag_match && !content_length_match && !file_match
"The URL #{url} could use HTTPS rather than HTTP"
end
def self.http_content_headers_and_checksum(url, hash_needed: false, user_agent: :default)
max_time = hash_needed ? "600" : "25"
args = curl_args(
extra_args: ["--connect-timeout", "15", "--include", "--max-time", max_time, url],
show_output: true,
user_agent: user_agent,
)
output = Open3.popen3(*args) { |_, stdout, _, _| stdout.read }
status_code = :unknown
while status_code == :unknown || status_code.to_s.start_with?("3")
headers, _, output = output.partition("\r\n\r\n")
status_code = headers[%r{HTTP\/.* (\d+)}, 1]
end
output_hash = Digest::SHA256.digest(output) if hash_needed
{
status: status_code,
etag: headers[%r{ETag: ([wW]\/)?"(([^"]|\\")*)"}, 2],
content_length: headers[/Content-Length: (\d+)/, 1],
file_hash: output_hash,
}
end
def audit_style
return unless @style_offenses
display_cop_names = ARGV.include?("--display-cop-names")
@style_offenses.each do |offense|
problem offense.to_s(display_cop_name: display_cop_names)
end
end
def audit_file
# Under normal circumstances (umask 0022), we expect a file mode of 644. If
# the user's umask is more restrictive, respect that by masking out the
# corresponding bits. (The also included 0100000 flag means regular file.)
wanted_mode = 0100644 & ~File.umask
actual_mode = formula.path.stat.mode
unless actual_mode == wanted_mode
problem format("Incorrect file permissions (%03o): chmod %03o %s",
actual_mode & 0777, wanted_mode & 0777, formula.path)
end
problem "'DATA' was found, but no '__END__'" if text.data? && !text.end?
if text.end? && !text.data?
problem "'__END__' was found, but 'DATA' is not used"
end
if text =~ /inreplace [^\n]* do [^\n]*\n[^\n]*\.gsub![^\n]*\n\ *end/m
problem "'inreplace ... do' was used for a single substitution (use the non-block form instead)."
end
problem "File should end with a newline" unless text.trailing_newline?
if formula.versioned_formula?
unversioned_formula = begin
# build this ourselves as we want e.g. homebrew/core to be present
full_name = if formula.tap
"#{formula.tap}/#{formula.name}"
else
formula.name
end
Formulary.factory(full_name.gsub(/@.*$/, "")).path
rescue FormulaUnavailableError, TapFormulaAmbiguityError,
TapFormulaWithOldnameAmbiguityError
Pathname.new formula.path.to_s.gsub(/@.*\.rb$/, ".rb")
end
unless unversioned_formula.exist?
unversioned_name = unversioned_formula.basename(".rb")
problem "#{formula} is versioned but no #{unversioned_name} formula exists"
end
elsif ARGV.build_stable? &&
!(versioned_formulae = Dir[formula.path.to_s.gsub(/\.rb$/, "@*.rb")]).empty?
versioned_aliases = formula.aliases.grep(/.@\d/)
_, last_alias_version =
File.basename(versioned_formulae.sort.reverse.first)
.gsub(/\.rb$/, "").split("@")
major, minor, = formula.version.to_s.split(".")
alias_name_major = "#{formula.name}@#{major}"
alias_name_major_minor = "#{alias_name_major}.#{minor}"
alias_name = if last_alias_version.split(".").length == 1
alias_name_major
else
alias_name_major_minor
end
valid_alias_names = [alias_name_major, alias_name_major_minor]
if formula.tap && !formula.tap.core_tap?
valid_alias_names.map! { |a| "#{formula.tap}/#{a}" }
end
valid_versioned_aliases = versioned_aliases & valid_alias_names
invalid_versioned_aliases = versioned_aliases - valid_alias_names
if valid_versioned_aliases.empty?
if formula.tap
problem <<-EOS.undent
Formula has other versions so create a versioned alias:
cd #{formula.tap.alias_dir}
ln -s #{formula.path.to_s.gsub(formula.tap.path, "..")} #{alias_name}
EOS
else
problem "Formula has other versions so create an alias named #{alias_name}."
end
end
unless invalid_versioned_aliases.empty?
problem <<-EOS.undent
Formula has invalid versioned aliases:
#{invalid_versioned_aliases.join("\n ")}
EOS
end
end
end
def audit_class
if @strict
unless formula.test_defined?
problem "A `test do` test block should be added"
end
end
classes = %w[GithubGistFormula ScriptFileFormula AmazonWebServicesFormula]
klass = classes.find do |c|
Object.const_defined?(c) && formula.class < Object.const_get(c)
end
problem "#{klass} is deprecated, use Formula instead" if klass
end
# core aliases + tap alias names + tap alias full name
@@aliases ||= Formula.aliases + Formula.tap_aliases
def audit_formula_name
return unless @strict
# skip for non-official taps
return if formula.tap.nil? || !formula.tap.official?
name = formula.name
full_name = formula.full_name
if Homebrew::MissingFormula.blacklisted_reason(name)
problem "'#{name}' is blacklisted."
end
if Formula.aliases.include? name
problem "Formula name conflicts with existing aliases."
return
end
if oldname = CoreTap.instance.formula_renames[name]
problem "'#{name}' is reserved as the old name of #{oldname}"
return
end
if !formula.core_formula? && Formula.core_names.include?(name)
problem "Formula name conflicts with existing core formula."
return
end
@@local_official_taps_name_map ||= Tap.select(&:official?).flat_map(&:formula_names)
.each_with_object({}) do |tap_formula_full_name, name_map|
tap_formula_name = tap_formula_full_name.split("/").last
name_map[tap_formula_name] ||= []
name_map[tap_formula_name] << tap_formula_full_name
name_map
end
same_name_tap_formulae = @@local_official_taps_name_map[name] || []
if @online
Homebrew.search_taps(name).each do |tap_formula_full_name|
tap_formula_name = tap_formula_full_name.split("/").last
next if tap_formula_name != name
same_name_tap_formulae << tap_formula_full_name
end
end
same_name_tap_formulae.delete(full_name)
return if same_name_tap_formulae.empty?
problem "Formula name conflicts with #{same_name_tap_formulae.join ", "}"
end
def audit_deps
@specs.each do |spec|
# Check for things we don't like to depend on.
# We allow non-Homebrew installs whenever possible.
spec.deps.each do |dep|
begin
dep_f = dep.to_formula
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap dependencies
next
rescue FormulaUnavailableError
problem "Can't find dependency #{dep.name.inspect}."
next
rescue TapFormulaAmbiguityError
problem "Ambiguous dependency #{dep.name.inspect}."
next
rescue TapFormulaWithOldnameAmbiguityError
problem "Ambiguous oldname dependency #{dep.name.inspect}."
next
end
if dep_f.oldname && dep.name.split("/").last == dep_f.oldname
problem "Dependency '#{dep.name}' was renamed; use new name '#{dep_f.name}'."
end
if @@aliases.include?(dep.name) &&
(dep_f.core_formula? || !dep_f.versioned_formula?)
problem "Dependency '#{dep.name}' is an alias; use the canonical name '#{dep.to_formula.full_name}'."
end
if @new_formula && dep_f.keg_only_reason &&
!["openssl", "apr", "apr-util"].include?(dep.name) &&
[:provided_by_macos, :provided_by_osx].include?(dep_f.keg_only_reason.reason)
problem "Dependency '#{dep.name}' may be unnecessary as it is provided by macOS; try to build this formula without it."
end
dep.options.reject do |opt|
next true if dep_f.option_defined?(opt)
dep_f.requirements.detect do |r|
if r.recommended?
opt.name == "with-#{r.name}"
elsif r.optional?
opt.name == "without-#{r.name}"
end
end
end.each do |opt|
problem "Dependency #{dep} does not define option #{opt.name.inspect}"
end
case dep.name
when "git"
problem "Don't use git as a dependency"
when "mercurial"
problem "Use `depends_on :hg` instead of `depends_on 'mercurial'`"
when "gfortran"
problem "Use `depends_on :fortran` instead of `depends_on 'gfortran'`"
when "ruby"
problem <<-EOS.undent
Don't use "ruby" as a dependency. If this formula requires a
minimum Ruby version not provided by the system you should
use the RubyRequirement:
depends_on :ruby => "1.8"
where "1.8" is the minimum version of Ruby required.
EOS
when "open-mpi", "mpich"
problem <<-EOS.undent
There are multiple conflicting ways to install MPI. Use an MPIRequirement:
depends_on :mpi => [<lang list>]
Where <lang list> is a comma delimited list that can include:
:cc, :cxx, :f77, :f90
EOS
when *BUILD_TIME_DEPS
next if dep.build? || dep.run?
problem <<-EOS.undent
#{dep} dependency should be
depends_on "#{dep}" => :build
Or if it is indeed a runtime dependency
depends_on "#{dep}" => :run
EOS
end
end
end
end
def audit_conflicts
formula.conflicts.each do |c|
begin
Formulary.factory(c.name)
rescue TapFormulaUnavailableError
# Don't complain about missing cross-tap conflicts.
next
rescue FormulaUnavailableError
problem "Can't find conflicting formula #{c.name.inspect}."
rescue TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
problem "Ambiguous conflicting formula #{c.name.inspect}."
end
end
versioned_conflicts_whitelist = %w[node@ bash-completion@].freeze
return unless formula.conflicts.any? && formula.versioned_formula?
return if formula.name.start_with?(*versioned_conflicts_whitelist)
problem <<-EOS
Versioned formulae should not use `conflicts_with`.
Use `keg_only :versioned_formula` instead.
EOS
end
def audit_keg_only_style
return unless @strict
return unless formula.keg_only?
whitelist = %w[
Apple
macOS
OS
Homebrew
Xcode
GPG
GNOME
BSD
Firefox
].freeze
reason = formula.keg_only_reason.to_s
# Formulae names can legitimately be uppercase/lowercase/both.
name = Regexp.new(formula.name, Regexp::IGNORECASE)
reason.sub!(name, "")
first_word = reason.split[0]
if reason =~ /\A[A-Z]/ && !reason.start_with?(*whitelist)
problem <<-EOS.undent
'#{first_word}' from the keg_only reason should be '#{first_word.downcase}'.
EOS
end
return unless reason.end_with?(".")
problem "keg_only reason should not end with a period."
end
def audit_options
formula.options.each do |o|
if o.name == "32-bit"
problem "macOS has been 64-bit only since 10.6 so 32-bit options are deprecated."
end
next unless @strict
if o.name == "universal"
problem "macOS has been 64-bit only since 10.6 so universal options are deprecated."
end
if o.name !~ /with(out)?-/ && o.name != "c++11" && o.name != "universal"
problem "Options should begin with with/without. Migrate '--#{o.name}' with `deprecated_option`."
end
next unless o.name =~ /^with(out)?-(?:checks?|tests)$/
unless formula.deps.any? { |d| d.name == "check" && (d.optional? || d.recommended?) }
problem "Use '--with#{$1}-test' instead of '--#{o.name}'. Migrate '--#{o.name}' with `deprecated_option`."
end
end
return unless @new_formula
return if formula.deprecated_options.empty?
return if formula.versioned_formula?
problem "New formulae should not use `deprecated_option`."
end
def audit_homepage
homepage = formula.homepage
return if homepage.nil? || homepage.empty?
return unless @online
return unless DevelopmentTools.curl_handles_most_https_homepages?
if http_content_problem = FormulaAuditor.check_http_content(homepage,
user_agents: [:browser, :default])
problem http_content_problem
end
end
def audit_bottle_spec
return unless formula.bottle_disabled?
return if formula.bottle_disable_reason.valid?
problem "Unrecognized bottle modifier"
end
def audit_github_repository
return unless @online
return unless @new_formula
regex = %r{https?://github\.com/([^/]+)/([^/]+)/?.*}
_, user, repo = *regex.match(formula.stable.url) if formula.stable
_, user, repo = *regex.match(formula.homepage) unless user
return if !user || !repo
repo.gsub!(/.git$/, "")
begin
metadata = GitHub.repository(user, repo)
rescue GitHub::HTTPNotFoundError
return
end
return if metadata.nil?
problem "GitHub fork (not canonical repository)" if metadata["fork"]
if (metadata["forks_count"] < 20) && (metadata["subscribers_count"] < 20) &&
(metadata["stargazers_count"] < 50)
problem "GitHub repository not notable enough (<20 forks, <20 watchers and <50 stars)"
end
return if Date.parse(metadata["created_at"]) <= (Date.today - 30)
problem "GitHub repository too new (<30 days old)"
end
def audit_specs
if head_only?(formula) && formula.tap.to_s.downcase !~ %r{[-/]head-only$}
problem "Head-only (no stable download)"
end
if devel_only?(formula) && formula.tap.to_s.downcase !~ %r{[-/]devel-only$}
problem "Devel-only (no stable download)"
end
%w[Stable Devel HEAD].each do |name|
next unless spec = formula.send(name.downcase)
ra = ResourceAuditor.new(spec, online: @online, strict: @strict).audit
problems.concat ra.problems.map { |problem| "#{name}: #{problem}" }
spec.resources.each_value do |resource|
ra = ResourceAuditor.new(resource, online: @online, strict: @strict).audit
problems.concat ra.problems.map { |problem|
"#{name} resource #{resource.name.inspect}: #{problem}"
}
end
next if spec.patches.empty?
spec.patches.each { |p| patch_problems(p) if p.external? }
next unless @new_formula
problem "New formulae should not require patches to build. Patches should be submitted and accepted upstream first."
end
%w[Stable Devel].each do |name|
next unless spec = formula.send(name.downcase)
version = spec.version
if version.to_s !~ /\d/
problem "#{name}: version (#{version}) is set to a string without a digit"
end
if version.to_s.start_with?("HEAD")
problem "#{name}: non-HEAD version name (#{version}) should not begin with HEAD"
end
end
if formula.stable && formula.devel
if formula.devel.version < formula.stable.version
problem "devel version #{formula.devel.version} is older than stable version #{formula.stable.version}"
elsif formula.devel.version == formula.stable.version
problem "stable and devel versions are identical"
end
end
unstable_whitelist = %w[
aalib 1.4rc5
angolmois 2.0.0alpha2
automysqlbackup 3.0-rc6
aview 1.3.0rc1
distcc 3.2rc1
elm-format 0.6.0-alpha
ftgl 2.1.3-rc5
hidapi 0.8.0-rc1
libcaca 0.99b19
nethack4 4.3.0-beta2
opensyobon 1.0rc2
premake 4.4-beta5
pwnat 0.3-beta
pxz 4.999.9
recode 3.7-beta2
speexdsp 1.2rc3
sqoop 1.4.6
tcptraceroute 1.5beta7
testssl 2.8rc3
tiny-fugue 5.0b8
vbindiff 3.0_beta4
].each_slice(2).to_a.map do |formula, version|
[formula, version.sub(/\d+$/, "")]
end
gnome_devel_whitelist = %w[
gtk-doc 1.25
libart 2.3.21
pygtkglext 1.1.0
].each_slice(2).to_a.map do |formula, version|
[formula, version.split(".")[0..1].join(".")]
end
stable = formula.stable
case stable && stable.url
when /[\d\._-](alpha|beta|rc\d)/
matched = $1
version_prefix = stable.version.to_s.sub(/\d+$/, "")
return if unstable_whitelist.include?([formula.name, version_prefix])
problem "Stable version URLs should not contain #{matched}"
when %r{download\.gnome\.org/sources}, %r{ftp\.gnome\.org/pub/GNOME/sources}i
version_prefix = stable.version.to_s.split(".")[0..1].join(".")
return if gnome_devel_whitelist.include?([formula.name, version_prefix])
version = Version.parse(stable.url)
if version >= Version.create("1.0")
minor_version = version.to_s.split(".", 3)[1].to_i
if minor_version.odd?
problem "#{stable.version} is a development release"
end
end
end
end
def audit_revision_and_version_scheme
return unless formula.tap # skip formula not from core or any taps
return unless formula.tap.git? # git log is required
return if @new_formula
fv = FormulaVersions.new(formula)
previous_version_and_checksum = fv.previous_version_and_checksum("origin/master")
[:stable, :devel].each do |spec_sym|
next unless spec = formula.send(spec_sym)
next unless previous_version_and_checksum[spec_sym][:version] == spec.version
next if previous_version_and_checksum[spec_sym][:checksum] == spec.checksum
problem "#{spec_sym}: sha256 changed without the version also changing; please create an issue upstream to rule out malicious circumstances and to find out why the file changed."
end
attributes = [:revision, :version_scheme]
attributes_map = fv.version_attributes_map(attributes, "origin/master")
current_version_scheme = formula.version_scheme
[:stable, :devel].each do |spec|
spec_version_scheme_map = attributes_map[:version_scheme][spec]
next if spec_version_scheme_map.empty?
version_schemes = spec_version_scheme_map.values.flatten
max_version_scheme = version_schemes.max
max_version = spec_version_scheme_map.select do |_, version_scheme|
version_scheme.first == max_version_scheme
end.keys.max
if max_version_scheme && current_version_scheme < max_version_scheme
problem "version_scheme should not decrease (from #{max_version_scheme} to #{current_version_scheme})"
end
if max_version_scheme && current_version_scheme >= max_version_scheme &&
current_version_scheme > 1 &&
!version_schemes.include?(current_version_scheme - 1)
problem "version_schemes should only increment by 1"
end
formula_spec = formula.send(spec)
next unless formula_spec
spec_version = formula_spec.version
next unless max_version
next if spec_version >= max_version
above_max_version_scheme = current_version_scheme > max_version_scheme
map_includes_version = spec_version_scheme_map.keys.include?(spec_version)
next if !current_version_scheme.zero? &&
(above_max_version_scheme || map_includes_version)
problem "#{spec} version should not decrease (from #{max_version} to #{spec_version})"
end
current_revision = formula.revision
revision_map = attributes_map[:revision][:stable]
if formula.stable && !revision_map.empty?
stable_revisions = revision_map[formula.stable.version]
stable_revisions ||= []
max_revision = stable_revisions.max || 0
if current_revision < max_revision
problem "revision should not decrease (from #{max_revision} to #{current_revision})"
end
stable_revisions -= [formula.revision]
if !current_revision.zero? && stable_revisions.empty? &&
revision_map.keys.length > 1
problem "'revision #{formula.revision}' should be removed"
elsif current_revision > 1 &&
current_revision != max_revision &&
!stable_revisions.include?(current_revision - 1)
problem "revisions should only increment by 1"
end
elsif !current_revision.zero? # head/devel-only formula
problem "'revision #{current_revision}' should be removed"
end
end
def audit_legacy_patches
return unless formula.respond_to?(:patches)
legacy_patches = Patch.normalize_legacy_patches(formula.patches).grep(LegacyPatch)
return if legacy_patches.empty?
problem "Use the patch DSL instead of defining a 'patches' method"
legacy_patches.each { |p| patch_problems(p) }
end
def patch_problems(patch)
case patch.url
when /raw\.github\.com/, %r{gist\.github\.com/raw}, %r{gist\.github\.com/.+/raw},
%r{gist\.githubusercontent\.com/.+/raw}
unless patch.url =~ /[a-fA-F0-9]{40}/
problem "GitHub/Gist patches should specify a revision:\n#{patch.url}"
end
when %r{https?://patch-diff\.githubusercontent\.com/raw/(.+)/(.+)/pull/(.+)\.(?:diff|patch)}
problem <<-EOS.undent
use GitHub pull request URLs:
https://github.com/#{$1}/#{$2}/pull/#{$3}.patch
Rather than patch-diff:
#{patch.url}
EOS
when %r{macports/trunk}
problem "MacPorts patches should specify a revision instead of trunk:\n#{patch.url}"
when %r{^http://trac\.macports\.org}
problem "Patches from MacPorts Trac should be https://, not http:\n#{patch.url}"
when %r{^http://bugs\.debian\.org}
problem "Patches from Debian should be https://, not http:\n#{patch.url}"
end
end
def audit_text
bin_names = Set.new
bin_names << formula.name
bin_names += formula.aliases
[formula.bin, formula.sbin].each do |dir|
next unless dir.exist?
bin_names += dir.children.map(&:basename).map(&:to_s)
end
bin_names.each do |name|
["system", "shell_output", "pipe_output"].each do |cmd|
if text =~ %r{(def test|test do).*(#{Regexp.escape(HOMEBREW_PREFIX)}/bin/)?#{cmd}[\(\s]+['"]#{Regexp.escape(name)}[\s'"]}m
problem %Q(fully scope test #{cmd} calls e.g. #{cmd} "\#{bin}/#{name}")
end
end
end
end
def audit_lines
text.without_patch.split("\n").each_with_index do |line, lineno|
line_problems(line, lineno+1)
end
end
def line_problems(line, _lineno)
if line =~ /<(Formula|AmazonWebServicesFormula|ScriptFileFormula|GithubGistFormula)/
problem "Use a space in class inheritance: class Foo < #{$1}"
end
# Commented-out cmake support from default template
problem "Commented cmake call found" if line.include?('# system "cmake')
# Comments from default template
[
"# PLEASE REMOVE",
"# Documentation:",
"# if this fails, try separate make/make install steps",
"# The URL of the archive",
"## Naming --",
"# if your formula requires any X11/XQuartz components",
"# if your formula fails when building in parallel",
"# Remove unrecognized options if warned by configure",
].each do |comment|
next unless line.include?(comment)
problem "Please remove default template comments"
end
# FileUtils is included in Formula
# encfs modifies a file with this name, so check for some leading characters
if line =~ %r{[^'"/]FileUtils\.(\w+)}
problem "Don't need 'FileUtils.' before #{$1}."
end
# Check for long inreplace block vars
if line =~ /inreplace .* do \|(.{2,})\|/
problem "\"inreplace <filenames> do |s|\" is preferred over \"|#{$1}|\"."
end
# Check for string interpolation of single values.
if line =~ /(system|inreplace|gsub!|change_make_var!).*[ ,]"#\{([\w.]+)\}"/
problem "Don't need to interpolate \"#{$2}\" with #{$1}"
end
# Check for string concatenation; prefer interpolation
if line =~ /(#\{\w+\s*\+\s*['"][^}]+\})/
problem "Try not to concatenate paths in string interpolation:\n #{$1}"
end
# Prefer formula path shortcuts in Pathname+
if line =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|libexec|lib|sbin|share|Frameworks)[/'"])}
problem "\"(#{$1}...#{$2})\" should be \"(#{$3.downcase}+...)\""
end
if line =~ /((man)\s*\+\s*(['"])(man[1-8])(['"]))/
problem "\"#{$1}\" should be \"#{$4}\""
end
# Prefer formula path shortcuts in strings
if line =~ %r[(\#\{prefix\}/(bin|include|libexec|lib|sbin|share|Frameworks))]
problem "\"#{$1}\" should be \"\#{#{$2.downcase}}\""
end
if line =~ %r[((\#\{prefix\}/share/man/|\#\{man\}/)(man[1-8]))]
problem "\"#{$1}\" should be \"\#{#{$3}}\""
end
if line =~ %r[((\#\{share\}/(man)))[/'"]]
problem "\"#{$1}\" should be \"\#{#{$3}}\""
end
if line =~ %r[(\#\{prefix\}/share/(info|man))]
problem "\"#{$1}\" should be \"\#{#{$2}}\""
end
if line =~ /depends_on :(automake|autoconf|libtool)/
problem ":#{$1} is deprecated. Usage should be \"#{$1}\""
end
if line =~ /depends_on :apr/
problem ":apr is deprecated. Usage should be \"apr-util\""
end
problem ":tex is deprecated" if line =~ /depends_on :tex/
if line =~ /depends_on\s+['"](.+)['"]\s+=>\s+:(lua|perl|python|ruby)(\d*)/
problem "#{$2} modules should be vendored rather than use deprecated `depends_on \"#{$1}\" => :#{$2}#{$3}`"
end
if line =~ /depends_on\s+['"](.+)['"]\s+=>\s+(.*)/
dep = $1
$2.split(" ").map do |o|
break if ["if", "unless"].include?(o)
next unless o =~ /^\[?['"](.*)['"]/
problem "Dependency #{dep} should not use option #{$1}"
end
end
# Commented-out depends_on
problem "Commented-out dep #{$1}" if line =~ /#\s*depends_on\s+(.+)\s*$/
if line =~ /if\s+ARGV\.include\?\s+'--(HEAD|devel)'/
problem "Use \"if build.#{$1.downcase}?\" instead"
end
problem "Use separate make calls" if line.include?("make && make")
problem "Use spaces instead of tabs for indentation" if line =~ /^[ ]*\t/
if line.include?("ENV.x11")
problem "Use \"depends_on :x11\" instead of \"ENV.x11\""
end
# Avoid hard-coding compilers
if line =~ %r{(system|ENV\[.+\]\s?=)\s?['"](/usr/bin/)?(gcc|llvm-gcc|clang)['" ]}
problem "Use \"\#{ENV.cc}\" instead of hard-coding \"#{$3}\""
end
if line =~ %r{(system|ENV\[.+\]\s?=)\s?['"](/usr/bin/)?((g|llvm-g|clang)\+\+)['" ]}
problem "Use \"\#{ENV.cxx}\" instead of hard-coding \"#{$3}\""
end
if line =~ /system\s+['"](env|export)(\s+|['"])/
problem "Use ENV instead of invoking '#{$1}' to modify the environment"
end
if formula.name != "wine" && line =~ /ENV\.universal_binary/
problem "macOS has been 64-bit only since 10.6 so ENV.universal_binary is deprecated."
end
if line =~ /build\.universal\?/
problem "macOS has been 64-bit only so build.universal? is deprecated."
end
if line =~ /version == ['"]HEAD['"]/
problem "Use 'build.head?' instead of inspecting 'version'"
end
if line =~ /build\.include\?[\s\(]+['"]\-\-(.*)['"]/
problem "Reference '#{$1}' without dashes"
end
if line =~ /build\.include\?[\s\(]+['"]with(out)?-(.*)['"]/
problem "Use build.with#{$1}? \"#{$2}\" instead of build.include? 'with#{$1}-#{$2}'"
end
if line =~ /build\.with\?[\s\(]+['"]-?-?with-(.*)['"]/
problem "Don't duplicate 'with': Use `build.with? \"#{$1}\"` to check for \"--with-#{$1}\""
end
if line =~ /build\.without\?[\s\(]+['"]-?-?without-(.*)['"]/
problem "Don't duplicate 'without': Use `build.without? \"#{$1}\"` to check for \"--without-#{$1}\""
end
if line =~ /unless build\.with\?(.*)/
problem "Use if build.without?#{$1} instead of unless build.with?#{$1}"
end
if line =~ /unless build\.without\?(.*)/
problem "Use if build.with?#{$1} instead of unless build.without?#{$1}"
end
if line =~ /(not\s|!)\s*build\.with?\?/
problem "Don't negate 'build.with?': use 'build.without?'"
end
if line =~ /(not\s|!)\s*build\.without?\?/
problem "Don't negate 'build.without?': use 'build.with?'"
end
if line =~ /ARGV\.(?!(debug\?|verbose\?|value[\(\s]))/
problem "Use build instead of ARGV to check options"
end
problem "Use new-style option definitions" if line.include?("def options")
if line.end_with?("def test")
problem "Use new-style test definitions (test do)"
end
if line.include?("MACOS_VERSION")
problem "Use MacOS.version instead of MACOS_VERSION"
end
if line.include?("MACOS_FULL_VERSION")
problem "Use MacOS.full_version instead of MACOS_FULL_VERSION"
end
cats = %w[leopard snow_leopard lion mountain_lion].join("|")
if line =~ /MacOS\.(?:#{cats})\?/
problem "\"#{$&}\" is deprecated, use a comparison to MacOS.version instead"
end
if line =~ /skip_clean\s+:all/
problem "`skip_clean :all` is deprecated; brew no longer strips symbols\n" \
"\tPass explicit paths to prevent Homebrew from removing empty folders."
end
if line =~ /depends_on [A-Z][\w:]+\.new$/
problem "`depends_on` can take requirement classes instead of instances"
end
if line =~ /^def (\w+).*$/
problem "Define method #{$1.inspect} in the class body, not at the top-level"
end
if line.include?("ENV.fortran") && !formula.requirements.map(&:class).include?(FortranRequirement)
problem "Use `depends_on :fortran` instead of `ENV.fortran`"
end
if line =~ /JAVA_HOME/i && !formula.requirements.map(&:class).include?(JavaRequirement)
problem "Use `depends_on :java` to set JAVA_HOME"
end
if line =~ /depends_on :(.+) (if.+|unless.+)$/
conditional_dep_problems($1.to_sym, $2, $&)
end
if line =~ /depends_on ['"](.+)['"] (if.+|unless.+)$/
conditional_dep_problems($1, $2, $&)
end
if line =~ /(Dir\[("[^\*{},]+")\])/
problem "#{$1} is unnecessary; just use #{$2}"
end
if line =~ /system (["'](#{FILEUTILS_METHODS})["' ])/o
system = $1
method = $2
problem "Use the `#{method}` Ruby method instead of `system #{system}`"
end
if line =~ /assert [^!]+\.include?/
problem "Use `assert_match` instead of `assert ...include?`"
end
if line.include?('system "npm", "install"') && !line.include?("Language::Node") &&
formula.name !~ /^kibana(\@\d+(\.\d+)?)?$/
problem "Use Language::Node for npm install args"
end
if line.include?("fails_with :llvm")
problem "'fails_with :llvm' is now a no-op so should be removed"
end
if line =~ /system\s+['"](otool|install_name_tool|lipo)/ && formula.name != "cctools"
problem "Use ruby-macho instead of calling #{$1}"
end
if formula.tap.to_s == "homebrew/core"
["OS.mac?", "OS.linux?"].each do |check|
next unless line.include?(check)
problem "Don't use #{check}; Homebrew/core only supports macOS"
end
end
if line =~ /((revision|version_scheme)\s+0)/
problem "'#{$1}' should be removed"
end
return unless @strict
problem "`#{$1}` in formulae is deprecated" if line =~ /(env :(std|userpaths))/
if line =~ /system ((["'])[^"' ]*(?:\s[^"' ]*)+\2)/
bad_system = $1
unless %w[| < > & ; *].any? { |c| bad_system.include? c }
good_system = bad_system.gsub(" ", "\", \"")
problem "Use `system #{good_system}` instead of `system #{bad_system}` "
end
end
problem "`#{$1}` is now unnecessary" if line =~ /(require ["']formula["'])/
if line =~ %r{#\{share\}/#{Regexp.escape(formula.name)}[/'"]}
problem "Use \#{pkgshare} instead of \#{share}/#{formula.name}"
end
return unless line =~ %r{share(\s*[/+]\s*)(['"])#{Regexp.escape(formula.name)}(?:\2|/)}
problem "Use pkgshare instead of (share#{$1}\"#{formula.name}\")"
end
def audit_reverse_migration
# Only enforce for new formula being re-added to core and official taps
return unless @strict
return unless formula.tap && formula.tap.official?
return unless formula.tap.tap_migrations.key?(formula.name)
problem <<-EOS.undent
#{formula.name} seems to be listed in tap_migrations.json!
Please remove #{formula.name} from present tap & tap_migrations.json
before submitting it to Homebrew/homebrew-#{formula.tap.repo}.
EOS
end
def audit_prefix_has_contents
return unless formula.prefix.directory?
return unless Keg.new(formula.prefix).empty_installation?
problem <<-EOS.undent
The installation seems to be empty. Please ensure the prefix
is set correctly and expected files are installed.
The prefix configure/make argument may be case-sensitive.
EOS
end
def conditional_dep_problems(dep, condition, line)
quoted_dep = quote_dep(dep)
dep = Regexp.escape(dep.to_s)
case condition
when /if build\.include\? ['"]with-#{dep}['"]$/, /if build\.with\? ['"]#{dep}['"]$/
problem %Q(Replace #{line.inspect} with "depends_on #{quoted_dep} => :optional")
when /unless build\.include\? ['"]without-#{dep}['"]$/, /unless build\.without\? ['"]#{dep}['"]$/
problem %Q(Replace #{line.inspect} with "depends_on #{quoted_dep} => :recommended")
end
end
def quote_dep(dep)
dep.is_a?(Symbol) ? dep.inspect : "'#{dep}'"
end
def problem_if_output(output)
problem(output) if output
end
def audit
only_audits = ARGV.value("only").to_s.split(",")
except_audits = ARGV.value("except").to_s.split(",")
if !only_audits.empty? && !except_audits.empty?
odie "--only and --except cannot be used simultaneously!"
end
methods.map(&:to_s).grep(/^audit_/).each do |audit_method_name|
name = audit_method_name.gsub(/^audit_/, "")
if !only_audits.empty?
next unless only_audits.include?(name)
elsif !except_audits.empty?
next if except_audits.include?(name)
end
send(audit_method_name)
end
end
private
def problem(p)
@problems << p
end
def head_only?(formula)
formula.head && formula.devel.nil? && formula.stable.nil?
end
def devel_only?(formula)
formula.devel && formula.stable.nil?
end
end
class ResourceAuditor
attr_reader :problems
attr_reader :version, :checksum, :using, :specs, :url, :mirrors, :name
def initialize(resource, options = {})
@name = resource.name
@version = resource.version
@checksum = resource.checksum
@url = resource.url
@mirrors = resource.mirrors
@using = resource.using
@specs = resource.specs
@online = options[:online]
@strict = options[:strict]
@problems = []
end
def audit
audit_version
audit_checksum
audit_download_strategy
audit_urls
self
end
def audit_version
if version.nil?
problem "missing version"
elsif version.to_s.empty?
problem "version is set to an empty string"
elsif !version.detected_from_url?
version_text = version
version_url = Version.detect(url, specs)
if version_url.to_s == version_text.to_s && version.instance_of?(Version)
problem "version #{version_text} is redundant with version scanned from URL"
end
end
if version.to_s.start_with?("v")
problem "version #{version} should not have a leading 'v'"
end
return unless version.to_s =~ /_\d+$/
problem "version #{version} should not end with an underline and a number"
end
def audit_checksum
return unless checksum
case checksum.hash_type
when :md5
problem "MD5 checksums are deprecated, please use SHA256"
return
when :sha1
problem "SHA1 checksums are deprecated, please use SHA256"
return
when :sha256 then len = 64
end
if checksum.empty?
problem "#{checksum.hash_type} is empty"
else
problem "#{checksum.hash_type} should be #{len} characters" unless checksum.hexdigest.length == len
problem "#{checksum.hash_type} contains invalid characters" unless checksum.hexdigest =~ /^[a-fA-F0-9]+$/
problem "#{checksum.hash_type} should be lowercase" unless checksum.hexdigest == checksum.hexdigest.downcase
end
end
def audit_download_strategy
if url =~ %r{^(cvs|bzr|hg|fossil)://} || url =~ %r{^(svn)\+http://}
problem "Use of the #{$&} scheme is deprecated, pass `:using => :#{$1}` instead"
end
url_strategy = DownloadStrategyDetector.detect(url)
if using == :git || url_strategy == GitDownloadStrategy
if specs[:tag] && !specs[:revision]
problem "Git should specify :revision when a :tag is specified."
end
end
return unless using
if using == :ssl3 || \
(Object.const_defined?("CurlSSL3DownloadStrategy") && using == CurlSSL3DownloadStrategy)
problem "The SSL3 download strategy is deprecated, please choose a different URL"
elsif (Object.const_defined?("CurlUnsafeDownloadStrategy") && using == CurlUnsafeDownloadStrategy) || \
(Object.const_defined?("UnsafeSubversionDownloadStrategy") && using == UnsafeSubversionDownloadStrategy)
problem "#{using.name} is deprecated, please choose a different URL"
end
if using == :cvs
mod = specs[:module]
problem "Redundant :module value in URL" if mod == name
if url =~ %r{:[^/]+$}
mod = url.split(":").last
if mod == name
problem "Redundant CVS module appended to URL"
else
problem "Specify CVS module as `:module => \"#{mod}\"` instead of appending it to the URL"
end
end
end
return unless url_strategy == DownloadStrategyDetector.detect("", using)
problem "Redundant :using value in URL"
end
def audit_urls
# Check GNU urls; doesn't apply to mirrors
if url =~ %r{^(?:https?|ftp)://ftpmirror.gnu.org/(.*)}
problem "Please use \"https://ftp.gnu.org/gnu/#{$1}\" instead of #{url}."
end
if mirrors.include?(url)
problem "URL should not be duplicated as a mirror: #{url}"
end
urls = [url] + mirrors
# Check a variety of SSL/TLS URLs that don't consistently auto-redirect
# or are overly common errors that need to be reduced & fixed over time.
urls.each do |p|
case p
when %r{^http://ftp\.gnu\.org/},
%r{^http://ftpmirror\.gnu\.org/},
%r{^http://download\.savannah\.gnu\.org/},
%r{^http://download-mirror\.savannah\.gnu\.org/},
%r{^http://[^/]*\.apache\.org/},
%r{^http://code\.google\.com/},
%r{^http://fossies\.org/},
%r{^http://mirrors\.kernel\.org/},
%r{^http://(?:[^/]*\.)?bintray\.com/},
%r{^http://tools\.ietf\.org/},
%r{^http://launchpad\.net/},
%r{^http://github\.com/},
%r{^http://bitbucket\.org/},
%r{^http://anonscm\.debian\.org/},
%r{^http://cpan\.metacpan\.org/},
%r{^http://hackage\.haskell\.org/},
%r{^http://(?:[^/]*\.)?archive\.org},
%r{^http://(?:[^/]*\.)?freedesktop\.org},
%r{^http://(?:[^/]*\.)?mirrorservice\.org/}
problem "Please use https:// for #{p}"
when %r{^http://search\.mcpan\.org/CPAN/(.*)}i
problem "#{p} should be `https://cpan.metacpan.org/#{$1}`"
when %r{^(http|ftp)://ftp\.gnome\.org/pub/gnome/(.*)}i
problem "#{p} should be `https://download.gnome.org/#{$2}`"
when %r{^git://anonscm\.debian\.org/users/(.*)}i
problem "#{p} should be `https://anonscm.debian.org/git/users/#{$1}`"
end
end
# Prefer HTTP/S when possible over FTP protocol due to possible firewalls.
urls.each do |p|
case p
when %r{^ftp://ftp\.mirrorservice\.org}
problem "Please use https:// for #{p}"
when %r{^ftp://ftp\.cpan\.org/pub/CPAN(.*)}i
problem "#{p} should be `http://search.cpan.org/CPAN#{$1}`"
end
end
# Check SourceForge urls
urls.each do |p|
# Skip if the URL looks like a SVN repo
next if p.include? "/svnroot/"
next if p.include? "svn.sourceforge"
# Is it a sourceforge http(s) URL?
next unless p =~ %r{^https?://.*\b(sourceforge|sf)\.(com|net)}
if p =~ /(\?|&)use_mirror=/
problem "Don't use #{$1}use_mirror in SourceForge urls (url is #{p})."
end
if p.end_with?("/download")
problem "Don't use /download in SourceForge urls (url is #{p})."
end
if p =~ %r{^https?://sourceforge\.}
problem "Use https://downloads.sourceforge.net to get geolocation (url is #{p})."
end
if p =~ %r{^https?://prdownloads\.}
problem "Don't use prdownloads in SourceForge urls (url is #{p}).\n" \
"\tSee: http://librelist.com/browser/homebrew/2011/1/12/prdownloads-is-bad/"
end
if p =~ %r{^http://\w+\.dl\.}
problem "Don't use specific dl mirrors in SourceForge urls (url is #{p})."
end
problem "Please use https:// for #{p}" if p.start_with? "http://downloads"
end
# Debian has an abundance of secure mirrors. Let's not pluck the insecure
# one out of the grab bag.
urls.each do |u|
next unless u =~ %r{^http://http\.debian\.net/debian/(.*)}i
problem <<-EOS.undent
Please use a secure mirror for Debian URLs.
We recommend:
https://mirrors.ocf.berkeley.edu/debian/#{$1}
EOS
end
# Check for Google Code download urls, https:// is preferred
# Intentionally not extending this to SVN repositories due to certificate
# issues.
urls.grep(%r{^http://.*\.googlecode\.com/files.*}) do |u|
problem "Please use https:// for #{u}"
end
# Check for new-url Google Code download urls, https:// is preferred
urls.grep(%r{^http://code\.google\.com/}) do |u|
problem "Please use https:// for #{u}"
end
# Check for git:// GitHub repo urls, https:// is preferred.
urls.grep(%r{^git://[^/]*github\.com/}) do |u|
problem "Please use https:// for #{u}"
end
# Check for git:// Gitorious repo urls, https:// is preferred.
urls.grep(%r{^git://[^/]*gitorious\.org/}) do |u|
problem "Please use https:// for #{u}"
end
# Check for http:// GitHub repo urls, https:// is preferred.
urls.grep(%r{^http://github\.com/.*\.git$}) do |u|
problem "Please use https:// for #{u}"
end
# Check for master branch GitHub archives.
urls.grep(%r{^https://github\.com/.*archive/master\.(tar\.gz|zip)$}) do
problem "Use versioned rather than branch tarballs for stable checksums."
end
# Use new-style archive downloads
urls.each do |u|
next unless u =~ %r{https://.*github.*/(?:tar|zip)ball/} && u !~ /\.git$/
problem "Use /archive/ URLs for GitHub tarballs (url is #{u})."
end
# Don't use GitHub .zip files
urls.each do |u|
next unless u =~ %r{https://.*github.*/(archive|releases)/.*\.zip$} && u !~ %r{releases/download}
problem "Use GitHub tarballs rather than zipballs (url is #{u})."
end
# Don't use GitHub codeload URLs
urls.each do |u|
next unless u =~ %r{https?://codeload\.github\.com/(.+)/(.+)/(?:tar\.gz|zip)/(.+)}
problem <<-EOS.undent
use GitHub archive URLs:
https://github.com/#{$1}/#{$2}/archive/#{$3}.tar.gz
Rather than codeload:
#{u}
EOS
end
# Check for Maven Central urls, prefer HTTPS redirector over specific host
urls.each do |u|
next unless u =~ %r{https?://(?:central|repo\d+)\.maven\.org/maven2/(.+)$}
problem "#{u} should be `https://search.maven.org/remotecontent?filepath=#{$1}`"
end
return unless @online
urls.each do |url|
next if !@strict && mirrors.include?(url)
strategy = DownloadStrategyDetector.detect(url, using)
if strategy <= CurlDownloadStrategy && !url.start_with?("file")
# A `brew mirror`'ed URL is usually not yet reachable at the time of
# pull request.
next if url =~ %r{^https://dl.bintray.com/homebrew/mirror/}
if http_content_problem = FormulaAuditor.check_http_content(url)
problem http_content_problem
end
elsif strategy <= GitDownloadStrategy
unless Utils.git_remote_exists url
problem "The URL #{url} is not a valid git URL"
end
elsif strategy <= SubversionDownloadStrategy
next unless DevelopmentTools.subversion_handles_most_https_certificates?
unless Utils.svn_remote_exists url
problem "The URL #{url} is not a valid svn URL"
end
end
end
end
def problem(text)
@problems << text
end
end
|
# The python_helper is used in the Formula class when the user calls
# `python`, `python2` or `python3`.
# This method has a dual nature. For one, it takes a &block and sets up
# the ENV such that a Python, as defined in the requirements, is the default.
# If there are multiple `PythonInstalled` requirements, the block is evaluated
# once for each Python. This makes it possible to easily support 2.x and
# 3.x Python bindings without code duplication in formulae.
# If you need to special case stuff, set :allowed_major_versions.
# Second, inside the block, a formula author may call this method to access
# certain convienience methods for the currently selected Python, e.g.
# `python.site_packages`.
def python_helper(options={:allowed_major_versions => [2, 3]}, &block)
if !block_given? and !@current_python.nil?
# We are already inside of a `python do ... end` block, so just return
# the current_python or false if the version.major is not allowed.
if options[:allowed_major_versions].include?(@current_python.version.major)
@current_python
else
false
end
else
# Look for PythonInstalled requirements for this formula
python_reqs = requirements.select{ |r| r.kind_of?(PythonInstalled) }
if python_reqs.empty?
raise "If you use python in the formula, you have to add `depends_on :python` (or :python3)!"
end
# Now select those that are satisfied and matching the version.major
python_reqs = python_reqs.select do |p|
p.satisfied? &&
options[:allowed_major_versions].include?(p.version.major) &&
if p.optional? || p.recommended?
self.build.with?(p.name)
else
true
end
end
# Allow to use an else-branch like so: `if python do ... end; else ... end`
return false if python_reqs.empty?
# Sort by version, so the older 2.x will be used first and if no
# block_given? then 2.x is preferred because it is returned.
# Further note, having 3.x last allows us to run `2to3 --write .`
# which modifies the sources in-place (for some packages that need this).
python_reqs.sort_by{ |py| py.version }.map do |py|
# Now is the time to set the site_packages to the correct value
py.site_packages = lib/py.xy/'site-packages'
if block_given?
puts "brew: Python block (#{py.binary})..." if ARGV.verbose?
require 'superenv'
# Ensure env changes are only temporary by using `with_build_environment`
ENV.with_build_environment do
# In order to install into the Cellar, the dir must exist and be in the
# PYTHONPATH. This will be executed in the context of the formula
# so that lib points to the HOMEBREW_PREFIX/Cellar/<formula>/<version>/lib
puts "brew: Setting PYTHONPATH=#{py.site_packages}" if ARGV.verbose?
mkdir_p py.site_packages
ENV.append 'PYTHONPATH', py.site_packages, ':'
ENV['PYTHON'] = py.binary
ENV.prepend 'CMAKE_INCLUDE_PATH', py.incdir, ':'
ENV.prepend 'PKG_CONFIG_PATH', py.pkg_config_path, ':' if py.pkg_config_path
ENV.prepend 'PATH', py.binary.dirname, ':' unless py.from_osx?
# Track the state of the currently selected python for this block,
# so if this python_helper is called again _inside_ the block, we can
# just return the right python (see `else`-branch a few lines down):
@current_python = py
res = instance_eval(&block)
@current_python = nil
res
end
else
puts "brew: Using #{py.binary}" if ARGV.verbose?
# We return here with intention, because no block_given?
return py
end
end
end
end
Python is less verbose with "brew: Using python.."
Now it is only shown for an `python do ... end` block
and not for ordinary python.site_packages or other
methods.
# The python_helper is used in the Formula class when the user calls
# `python`, `python2` or `python3`.
# This method has a dual nature. For one, it takes a &block and sets up
# the ENV such that a Python, as defined in the requirements, is the default.
# If there are multiple `PythonInstalled` requirements, the block is evaluated
# once for each Python. This makes it possible to easily support 2.x and
# 3.x Python bindings without code duplication in formulae.
# If you need to special case stuff, set :allowed_major_versions.
# Second, inside the block, a formula author may call this method to access
# certain convienience methods for the currently selected Python, e.g.
# `python.site_packages`.
def python_helper(options={:allowed_major_versions => [2, 3]}, &block)
if !block_given? and !@current_python.nil?
# We are already inside of a `python do ... end` block, so just return
# the current_python or false if the version.major is not allowed.
if options[:allowed_major_versions].include?(@current_python.version.major)
@current_python
else
false
end
else
# Look for PythonInstalled requirements for this formula
python_reqs = requirements.select{ |r| r.kind_of?(PythonInstalled) }
if python_reqs.empty?
raise "If you use python in the formula, you have to add `depends_on :python` (or :python3)!"
end
# Now select those that are satisfied and matching the version.major
python_reqs = python_reqs.select do |p|
p.satisfied? &&
options[:allowed_major_versions].include?(p.version.major) &&
if p.optional? || p.recommended?
self.build.with?(p.name)
else
true
end
end
# Allow to use an else-branch like so: `if python do ... end; else ... end`
return false if python_reqs.empty?
# Sort by version, so the older 2.x will be used first and if no
# block_given? then 2.x is preferred because it is returned.
# Further note, having 3.x last allows us to run `2to3 --write .`
# which modifies the sources in-place (for some packages that need this).
python_reqs.sort_by{ |py| py.version }.map do |py|
# Now is the time to set the site_packages to the correct value
py.site_packages = lib/py.xy/'site-packages'
if block_given?
puts "brew: Python block (#{py.binary})..." if ARGV.verbose? && ARGV.debug?
require 'superenv'
# Ensure env changes are only temporary by using `with_build_environment`
ENV.with_build_environment do
# In order to install into the Cellar, the dir must exist and be in the
# PYTHONPATH. This will be executed in the context of the formula
# so that lib points to the HOMEBREW_PREFIX/Cellar/<formula>/<version>/lib
puts "brew: Setting PYTHONPATH=#{py.site_packages}" if ARGV.verbose?
mkdir_p py.site_packages
ENV.append 'PYTHONPATH', py.site_packages, ':'
ENV['PYTHON'] = py.binary
ENV.prepend 'CMAKE_INCLUDE_PATH', py.incdir, ':'
ENV.prepend 'PKG_CONFIG_PATH', py.pkg_config_path, ':' if py.pkg_config_path
ENV.prepend 'PATH', py.binary.dirname, ':' unless py.from_osx?
# Track the state of the currently selected python for this block,
# so if this python_helper is called again _inside_ the block, we can
# just return the right python (see `else`-branch a few lines down):
@current_python = py
res = instance_eval(&block)
@current_python = nil
res
end
else
# We return the first available python, because no block_given?
return py
end
end
end
end
|
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2008-2011, Sebastian Staudt
require 'errors/rcon_no_auth_error'
require 'steam/packets/rcon/rcon_auth_request'
require 'steam/packets/rcon/rcon_auth_response'
require 'steam/packets/rcon/rcon_exec_request'
require 'steam/packets/rcon/rcon_terminator'
require 'steam/servers/game_server'
require 'steam/servers/master_server'
require 'steam/sockets/rcon_socket'
require 'steam/sockets/source_socket'
# This class represents a Source game server and can be used to query
# information about and remotely execute commands via RCON on the server
#
# A Source game server is an instance of the Source Dedicated Server (SrcDS)
# running games using Valve's Source engine, like Counter-Strike: Source,
# Team Fortress 2 or Left4Dead.
#
# @author Sebastian Staudt
# @see GoldSrcServer
class SourceServer
include GameServer
# Returns a master server instance for the default master server for Source
# games
#
# @return [MasterServer] The Source master server
def self.master
MasterServer.new *MasterServer::SOURCE_MASTER_SERVER
end
# Creates a new instance of a server object representing a Source server,
# i.e. SrcDS instance
#
# @param [String] address Either an IP address, a DNS name or one of them
# combined with the port number. If a port number is given, e.g.
# 'server.example.com:27016' it will override the second argument.
# @param [Fixnum] port The port the server is listening on
# @raise [SteamCondenserError] if an host name cannot be resolved
def initialize(address, port = 27015)
super
end
# Initializes the sockets to communicate with the Source server
#
# @see RCONSocket
# @see SourceSocket
def init_socket
@rcon_socket = RCONSocket.new @ip_address, @port
@socket = SourceSocket.new @ip_address, @port
end
# Authenticates the connection for RCON communication with the server
#
# @param [String] password The RCON password of the server
# @return [Boolean] whether authentication was successful
# @see #rcon_authenticated?
# @see #rcon_exec
def rcon_auth(password)
@rcon_request_id = rand 2**16
@rcon_socket.send RCONAuthRequest.new(@rcon_request_id, password)
@rcon_socket.reply
reply = @rcon_socket.reply
raise RCONNoAuthError if reply.request_id == -1
@rcon_authenticated = reply.request_id == @rcon_request_id
end
# Remotely executes a command on the server via RCON
#
# @param [String] command The command to execute on the server via RCON
# @return [String] The output of the executed command
# @see #rcon_auth
def rcon_exec(command)
raise RCONNoAuthError unless @rcon_authenticated
@rcon_socket.send RCONExecRequest.new(@rcon_request_id, command)
@rcon_socket.send RCONTerminator.new(@rcon_request_id)
response = ''
begin
response_packet = @rcon_socket.reply
if response_packet.is_a? RCONAuthResponse
@rcon_authenticated = false
raise RCONNoAuthError
end
response << response_packet.response
end while response.length == 0 || response_packet.response.size > 0
response.strip
end
end
Fixed handling of empty RCON responses
See issue #128
# This code is free software; you can redistribute it and/or modify it under
# the terms of the new BSD License.
#
# Copyright (c) 2008-2011, Sebastian Staudt
require 'errors/rcon_no_auth_error'
require 'steam/packets/rcon/rcon_auth_request'
require 'steam/packets/rcon/rcon_auth_response'
require 'steam/packets/rcon/rcon_exec_request'
require 'steam/packets/rcon/rcon_terminator'
require 'steam/servers/game_server'
require 'steam/servers/master_server'
require 'steam/sockets/rcon_socket'
require 'steam/sockets/source_socket'
# This class represents a Source game server and can be used to query
# information about and remotely execute commands via RCON on the server
#
# A Source game server is an instance of the Source Dedicated Server (SrcDS)
# running games using Valve's Source engine, like Counter-Strike: Source,
# Team Fortress 2 or Left4Dead.
#
# @author Sebastian Staudt
# @see GoldSrcServer
class SourceServer
include GameServer
# Returns a master server instance for the default master server for Source
# games
#
# @return [MasterServer] The Source master server
def self.master
MasterServer.new *MasterServer::SOURCE_MASTER_SERVER
end
# Creates a new instance of a server object representing a Source server,
# i.e. SrcDS instance
#
# @param [String] address Either an IP address, a DNS name or one of them
# combined with the port number. If a port number is given, e.g.
# 'server.example.com:27016' it will override the second argument.
# @param [Fixnum] port The port the server is listening on
# @raise [SteamCondenserError] if an host name cannot be resolved
def initialize(address, port = 27015)
super
end
# Initializes the sockets to communicate with the Source server
#
# @see RCONSocket
# @see SourceSocket
def init_socket
@rcon_socket = RCONSocket.new @ip_address, @port
@socket = SourceSocket.new @ip_address, @port
end
# Authenticates the connection for RCON communication with the server
#
# @param [String] password The RCON password of the server
# @return [Boolean] whether authentication was successful
# @see #rcon_authenticated?
# @see #rcon_exec
def rcon_auth(password)
@rcon_request_id = rand 2**16
@rcon_socket.send RCONAuthRequest.new(@rcon_request_id, password)
@rcon_socket.reply
reply = @rcon_socket.reply
raise RCONNoAuthError if reply.request_id == -1
@rcon_authenticated = reply.request_id == @rcon_request_id
end
# Remotely executes a command on the server via RCON
#
# @param [String] command The command to execute on the server via RCON
# @return [String] The output of the executed command
# @see #rcon_auth
def rcon_exec(command)
raise RCONNoAuthError unless @rcon_authenticated
@rcon_socket.send RCONExecRequest.new(@rcon_request_id, command)
@rcon_socket.send RCONTerminator.new(@rcon_request_id)
response = []
begin
response_packet = @rcon_socket.reply
if response_packet.is_a? RCONAuthResponse
@rcon_authenticated = false
raise RCONNoAuthError
end
response << response_packet.response
end while response.size < 3 || response_packet.response.size > 0
response.join('').strip
end
end
|
require 'forwardable'
require 'resource'
require 'checksum'
require 'version'
require 'build_options'
require 'dependency_collector'
require 'bottles'
require 'patch'
class SoftwareSpec
extend Forwardable
attr_reader :name, :owner
attr_reader :build, :resources, :patches
attr_reader :dependency_collector
attr_reader :bottle_specification
def_delegators :@resource, :stage, :fetch, :verify_download_integrity
def_delegators :@resource, :cached_download, :clear_cache
def_delegators :@resource, :checksum, :mirrors, :specs, :using, :downloader
def_delegators :@resource, :version, :mirror, *Checksum::TYPES
def initialize
@resource = Resource.new
@resources = {}
@build = BuildOptions.new(ARGV.options_only)
@dependency_collector = DependencyCollector.new
@bottle_specification = BottleSpecification.new
@patches = []
end
def owner= owner
@name = owner.name
@owner = owner
@resource.owner = self
resources.each_value do |r|
r.owner = self
r.version ||= version
end
patches.each { |p| p.owner = self }
end
def url val=nil, specs={}
return @resource.url if val.nil?
@resource.url(val, specs)
dependency_collector.add(@resource)
end
def bottled?
bottle_specification.tag?(bottle_tag)
end
def bottle &block
bottle_specification.instance_eval(&block)
end
def resource? name
resources.has_key?(name)
end
def resource name, &block
if block_given?
raise DuplicateResourceError.new(name) if resource?(name)
res = Resource.new(name, &block)
resources[name] = res
dependency_collector.add(res)
else
resources.fetch(name) { raise ResourceMissingError.new(owner, name) }
end
end
def option name, description=nil
name = 'c++11' if name == :cxx11
name = name.to_s if Symbol === name
raise "Option name is required." if name.empty?
raise "Options should not start with dashes." if name[0, 1] == "-"
build.add(name, description)
end
def depends_on spec
dep = dependency_collector.add(spec)
build.add_dep_option(dep) if dep
end
def deps
dependency_collector.deps
end
def requirements
dependency_collector.requirements
end
def patch strip=:p1, io=nil, &block
patches << Patch.create(strip, io, &block)
end
def add_legacy_patches(list)
list = Patch.normalize_legacy_patches(list)
list.each { |p| p.owner = self }
patches.concat(list)
end
end
class HeadSoftwareSpec < SoftwareSpec
def initialize
super
@resource.version = Version.new('HEAD')
end
def verify_download_integrity fn
return
end
end
class Bottle
class Filename
attr_reader :name, :version, :tag, :revision
def self.create(formula, tag, revision)
new(formula.name, formula.pkg_version, tag, revision)
end
def initialize(name, version, tag, revision)
@name = name
@version = version
@tag = tag
@revision = revision
end
def to_s
prefix + suffix
end
alias_method :to_str, :to_s
def prefix
"#{name}-#{version}.#{tag}"
end
def suffix
s = revision > 0 ? ".#{revision}" : ""
".bottle#{s}.tar.gz"
end
end
extend Forwardable
attr_reader :name, :resource, :prefix, :cellar, :revision
def_delegators :resource, :url, :fetch, :verify_download_integrity
def_delegators :resource, :downloader, :cached_download, :clear_cache
def initialize(formula, spec)
@name = formula.name
@resource = Resource.new
@resource.owner = formula
checksum, tag = spec.checksum_for(bottle_tag)
filename = Filename.create(formula, tag, spec.revision)
@resource.url = build_url(spec.root_url, filename)
@resource.download_strategy = CurlBottleDownloadStrategy
@resource.version = formula.pkg_version
@resource.checksum = checksum
@prefix = spec.prefix
@cellar = spec.cellar
@revision = spec.revision
end
def compatible_cellar?
cellar == :any || cellar == HOMEBREW_CELLAR.to_s
end
def stage
resource.downloader.stage
end
private
def build_url(root_url, filename)
"#{root_url}/#{filename}"
end
end
class BottleSpecification
DEFAULT_PREFIX = "/usr/local".freeze
DEFAULT_CELLAR = "/usr/local/Cellar".freeze
DEFAULT_ROOT_URL = "https://downloads.sf.net/project/machomebrew/Bottles".freeze
attr_rw :root_url, :prefix, :cellar, :revision
attr_reader :checksum, :collector
def initialize
@revision = 0
@prefix = DEFAULT_PREFIX
@cellar = DEFAULT_CELLAR
@root_url = DEFAULT_ROOT_URL
@collector = BottleCollector.new
end
def tag?(tag)
!!checksum_for(tag)
end
# Checksum methods in the DSL's bottle block optionally take
# a Hash, which indicates the platform the checksum applies on.
Checksum::TYPES.each do |cksum|
define_method(cksum) do |val|
digest, tag = val.shift
collector[tag] = Checksum.new(cksum, digest)
end
end
def checksum_for(tag)
collector.fetch_checksum_for(tag)
end
def checksums
checksums = {}
os_versions = collector.keys
os_versions.map! {|osx| MacOS::Version.from_symbol osx rescue nil }.compact!
os_versions.sort.reverse_each do |os_version|
osx = os_version.to_sym
checksum = collector[osx]
checksums[checksum.hash_type] ||= []
checksums[checksum.hash_type] << { checksum => osx }
end
checksums
end
end
Stop exposing the downloader as an attribute
require 'forwardable'
require 'resource'
require 'checksum'
require 'version'
require 'build_options'
require 'dependency_collector'
require 'bottles'
require 'patch'
class SoftwareSpec
extend Forwardable
attr_reader :name, :owner
attr_reader :build, :resources, :patches
attr_reader :dependency_collector
attr_reader :bottle_specification
def_delegators :@resource, :stage, :fetch, :verify_download_integrity
def_delegators :@resource, :cached_download, :clear_cache
def_delegators :@resource, :checksum, :mirrors, :specs, :using
def_delegators :@resource, :version, :mirror, *Checksum::TYPES
def initialize
@resource = Resource.new
@resources = {}
@build = BuildOptions.new(ARGV.options_only)
@dependency_collector = DependencyCollector.new
@bottle_specification = BottleSpecification.new
@patches = []
end
def owner= owner
@name = owner.name
@owner = owner
@resource.owner = self
resources.each_value do |r|
r.owner = self
r.version ||= version
end
patches.each { |p| p.owner = self }
end
def url val=nil, specs={}
return @resource.url if val.nil?
@resource.url(val, specs)
dependency_collector.add(@resource)
end
def bottled?
bottle_specification.tag?(bottle_tag)
end
def bottle &block
bottle_specification.instance_eval(&block)
end
def resource? name
resources.has_key?(name)
end
def resource name, &block
if block_given?
raise DuplicateResourceError.new(name) if resource?(name)
res = Resource.new(name, &block)
resources[name] = res
dependency_collector.add(res)
else
resources.fetch(name) { raise ResourceMissingError.new(owner, name) }
end
end
def option name, description=nil
name = 'c++11' if name == :cxx11
name = name.to_s if Symbol === name
raise "Option name is required." if name.empty?
raise "Options should not start with dashes." if name[0, 1] == "-"
build.add(name, description)
end
def depends_on spec
dep = dependency_collector.add(spec)
build.add_dep_option(dep) if dep
end
def deps
dependency_collector.deps
end
def requirements
dependency_collector.requirements
end
def patch strip=:p1, io=nil, &block
patches << Patch.create(strip, io, &block)
end
def add_legacy_patches(list)
list = Patch.normalize_legacy_patches(list)
list.each { |p| p.owner = self }
patches.concat(list)
end
end
class HeadSoftwareSpec < SoftwareSpec
def initialize
super
@resource.version = Version.new('HEAD')
end
def verify_download_integrity fn
return
end
end
class Bottle
class Filename
attr_reader :name, :version, :tag, :revision
def self.create(formula, tag, revision)
new(formula.name, formula.pkg_version, tag, revision)
end
def initialize(name, version, tag, revision)
@name = name
@version = version
@tag = tag
@revision = revision
end
def to_s
prefix + suffix
end
alias_method :to_str, :to_s
def prefix
"#{name}-#{version}.#{tag}"
end
def suffix
s = revision > 0 ? ".#{revision}" : ""
".bottle#{s}.tar.gz"
end
end
extend Forwardable
attr_reader :name, :resource, :prefix, :cellar, :revision
def_delegators :resource, :url, :fetch, :verify_download_integrity
def_delegators :resource, :cached_download, :clear_cache
def initialize(formula, spec)
@name = formula.name
@resource = Resource.new
@resource.owner = formula
checksum, tag = spec.checksum_for(bottle_tag)
filename = Filename.create(formula, tag, spec.revision)
@resource.url = build_url(spec.root_url, filename)
@resource.download_strategy = CurlBottleDownloadStrategy
@resource.version = formula.pkg_version
@resource.checksum = checksum
@prefix = spec.prefix
@cellar = spec.cellar
@revision = spec.revision
end
def compatible_cellar?
cellar == :any || cellar == HOMEBREW_CELLAR.to_s
end
def stage
resource.downloader.stage
end
private
def build_url(root_url, filename)
"#{root_url}/#{filename}"
end
end
class BottleSpecification
DEFAULT_PREFIX = "/usr/local".freeze
DEFAULT_CELLAR = "/usr/local/Cellar".freeze
DEFAULT_ROOT_URL = "https://downloads.sf.net/project/machomebrew/Bottles".freeze
attr_rw :root_url, :prefix, :cellar, :revision
attr_reader :checksum, :collector
def initialize
@revision = 0
@prefix = DEFAULT_PREFIX
@cellar = DEFAULT_CELLAR
@root_url = DEFAULT_ROOT_URL
@collector = BottleCollector.new
end
def tag?(tag)
!!checksum_for(tag)
end
# Checksum methods in the DSL's bottle block optionally take
# a Hash, which indicates the platform the checksum applies on.
Checksum::TYPES.each do |cksum|
define_method(cksum) do |val|
digest, tag = val.shift
collector[tag] = Checksum.new(cksum, digest)
end
end
def checksum_for(tag)
collector.fetch_checksum_for(tag)
end
def checksums
checksums = {}
os_versions = collector.keys
os_versions.map! {|osx| MacOS::Version.from_symbol osx rescue nil }.compact!
os_versions.sort.reverse_each do |os_version|
osx = os_version.to_sym
checksum = collector[osx]
checksums[checksum.hash_type] ||= []
checksums[checksum.hash_type] << { checksum => osx }
end
checksums
end
end
|
require 'htmlentities'
class StrSanitizer
# This modules encodes and decodes HTML Entities of a string
#
# Author: Jakaria (mailto: jakariablaine120@gmail.com)
# Copyright: Copyright (c) 2017 Jakaria
module HtmlEntities
# Instantiate htmlentities class to use it for encoding and decoding html entities
#
# Params:
# +none+
def initizalize
@coder = HTMLEntities.new
end
# Encodes the HTML entities of the given string
#
# Params:
# +str+:: A +string+ which needs to be escaped from html entities
#
# Returns:
# +string+:: An HTML entities escaped +string+
def html_encode(string)
@coder = HTMLEntities.new
@coder.encode(string)
end
# Decodes the HTML entities of the given string
#
# Params:
# +str+:: A +string+ which needs to be decoded to html entities
#
# Returns:
# +string+:: A string with decoded HTML entities +string+
def html_decode(string)
@coder = HTMLEntities.new
@coder.decode(string)
end
end
end
Add 'options' param to the html_encode method
require 'htmlentities'
class StrSanitizer
# This modules encodes and decodes HTML Entities of a string
#
# Author: Jakaria (mailto: jakariablaine120@gmail.com)
# Copyright: Copyright (c) 2017 Jakaria
module HtmlEntities
# Instantiate htmlentities class to use it for encoding and decoding html entities
#
# Params:
# +none+
def initizalize
@coder = HTMLEntities.new
end
# Encodes the HTML entities of the given string
#
# Params:
# +str+:: A +string+ which needs to be escaped from html entities
# +options+:: Options for encoding. You can provide one or more than one option.
# If no option is given, :basic option will be used by default.
# Options available :basic, :named, :decimal, :hexadecimal
#
# Returns:
# +string+:: An HTML entities escaped +string+
def html_encode(string, *options)
@coder = HTMLEntities.new
@coder.encode(string, *options)
end
# Decodes the HTML entities of the given string
#
# Params:
# +str+:: A +string+ which needs to be decoded to html entities
#
# Returns:
# +string+:: A string with decoded HTML entities +string+
def html_decode(string)
@coder = HTMLEntities.new
@coder.decode(string)
end
end
end
|
module SublimevideoLayout
VERSION = "0.5.4"
end
Version 0.5.5
module SublimevideoLayout
VERSION = "0.5.5"
end
|
#########################################################################
#
#########################################################################
def ok_to_start
p 'bla'
# DcPermission.all.delete
# DcPolicyRole.all.delete
# DcUser.all.delete
p DcPermission.all.to_a
if DcPermission.all.to_a.size > 0
p 'DcPermission (Permissions) collection is not empty! Aborting.'
return false
end
if DcPolicyRole.all.to_a.size > 0
p 'DcUserRole (User roles) collection is not empty! Aborting.'
return false
end
if DcUser.all.to_a.size > 0
p 'DcUser (Users) collection is not empty! Aborting.'
return false
end
true
end
#########################################################################
#
#########################################################################
def read_input(message, default='')
print "#{message} "
response = STDIN.gets.chomp
response.blank? ? default : response
end
########################################################################
#
########################################################################
def create_superadmin
username = read_input('Enter username for superadmin role:')
return p 'Username should be at least 6 character long' unless username.size >=6
#
password1 = read_input("Enter password for #{username} user :")
return p 'Password should be at least 8 character long' unless password1.size >=8
#
password2 = read_input("Please repeat password for #{username} user :")
return p 'Passwords are not equal' unless password2 == password1
#
# Guest role first
role = DcPolicyRole.new
role.name = 'guest'
role.system_name = 'guest'
role.save
# Superadmin role
sa = DcPolicyRole.new
sa.name = 'superadmin'
sa.system_name = 'superadmin'
sa.save
# Superadmin user
usr = DcUser.new
usr.username = username
usr.password = password1
usr.password_confirmation = password2
usr.first_name = 'superadmin'
usr.save
# user role
# r = usr.dc_user_roles.new
# r.dc_policy_role_id = role._id
# r.save
r = DcUserRole.new
r.dc_policy_role_id = sa._id
usr.dc_user_roles << r
# cmsedit permission
permission = DcPermission.new
permission.table_name = 'Default permission'
permission.is_default = true
permission.save
#
r = DcPolicyRule.new
r.dc_policy_role_id = sa._id
r.permission = DcPermission::SUPERADMIN
permission.dc_policy_rules << r
# create login poll
poll = DcPoll.new
poll.name = 'login'
poll.display = 'td'
poll.operation = 'link'
poll.parameters = '/dc_common/process_login'
poll.title = 'Autocreated login form'
poll.save
#
i = poll.dc_poll_items.new
i.name = 'username'
i.size = 15
i.text = 'Username'
i.type = 'text_field'
i.save
#
i = poll.dc_poll_items.new
i.name = 'password'
i.size = 15
i.text = 'Password'
i.type = 'password_field'
i.save
#
i = poll.dc_poll_items.new
i.name = 'send'
i.text = 'Login'
i.type = 'submit_tag'
i.save
#
p "Superadmin user created. Please remember login data #{username}/#{password1}"
end
########################################################################
# Initial database seed
########################################################################
def seed
DcSite.all.delete
DcSimpleMenu.all.delete
DcPage.all.delete
DcPiece.all.delete
if DcSite.all.size > 0
p 'DcSite (Sites) collection is not empty! Aborting.'
return
end
#
if (sa = DcPolicyRole.find_by(system_name: 'superadmin')).nil?
p 'superadmin role not defined! Aborting.'
return
end
#
if (guest = DcPolicyRole.find_by(system_name: 'guest')).nil?
p 'guest role not defined! Aborting.'
return
end
# Test site document points to real site document
site = DcSite.new(
name: 'test',
alias_for: 'www.mysite.com')
site.save
# Site document
site = DcSite.new(
name: 'www.mysite.com',
homepage_link: "home",
menu_class: "DcSimpleMenu",
menu_name: "site-menu",
page_class: "DcPage",
page_table: "dc_page",
files_directory: "files",
settings: "ckeditor:\n config_file: /files/ck_config.js\n css_file: /files/ck_css.css\n",
site_layout: "content")
# this should end in application css file
site.css =<<EOT
#site-top, #site-main, #site-bottom, #site-menu {
width: 960px;
margin: 0px auto;
padding-top: 5px;}
EOT
site.save
# Default site policy
policy = DcPolicy.new(
description: "Default policy",
is_default: true,
message: "Access denied.",
name: "Default policy")
site.dc_policies << policy
# Policy rules. Administrator can edit guest can view
rule = DcPolicyRule.new( dc_policy_role_id: sa._id, permission: DcPermission::CAN_EDIT)
policy.dc_policy_rules << rule
rule = DcPolicyRule.new( dc_policy_role_id: guest._id, permission: DcPermission::CAN_VIEW)
policy.dc_policy_rules << rule
# Design document
design = DcDesign.new(name: 'simple',description: 'Simple page')
design.body =<<EOT
<div id="site">
<div id="site-top">
<a href="/">SITE LOGO</a>
</div>
<div id="site-menu">
<%= dc_render(:dc_simple_menu, method: 'as_table') %>\
</div>
<div id="site-main">
<%= dc_render(:dc_page) %>
</div>
<div id="site-bottom">
<%= dc_render(:dc_piece, name: 'site-bottom') %>
</div>
</div>
EOT
design.save
# Page document
page = DcPage.new(
subject: 'Home page',
subject_link: 'home',
dc_design_id: design._id,
dc_site_id: site._id,
publish_date: Time.now,
body: '<p>First page data</p>'
)
page.save
# Site bottom document
bottom = DcPiece.new(
name: 'site-bottom',
description: 'Site bottom document',
site_id: site._id,
body: '<p>(C)opyright by ME</p>'
)
bottom.save
# Menu
menu = DcSimpleMenu.new(
name: "site-menu",
description: "Menu for my Site",
)
menu.css =<<EOT
.site-menu {
width:500px;
margin: 0 auto;
border-spacing: 0px;
font-weight: bold;
border: none;
}
.td-site-menu-item {
font-size: 18px;
background-color: #fff;
border-left: 20px solid #fff;
border-right: 20px solid #fff;
padding: 10px;
text-align: center;
border-radius: 1px;
white-space: nowrap
}
.td-site-menu-item:hover {
background-color: #000;
}
.td-site-menu-selected {
font-size: 18px;
background-color: #000;
border-left: 20px solid white;
border-right: 20px solid white;
padding: 10px;
text-align: center;
white-space: nowrap;
}
.site-menu a {
color: #000;
}
.td-site-menu-item:hover a, .td-site-menu-selected a {
color: #fff;
}
EOT
menu.save
# Items
item = DcSimpleMenuItem.new(caption: 'Home', link: 'home', order: 10)
menu.dc_simple_menu_items << item
# This menu item will be selected when page is displayed
page.menu_id= item._id
page.save
item = DcSimpleMenuItem.new(caption: 'Menu item 2', link: 'menu-item-2', order: 20)
menu.dc_simple_menu_items << item
item = DcSimpleMenuItem.new(caption: 'My site', link: 'http://www.drgcms.org',
target: '_blank', order: 30)
menu.dc_simple_menu_items << item
p 'Seed data created succesfully.'
end
#########################################################################
#
#########################################################################
namespace :drg_cms do
desc "At the beginning god created superadmin"
task :at_the_beginning => :environment do
if ok_to_start
create_superadmin
end
end
desc "Seed initial data"
task :seed => :environment do
seed
end
end
Remove unnecessary debug code.
#########################################################################
#
#########################################################################
def ok_to_start
# DcPermission.all.delete
# DcPolicyRole.all.delete
# DcUser.all.delete
if DcPermission.all.to_a.size > 0
p 'DcPermission (Permissions) collection is not empty! Aborting.'
return false
end
if DcPolicyRole.all.to_a.size > 0
p 'DcUserRole (User roles) collection is not empty! Aborting.'
return false
end
if DcUser.all.to_a.size > 0
p 'DcUser (Users) collection is not empty! Aborting.'
return false
end
true
end
#########################################################################
#
#########################################################################
def read_input(message, default='')
print "#{message} "
response = STDIN.gets.chomp
response.blank? ? default : response
end
########################################################################
#
########################################################################
def create_superadmin
username = read_input('Enter username for superadmin role:')
return p 'Username should be at least 6 character long' unless username.size >=6
#
password1 = read_input("Enter password for #{username} user :")
return p 'Password should be at least 8 character long' unless password1.size >=8
#
password2 = read_input("Please repeat password for #{username} user :")
return p 'Passwords are not equal' unless password2 == password1
#
# Guest role first
role = DcPolicyRole.new
role.name = 'guest'
role.system_name = 'guest'
role.save
# Superadmin role
sa = DcPolicyRole.new
sa.name = 'superadmin'
sa.system_name = 'superadmin'
sa.save
# Superadmin user
usr = DcUser.new
usr.username = username
usr.password = password1
usr.password_confirmation = password2
usr.first_name = 'superadmin'
usr.save
# user role
# r = usr.dc_user_roles.new
# r.dc_policy_role_id = role._id
# r.save
r = DcUserRole.new
r.dc_policy_role_id = sa._id
usr.dc_user_roles << r
# cmsedit permission
permission = DcPermission.new
permission.table_name = 'Default permission'
permission.is_default = true
permission.save
#
r = DcPolicyRule.new
r.dc_policy_role_id = sa._id
r.permission = DcPermission::SUPERADMIN
permission.dc_policy_rules << r
# create login poll
poll = DcPoll.new
poll.name = 'login'
poll.display = 'td'
poll.operation = 'link'
poll.parameters = '/dc_common/process_login'
poll.title = 'Autocreated login form'
poll.save
#
i = poll.dc_poll_items.new
i.name = 'username'
i.size = 15
i.text = 'Username'
i.type = 'text_field'
i.save
#
i = poll.dc_poll_items.new
i.name = 'password'
i.size = 15
i.text = 'Password'
i.type = 'password_field'
i.save
#
i = poll.dc_poll_items.new
i.name = 'send'
i.text = 'Login'
i.type = 'submit_tag'
i.save
#
p "Superadmin user created. Please remember login data #{username}/#{password1}"
end
########################################################################
# Initial database seed
########################################################################
def seed
DcSite.all.delete
DcSimpleMenu.all.delete
DcPage.all.delete
DcPiece.all.delete
if DcSite.all.size > 0
p 'DcSite (Sites) collection is not empty! Aborting.'
return
end
#
if (sa = DcPolicyRole.find_by(system_name: 'superadmin')).nil?
p 'superadmin role not defined! Aborting.'
return
end
#
if (guest = DcPolicyRole.find_by(system_name: 'guest')).nil?
p 'guest role not defined! Aborting.'
return
end
# Test site document points to real site document
site = DcSite.new(
name: 'test',
alias_for: 'www.mysite.com')
site.save
# Site document
site = DcSite.new(
name: 'www.mysite.com',
homepage_link: "home",
menu_class: "DcSimpleMenu",
menu_name: "site-menu",
page_class: "DcPage",
page_table: "dc_page",
files_directory: "files",
settings: "ckeditor:\n config_file: /files/ck_config.js\n css_file: /files/ck_css.css\n",
site_layout: "content")
# this should end in application css file
site.css =<<EOT
#site-top, #site-main, #site-bottom, #site-menu {
width: 960px;
margin: 0px auto;
padding-top: 5px;}
EOT
site.save
# Default site policy
policy = DcPolicy.new(
description: "Default policy",
is_default: true,
message: "Access denied.",
name: "Default policy")
site.dc_policies << policy
# Policy rules. Administrator can edit guest can view
rule = DcPolicyRule.new( dc_policy_role_id: sa._id, permission: DcPermission::CAN_EDIT)
policy.dc_policy_rules << rule
rule = DcPolicyRule.new( dc_policy_role_id: guest._id, permission: DcPermission::CAN_VIEW)
policy.dc_policy_rules << rule
# Design document
design = DcDesign.new(name: 'simple',description: 'Simple page')
design.body =<<EOT
<div id="site">
<div id="site-top">
<a href="/">SITE LOGO</a>
</div>
<div id="site-menu">
<%= dc_render(:dc_simple_menu, method: 'as_table') %>\
</div>
<div id="site-main">
<%= dc_render(:dc_page) %>
</div>
<div id="site-bottom">
<%= dc_render(:dc_piece, name: 'site-bottom') %>
</div>
</div>
EOT
design.save
# Page document
page = DcPage.new(
subject: 'Home page',
subject_link: 'home',
dc_design_id: design._id,
dc_site_id: site._id,
publish_date: Time.now,
body: '<p>First page data</p>'
)
page.save
# Site bottom document
bottom = DcPiece.new(
name: 'site-bottom',
description: 'Site bottom document',
site_id: site._id,
body: '<p>(C)opyright by ME</p>'
)
bottom.save
# Menu
menu = DcSimpleMenu.new(
name: "site-menu",
description: "Menu for my Site",
)
menu.css =<<EOT
.site-menu {
width:500px;
margin: 0 auto;
border-spacing: 0px;
font-weight: bold;
border: none;
}
.td-site-menu-item {
font-size: 18px;
background-color: #fff;
border-left: 20px solid #fff;
border-right: 20px solid #fff;
padding: 10px;
text-align: center;
border-radius: 1px;
white-space: nowrap
}
.td-site-menu-item:hover {
background-color: #000;
}
.td-site-menu-selected {
font-size: 18px;
background-color: #000;
border-left: 20px solid white;
border-right: 20px solid white;
padding: 10px;
text-align: center;
white-space: nowrap;
}
.site-menu a {
color: #000;
}
.td-site-menu-item:hover a, .td-site-menu-selected a {
color: #fff;
}
EOT
menu.save
# Items
item = DcSimpleMenuItem.new(caption: 'Home', link: 'home', order: 10)
menu.dc_simple_menu_items << item
# This menu item will be selected when page is displayed
page.menu_id= item._id
page.save
item = DcSimpleMenuItem.new(caption: 'Menu item 2', link: 'menu-item-2', order: 20)
menu.dc_simple_menu_items << item
item = DcSimpleMenuItem.new(caption: 'My site', link: 'http://www.drgcms.org',
target: '_blank', order: 30)
menu.dc_simple_menu_items << item
p 'Seed data created succesfully.'
end
#########################################################################
#
#########################################################################
namespace :drg_cms do
desc "At the beginning god created superadmin"
task :at_the_beginning => :environment do
if ok_to_start
create_superadmin
end
end
desc "Seed initial data"
task :seed => :environment do
seed
end
end |
# -*-ruby-*-
require 'find'
def get_model_locations
@model_locations = ENV['MODEL_LOCATIONS']
if @model_locations.blank?
puts "Did not find any value for model locations in the MODEL_LOCATIONS environment variable! Exiting."
exit
end
puts "Model locations = '#{@model_locations}'"
end
def get_mc_user
@mc_user = Person.find_by_email_address("nlcommons@modelingcommons.org")
if @mc_user.nil?
puts "Did not find any user for the Modeling Commons! Exiting."
exit
end
end
def get_uri_user
@uri_user = Person.find_by_email_address("uri@northwestern.edu")
if @uri_user.nil?
puts "Did not find any user for Uri Wilensky! Exiting."
exit
end
end
def setup
get_model_locations
get_mc_user
get_uri_user
@ccl_group = Group.find_or_create_by_name('CCL')
@ccl_tag = Tag.find_or_create_by_name('ccl', :person_id => @mc_user.id)
@community_models_tag = Tag.find_or_create_by_name('community models', :person_id => @mc_user.id)
end
def skip_directory?(directory_name)
true if File.basename(directory_name) == '.' or
File.basename(directory_name) == '..' or
File.basename(directory_name) == 'under development'
end
namespace :netlogo do
desc 'Loads the latest batch of models from the filesystem into the Modeling Commons'
task :load_models => :environment do
setup
Find.find(@model_locations) do |path|
puts "\n"
puts "\tpath = '#{path}'"
Find.prune and next if skip_directory?(path)
filename = File.basename(path).slice(/^[^.]+/)
puts "\t\tfilename = '#{filename}'"
suffix = path.slice(/\.\w+$/)
puts "\t\tsuffix = '#{suffix}'\n"
# Get matches, and handle accordingly
matching_nodes = Node.all(:conditions => { :name => filename} ).select { |n| n.people.member?(@mc_user) or n.people.member?(@uri_user) }
if suffix == '.nlogo'
if matching_nodes.empty?
# Create a new node, if necessary
puts "\t\tNo matching node found. We will need to create a new one."
node = Node.new(:parent_id => nil, :name => filename,
:group => ccl_group, :changeability => PermissionSetting.group)
if !node.save
puts "\t\t*** Error trying to save a new node."
puts "\t\t\t#{node.errors.inspect}"
end
# Add ccl tag to this model
puts "\tAdding CCL tag, ID '#{ccl_tag.id}' for node_id '#{node.id}', person_id '#{mc_user.id}'"
tn = TaggedNode.new(:node_id => node.id, :tag_id => ccl_tag.id, :person_id => mc_user.id, :comment => '')
if !tn.save
puts "\t\t*** Error trying to save a new tagged node."
puts "\t\t\t#{tn.errors.inspect}"
end
# Add community models tag to this model
if path =~ /community model/
puts "\tAdding community models tag, ID '#{community_models_tag.id}'"
tn = TaggedNode.new(:node_id => node.id, :tag_id => community_models_tag.id, :person_id => mc_user.id, :comment => '')
if !tn.save
puts "\t\t*** Error trying to save a new tagged node."
puts "\t\t\t#{tn.errors.inspect}"
end
end
file_contents = File.open(path).read
new_version = NodeVersion.new(:node_id => node.id,
:person_id => @mc_user.id,
:contents => file_contents,
:description => 'Updated from NetLogo 5.0')
if !new_version.save
puts "\t\t*** Error trying to save a new version of the new node '#{node.name}', ID '#{node.id}': '#{e.inspect}'"
puts "\t\t\t#{node.inspect}"
end
elsif matching_nodes.length == 1
matching_node = matching_nodes.first
model_contents = File.open(path).read
# Add a new version to an existing node
puts "\t\tAbout to check node.contents"
puts "\t\t\tmatching_node.contents.length = '#{matching_node.contents.length}'"
puts "\t\t\tmodel_contents.length = '#{model_contents.length}'"
if matching_node.contents == model_contents
puts "\t\tNot adding a new version -- current one is identical"
next
else
puts "\t\tFound a matching node. Creating a new node_version for this node."
end
if model_contents.blank?
puts "\t\t\tNo content the model in file '#{path}'!"
next
else
puts "\t\t\tModel is '#{model_contents.length}' characters long."
end
new_version =
nv = NodeVersion.new(:node_id => matching_node.id,
:person_id => @mc_user.id,
:contents => model_contents,
:description => 'Updated to NetLogo 5.0RC7')
if nv.save
puts "\t\t\tSuccessfully saved a new node_version"
else
puts "\t\t*** Error trying to create a new version of existing node '#{matching_node.name}', ID '#{matching_node.id}': '#{e.inspect}'"
next
end
else
# Too many to choose from -- aborting!
puts "\t\tFound more than one. Ack!"
end
elsif suffix == '.png'
puts "\tIgnoring .png preview -- we will get back to it later."
else
puts "\tIgnoring this file, with an unknown file type of '#{suffix}'."
end # if
end # find
# Now we will look for previews. We could have done it in the previous find loop, but
# then we ran a big risk of finding the preview before the node.
# Add any nodes we find
Find.find(@model_locations) do |path|
puts "Now looking at file '#{path}'"
# Skip directories
if FileTest.directory?(path)
if File.basename(path) == '.' or File.basename(path) == '..' or File.basename(path) == 'under development'
Find.prune
end
puts "\tSkipping directory '#{path}'"
next
# Handle files
else
filename = File.basename(path).slice(/^[^.]+/)
puts "\tfilename = '#{filename}'"
suffix = path.slice(/\.\w+$/)
puts "\tsuffix = '#{suffix}'"
# Get matches, and handle accordingly
matching_nodes = Node.all(:conditions => { :name => filename} ).select { |n| n.people.member?(@mc_user)}
if suffix == '.png'
if matching_nodes.empty?
puts "\t\tNo matching node found. What the heck?"
elsif matching_nodes.length == 1
matching_node = matching_nodes.first
file_contents = File.open(path).read
puts "\t\tFound a matching node. Creating a new attachment, of type preview."
if matching_node.preview
puts "\t\tThere is already a preview; checking if it is identical."
if matching_node.preview.contents == file_contents
puts "\t\tNot adding a new version -- current one is identical"
next
end
puts "\t\t\tNo existing preview attachment, so we must create one"
end
new_version =
attachment = NodeAttachment.new(:node_id => matching_node.id,
:person_id => @mc_user.id,
:description => "Preview for '#{filename}'",
:filename => filename + '.png',
:type => 'preview',
:contents => file_contents)
if new_version.save
puts "\t\t\tSuccessfully saved a new preview"
else
puts "\t\t*** Error trying to create a attachment to node '#{matching_node.name}', ID '#{matching_node.id}'"
end
elsif suffix == '.nlogo'
puts "\tIgnoring .nlogo file -- we dealt with these earlier."
else
puts "\tIgnoring this file, with an unknown file type of '#{suffix}'."
end # if empty
end # if suffix
end # if Filetest
end # find
puts "Done."
end
end
Bump NetLogo version number
Former-commit-id: 713fcb689aadb7630b7c8ef0b9f8da501d734794
# -*-ruby-*-
require 'find'
def get_model_locations
@model_locations = ENV['MODEL_LOCATIONS']
if @model_locations.blank?
puts "Did not find any value for model locations in the MODEL_LOCATIONS environment variable! Exiting."
exit
end
puts "Model locations = '#{@model_locations}'"
end
def get_mc_user
@mc_user = Person.find_by_email_address("nlcommons@modelingcommons.org")
if @mc_user.nil?
puts "Did not find any user for the Modeling Commons! Exiting."
exit
end
end
def get_uri_user
@uri_user = Person.find_by_email_address("uri@northwestern.edu")
if @uri_user.nil?
puts "Did not find any user for Uri Wilensky! Exiting."
exit
end
end
def setup
get_model_locations
get_mc_user
get_uri_user
@ccl_group = Group.find_or_create_by_name('CCL')
@ccl_tag = Tag.find_or_create_by_name('ccl', :person_id => @mc_user.id)
@community_models_tag = Tag.find_or_create_by_name('community models', :person_id => @mc_user.id)
end
def skip_directory?(directory_name)
true if File.basename(directory_name) == '.' or
File.basename(directory_name) == '..' or
File.basename(directory_name) == 'under development'
end
namespace :netlogo do
desc 'Loads the latest batch of models from the filesystem into the Modeling Commons'
task :load_models => :environment do
setup
Find.find(@model_locations) do |path|
puts "\n"
puts "\tpath = '#{path}'"
Find.prune and next if skip_directory?(path)
filename = File.basename(path).slice(/^[^.]+/)
puts "\t\tfilename = '#{filename}'"
suffix = path.slice(/\.\w+$/)
puts "\t\tsuffix = '#{suffix}'\n"
# Get matches, and handle accordingly
matching_nodes = Node.all(:conditions => { :name => filename} ).select { |n| n.people.member?(@mc_user) or n.people.member?(@uri_user) }
if suffix == '.nlogo'
if matching_nodes.empty?
# Create a new node, if necessary
puts "\t\tNo matching node found. We will need to create a new one."
node = Node.new(:parent_id => nil, :name => filename,
:group => ccl_group, :changeability => PermissionSetting.group)
if !node.save
puts "\t\t*** Error trying to save a new node."
puts "\t\t\t#{node.errors.inspect}"
end
# Add ccl tag to this model
puts "\tAdding CCL tag, ID '#{ccl_tag.id}' for node_id '#{node.id}', person_id '#{mc_user.id}'"
tn = TaggedNode.new(:node_id => node.id, :tag_id => ccl_tag.id, :person_id => mc_user.id, :comment => '')
if !tn.save
puts "\t\t*** Error trying to save a new tagged node."
puts "\t\t\t#{tn.errors.inspect}"
end
# Add community models tag to this model
if path =~ /community model/
puts "\tAdding community models tag, ID '#{community_models_tag.id}'"
tn = TaggedNode.new(:node_id => node.id, :tag_id => community_models_tag.id, :person_id => mc_user.id, :comment => '')
if !tn.save
puts "\t\t*** Error trying to save a new tagged node."
puts "\t\t\t#{tn.errors.inspect}"
end
end
file_contents = File.open(path).read
new_version = NodeVersion.new(:node_id => node.id,
:person_id => @mc_user.id,
:contents => file_contents,
:description => 'Updated from NetLogo 5.0')
if !new_version.save
puts "\t\t*** Error trying to save a new version of the new node '#{node.name}', ID '#{node.id}': '#{e.inspect}'"
puts "\t\t\t#{node.inspect}"
end
elsif matching_nodes.length == 1
matching_node = matching_nodes.first
model_contents = File.open(path).read
# Add a new version to an existing node
puts "\t\tAbout to check node.contents"
puts "\t\t\tmatching_node.contents.length = '#{matching_node.contents.length}'"
puts "\t\t\tmodel_contents.length = '#{model_contents.length}'"
if matching_node.contents == model_contents
puts "\t\tNot adding a new version -- current one is identical"
next
else
puts "\t\tFound a matching node. Creating a new node_version for this node."
end
if model_contents.blank?
puts "\t\t\tNo content the model in file '#{path}'!"
next
else
puts "\t\t\tModel is '#{model_contents.length}' characters long."
end
new_version =
nv = NodeVersion.new(:node_id => matching_node.id,
:person_id => @mc_user.id,
:contents => model_contents,
:description => 'Updated to NetLogo 5.0')
if nv.save
puts "\t\t\tSuccessfully saved a new node_version"
else
puts "\t\t*** Error trying to create a new version of existing node '#{matching_node.name}', ID '#{matching_node.id}': '#{e.inspect}'"
next
end
else
# Too many to choose from -- aborting!
puts "\t\tFound more than one. Ack!"
end
elsif suffix == '.png'
puts "\tIgnoring .png preview -- we will get back to it later."
else
puts "\tIgnoring this file, with an unknown file type of '#{suffix}'."
end # if
end # find
# Now we will look for previews. We could have done it in the previous find loop, but
# then we ran a big risk of finding the preview before the node.
# Add any nodes we find
Find.find(@model_locations) do |path|
puts "Now looking at file '#{path}'"
# Skip directories
if FileTest.directory?(path)
if File.basename(path) == '.' or File.basename(path) == '..' or File.basename(path) == 'under development'
Find.prune
end
puts "\tSkipping directory '#{path}'"
next
# Handle files
else
filename = File.basename(path).slice(/^[^.]+/)
puts "\tfilename = '#{filename}'"
suffix = path.slice(/\.\w+$/)
puts "\tsuffix = '#{suffix}'"
# Get matches, and handle accordingly
matching_nodes = Node.all(:conditions => { :name => filename} ).select { |n| n.people.member?(@mc_user)}
if suffix == '.png'
if matching_nodes.empty?
puts "\t\tNo matching node found. What the heck?"
elsif matching_nodes.length == 1
matching_node = matching_nodes.first
file_contents = File.open(path).read
puts "\t\tFound a matching node. Creating a new attachment, of type preview."
if matching_node.preview
puts "\t\tThere is already a preview; checking if it is identical."
if matching_node.preview.contents == file_contents
puts "\t\tNot adding a new version -- current one is identical"
next
end
puts "\t\t\tNo existing preview attachment, so we must create one"
end
new_version =
attachment = NodeAttachment.new(:node_id => matching_node.id,
:person_id => @mc_user.id,
:description => "Preview for '#{filename}'",
:filename => filename + '.png',
:type => 'preview',
:contents => file_contents)
if new_version.save
puts "\t\t\tSuccessfully saved a new preview"
else
puts "\t\t*** Error trying to create a attachment to node '#{matching_node.name}', ID '#{matching_node.id}'"
end
elsif suffix == '.nlogo'
puts "\tIgnoring .nlogo file -- we dealt with these earlier."
else
puts "\tIgnoring this file, with an unknown file type of '#{suffix}'."
end # if empty
end # if suffix
end # if Filetest
end # find
puts "Done."
end
end
|
namespace :peoplefinder do
namespace :import do
desc 'Check validity of CSV file before import'
task :csv_check, [:path] => :environment do |_, args|
if File.exist?(args[:path])
importer = Peoplefinder::CsvPeopleImporter.new(File.new(args[:path]))
if importer.valid?
puts 'The given file is valid'
else
puts 'The given file has some errors:'
importer.errors.each do |error|
puts error
end
end
else
puts 'The given file doesn\'t exist'
end
end
end
end
Add csv import rake task
namespace :peoplefinder do
namespace :import do
desc 'Check validity of CSV file before import'
task :csv_check, [:path] => :environment do |_, args|
if File.exist?(args[:path])
importer = Peoplefinder::CsvPeopleImporter.new(File.new(args[:path]))
if importer.valid?
puts 'The given file is valid'
else
puts 'The given file has some errors:'
importer.errors.each do |error|
puts error
end
end
else
puts 'The given file doesn\'t exist'
end
end
desc 'Import valid CSV file'
task :csv_import, [:path] => :environment do |_, args|
if File.exist?(args[:path])
importer = Peoplefinder::CsvPeopleImporter.new(File.new(args[:path]))
result = importer.import
if result.nil?
puts 'The given file is not valid, please run the csv check task'
else
puts "#{result} people imported"
end
else
puts 'The given file doesn\'t exist'
end
end
end
end
|
class TopMoviesAllTime::Scraper
def self.get_lists
lists = {}
lists[:domestic] = Nokogiri::HTML(open("http://www.boxofficemojo.com/alltime/domestic.htm"))
lists[:adjusted] = Nokogiri::HTML(open("http://www.boxofficemojo.com/alltime/adjusted.htm"))
lists[:worldwide] = Nokogiri::HTML(open("http://www.boxofficemojo.com/alltime/world/"))
return lists
end
def self.adjusted_rankings
adjusted_rankings = {}
scrape_list(get_lists[:adjusted]).each {|t| adjusted_rankings[t.css("td[1]").text] = t.css("td[2] a b").text}
adjusted_rankings.shift
adjusted_rankings
end
def self.domestic_rankings
domestic_rankings = {}
scrape_list(get_lists[:domestic]).each {|t| domestic_rankings[t.css("td[1]").text] = t.css("td[2] a b").text}
5.times {domestic_rankings.shift}
domestic_rankings
end
def self.worldwide_rankings
worldwide_rankings = {}
scrape_list(get_lists[:worldwide]).each {|t| worldwide_rankings[t.css("td[1]").text] = t.css("td[2] a b").text}
worldwide_rankings.shift
worldwide_rankings
end
def self.set_attributes(movie, url)
doc = Nokogiri::HTML(open(url))
adjusted_doc = Nokogiri::HTML(open(url + "&adjust_yr=2017&p=.htm"))
ticket_doc = Nokogiri::HTML(open(url + "&adjust_yr=1&p=.htm"))
movie.release_date = doc.xpath('//td[contains(text(), "Release Date")]').css("b").text
movie.domestic_gross = doc.xpath('//font[contains(text(), "Domestic Total Gross")]').css("b").text
movie.worldwide_gross = doc.css("div.mp_box_content table tr[4] td[2] b").text.split("Rank").first
movie.adjusted_gross = adjusted_doc.xpath('//font[contains(text(), "Adj.")]').css("b").text
movie.tickets_sold = ticket_doc.xpath('//font[contains(text(), "Est. Tickets")]').css("b").text
end
def self.scrape_list(list)
list.css("div#main div#body table table tr")
end
def self.make_movies
scrape_list(get_lists[:adjusted]).each {|t| find_or_create_movie(t)}
scrape_list(get_lists[:domestic]).each {|t| find_or_create_movie(t)}
scrape_list(get_lists[:worldwide]).each {|t| find_or_create_movie(t)}
end
def self.find_or_create_movie(list)
unless TopMoviesAllTime::Movie.find_by_title(list.css("td[2] a b").text) != nil
TopMoviesAllTime::Movie.new(list.css("td[2] a b").text,
self.url_normalizer(list.css("td[2] a").attribute("href").value))
end
end
def self.url_normalizer(url)
url.scan(/page=releases/) == [] ? "http://www.boxofficemojo.com#{url}" : "http://www.boxofficemojo.com#{url.split("releases").join("main")}"
end
#binding.pry
end
refactoring
class TopMoviesAllTime::Scraper
def self.get_lists
lists = {}
lists[:domestic] = Nokogiri::HTML(open("http://www.boxofficemojo.com/alltime/domestic.htm"))
lists[:adjusted] = Nokogiri::HTML(open("http://www.boxofficemojo.com/alltime/adjusted.htm"))
lists[:worldwide] = Nokogiri::HTML(open("http://www.boxofficemojo.com/alltime/world/"))
return lists
end
def self.scrape_list(list)
list.css("div#main div#body table table tr")
end
def self.adjusted_rankings
adjusted_rankings = {}
scrape_list(get_lists[:adjusted]).each {|t| adjusted_rankings[t.css("td[1]").text] = t.css("td[2] a b").text}
adjusted_rankings.shift
adjusted_rankings
end
def self.domestic_rankings
domestic_rankings = {}
scrape_list(get_lists[:domestic]).each {|t| domestic_rankings[t.css("td[1]").text] = t.css("td[2] a b").text}
5.times {domestic_rankings.shift}
domestic_rankings
end
def self.worldwide_rankings
worldwide_rankings = {}
scrape_list(get_lists[:worldwide]).each {|t| worldwide_rankings[t.css("td[1]").text] = t.css("td[2] a b").text}
worldwide_rankings.shift
worldwide_rankings
end
def self.make_movies
scrape_list(get_lists[:adjusted]).each {|t| find_or_create_movie(t)}
scrape_list(get_lists[:domestic]).each {|t| find_or_create_movie(t)}
scrape_list(get_lists[:worldwide]).each {|t| find_or_create_movie(t)}
end
def self.find_or_create_movie(list)
unless TopMoviesAllTime::Movie.find_by_title(list.css("td[2] a b").text) != nil
TopMoviesAllTime::Movie.new(list.css("td[2] a b").text,
self.url_normalizer(list.css("td[2] a").attribute("href").value))
end
end
def self.url_normalizer(url)
url.scan(/page=releases/) == [] ? "http://www.boxofficemojo.com#{url}" : "http://www.boxofficemojo.com#{url.split("releases").join("main")}"
end
def self.set_attributes(movie, url)
doc = Nokogiri::HTML(open(url))
adjusted_doc = Nokogiri::HTML(open(url + "&adjust_yr=2017&p=.htm"))
ticket_doc = Nokogiri::HTML(open(url + "&adjust_yr=1&p=.htm"))
movie.release_date = doc.xpath('//td[contains(text(), "Release Date")]').css("b").text
movie.domestic_gross = doc.xpath('//font[contains(text(), "Domestic Total Gross")]').css("b").text
movie.worldwide_gross = doc.css("div.mp_box_content table tr[4] td[2] b").text.split("Rank").first
movie.adjusted_gross = adjusted_doc.xpath('//font[contains(text(), "Adj.")]').css("b").text
movie.tickets_sold = ticket_doc.xpath('//font[contains(text(), "Est. Tickets")]').css("b").text
end
#binding.pry
end
|
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Js
module Tasks
class << self
def update
build(
:begin_msg => "Updating build... ",
:output_dir => File.expand_path(File.join(File.dirname(__FILE__), "../../../assets/javascripts/twitter_cldr")),
:files => { "twitter_cldr_%s.js" => false }
)
end
def compile
build(
:begin_msg => "Compiling build... ",
:output_dir => get_output_dir,
:files => { "twitter_cldr_%s.min.js" => true, "twitter_cldr_%s.js" => false }
)
end
private
def build(options = {})
locales = get_locales
$stdout.write(options[:begin_msg])
compiler = TwitterCldr::Js::Compiler.new(:locales => locales)
output_dir = options[:output_dir] || get_output_dir
build_duration = time_operation do
options[:files].each_pair do |file_pattern, minify|
compiler.compile_each(:minify => minify) do |bundle, locale|
out_file = File.join(output_dir, file_pattern % locale)
FileUtils.mkdir_p(File.basename(output_dir))
File.open(out_file, "w+") do |f|
f.write(bundle)
end
end
end
end
puts "done"
puts build_summary(
:locale_count => compiler.locales.size,
:build_duration => build_duration,
:dir => output_dir
)
end
def build_summary(options = {})
%Q(Built %{locale_count} %<{ "locale_count": { "one": "locale", "other": "locales" } }> %{timespan} into %{dir}).localize % {
:locale_count => options[:locale_count],
:timespan => TwitterCldr::Localized::LocalizedTimespan.new(options[:build_duration], :locale => :en).to_s.downcase,
:dir => options[:dir]
}
end
def time_operation
start_time = Time.now.to_i
yield
Time.now.to_i - start_time
end
def get_output_dir
ENV["OUTPUT_DIR"] || File.join(FileUtils.getwd, "twitter_cldr")
end
def get_locales
if ENV["LOCALES"]
locales = ENV["LOCALES"].split(",").map { |locale| TwitterCldr.convert_locale(locale.strip.downcase.to_sym) }
bad_locales = locales.select { |locale| !TwitterCldr.supported_locale?(locale) }
puts "Ignoring unsupported locales: #{bad_locales.join(", ")}"
locales - bad_locales
else
TwitterCldr.supported_locales
end
end
end
end
end
end
Generate JS files without 'twitter_cldr_' prefix.
# encoding: UTF-8
# Copyright 2012 Twitter, Inc
# http://www.apache.org/licenses/LICENSE-2.0
module TwitterCldr
module Js
module Tasks
class << self
def update
build(
:begin_msg => "Updating build... ",
:output_dir => File.expand_path(File.join(File.dirname(__FILE__), "../../../assets/javascripts/twitter_cldr")),
:files => { "%s.js" => false }
)
end
def compile
build(
:begin_msg => "Compiling build... ",
:output_dir => get_output_dir,
:files => { "min/%s.min.js" => true, "full/%s.js" => false }
)
end
private
def build(options = {})
locales = get_locales
$stdout.write(options[:begin_msg])
compiler = TwitterCldr::Js::Compiler.new(:locales => locales)
output_dir = File.expand_path(options[:output_dir] || get_output_dir)
build_duration = time_operation do
options[:files].each_pair do |file_pattern, minify|
compiler.compile_each(:minify => minify) do |bundle, locale|
out_file = File.join(output_dir, file_pattern % locale)
FileUtils.mkdir_p(File.dirname(out_file))
File.open(out_file, "w+") do |f|
f.write(bundle)
end
end
end
end
puts "done"
puts build_summary(
:locale_count => compiler.locales.size,
:build_duration => build_duration,
:dir => output_dir
)
end
def build_summary(options = {})
%Q(Built %{locale_count} %<{ "locale_count": { "one": "locale", "other": "locales" } }> %{timespan} into %{dir}).localize % {
:locale_count => options[:locale_count],
:timespan => TwitterCldr::Localized::LocalizedTimespan.new(options[:build_duration], :locale => :en).to_s.downcase,
:dir => options[:dir]
}
end
def time_operation
start_time = Time.now.to_i
yield
Time.now.to_i - start_time
end
def get_output_dir
ENV["OUTPUT_DIR"] || File.join(FileUtils.getwd, "twitter_cldr")
end
def get_locales
if ENV["LOCALES"]
locales = ENV["LOCALES"].split(",").map { |locale| TwitterCldr.convert_locale(locale.strip.downcase.to_sym) }
bad_locales = locales.select { |locale| !TwitterCldr.supported_locale?(locale) }
puts "Ignoring unsupported locales: #{bad_locales.join(", ")}"
locales - bad_locales
else
TwitterCldr.supported_locales
end
end
end
end
end
end |
module UniversalCrm
module Models
module Ticket
extend ActiveSupport::Concern
included do
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Search
include Universal::Concerns::Status
include Universal::Concerns::Kind
include Universal::Concerns::Flaggable
include Universal::Concerns::Taggable
include Universal::Concerns::Polymorphic #the customer
include Universal::Concerns::Commentable
include Universal::Concerns::Numbered
include Universal::Concerns::Scoped
include Universal::Concerns::Tokened
include Universal::Concerns::HasAttachments
store_in session: UniversalCrm::Configuration.mongoid_session_name, collection: 'crm_tickets'
field :t, as: :title
field :c, as: :content
field :hb, as: :html_body
field :te, as: :to_email
field :fe, as: :from_email
statuses %w(active actioned closed), default: :active
kinds %w(normal email), :normal
flags %w(priority)
belongs_to :document, polymorphic: true #the related document that this ticket should link to.
belongs_to :responsible, class_name: Universal::Configuration.class_name_user, foreign_key: :responsible_id
default_scope ->(){order_by(status: :asc, updated_at: :desc)}
search_in :t, :c, :te, :fe
def numbered_title
[self.number, self.title].join(' - ')
end
def inbound_email_address(config)
"tk-#{self.token}@#{config.inbound_domain}"
end
def close!(user)
if self.active?
self.save_comment!("Ticket Closed", user)
self.closed!
end
end
def open!(user=nil)
if self.closed?
self.save_comment!("Ticket Opened", user)
self.active!
end
end
def action!(user=nil)
if self.active?
self.save_comment!("Ticket Actioned", user)
self.actioned!
end
end
def open!(user=nil)
if self.closed?
self.save_comment!("Ticket Opened", user)
self.active!
end
end
def open!(user=nil)
if self.closed?
self.save_comment!("Ticket Opened", user)
self.active!
end
end
def open!(user=nil)
if self.closed?
self.save_comment!("Ticket Opened", user)
self.active!
end
end
def to_json
{
id: self.id.to_s,
number: self.number.to_s,
status: self.status,
kind: self.kind.to_s,
subject_name: self.subject.name,
subject_id: self.subject_id.to_s,
title: self.title,
content: self.content,
html_body: self.html_body,
to_email: self.to_email,
from_email: self.from_email,
updated_at: self.updated_at.strftime('%b %d, %Y, %l:%M%P'),
created_at: self.created_at.strftime('%b %d, %Y, %l:%M%P'),
comment_count: self.comments.system_generated.count,
reply_count: self.comments.not_system_generated.count,
token: self.token,
flags: self.flags,
attachments: self.attachments.map{|a| {name: a.name, url: a.file.url, filename: a.file_filename}}
}
end
end
module ClassMethods
end
end
end
end
close actioned email
module UniversalCrm
module Models
module Ticket
extend ActiveSupport::Concern
included do
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Search
include Universal::Concerns::Status
include Universal::Concerns::Kind
include Universal::Concerns::Flaggable
include Universal::Concerns::Taggable
include Universal::Concerns::Polymorphic #the customer
include Universal::Concerns::Commentable
include Universal::Concerns::Numbered
include Universal::Concerns::Scoped
include Universal::Concerns::Tokened
include Universal::Concerns::HasAttachments
store_in session: UniversalCrm::Configuration.mongoid_session_name, collection: 'crm_tickets'
field :t, as: :title
field :c, as: :content
field :hb, as: :html_body
field :te, as: :to_email
field :fe, as: :from_email
statuses %w(active actioned closed), default: :active
kinds %w(normal email), :normal
flags %w(priority)
belongs_to :document, polymorphic: true #the related document that this ticket should link to.
belongs_to :responsible, class_name: Universal::Configuration.class_name_user, foreign_key: :responsible_id
default_scope ->(){order_by(status: :asc, updated_at: :desc)}
search_in :t, :c, :te, :fe
def numbered_title
[self.number, self.title].join(' - ')
end
def inbound_email_address(config)
"tk-#{self.token}@#{config.inbound_domain}"
end
def close!(user)
if self.active? or self.actioned?
self.save_comment!("Ticket Closed", user)
self.closed!
end
end
def open!(user=nil)
if self.closed?
self.save_comment!("Ticket Opened", user)
self.active!
end
end
def action!(user=nil)
if self.active?
self.save_comment!("Ticket Actioned", user)
self.actioned!
end
end
def to_json
{
id: self.id.to_s,
number: self.number.to_s,
status: self.status,
kind: self.kind.to_s,
subject_name: self.subject.name,
subject_id: self.subject_id.to_s,
title: self.title,
content: self.content,
html_body: self.html_body,
to_email: self.to_email,
from_email: self.from_email,
updated_at: self.updated_at.strftime('%b %d, %Y, %l:%M%P'),
created_at: self.created_at.strftime('%b %d, %Y, %l:%M%P'),
comment_count: self.comments.system_generated.count,
reply_count: self.comments.not_system_generated.count,
token: self.token,
flags: self.flags,
attachments: self.attachments.map{|a| {name: a.name, url: a.file.url, filename: a.file_filename}}
}
end
end
module ClassMethods
end
end
end
end
|
module Vex
module Dsl
module Wrappers
module Parameters
def parameters=(val)
logger.debug("[DEBUG] - Parameters passed as #{val.inspect}" )
if val.is_a? Array
logger.debug("[DEBUG] --- Parsing array" )
new_hash = Hash.new
val.each do |value|
new_hash[value["key"]] = value["value"]
end
logger.debug("[DEBUG] --- Setting data to #{new_hash.inspect}" )
self.data = new_hash
elsif val.is_a? Hash
self.data = val
else
raise(ArgumentError, "Value must be a hash or array")
end
end
class Wrapper
def initialize(key,value)
@key = key
@value = value
end
def key
@key
end
def value
@value
end
end
end
end
end
end
Validations so we don't put empty or nil values in.
module Vex
module Dsl
module Wrappers
module Parameters
def parameters=(val)
logger.debug("[DEBUG] - Parameters passed as #{val.inspect}" )
if val.is_a? Array
logger.debug("[DEBUG] --- Parsing array" )
new_hash = Hash.new
val.each do |value|
unless value["key"].nil? or value["value"].nil? or value["key"].length < 2 or value["value"].length < 2
new_hash[value["key"]] = value["value"]
end
end
logger.debug("[DEBUG] --- Setting data to #{new_hash.inspect}" )
self.data = new_hash
elsif val.is_a? Hash
self.data = val
else
raise(ArgumentError, "Value must be a hash or array")
end
end
class Wrapper
def initialize(key,value)
@key = key
@value = value
end
def key
@key
end
def value
@value
end
end
end
end
end
end |
# encoding: utf-8
module VideoScreenshoter
class Abstract
attr_accessor :ffmpeg, :imagemagick, :output_dir, :output_file, :input, :times, :duration, :verbose, :size, :presets
def initialize params
[:ffmpeg, :imagemagick, :output_dir, :output_file, :verbose].each do |attr|
self.send("#{attr}=".to_sym, params[attr].nil? ? VideoScreenshoter.send(attr) : params[attr])
end
FileUtils.mkdir_p self.output_dir
self.input = params[:input]
self.duration = input_duration
raise ArgumentError.new('Incorrect or empty m3u8 playlist') if duration.to_i == 0
self.times = params[:times].to_a.map do |time|
if time.is_a?(String) && matches = time.match(/(.*)%$/)
time = matches[1].to_f / 100 * duration
end
time = duration + time if time < 0
time = time.to_i
time
end.uniq
self.size = params[:size] ? "-s #{params[:size]}" : ''
if params[:presets] && params[:presets].is_a?(Hash)
self.presets = {}
params[:presets].each do |name, preset|
self.presets[name.to_sym] = preset.index('-') == 0 ? preset : "-resize #{preset}"
end
end
end
def output_fullpath time
sprintf(File.join(output_dir, output_file), time)
end
def ffmpeg_command input, output, time
"#{ffmpeg} -i #{input} -acodec -an -ss #{time} #{size} -f image2 -vframes 1 -y #{output} 2>/dev/null 1>&2"
end
def imagemagick_command input, preset_name
"#{imagemagick} #{input} #{presets[preset_name.to_sym]} #{File.join(File.dirname(input), File.basename(input, File.extname(input)) + '_' + preset_name.to_s + File.extname(input))}"
end
def imagemagick_run scr
if presets
presets.each do |preset_name, preset|
cmd = imagemagick_command(scr, preset_name)
puts cmd if verbose
`#{cmd}`
end
end
end
def run
raise NotImplementedError
end
protected
def input_duration
raise NotImplementedError
end
end
end
Add preset name to output_fullpath function
# encoding: utf-8
module VideoScreenshoter
class Abstract
attr_accessor :ffmpeg, :imagemagick, :output_dir, :output_file, :input, :times, :duration, :verbose, :size, :presets
def initialize params
[:ffmpeg, :imagemagick, :output_dir, :output_file, :verbose].each do |attr|
self.send("#{attr}=".to_sym, params[attr].nil? ? VideoScreenshoter.send(attr) : params[attr])
end
FileUtils.mkdir_p self.output_dir
self.input = params[:input]
self.duration = input_duration
raise ArgumentError.new('Incorrect or empty m3u8 playlist') if duration.to_i == 0
self.times = params[:times].to_a.map do |time|
if time.is_a?(String) && matches = time.match(/(.*)%$/)
time = matches[1].to_f / 100 * duration
end
time = duration + time if time < 0
time = time.to_i
time
end.uniq
self.size = params[:size] ? "-s #{params[:size]}" : ''
if params[:presets] && params[:presets].is_a?(Hash)
self.presets = {}
params[:presets].each do |name, preset|
self.presets[name.to_sym] = preset.index('-') == 0 ? preset : "-resize #{preset}"
end
end
end
def output_fullpath time, preset = nil
res = sprintf(File.join(output_dir, output_file), time)
res.sub!(File.extname(res), "_#{preset}#{File.extname(res)}") if preset
res
end
def ffmpeg_command input, output, time
"#{ffmpeg} -i #{input} -acodec -an -ss #{time} #{size} -f image2 -vframes 1 -y #{output} 2>/dev/null 1>&2"
end
def imagemagick_command input, preset_name
"#{imagemagick} #{input} #{presets[preset_name.to_sym]} #{File.join(File.dirname(input), File.basename(input, File.extname(input)) + '_' + preset_name.to_s + File.extname(input))}"
end
def imagemagick_run scr
if presets
presets.each do |preset_name, preset|
cmd = imagemagick_command(scr, preset_name)
puts cmd if verbose
`#{cmd}`
end
end
end
def run
raise NotImplementedError
end
protected
def input_duration
raise NotImplementedError
end
end
end
|
# Collects and reports on messages sent to an instance.
class WisperSubscription
VERSION = '0.1.0'
end
Bumping to 0.1.1.
RSpec: 19 examples, 0 failures
RuboCop: 4 files inspected, no offences detected
# Collects and reports on messages sent to an instance.
class WisperSubscription
VERSION = '0.1.1'
end
|
$LOAD_PATH.unshift *Dir[File.expand_path('../../files/default/vendor/gems/**/lib', __FILE__)]
require 'docker'
class Chef
class Provider
class DockerImage < Chef::Provider::LWRPBase
# register with the resource resolution system
provides :docker_image if Chef::Provider.respond_to?(:provides)
################
# Helper methods
################
def build_from_directory
i = Docker::Image.build_from_dir(
new_resource.source,
'nocache' => new_resource.nocache,
'rm' => new_resource.rm
)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
end
def build_from_dockerfile
i = Docker::Image.build(
IO.read(new_resource.source),
'nocache' => new_resource.nocache,
'rm' => new_resource.rm
)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
end
def build_from_tar
i = Docker::Image.build_from_tar(
::File.open(new_resource.source, 'r'),
'nocache' => new_resource.nocache,
'rm' => new_resource.rm
)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
end
def build_image
if ::File.directory?(new_resource.source)
build_from_directory
elsif ::File.extname(new_resource.source) == '.tar'
build_from_tar
else
build_from_dockerfile
end
end
def import_image
retries ||= new_resource.retries
i = Docker::Image.import(new_resource.source)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def pull_image
retries ||= new_resource.retries
Docker::Image.create(
'fromImage' => new_resource.repo,
'tag' => new_resource.tag
)
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def push_image
retries ||= new_resource.retries
i = Docker::Image.get("#{new_resource.repo}:#{new_resource.tag}")
i.push
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def remove_image
retries ||= new_resource.retries
i = Docker::Image.get("#{new_resource.repo}:#{new_resource.tag}")
i.remove(force: new_resource.force, noprune: new_resource.noprune)
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def save_image
retries ||= new_resource.retries
Docker::Image.save(new_resource.repo, new_resource.destination)
rescue Docker::Error, Errno::ENOENT => e
retry unless (tries -= 1).zero?
raise e.message
end
#########
# Actions
#########
action :build do
build_image
new_resource.updated_by_last_action(true)
end
action :build_if_missing do
next if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
action_build
new_resource.updated_by_last_action(true)
end
action :import do
next if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
import_image
new_resource.updated_by_last_action(true)
end
action :pull do
pull_image
new_resource.updated_by_last_action(true)
end
action :pull_if_missing do
next if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
action_pull
end
action :push do
push_image
new_resource.updated_by_last_action(true)
end
action :remove do
next unless Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
remove_image
new_resource.updated_by_last_action(true)
end
action :save do
save_image
new_resource.updated_by_last_action(true)
end
end
end
end
updating pull to only set last_action to true if a new image was downloaded
$LOAD_PATH.unshift *Dir[File.expand_path('../../files/default/vendor/gems/**/lib', __FILE__)]
require 'docker'
class Chef
class Provider
class DockerImage < Chef::Provider::LWRPBase
# register with the resource resolution system
provides :docker_image if Chef::Provider.respond_to?(:provides)
################
# Helper methods
################
def build_from_directory
i = Docker::Image.build_from_dir(
new_resource.source,
'nocache' => new_resource.nocache,
'rm' => new_resource.rm
)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
end
def build_from_dockerfile
i = Docker::Image.build(
IO.read(new_resource.source),
'nocache' => new_resource.nocache,
'rm' => new_resource.rm
)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
end
def build_from_tar
i = Docker::Image.build_from_tar(
::File.open(new_resource.source, 'r'),
'nocache' => new_resource.nocache,
'rm' => new_resource.rm
)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
end
def build_image
if ::File.directory?(new_resource.source)
build_from_directory
elsif ::File.extname(new_resource.source) == '.tar'
build_from_tar
else
build_from_dockerfile
end
end
def import_image
retries ||= new_resource.retries
i = Docker::Image.import(new_resource.source)
i.tag('repo' => new_resource.repo, 'tag' => new_resource.tag, 'force' => new_resource.force)
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def pull_image
retries ||= new_resource.retries
o = Docker::Image.get("#{new_resource.repo}:#{new_resource.tag}") if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
i = Docker::Image.create(
'fromImage' => new_resource.repo,
'tag' => new_resource.tag
)
return false if o && o.id =~ /^#{i.id}/
return true
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def push_image
retries ||= new_resource.retries
i = Docker::Image.get("#{new_resource.repo}:#{new_resource.tag}")
i.push
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def remove_image
retries ||= new_resource.retries
i = Docker::Image.get("#{new_resource.repo}:#{new_resource.tag}")
i.remove(force: new_resource.force, noprune: new_resource.noprune)
rescue Docker::Error => e
retry unless (tries -= 1).zero?
raise e.message
end
def save_image
retries ||= new_resource.retries
Docker::Image.save(new_resource.repo, new_resource.destination)
rescue Docker::Error, Errno::ENOENT => e
retry unless (tries -= 1).zero?
raise e.message
end
#########
# Actions
#########
action :build do
build_image
new_resource.updated_by_last_action(true)
end
action :build_if_missing do
next if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
action_build
new_resource.updated_by_last_action(true)
end
action :import do
next if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
import_image
new_resource.updated_by_last_action(true)
end
action :pull do
r = pull_image
new_resource.updated_by_last_action(r)
end
action :pull_if_missing do
next if Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
action_pull
end
action :push do
push_image
new_resource.updated_by_last_action(true)
end
action :remove do
next unless Docker::Image.exist?("#{new_resource.repo}:#{new_resource.tag}")
remove_image
new_resource.updated_by_last_action(true)
end
action :save do
save_image
new_resource.updated_by_last_action(true)
end
end
end
end
|
require 'pxp-agent/config_helper.rb'
test_name 'Attempt to start pxp-agent with invalid SSL config'
agent1 = agents[0]
# On teardown, restore valid config file
teardown do
on agent1, puppet('resource service pxp-agent ensure=stopped')
create_remote_file(agent1, pxp_agent_config_file(agent1), pxp_config_json_using_test_certs(master, agent1, 1).to_s)
on agent1, puppet('resource service pxp-agent ensure=running')
end
step 'Setup - Stop pxp-agent service'
on agent1, puppet('resource service pxp-agent ensure=stopped')
step "Setup - Wipe pxp-agent log"
on(agent1, "rm -rf #{logfile(agent1)}")
step "Setup - Change pxp-agent config to use a cert that doesn't match private key"
invalid_config_mismatching_keys = {:broker_ws_uri => broker_ws_uri(master),
:ssl_key => ssl_key_file(agent1, 1),
:ssl_ca_cert => ssl_ca_file(agent1),
:ssl_cert => ssl_cert_file(agent1, 1, use_alt_path=true)}
create_remote_file(agent1, pxp_agent_config_file(agent1), pxp_config_json(master, agent1, invalid_config_mismatching_keys).to_s)
step 'C94730 - Attempt to run pxp-agent with mismatching SSL cert and private key'
expected_private_key_error='failed to load private key'
on agent1, puppet('resource service pxp-agent ensure=running')
# If the expected error does not appear in log within 30 seconds, then do an
# explicit assertion so we see the log contents in the test failure output
begin
retry_on(agent1, "grep '#{expected_private_key_error}' #{logfile(agent1)}", {:max_retries => 30,
:retry_interval => 1})
rescue
on(agent1, "cat #{log_file}") do |result|
assert_match(expected_private_key_error, result.stdout,
"Expected error '#{expected_private_key_error}' did not appear in pxp-agent.log")
end
end
assert(on(agent1, "grep 'pxp-agent will start unconfigured' #{logfile(agent1)}"),
"pxp-agent should log that is will start unconfigured")
on agent1, puppet('resource service pxp-agent') do |result|
assert_match(/running/, result.stdout, "pxp-agent service should be running (unconfigured)")
end
step "Stop service and wipe log"
on agent1, puppet('resource service pxp-agent ensure=stopped')
on(agent, "rm -rf #{logfile(agent1)}")
step "Change pxp-agent config so the cert and key match but they are of a different ca than the broker"
invalid_config_wrong_ca = {:broker_ws_uri => broker_ws_uri(master),
:ssl_key => ssl_key_file(agent1, 1, use_alt_path=true),
:ssl_ca_cert => ssl_ca_file(agent1),
:ssl_cert => ssl_cert_file(agent1, 1, use_alt_path=true)}
create_remote_file(agent1, pxp_agent_config_file(agent1), pxp_config_json(master, agent1, invalid_config_wrong_ca).to_s)
step 'C94729 - Attempt to run pxp-agent with SSL keypair from a different ca'
on agent1, puppet('resource service pxp-agent ensure=running')
retry_on(agent1, "grep 'TLS handshake failed' #{logfile(agent1)}", {:max_retries => 30,
:retry_interval => 1})
assert(on(agent1, "grep 'retrying in' #{logfile(agent1)}"),
"pxp-agent should log that it will retry connection")
on agent1, puppet('resource service pxp-agent') do |result|
assert_match(/running/, result.stdout, "pxp-agent service should be running (failing handshake)")
end
on agent1, puppet('resource service pxp-agent ensure=stopped')
on agent1, puppet('resource service pxp-agent') do |result|
assert_match(/stopped/, result.stdout,
"pxp-agent service should stop cleanly when it is running in a loop retrying invalid certs")
end
(maint) Acceptance - remove incorrect named arguments from SSL config test
The invalid_ssl_config test was calling a helper method with what appeared to be a named argument, but was actually just creating a local variable.
Note that proper keyword arguments are possible but are only in Ruby 2.0 onwards; and our CI might use Ruby 1.9.3 so they have not been used here.
require 'pxp-agent/config_helper.rb'
test_name 'Attempt to start pxp-agent with invalid SSL config'
agent1 = agents[0]
# On teardown, restore valid config file
teardown do
on agent1, puppet('resource service pxp-agent ensure=stopped')
create_remote_file(agent1, pxp_agent_config_file(agent1), pxp_config_json_using_test_certs(master, agent1, 1).to_s)
on agent1, puppet('resource service pxp-agent ensure=running')
end
step 'Setup - Stop pxp-agent service'
on agent1, puppet('resource service pxp-agent ensure=stopped')
step "Setup - Wipe pxp-agent log"
on(agent1, "rm -rf #{logfile(agent1)}")
step "Setup - Change pxp-agent config to use a cert that doesn't match private key"
invalid_config_mismatching_keys = {:broker_ws_uri => broker_ws_uri(master),
:ssl_key => ssl_key_file(agent1, 1),
:ssl_ca_cert => ssl_ca_file(agent1),
:ssl_cert => ssl_cert_file(agent1, 1, true)}
create_remote_file(agent1, pxp_agent_config_file(agent1), pxp_config_json(master, agent1, invalid_config_mismatching_keys).to_s)
step 'C94730 - Attempt to run pxp-agent with mismatching SSL cert and private key'
expected_private_key_error='failed to load private key'
on agent1, puppet('resource service pxp-agent ensure=running')
# If the expected error does not appear in log within 30 seconds, then do an
# explicit assertion so we see the log contents in the test failure output
begin
retry_on(agent1, "grep '#{expected_private_key_error}' #{logfile(agent1)}", {:max_retries => 30,
:retry_interval => 1})
rescue
on(agent1, "cat #{log_file}") do |result|
assert_match(expected_private_key_error, result.stdout,
"Expected error '#{expected_private_key_error}' did not appear in pxp-agent.log")
end
end
assert(on(agent1, "grep 'pxp-agent will start unconfigured' #{logfile(agent1)}"),
"pxp-agent should log that is will start unconfigured")
on agent1, puppet('resource service pxp-agent') do |result|
assert_match(/running/, result.stdout, "pxp-agent service should be running (unconfigured)")
end
step "Stop service and wipe log"
on agent1, puppet('resource service pxp-agent ensure=stopped')
on(agent, "rm -rf #{logfile(agent1)}")
step "Change pxp-agent config so the cert and key match but they are of a different ca than the broker"
invalid_config_wrong_ca = {:broker_ws_uri => broker_ws_uri(master),
:ssl_key => ssl_key_file(agent1, 1, true),
:ssl_ca_cert => ssl_ca_file(agent1),
:ssl_cert => ssl_cert_file(agent1, 1, true)}
create_remote_file(agent1, pxp_agent_config_file(agent1), pxp_config_json(master, agent1, invalid_config_wrong_ca).to_s)
step 'C94729 - Attempt to run pxp-agent with SSL keypair from a different ca'
on agent1, puppet('resource service pxp-agent ensure=running')
retry_on(agent1, "grep 'TLS handshake failed' #{logfile(agent1)}", {:max_retries => 30,
:retry_interval => 1})
assert(on(agent1, "grep 'retrying in' #{logfile(agent1)}"),
"pxp-agent should log that it will retry connection")
on agent1, puppet('resource service pxp-agent') do |result|
assert_match(/running/, result.stdout, "pxp-agent service should be running (failing handshake)")
end
on agent1, puppet('resource service pxp-agent ensure=stopped')
on agent1, puppet('resource service pxp-agent') do |result|
assert_match(/stopped/, result.stdout,
"pxp-agent service should stop cleanly when it is running in a loop retrying invalid certs")
end
|
require 'mail'
require 'action_mailer/tmail_compat'
require 'action_mailer/collector'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/proc'
require 'action_mailer/log_subscriber'
module ActionMailer #:nodoc:
# Action Mailer allows you to send email from your application using a mailer model and views.
#
# = Mailer Models
#
# To use Action Mailer, you need to create a mailer model.
#
# $ rails generate mailer Notifier
#
# The generated model inherits from <tt>ActionMailer::Base</tt>. Emails are defined by creating methods
# within the model which are then used to set variables to be used in the mail template, to
# change options on the mail, or to add attachments.
#
# Examples:
#
# class Notifier < ActionMailer::Base
# default :from => 'no-reply@example.com',
# :return_path => 'system@example.com'
#
# def welcome(recipient)
# @account = recipient
# mail(:to => recipient.email_address_with_name,
# :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
# end
# end
#
# Within the mailer method, you have access to the following methods:
#
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
#
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
# in the same manner as <tt>attachments[]=</tt>
#
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields (like <tt>To:</tt>
# <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
# can appear multiple times. If you want to change a field that can appear multiple times,
# you need to set it to nil first so that Mail knows you are replacing it, not adding
# another field of the same name.)
#
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
#
# * <tt>mail</tt> - Allows you to specify your email to send.
#
# The hash passed to the mail method allows you to specify any header that a Mail::Message
# will accept (any valid Email header including optional fields).
#
# The mail method, if not passed a block, will inspect your views and send all the views with
# the same name as the method, so the above action would send the +welcome.text.plain.erb+ view
# file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
#
# If you want to explicitly render only certain templates, pass a block:
#
# mail(:to => user.email) do |format|
# format.text
# format.html
# end
#
# The block syntax is useful if also need to specify information specific to a part:
#
# mail(:to => user.email) do |format|
# format.text(:content_transfer_encoding => "base64")
# format.html
# end
#
# Or even to render a special view:
#
# mail(:to => user.email) do |format|
# format.text
# format.html { render "some_other_template" }
# end
#
# = Mailer views
#
# Like Action Controller, each mailer class has a corresponding view directory in which each
# method of the class looks for a template with its name.
#
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
# name as the method in your mailer model. For example, in the mailer defined above, the template at
# <tt>app/views/notifier/signup_notification.text.plain.erb</tt> would be used to generate the email.
#
# Variables defined in the model are accessible as instance variables in the view.
#
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
#
# Hi <%= @account.name %>,
# Thanks for joining our service! Please check back often.
#
# You can even use Action Pack helpers in these views. For example:
#
# You got a new note!
# <%= truncate(@note.body, 25) %>
#
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
#
# You got a new note from <%= message.from %>!
# <%= truncate(@note.body, 25) %>
#
#
# = Generating URLs
#
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
# to provide all of the details needed to generate a URL.
#
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
#
# <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
#
# When using named routes you only need to supply the <tt>:host</tt>:
#
# <%= users_url(:host => "example.com") %>
#
# You will want to avoid using the <tt>name_of_route_path</tt> form of named routes because it doesn't
# make sense to generate relative URLs in email messages.
#
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
# option in the <tt>ActionMailer::Base.default_url_options</tt> hash as follows:
#
# ActionMailer::Base.default_url_options[:host] = "example.com"
#
# This can also be set as a configuration option in <tt>config/application.rb</tt>:
#
# config.action_mailer.default_url_options = { :host => "example.com" }
#
# If you do decide to set a default <tt>:host</tt> for your mailers you will want to use the
# <tt>:only_path => false</tt> option when using <tt>url_for</tt>. This will ensure that absolute URLs are
# generated because the <tt>url_for</tt> view helper will, by default, generate relative URLs when a
# <tt>:host</tt> option isn't explicitly provided.
#
# = Sending mail
#
# Once a mailer action and template are defined, you can deliver your message or create it and save it
# for delivery later:
#
# Notifier.welcome(david).deliver # sends the email
# mail = Notifier.welcome(david) # => a Mail::Message object
# mail.deliver # sends the email
#
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
#
# = Multipart Emails
#
# Multipart messages can also be used implicitly because Action Mailer will automatically
# detect and use multipart templates, where each template is named after the name of the action, followed
# by the content type. Each such detected template will be added as separate part to the message.
#
# For example, if the following templates existed:
# * signup_notification.text.plain.erb
# * signup_notification.text.html.erb
# * signup_notification.text.xml.builder
# * signup_notification.text.yaml.erb
#
# Each would be rendered and added as a separate part to the message, with the corresponding content
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
# which indicates that the email contains multiple different representations of the same email
# body. The same instance variables defined in the action are passed to all email templates.
#
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
# This means that you'll have to manually add each part to the email and set the content type of the email
# to <tt>multipart/alternative</tt>.
#
# = Attachments
#
# You can see above how to make a multipart HTML / Text email, to send attachments is just
# as easy:
#
# class ApplicationMailer < ActionMailer::Base
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(:to => recipient, :subject => "New account information")
# end
# end
#
# Which will (if it had both a <tt>welcome.text.plain.erb</tt> and <tt>welcome.text.html.erb</tt>
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
# with the filename +free_book.pdf+.
#
# = Inline Attachments
#
# You can also specify that a file should be displayed inline with other HTML. For example a
# corporate logo or a photo or the like.
#
# To do this is simple, in the Mailer:
#
# class ApplicationMailer < ActionMailer::Base
# def welcome(recipient)
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
# mail(:to => recipient, :subject => "Here is what we look like")
# end
# end
#
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
# make a call to +image_tag+ passing in the attachment you want to display and then call
# +url+ on the attachment to get the relative content id path for the image source:
#
# <h1>Please Don't Cringe</h1>
#
# <%= image_tag attachments['photo.png'].url -%>
#
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
#
# <h1>Please Don't Cringe</h1>
#
# <%= image_tag attachments['photo.png'].url, :alt => 'Our Photo', :class => 'photo' -%>
#
# = Observing and Intercepting Mails
#
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
# register objects that are called during the mail delivery life cycle.
#
# An observer object must implement the <tt>:delivered_email(message)</tt> method which will be
# called once for every email sent after the email has been sent.
#
# An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be
# called before the email is sent, allowing you to make modifications to the email before it hits
# the delivery agents. Your object should make and needed modifications directly to the passed
# in Mail::Message instance.
#
# = Default Hash
#
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
# default method inside the class definition:
#
# class Notifier < ActionMailer::Base
# default :sender => 'system@example.com'
# end
#
# You can pass in any header value that a <tt>Mail::Message</tt>, out of the box, <tt>ActionMailer::Base</tt>
# sets the following:
#
# * <tt>:mime_version => "1.0"</tt>
# * <tt>:charset => "UTF-8",</tt>
# * <tt>:content_type => "text/plain",</tt>
# * <tt>:parts_order => [ "text/plain", "text/enriched", "text/html" ]</tt>
#
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
# but Action Mailer translates them appropriately and sets the correct values.
#
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
# an underscorised symbol, so the following will work:
#
# class Notifier < ActionMailer::Base
# default 'Content-Transfer-Encoding' => '7bit',
# :content_description => 'This is a description'
# end
#
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
# can define methods that evaluate as the message is being generated:
#
# class Notifier < ActionMailer::Base
# default 'X-Special-Header' => Proc.new { my_method }
#
# private
#
# def my_method
# 'some complex call'
# end
# end
#
# Note that the proc is evaluated right at the start of the mail message generation, so if you
# set something in the defaults using a proc, and then set the same thing inside of your
# mailer method, it will get over written by the mailer method.
#
# = Configuration options
#
# These options are specified on the class level, like
# <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
# * <tt>default</tt> - You can pass this in at a class level as well as within the class itself as
# per the above section.
#
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
#
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
# "localhost" setting.
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
# authentication type here.
# This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
# and starts to use it.
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@addres</tt>
# added automatically before the message is sent.
#
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
# <tt>tmp/mails</tt>.
#
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
# object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to
# implement for a custom delivery agent.
#
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
# be turned off to aid in functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
#
# * <tt>default_charset</tt> - This is now deprecated, use the +default+ method above to
# set the default +:charset+.
#
# * <tt>default_content_type</tt> - This is now deprecated, use the +default+ method above
# to set the default +:content_type+.
#
# * <tt>default_mime_version</tt> - This is now deprecated, use the +default+ method above
# to set the default +:mime_version+.
#
# * <tt>default_implicit_parts_order</tt> - This is now deprecated, use the +default+ method above
# to set the default +:parts_order+. Parts Order is used when a message is built implicitly
# (i.e. multiple parts are assembled from templates which specify the content type in their
# filenames) this variable controls how the parts are ordered.
class Base < AbstractController::Base
include DeliveryMethods
abstract!
include AbstractController::Logger
include AbstractController::Rendering
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::Translation
include AbstractController::AssetPaths
helper ActionMailer::MailHelper
include ActionMailer::OldApi
include ActionMailer::DeprecatedApi
delegate :register_observer, :to => Mail
delegate :register_interceptor, :to => Mail
private_class_method :new #:nodoc:
class_attribute :default_params
self.default_params = {
:mime_version => "1.0",
:charset => "UTF-8",
:content_type => "text/plain",
:parts_order => [ "text/plain", "text/enriched", "text/html" ]
}.freeze
class << self
def mailer_name
@mailer_name ||= name.underscore
end
attr_writer :mailer_name
alias :controller_path :mailer_name
def default(value = nil)
self.default_params = default_params.merge(value).freeze if value
default_params
end
# Receives a raw email, parses it into an email object, decodes it,
# instantiates a new mailer, and passes the email object to the mailer
# object's +receive+ method. If you want your mailer to be able to
# process incoming messages, you'll need to implement a +receive+
# method that accepts the raw email string as a parameter:
#
# class MyMailer < ActionMailer::Base
# def receive(mail)
# ...
# end
# end
def receive(raw_mail)
ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
mail = Mail.new(raw_mail)
set_payload_for_mail(payload, mail)
new.receive(mail)
end
end
# Wraps an email delivery inside of Active Support Notifications instrumentation. This
# method is actually called by the <tt>Mail::Message</tt> object itself through a callback
# when you call <tt>:deliver</tt> on the Mail::Message, calling +deliver_mail+ directly
# and passing a Mail::Message will do nothing except tell the logger you sent the email.
def deliver_mail(mail) #:nodoc:
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
self.set_payload_for_mail(payload, mail)
yield # Let Mail do the delivery actions
end
end
def respond_to?(method, *args) #:nodoc:
super || action_methods.include?(method.to_s)
end
protected
def set_payload_for_mail(payload, mail) #:nodoc:
payload[:mailer] = self.name
payload[:message_id] = mail.message_id
payload[:subject] = mail.subject
payload[:to] = mail.to
payload[:from] = mail.from
payload[:bcc] = mail.bcc if mail.bcc.present?
payload[:cc] = mail.cc if mail.cc.present?
payload[:date] = mail.date
payload[:mail] = mail.encoded
end
def method_missing(method, *args) #:nodoc:
if action_methods.include?(method.to_s)
new(method, *args).message
else
super
end
end
end
attr_internal :message
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
# will be initialized according to the named method. If not, the mailer will
# remain uninitialized (useful when you only need to invoke the "receive"
# method, for instance).
def initialize(method_name=nil, *args)
super()
@_message = Mail.new
process(method_name, *args) if method_name
end
def process(*args) #:nodoc:
lookup_context.skip_default_locale!
super
end
# Allows you to pass random and unusual headers to the new +Mail::Message+ object
# which will add them to itself.
#
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
#
# You can also pass a hash into headers of header field names and values, which
# will then be set on the Mail::Message object:
#
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
# 'In-Reply-To' => incoming.message_id
#
# The resulting Mail::Message will have the following in it's header:
#
# X-Special-Domain-Specific-Header: SecretValue
def headers(args=nil)
if args
@_message.headers(args)
else
@_message
end
end
# Allows you to add attachments to an email, like so:
#
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
#
# If you do this, then Mail will take the file name and work out the mime type
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
# base64 encode the contents of the attachment all for you.
#
# You can also specify overrides if you want by passing a hash instead of a string:
#
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
# :content => File.read('/path/to/filename.jpg')}
#
# If you want to use a different encoding than Base64, you can pass an encoding in,
# but then it is up to you to pass in the content pre-encoded, and don't expect
# Mail to know how to decode this data:
#
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
# :encoding => 'SpecialEncoding',
# :content => file_content }
#
# You can also search for specific attachments:
#
# # By Filename
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
#
# # or by index
# mail.attachments[0] #=> Mail::Part (first attachment)
#
def attachments
@_message.attachments
end
# The main method that creates the message and renders the email templates. There are
# two ways to call this method, with a block, or without a block.
#
# Both methods accept a headers hash. This hash allows you to specify the most used headers
# in an email message, these are:
#
# * <tt>:subject</tt> - The subject of the message, if this is omitted, Action Mailer will
# ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
# <tt>[:actionmailer, mailer_scope, action_name]</tt> or if this is missing, will translate the
# humanized version of the <tt>action_name</tt>
# * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
# of addresses.
# * <tt>:from</tt> - Who the message is from
# * <tt>:cc</tt> - Who you would like to Carbon-Copy on this email, can be a string of addresses,
# or an array of addresses.
# * <tt>:bcc</tt> - Who you would like to Blind-Carbon-Copy on this email, can be a string of
# addresses, or an array of addresses.
# * <tt>:reply_to</tt> - Who to set the Reply-To header of the email to.
# * <tt>:date</tt> - The date to say the email was sent on.
#
# You can set default values for any of the above headers (except :date) by using the <tt>default</tt>
# class method:
#
# class Notifier < ActionMailer::Base
# self.default :from => 'no-reply@test.lindsaar.net',
# :bcc => 'email_logger@test.lindsaar.net',
# :reply_to => 'bounces@test.lindsaar.net'
# end
#
# If you need other headers not listed above, you can either pass them in
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
# method.
#
# When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
# address for the Mail message. Setting this is useful when you want delivery notifications
# sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
# <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
# field for the 'envelope from' value.
#
# If you do not pass a block to the +mail+ method, it will find all templates in the
# view paths using by default the mailer name and the method name that it is being
# called from, it will then create parts for each of these templates intelligently,
# making educated guesses on correct content type and sequence, and return a fully
# prepared Mail::Message ready to call <tt>:deliver</tt> on to send.
#
# For example:
#
# class Notifier < ActionMailer::Base
# default :from => 'no-reply@test.lindsaar.net',
#
# def welcome
# mail(:to => 'mikel@test.lindsaar.net')
# end
# end
#
# Will look for all templates at "app/views/notifier" with name "welcome". However, those
# can be customized:
#
# mail(:template_path => 'notifications', :template_name => 'another')
#
# And now it will look for all templates at "app/views/notifications" with name "another".
#
# If you do pass a block, you can render specific templates of your choice:
#
# mail(:to => 'mikel@test.lindsaar.net') do |format|
# format.text
# format.html
# end
#
# You can even render text directly without using a template:
#
# mail(:to => 'mikel@test.lindsaar.net') do |format|
# format.text { render :text => "Hello Mikel!" }
# format.html { render :text => "<h1>Hello Mikel!</h1>" }
# end
#
# Which will render a <tt>multipart/alternative</tt> email with <tt>text/plain</tt> and
# <tt>text/html</tt> parts.
#
# The block syntax also allows you to customize the part headers if desired:
#
# mail(:to => 'mikel@test.lindsaar.net') do |format|
# format.text(:content_transfer_encoding => "base64")
# format.html
# end
#
def mail(headers={}, &block)
# Guard flag to prevent both the old and the new API from firing
# Should be removed when old API is removed
@mail_was_called = true
m = @_message
# At the beginning, do not consider class default for parts order neither content_type
content_type = headers[:content_type]
parts_order = headers[:parts_order]
# Call all the procs (if any)
default_values = self.class.default.merge(self.class.default) do |k,v|
v.respond_to?(:call) ? v.bind(self).call : v
end
# Handle defaults
headers = headers.reverse_merge(default_values)
headers[:subject] ||= default_i18n_subject
# Apply charset at the beginning so all fields are properly quoted
m.charset = charset = headers[:charset]
# Set configure delivery behavior
wrap_delivery_behavior!(headers.delete(:delivery_method))
# Assign all headers except parts_order, content_type and body
assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
assignable.each { |k, v| m[k] = v }
# Render the templates and blocks
responses, explicit_order = collect_responses_and_parts_order(headers, &block)
create_parts_from_responses(m, responses)
# Setup content type, reapply charset and handle parts order
m.content_type = set_content_type(m, content_type, headers[:content_type])
m.charset = charset
if m.multipart?
parts_order ||= explicit_order || headers[:parts_order]
m.body.set_sort_order(parts_order)
m.body.sort_parts!
end
m
end
protected
def set_content_type(m, user_content_type, class_default)
params = m.content_type_parameters || {}
case
when user_content_type.present?
user_content_type
when m.has_attachments?
if m.attachments.detect { |a| a.inline? }
["multipart", "related", params]
else
["multipart", "mixed", params]
end
when m.multipart?
["multipart", "alternative", params]
else
m.content_type || class_default
end
end
def default_i18n_subject #:nodoc:
mailer_scope = self.class.mailer_name.gsub('/', '.')
I18n.t(:subject, :scope => [mailer_scope, action_name], :default => action_name.humanize)
end
def collect_responses_and_parts_order(headers) #:nodoc:
responses, parts_order = [], nil
if block_given?
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
yield(collector)
parts_order = collector.responses.map { |r| r[:content_type] }
responses = collector.responses
elsif headers[:body]
responses << {
:body => headers.delete(:body),
:content_type => self.class.default[:content_type] || "text/plain"
}
else
templates_path = headers.delete(:template_path) || self.class.mailer_name
templates_name = headers.delete(:template_name) || action_name
each_template(templates_path, templates_name) do |template|
self.formats = template.formats
responses << {
:body => render(:template => template),
:content_type => template.mime_type.to_s
}
end
end
[responses, parts_order]
end
def each_template(paths, name, &block) #:nodoc:
Array.wrap(paths).each do |path|
templates = lookup_context.find_all(name, path)
templates = templates.uniq_by { |t| t.formats }
unless templates.empty?
templates.each(&block)
return
end
end
end
def create_parts_from_responses(m, responses) #:nodoc:
if responses.size == 1 && !m.has_attachments?
responses[0].each { |k,v| m[k] = v }
elsif responses.size > 1 && m.has_attachments?
container = Mail::Part.new
container.content_type = "multipart/alternative"
responses.each { |r| insert_part(container, r, m.charset) }
m.add_part(container)
else
responses.each { |r| insert_part(m, r, m.charset) }
end
end
def insert_part(container, response, charset) #:nodoc:
response[:charset] ||= charset
part = Mail::Part.new(response)
container.add_part(part)
end
module DeprecatedUrlOptions
def default_url_options
deprecated_url_options
end
def default_url_options=(val)
deprecated_url_options
end
def deprecated_url_options
raise "You can no longer call ActionMailer::Base.default_url_options " \
"directly. You need to set config.action_mailer.default_url_options. " \
"If you are using ActionMailer standalone, you need to include the " \
"routing url_helpers directly."
end
end
# This module will complain if the user tries to set default_url_options
# directly instead of through the config object. In Action Mailer's Railtie,
# we include the router's url_helpers, which will override this module.
extend DeprecatedUrlOptions
ActiveSupport.run_load_hooks(:action_mailer, self)
end
end
Mention that ActionMailer::Base.default_url_options is now deprecated
require 'mail'
require 'action_mailer/tmail_compat'
require 'action_mailer/collector'
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/proc'
require 'action_mailer/log_subscriber'
module ActionMailer #:nodoc:
# Action Mailer allows you to send email from your application using a mailer model and views.
#
# = Mailer Models
#
# To use Action Mailer, you need to create a mailer model.
#
# $ rails generate mailer Notifier
#
# The generated model inherits from <tt>ActionMailer::Base</tt>. Emails are defined by creating methods
# within the model which are then used to set variables to be used in the mail template, to
# change options on the mail, or to add attachments.
#
# Examples:
#
# class Notifier < ActionMailer::Base
# default :from => 'no-reply@example.com',
# :return_path => 'system@example.com'
#
# def welcome(recipient)
# @account = recipient
# mail(:to => recipient.email_address_with_name,
# :bcc => ["bcc@example.com", "Order Watcher <watcher@example.com>"])
# end
# end
#
# Within the mailer method, you have access to the following methods:
#
# * <tt>attachments[]=</tt> - Allows you to add attachments to your email in an intuitive
# manner; <tt>attachments['filename.png'] = File.read('path/to/filename.png')</tt>
#
# * <tt>attachments.inline[]=</tt> - Allows you to add an inline attachment to your email
# in the same manner as <tt>attachments[]=</tt>
#
# * <tt>headers[]=</tt> - Allows you to specify any header field in your email such
# as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields (like <tt>To:</tt>
# <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt>
# can appear multiple times. If you want to change a field that can appear multiple times,
# you need to set it to nil first so that Mail knows you are replacing it, not adding
# another field of the same name.)
#
# * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such
# as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt>
#
# * <tt>mail</tt> - Allows you to specify your email to send.
#
# The hash passed to the mail method allows you to specify any header that a Mail::Message
# will accept (any valid Email header including optional fields).
#
# The mail method, if not passed a block, will inspect your views and send all the views with
# the same name as the method, so the above action would send the +welcome.text.plain.erb+ view
# file as well as the +welcome.text.html.erb+ view file in a +multipart/alternative+ email.
#
# If you want to explicitly render only certain templates, pass a block:
#
# mail(:to => user.email) do |format|
# format.text
# format.html
# end
#
# The block syntax is useful if also need to specify information specific to a part:
#
# mail(:to => user.email) do |format|
# format.text(:content_transfer_encoding => "base64")
# format.html
# end
#
# Or even to render a special view:
#
# mail(:to => user.email) do |format|
# format.text
# format.html { render "some_other_template" }
# end
#
# = Mailer views
#
# Like Action Controller, each mailer class has a corresponding view directory in which each
# method of the class looks for a template with its name.
#
# To define a template to be used with a mailing, create an <tt>.erb</tt> file with the same
# name as the method in your mailer model. For example, in the mailer defined above, the template at
# <tt>app/views/notifier/signup_notification.text.plain.erb</tt> would be used to generate the email.
#
# Variables defined in the model are accessible as instance variables in the view.
#
# Emails by default are sent in plain text, so a sample view for our model example might look like this:
#
# Hi <%= @account.name %>,
# Thanks for joining our service! Please check back often.
#
# You can even use Action Pack helpers in these views. For example:
#
# You got a new note!
# <%= truncate(@note.body, 25) %>
#
# If you need to access the subject, from or the recipients in the view, you can do that through message object:
#
# You got a new note from <%= message.from %>!
# <%= truncate(@note.body, 25) %>
#
#
# = Generating URLs
#
# URLs can be generated in mailer views using <tt>url_for</tt> or named routes. Unlike controllers from
# Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need
# to provide all of the details needed to generate a URL.
#
# When using <tt>url_for</tt> you'll need to provide the <tt>:host</tt>, <tt>:controller</tt>, and <tt>:action</tt>:
#
# <%= url_for(:host => "example.com", :controller => "welcome", :action => "greeting") %>
#
# When using named routes you only need to supply the <tt>:host</tt>:
#
# <%= users_url(:host => "example.com") %>
#
# You will want to avoid using the <tt>name_of_route_path</tt> form of named routes because it doesn't
# make sense to generate relative URLs in email messages.
#
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
# option as a configuration option in <tt>config/application.rb</tt>:
#
# config.action_mailer.default_url_options = { :host => "example.com" }
#
# Setting <tt>ActionMailer::Base.default_url_options</tt> directly is now deprecated, use the configuration
# option mentioned above to set the default host.
#
# If you do decide to set a default <tt>:host</tt> for your mailers you will want to use the
# <tt>:only_path => false</tt> option when using <tt>url_for</tt>. This will ensure that absolute URLs are
# generated because the <tt>url_for</tt> view helper will, by default, generate relative URLs when a
# <tt>:host</tt> option isn't explicitly provided.
#
# = Sending mail
#
# Once a mailer action and template are defined, you can deliver your message or create it and save it
# for delivery later:
#
# Notifier.welcome(david).deliver # sends the email
# mail = Notifier.welcome(david) # => a Mail::Message object
# mail.deliver # sends the email
#
# You never instantiate your mailer class. Rather, you just call the method you defined on the class itself.
#
# = Multipart Emails
#
# Multipart messages can also be used implicitly because Action Mailer will automatically
# detect and use multipart templates, where each template is named after the name of the action, followed
# by the content type. Each such detected template will be added as separate part to the message.
#
# For example, if the following templates existed:
# * signup_notification.text.plain.erb
# * signup_notification.text.html.erb
# * signup_notification.text.xml.builder
# * signup_notification.text.yaml.erb
#
# Each would be rendered and added as a separate part to the message, with the corresponding content
# type. The content type for the entire message is automatically set to <tt>multipart/alternative</tt>,
# which indicates that the email contains multiple different representations of the same email
# body. The same instance variables defined in the action are passed to all email templates.
#
# Implicit template rendering is not performed if any attachments or parts have been added to the email.
# This means that you'll have to manually add each part to the email and set the content type of the email
# to <tt>multipart/alternative</tt>.
#
# = Attachments
#
# You can see above how to make a multipart HTML / Text email, to send attachments is just
# as easy:
#
# class ApplicationMailer < ActionMailer::Base
# def welcome(recipient)
# attachments['free_book.pdf'] = File.read('path/to/file.pdf')
# mail(:to => recipient, :subject => "New account information")
# end
# end
#
# Which will (if it had both a <tt>welcome.text.plain.erb</tt> and <tt>welcome.text.html.erb</tt>
# template in the view directory), send a complete <tt>multipart/mixed</tt> email with two parts,
# the first part being a <tt>multipart/alternative</tt> with the text and HTML email parts inside,
# and the second being a <tt>application/pdf</tt> with a Base64 encoded copy of the file.pdf book
# with the filename +free_book.pdf+.
#
# = Inline Attachments
#
# You can also specify that a file should be displayed inline with other HTML. For example a
# corporate logo or a photo or the like.
#
# To do this is simple, in the Mailer:
#
# class ApplicationMailer < ActionMailer::Base
# def welcome(recipient)
# attachments.inline['photo.png'] = File.read('path/to/photo.png')
# mail(:to => recipient, :subject => "Here is what we look like")
# end
# end
#
# And then to reference the image in the view, you create a <tt>welcome.html.erb</tt> file and
# make a call to +image_tag+ passing in the attachment you want to display and then call
# +url+ on the attachment to get the relative content id path for the image source:
#
# <h1>Please Don't Cringe</h1>
#
# <%= image_tag attachments['photo.png'].url -%>
#
# As we are using Action View's +image_tag+ method, you can pass in any other options you want:
#
# <h1>Please Don't Cringe</h1>
#
# <%= image_tag attachments['photo.png'].url, :alt => 'Our Photo', :class => 'photo' -%>
#
# = Observing and Intercepting Mails
#
# Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to
# register objects that are called during the mail delivery life cycle.
#
# An observer object must implement the <tt>:delivered_email(message)</tt> method which will be
# called once for every email sent after the email has been sent.
#
# An interceptor object must implement the <tt>:delivering_email(message)</tt> method which will be
# called before the email is sent, allowing you to make modifications to the email before it hits
# the delivery agents. Your object should make and needed modifications directly to the passed
# in Mail::Message instance.
#
# = Default Hash
#
# Action Mailer provides some intelligent defaults for your emails, these are usually specified in a
# default method inside the class definition:
#
# class Notifier < ActionMailer::Base
# default :sender => 'system@example.com'
# end
#
# You can pass in any header value that a <tt>Mail::Message</tt>, out of the box, <tt>ActionMailer::Base</tt>
# sets the following:
#
# * <tt>:mime_version => "1.0"</tt>
# * <tt>:charset => "UTF-8",</tt>
# * <tt>:content_type => "text/plain",</tt>
# * <tt>:parts_order => [ "text/plain", "text/enriched", "text/html" ]</tt>
#
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
# but Action Mailer translates them appropriately and sets the correct values.
#
# As you can pass in any header, you need to either quote the header as a string, or pass it in as
# an underscorised symbol, so the following will work:
#
# class Notifier < ActionMailer::Base
# default 'Content-Transfer-Encoding' => '7bit',
# :content_description => 'This is a description'
# end
#
# Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you
# can define methods that evaluate as the message is being generated:
#
# class Notifier < ActionMailer::Base
# default 'X-Special-Header' => Proc.new { my_method }
#
# private
#
# def my_method
# 'some complex call'
# end
# end
#
# Note that the proc is evaluated right at the start of the mail message generation, so if you
# set something in the defaults using a proc, and then set the same thing inside of your
# mailer method, it will get over written by the mailer method.
#
# = Configuration options
#
# These options are specified on the class level, like
# <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
# * <tt>default</tt> - You can pass this in at a class level as well as within the class itself as
# per the above section.
#
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
#
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
# * <tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default
# "localhost" setting.
# * <tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
# * <tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
# * <tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
# * <tt>:authentication</tt> - If your mail server requires authentication, you need to specify the
# authentication type here.
# This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
# * <tt>:enable_starttls_auto</tt> - When set to true, detects if STARTTLS is enabled in your SMTP server
# and starts to use it.
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method.
# * <tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
# * <tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt> with <tt>-f sender@addres</tt>
# added automatically before the message is sent.
#
# * <tt>file_settings</tt> - Allows you to override options for the <tt>:file</tt> delivery method.
# * <tt>:location</tt> - The directory into which emails will be written. Defaults to the application
# <tt>tmp/mails</tt>.
#
# * <tt>raise_delivery_errors</tt> - Whether or not errors should be raised if the email fails to be delivered.
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default),
# <tt>:sendmail</tt>, <tt>:test</tt>, and <tt>:file</tt>. Or you may provide a custom delivery method
# object eg. MyOwnDeliveryMethodClass.new. See the Mail gem documentation on the interface you need to
# implement for a custom delivery agent.
#
# * <tt>perform_deliveries</tt> - Determines whether emails are actually sent from Action Mailer when you
# call <tt>.deliver</tt> on an mail message or on an Action Mailer method. This is on by default but can
# be turned off to aid in functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with
# <tt>delivery_method :test</tt>. Most useful for unit and functional testing.
#
# * <tt>default_charset</tt> - This is now deprecated, use the +default+ method above to
# set the default +:charset+.
#
# * <tt>default_content_type</tt> - This is now deprecated, use the +default+ method above
# to set the default +:content_type+.
#
# * <tt>default_mime_version</tt> - This is now deprecated, use the +default+ method above
# to set the default +:mime_version+.
#
# * <tt>default_implicit_parts_order</tt> - This is now deprecated, use the +default+ method above
# to set the default +:parts_order+. Parts Order is used when a message is built implicitly
# (i.e. multiple parts are assembled from templates which specify the content type in their
# filenames) this variable controls how the parts are ordered.
class Base < AbstractController::Base
include DeliveryMethods
abstract!
include AbstractController::Logger
include AbstractController::Rendering
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::Translation
include AbstractController::AssetPaths
helper ActionMailer::MailHelper
include ActionMailer::OldApi
include ActionMailer::DeprecatedApi
delegate :register_observer, :to => Mail
delegate :register_interceptor, :to => Mail
private_class_method :new #:nodoc:
class_attribute :default_params
self.default_params = {
:mime_version => "1.0",
:charset => "UTF-8",
:content_type => "text/plain",
:parts_order => [ "text/plain", "text/enriched", "text/html" ]
}.freeze
class << self
def mailer_name
@mailer_name ||= name.underscore
end
attr_writer :mailer_name
alias :controller_path :mailer_name
def default(value = nil)
self.default_params = default_params.merge(value).freeze if value
default_params
end
# Receives a raw email, parses it into an email object, decodes it,
# instantiates a new mailer, and passes the email object to the mailer
# object's +receive+ method. If you want your mailer to be able to
# process incoming messages, you'll need to implement a +receive+
# method that accepts the raw email string as a parameter:
#
# class MyMailer < ActionMailer::Base
# def receive(mail)
# ...
# end
# end
def receive(raw_mail)
ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload|
mail = Mail.new(raw_mail)
set_payload_for_mail(payload, mail)
new.receive(mail)
end
end
# Wraps an email delivery inside of Active Support Notifications instrumentation. This
# method is actually called by the <tt>Mail::Message</tt> object itself through a callback
# when you call <tt>:deliver</tt> on the Mail::Message, calling +deliver_mail+ directly
# and passing a Mail::Message will do nothing except tell the logger you sent the email.
def deliver_mail(mail) #:nodoc:
ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload|
self.set_payload_for_mail(payload, mail)
yield # Let Mail do the delivery actions
end
end
def respond_to?(method, *args) #:nodoc:
super || action_methods.include?(method.to_s)
end
protected
def set_payload_for_mail(payload, mail) #:nodoc:
payload[:mailer] = self.name
payload[:message_id] = mail.message_id
payload[:subject] = mail.subject
payload[:to] = mail.to
payload[:from] = mail.from
payload[:bcc] = mail.bcc if mail.bcc.present?
payload[:cc] = mail.cc if mail.cc.present?
payload[:date] = mail.date
payload[:mail] = mail.encoded
end
def method_missing(method, *args) #:nodoc:
if action_methods.include?(method.to_s)
new(method, *args).message
else
super
end
end
end
attr_internal :message
# Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer
# will be initialized according to the named method. If not, the mailer will
# remain uninitialized (useful when you only need to invoke the "receive"
# method, for instance).
def initialize(method_name=nil, *args)
super()
@_message = Mail.new
process(method_name, *args) if method_name
end
def process(*args) #:nodoc:
lookup_context.skip_default_locale!
super
end
# Allows you to pass random and unusual headers to the new +Mail::Message+ object
# which will add them to itself.
#
# headers['X-Special-Domain-Specific-Header'] = "SecretValue"
#
# You can also pass a hash into headers of header field names and values, which
# will then be set on the Mail::Message object:
#
# headers 'X-Special-Domain-Specific-Header' => "SecretValue",
# 'In-Reply-To' => incoming.message_id
#
# The resulting Mail::Message will have the following in it's header:
#
# X-Special-Domain-Specific-Header: SecretValue
def headers(args=nil)
if args
@_message.headers(args)
else
@_message
end
end
# Allows you to add attachments to an email, like so:
#
# mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg')
#
# If you do this, then Mail will take the file name and work out the mime type
# set the Content-Type, Content-Disposition, Content-Transfer-Encoding and
# base64 encode the contents of the attachment all for you.
#
# You can also specify overrides if you want by passing a hash instead of a string:
#
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
# :content => File.read('/path/to/filename.jpg')}
#
# If you want to use a different encoding than Base64, you can pass an encoding in,
# but then it is up to you to pass in the content pre-encoded, and don't expect
# Mail to know how to decode this data:
#
# file_content = SpecialEncode(File.read('/path/to/filename.jpg'))
# mail.attachments['filename.jpg'] = {:mime_type => 'application/x-gzip',
# :encoding => 'SpecialEncoding',
# :content => file_content }
#
# You can also search for specific attachments:
#
# # By Filename
# mail.attachments['filename.jpg'] #=> Mail::Part object or nil
#
# # or by index
# mail.attachments[0] #=> Mail::Part (first attachment)
#
def attachments
@_message.attachments
end
# The main method that creates the message and renders the email templates. There are
# two ways to call this method, with a block, or without a block.
#
# Both methods accept a headers hash. This hash allows you to specify the most used headers
# in an email message, these are:
#
# * <tt>:subject</tt> - The subject of the message, if this is omitted, Action Mailer will
# ask the Rails I18n class for a translated <tt>:subject</tt> in the scope of
# <tt>[:actionmailer, mailer_scope, action_name]</tt> or if this is missing, will translate the
# humanized version of the <tt>action_name</tt>
# * <tt>:to</tt> - Who the message is destined for, can be a string of addresses, or an array
# of addresses.
# * <tt>:from</tt> - Who the message is from
# * <tt>:cc</tt> - Who you would like to Carbon-Copy on this email, can be a string of addresses,
# or an array of addresses.
# * <tt>:bcc</tt> - Who you would like to Blind-Carbon-Copy on this email, can be a string of
# addresses, or an array of addresses.
# * <tt>:reply_to</tt> - Who to set the Reply-To header of the email to.
# * <tt>:date</tt> - The date to say the email was sent on.
#
# You can set default values for any of the above headers (except :date) by using the <tt>default</tt>
# class method:
#
# class Notifier < ActionMailer::Base
# self.default :from => 'no-reply@test.lindsaar.net',
# :bcc => 'email_logger@test.lindsaar.net',
# :reply_to => 'bounces@test.lindsaar.net'
# end
#
# If you need other headers not listed above, you can either pass them in
# as part of the headers hash or use the <tt>headers['name'] = value</tt>
# method.
#
# When a <tt>:return_path</tt> is specified as header, that value will be used as the 'envelope from'
# address for the Mail message. Setting this is useful when you want delivery notifications
# sent to a different address than the one in <tt>:from</tt>. Mail will actually use the
# <tt>:return_path</tt> in preference to the <tt>:sender</tt> in preference to the <tt>:from</tt>
# field for the 'envelope from' value.
#
# If you do not pass a block to the +mail+ method, it will find all templates in the
# view paths using by default the mailer name and the method name that it is being
# called from, it will then create parts for each of these templates intelligently,
# making educated guesses on correct content type and sequence, and return a fully
# prepared Mail::Message ready to call <tt>:deliver</tt> on to send.
#
# For example:
#
# class Notifier < ActionMailer::Base
# default :from => 'no-reply@test.lindsaar.net',
#
# def welcome
# mail(:to => 'mikel@test.lindsaar.net')
# end
# end
#
# Will look for all templates at "app/views/notifier" with name "welcome". However, those
# can be customized:
#
# mail(:template_path => 'notifications', :template_name => 'another')
#
# And now it will look for all templates at "app/views/notifications" with name "another".
#
# If you do pass a block, you can render specific templates of your choice:
#
# mail(:to => 'mikel@test.lindsaar.net') do |format|
# format.text
# format.html
# end
#
# You can even render text directly without using a template:
#
# mail(:to => 'mikel@test.lindsaar.net') do |format|
# format.text { render :text => "Hello Mikel!" }
# format.html { render :text => "<h1>Hello Mikel!</h1>" }
# end
#
# Which will render a <tt>multipart/alternative</tt> email with <tt>text/plain</tt> and
# <tt>text/html</tt> parts.
#
# The block syntax also allows you to customize the part headers if desired:
#
# mail(:to => 'mikel@test.lindsaar.net') do |format|
# format.text(:content_transfer_encoding => "base64")
# format.html
# end
#
def mail(headers={}, &block)
# Guard flag to prevent both the old and the new API from firing
# Should be removed when old API is removed
@mail_was_called = true
m = @_message
# At the beginning, do not consider class default for parts order neither content_type
content_type = headers[:content_type]
parts_order = headers[:parts_order]
# Call all the procs (if any)
default_values = self.class.default.merge(self.class.default) do |k,v|
v.respond_to?(:call) ? v.bind(self).call : v
end
# Handle defaults
headers = headers.reverse_merge(default_values)
headers[:subject] ||= default_i18n_subject
# Apply charset at the beginning so all fields are properly quoted
m.charset = charset = headers[:charset]
# Set configure delivery behavior
wrap_delivery_behavior!(headers.delete(:delivery_method))
# Assign all headers except parts_order, content_type and body
assignable = headers.except(:parts_order, :content_type, :body, :template_name, :template_path)
assignable.each { |k, v| m[k] = v }
# Render the templates and blocks
responses, explicit_order = collect_responses_and_parts_order(headers, &block)
create_parts_from_responses(m, responses)
# Setup content type, reapply charset and handle parts order
m.content_type = set_content_type(m, content_type, headers[:content_type])
m.charset = charset
if m.multipart?
parts_order ||= explicit_order || headers[:parts_order]
m.body.set_sort_order(parts_order)
m.body.sort_parts!
end
m
end
protected
def set_content_type(m, user_content_type, class_default)
params = m.content_type_parameters || {}
case
when user_content_type.present?
user_content_type
when m.has_attachments?
if m.attachments.detect { |a| a.inline? }
["multipart", "related", params]
else
["multipart", "mixed", params]
end
when m.multipart?
["multipart", "alternative", params]
else
m.content_type || class_default
end
end
def default_i18n_subject #:nodoc:
mailer_scope = self.class.mailer_name.gsub('/', '.')
I18n.t(:subject, :scope => [mailer_scope, action_name], :default => action_name.humanize)
end
def collect_responses_and_parts_order(headers) #:nodoc:
responses, parts_order = [], nil
if block_given?
collector = ActionMailer::Collector.new(lookup_context) { render(action_name) }
yield(collector)
parts_order = collector.responses.map { |r| r[:content_type] }
responses = collector.responses
elsif headers[:body]
responses << {
:body => headers.delete(:body),
:content_type => self.class.default[:content_type] || "text/plain"
}
else
templates_path = headers.delete(:template_path) || self.class.mailer_name
templates_name = headers.delete(:template_name) || action_name
each_template(templates_path, templates_name) do |template|
self.formats = template.formats
responses << {
:body => render(:template => template),
:content_type => template.mime_type.to_s
}
end
end
[responses, parts_order]
end
def each_template(paths, name, &block) #:nodoc:
Array.wrap(paths).each do |path|
templates = lookup_context.find_all(name, path)
templates = templates.uniq_by { |t| t.formats }
unless templates.empty?
templates.each(&block)
return
end
end
end
def create_parts_from_responses(m, responses) #:nodoc:
if responses.size == 1 && !m.has_attachments?
responses[0].each { |k,v| m[k] = v }
elsif responses.size > 1 && m.has_attachments?
container = Mail::Part.new
container.content_type = "multipart/alternative"
responses.each { |r| insert_part(container, r, m.charset) }
m.add_part(container)
else
responses.each { |r| insert_part(m, r, m.charset) }
end
end
def insert_part(container, response, charset) #:nodoc:
response[:charset] ||= charset
part = Mail::Part.new(response)
container.add_part(part)
end
module DeprecatedUrlOptions
def default_url_options
deprecated_url_options
end
def default_url_options=(val)
deprecated_url_options
end
def deprecated_url_options
raise "You can no longer call ActionMailer::Base.default_url_options " \
"directly. You need to set config.action_mailer.default_url_options. " \
"If you are using ActionMailer standalone, you need to include the " \
"routing url_helpers directly."
end
end
# This module will complain if the user tries to set default_url_options
# directly instead of through the config object. In Action Mailer's Railtie,
# we include the router's url_helpers, which will override this module.
extend DeprecatedUrlOptions
ActiveSupport.run_load_hooks(:action_mailer, self)
end
end
|
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/kernel/singleton_class'
if RUBY_ENGINE == 'ruby' && RUBY_VERSION == '1.9.3' && RUBY_PATCHLEVEL == 0
# This is a hack to work around a bug in Ruby 1.9.3p0:
# http://redmine.ruby-lang.org/issues/5564
#
# Basically, at runtime we may need to perform some encoding conversions on the templates,
# but if the converter hasn't been loaded by Ruby beforehand (i.e. now), then it won't be
# able to find it (due to a bug).
#
# However, we don't know what conversions we may need to do a runtime. So we load up a
# marshal-dumped structure which contains a pre-generated list of all the possible conversions,
# and we load all of them.
#
# In my testing this increased the process size by about 3.9 MB (after the conversions array
# is GC'd) and took around 170ms to run, which seems acceptable for a workaround.
#
# The script to dump the conversions is: https://gist.github.com/1342729
filename = File.join(File.dirname(__FILE__), 'data', 'encoding_conversions.dump')
conversions = Marshal.load(File.read(filename))
conversions.each do |from, to_array|
to_array.each do |to|
Encoding::Converter.new(from, to)
end
end
end
module ActionView
# = Action View Template
class Template
extend ActiveSupport::Autoload
# === Encodings in ActionView::Template
#
# ActionView::Template is one of a few sources of potential
# encoding issues in Rails. This is because the source for
# templates are usually read from disk, and Ruby (like most
# encoding-aware programming languages) assumes that the
# String retrieved through File IO is encoded in the
# <tt>default_external</tt> encoding. In Rails, the default
# <tt>default_external</tt> encoding is UTF-8.
#
# As a result, if a user saves their template as ISO-8859-1
# (for instance, using a non-Unicode-aware text editor),
# and uses characters outside of the ASCII range, their
# users will see diamonds with question marks in them in
# the browser.
#
# For the rest of this documentation, when we say "UTF-8",
# we mean "UTF-8 or whatever the default_internal encoding
# is set to". By default, it will be UTF-8.
#
# To mitigate this problem, we use a few strategies:
# 1. If the source is not valid UTF-8, we raise an exception
# when the template is compiled to alert the user
# to the problem.
# 2. The user can specify the encoding using Ruby-style
# encoding comments in any template engine. If such
# a comment is supplied, Rails will apply that encoding
# to the resulting compiled source returned by the
# template handler.
# 3. In all cases, we transcode the resulting String to
# the UTF-8.
#
# This means that other parts of Rails can always assume
# that templates are encoded in UTF-8, even if the original
# source of the template was not UTF-8.
#
# From a user's perspective, the easiest thing to do is
# to save your templates as UTF-8. If you do this, you
# do not need to do anything else for things to "just work".
#
# === Instructions for template handlers
#
# The easiest thing for you to do is to simply ignore
# encodings. Rails will hand you the template source
# as the default_internal (generally UTF-8), raising
# an exception for the user before sending the template
# to you if it could not determine the original encoding.
#
# For the greatest simplicity, you can support only
# UTF-8 as the <tt>default_internal</tt>. This means
# that from the perspective of your handler, the
# entire pipeline is just UTF-8.
#
# === Advanced: Handlers with alternate metadata sources
#
# If you want to provide an alternate mechanism for
# specifying encodings (like ERB does via <%# encoding: ... %>),
# you may indicate that you will handle encodings yourself
# by implementing <tt>self.handles_encoding?</tt>
# on your handler.
#
# If you do, Rails will not try to encode the String
# into the default_internal, passing you the unaltered
# bytes tagged with the assumed encoding (from
# default_external).
#
# In this case, make sure you return a String from
# your handler encoded in the default_internal. Since
# you are handling out-of-band metadata, you are
# also responsible for alerting the user to any
# problems with converting the user's data to
# the <tt>default_internal</tt>.
#
# To do so, simply raise the raise +WrongEncodingError+
# as follows:
#
# raise WrongEncodingError.new(
# problematic_string,
# expected_encoding
# )
eager_autoload do
autoload :Error
autoload :Handlers
autoload :Text
end
extend Template::Handlers
attr_accessor :locals, :formats, :virtual_path
attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
# This finalizer is needed (and exactly with a proc inside another proc)
# otherwise templates leak in development.
Finalizer = proc do |method_name, mod|
proc do
mod.module_eval do
remove_possible_method method_name
end
end
end
def initialize(source, identifier, handler, details)
format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
@source = source
@identifier = identifier
@handler = handler
@compiled = false
@original_encoding = nil
@locals = details[:locals] || []
@virtual_path = details[:virtual_path]
@updated_at = details[:updated_at] || Time.now
@formats = Array.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f }
end
# Returns if the underlying handler supports streaming. If so,
# a streaming buffer *may* be passed when it start rendering.
def supports_streaming?
handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
end
# Render a template. If the template was not compiled yet, it is done
# exactly before rendering.
#
# This method is instrumented as "!render_template.action_view". Notice that
# we use a bang in this instrumentation because you don't want to
# consume this in production. This is only slow if it's being listened to.
def render(view, locals, buffer=nil, &block)
ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do
compile!(view)
view.send(method_name, locals, buffer, &block)
end
rescue Exception => e
handle_render_error(view, e)
end
def mime_type
@mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
end
# Receives a view object and return a template similar to self by using @virtual_path.
#
# This method is useful if you have a template object but it does not contain its source
# anymore since it was already compiled. In such cases, all you need to do is to call
# refresh passing in the view object.
#
# Notice this method raises an error if the template to be refreshed does not have a
# virtual path set (true just for inline templates).
def refresh(view)
raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
lookup = view.lookup_context
pieces = @virtual_path.split("/")
name = pieces.pop
partial = !!name.sub!(/^_/, "")
lookup.disable_cache do
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
end
end
def inspect
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
end
protected
# Compile a template. This method ensures a template is compiled
# just once and removes the source after it is compiled.
def compile!(view) #:nodoc:
return if @compiled
if view.is_a?(ActionView::CompiledTemplates)
mod = ActionView::CompiledTemplates
else
mod = view.singleton_class
end
compile(view, mod)
# Just discard the source if we have a virtual path. This
# means we can get the template back.
@source = nil if @virtual_path
@compiled = true
end
# Among other things, this method is responsible for properly setting
# the encoding of the source. Until this point, we assume that the
# source is BINARY data. If no additional information is supplied,
# we assume the encoding is the same as <tt>Encoding.default_external</tt>.
#
# The user can also specify the encoding via a comment on the first
# line of the template (# encoding: NAME-OF-ENCODING). This will work
# with any template engine, as we process out the encoding comment
# before passing the source on to the template engine, leaving a
# blank line in its stead.
#
# If the template engine handles encodings, we send the encoded
# String to the engine without further processing. This allows
# the template engine to support additional mechanisms for
# specifying the encoding. For instance, ERB supports <%# encoding: %>
#
# Otherwise, after we figure out the correct encoding, we then
# encode the source into <tt>Encoding.default_internal</tt>.
# In general, this means that templates will be UTF-8 inside of Rails,
# regardless of the original source encoding.
def compile(view, mod) #:nodoc:
method_name = self.method_name
if source.encoding_aware?
# Look for # encoding: *. If we find one, we'll encode the
# String in that encoding, otherwise, we'll use the
# default external encoding.
if source.sub!(/\A#{ENCODING_FLAG}/, '')
encoding = magic_encoding = $1
else
encoding = Encoding.default_external
end
# Tag the source with the default external encoding
# or the encoding specified in the file
source.force_encoding(encoding)
# If the user didn't specify an encoding, and the handler
# handles encodings, we simply pass the String as is to
# the handler (with the default_external tag)
if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
source
# Otherwise, if the String is valid in the encoding,
# encode immediately to default_internal. This means
# that if a handler doesn't handle encodings, it will
# always get Strings in the default_internal
elsif source.valid_encoding?
source.encode!
# Otherwise, since the String is invalid in the encoding
# specified, raise an exception
else
raise WrongEncodingError.new(source, encoding)
end
end
code = @handler.call(self)
# Make sure that the resulting String to be evalled is in the
# encoding of the code
source = <<-end_src
def #{method_name}(local_assigns, output_buffer)
_old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
ensure
@virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
end
end_src
if source.encoding_aware?
# Make sure the source is in the encoding of the returned code
source.force_encoding(code.encoding)
# In case we get back a String from a handler that is not in
# BINARY or the default_internal, encode it to the default_internal
source.encode!
# Now, validate that the source we got back from the template
# handler is valid in the default_internal. This is for handlers
# that handle encoding but screw up
unless source.valid_encoding?
raise WrongEncodingError.new(@source, Encoding.default_internal)
end
end
begin
mod.module_eval(source, identifier, 0)
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
rescue Exception => e # errors from template code
if logger = (view && view.logger)
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
logger.debug "Function body: #{source}"
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
end
raise ActionView::Template::Error.new(self, {}, e)
end
end
def handle_render_error(view, e) #:nodoc:
if e.is_a?(Template::Error)
e.sub_template_of(self)
raise e
else
assigns = view.respond_to?(:assigns) ? view.assigns : {}
template = @virtual_path ? refresh(view) : self
raise Template::Error.new(template, assigns, e)
end
end
def locals_code #:nodoc:
@locals.map { |key| "#{key} = local_assigns[:#{key}];" }.join
end
def method_name #:nodoc:
@method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
end
def identifier_method_name #:nodoc:
inspect.gsub(/[^a-z_]/, '_')
end
end
end
RUBY_ENGINE is not defined on 1.8
require 'active_support/core_ext/array/wrap'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/kernel/singleton_class'
if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'ruby' && RUBY_VERSION == '1.9.3' && RUBY_PATCHLEVEL == 0
# This is a hack to work around a bug in Ruby 1.9.3p0:
# http://redmine.ruby-lang.org/issues/5564
#
# Basically, at runtime we may need to perform some encoding conversions on the templates,
# but if the converter hasn't been loaded by Ruby beforehand (i.e. now), then it won't be
# able to find it (due to a bug).
#
# However, we don't know what conversions we may need to do a runtime. So we load up a
# marshal-dumped structure which contains a pre-generated list of all the possible conversions,
# and we load all of them.
#
# In my testing this increased the process size by about 3.9 MB (after the conversions array
# is GC'd) and took around 170ms to run, which seems acceptable for a workaround.
#
# The script to dump the conversions is: https://gist.github.com/1342729
filename = File.join(File.dirname(__FILE__), 'data', 'encoding_conversions.dump')
conversions = Marshal.load(File.read(filename))
conversions.each do |from, to_array|
to_array.each do |to|
Encoding::Converter.new(from, to)
end
end
end
module ActionView
# = Action View Template
class Template
extend ActiveSupport::Autoload
# === Encodings in ActionView::Template
#
# ActionView::Template is one of a few sources of potential
# encoding issues in Rails. This is because the source for
# templates are usually read from disk, and Ruby (like most
# encoding-aware programming languages) assumes that the
# String retrieved through File IO is encoded in the
# <tt>default_external</tt> encoding. In Rails, the default
# <tt>default_external</tt> encoding is UTF-8.
#
# As a result, if a user saves their template as ISO-8859-1
# (for instance, using a non-Unicode-aware text editor),
# and uses characters outside of the ASCII range, their
# users will see diamonds with question marks in them in
# the browser.
#
# For the rest of this documentation, when we say "UTF-8",
# we mean "UTF-8 or whatever the default_internal encoding
# is set to". By default, it will be UTF-8.
#
# To mitigate this problem, we use a few strategies:
# 1. If the source is not valid UTF-8, we raise an exception
# when the template is compiled to alert the user
# to the problem.
# 2. The user can specify the encoding using Ruby-style
# encoding comments in any template engine. If such
# a comment is supplied, Rails will apply that encoding
# to the resulting compiled source returned by the
# template handler.
# 3. In all cases, we transcode the resulting String to
# the UTF-8.
#
# This means that other parts of Rails can always assume
# that templates are encoded in UTF-8, even if the original
# source of the template was not UTF-8.
#
# From a user's perspective, the easiest thing to do is
# to save your templates as UTF-8. If you do this, you
# do not need to do anything else for things to "just work".
#
# === Instructions for template handlers
#
# The easiest thing for you to do is to simply ignore
# encodings. Rails will hand you the template source
# as the default_internal (generally UTF-8), raising
# an exception for the user before sending the template
# to you if it could not determine the original encoding.
#
# For the greatest simplicity, you can support only
# UTF-8 as the <tt>default_internal</tt>. This means
# that from the perspective of your handler, the
# entire pipeline is just UTF-8.
#
# === Advanced: Handlers with alternate metadata sources
#
# If you want to provide an alternate mechanism for
# specifying encodings (like ERB does via <%# encoding: ... %>),
# you may indicate that you will handle encodings yourself
# by implementing <tt>self.handles_encoding?</tt>
# on your handler.
#
# If you do, Rails will not try to encode the String
# into the default_internal, passing you the unaltered
# bytes tagged with the assumed encoding (from
# default_external).
#
# In this case, make sure you return a String from
# your handler encoded in the default_internal. Since
# you are handling out-of-band metadata, you are
# also responsible for alerting the user to any
# problems with converting the user's data to
# the <tt>default_internal</tt>.
#
# To do so, simply raise the raise +WrongEncodingError+
# as follows:
#
# raise WrongEncodingError.new(
# problematic_string,
# expected_encoding
# )
eager_autoload do
autoload :Error
autoload :Handlers
autoload :Text
end
extend Template::Handlers
attr_accessor :locals, :formats, :virtual_path
attr_reader :source, :identifier, :handler, :original_encoding, :updated_at
# This finalizer is needed (and exactly with a proc inside another proc)
# otherwise templates leak in development.
Finalizer = proc do |method_name, mod|
proc do
mod.module_eval do
remove_possible_method method_name
end
end
end
def initialize(source, identifier, handler, details)
format = details[:format] || (handler.default_format if handler.respond_to?(:default_format))
@source = source
@identifier = identifier
@handler = handler
@compiled = false
@original_encoding = nil
@locals = details[:locals] || []
@virtual_path = details[:virtual_path]
@updated_at = details[:updated_at] || Time.now
@formats = Array.wrap(format).map { |f| f.is_a?(Mime::Type) ? f.ref : f }
end
# Returns if the underlying handler supports streaming. If so,
# a streaming buffer *may* be passed when it start rendering.
def supports_streaming?
handler.respond_to?(:supports_streaming?) && handler.supports_streaming?
end
# Render a template. If the template was not compiled yet, it is done
# exactly before rendering.
#
# This method is instrumented as "!render_template.action_view". Notice that
# we use a bang in this instrumentation because you don't want to
# consume this in production. This is only slow if it's being listened to.
def render(view, locals, buffer=nil, &block)
ActiveSupport::Notifications.instrument("!render_template.action_view", :virtual_path => @virtual_path) do
compile!(view)
view.send(method_name, locals, buffer, &block)
end
rescue Exception => e
handle_render_error(view, e)
end
def mime_type
@mime_type ||= Mime::Type.lookup_by_extension(@formats.first.to_s) if @formats.first
end
# Receives a view object and return a template similar to self by using @virtual_path.
#
# This method is useful if you have a template object but it does not contain its source
# anymore since it was already compiled. In such cases, all you need to do is to call
# refresh passing in the view object.
#
# Notice this method raises an error if the template to be refreshed does not have a
# virtual path set (true just for inline templates).
def refresh(view)
raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path
lookup = view.lookup_context
pieces = @virtual_path.split("/")
name = pieces.pop
partial = !!name.sub!(/^_/, "")
lookup.disable_cache do
lookup.find_template(name, [ pieces.join('/') ], partial, @locals)
end
end
def inspect
@inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", '') : identifier
end
protected
# Compile a template. This method ensures a template is compiled
# just once and removes the source after it is compiled.
def compile!(view) #:nodoc:
return if @compiled
if view.is_a?(ActionView::CompiledTemplates)
mod = ActionView::CompiledTemplates
else
mod = view.singleton_class
end
compile(view, mod)
# Just discard the source if we have a virtual path. This
# means we can get the template back.
@source = nil if @virtual_path
@compiled = true
end
# Among other things, this method is responsible for properly setting
# the encoding of the source. Until this point, we assume that the
# source is BINARY data. If no additional information is supplied,
# we assume the encoding is the same as <tt>Encoding.default_external</tt>.
#
# The user can also specify the encoding via a comment on the first
# line of the template (# encoding: NAME-OF-ENCODING). This will work
# with any template engine, as we process out the encoding comment
# before passing the source on to the template engine, leaving a
# blank line in its stead.
#
# If the template engine handles encodings, we send the encoded
# String to the engine without further processing. This allows
# the template engine to support additional mechanisms for
# specifying the encoding. For instance, ERB supports <%# encoding: %>
#
# Otherwise, after we figure out the correct encoding, we then
# encode the source into <tt>Encoding.default_internal</tt>.
# In general, this means that templates will be UTF-8 inside of Rails,
# regardless of the original source encoding.
def compile(view, mod) #:nodoc:
method_name = self.method_name
if source.encoding_aware?
# Look for # encoding: *. If we find one, we'll encode the
# String in that encoding, otherwise, we'll use the
# default external encoding.
if source.sub!(/\A#{ENCODING_FLAG}/, '')
encoding = magic_encoding = $1
else
encoding = Encoding.default_external
end
# Tag the source with the default external encoding
# or the encoding specified in the file
source.force_encoding(encoding)
# If the user didn't specify an encoding, and the handler
# handles encodings, we simply pass the String as is to
# the handler (with the default_external tag)
if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding?
source
# Otherwise, if the String is valid in the encoding,
# encode immediately to default_internal. This means
# that if a handler doesn't handle encodings, it will
# always get Strings in the default_internal
elsif source.valid_encoding?
source.encode!
# Otherwise, since the String is invalid in the encoding
# specified, raise an exception
else
raise WrongEncodingError.new(source, encoding)
end
end
code = @handler.call(self)
# Make sure that the resulting String to be evalled is in the
# encoding of the code
source = <<-end_src
def #{method_name}(local_assigns, output_buffer)
_old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code}
ensure
@virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer
end
end_src
if source.encoding_aware?
# Make sure the source is in the encoding of the returned code
source.force_encoding(code.encoding)
# In case we get back a String from a handler that is not in
# BINARY or the default_internal, encode it to the default_internal
source.encode!
# Now, validate that the source we got back from the template
# handler is valid in the default_internal. This is for handlers
# that handle encoding but screw up
unless source.valid_encoding?
raise WrongEncodingError.new(@source, Encoding.default_internal)
end
end
begin
mod.module_eval(source, identifier, 0)
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
rescue Exception => e # errors from template code
if logger = (view && view.logger)
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
logger.debug "Function body: #{source}"
logger.debug "Backtrace: #{e.backtrace.join("\n")}"
end
raise ActionView::Template::Error.new(self, {}, e)
end
end
def handle_render_error(view, e) #:nodoc:
if e.is_a?(Template::Error)
e.sub_template_of(self)
raise e
else
assigns = view.respond_to?(:assigns) ? view.assigns : {}
template = @virtual_path ? refresh(view) : self
raise Template::Error.new(template, assigns, e)
end
end
def locals_code #:nodoc:
@locals.map { |key| "#{key} = local_assigns[:#{key}];" }.join
end
def method_name #:nodoc:
@method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".gsub('-', "_")
end
def identifier_method_name #:nodoc:
inspect.gsub(/[^a-z_]/, '_')
end
end
end
|
require 'abstract_unit'
module ActionDispatch
module Journey
class TestRoutes < ActiveSupport::TestCase
def test_clear
routes = Routes.new
exp = Router::Strexp.build '/foo(/:id)', {}, ['/.?']
path = Path::Pattern.new exp
requirements = { :hello => /world/ }
routes.add_route nil, path, requirements, {:id => nil}, {}
assert_equal 1, routes.length
routes.clear
assert_equal 0, routes.length
end
def test_ast
routes = Routes.new
path = Path::Pattern.from_string '/hello'
routes.add_route nil, path, {}, {}, {}
ast = routes.ast
routes.add_route nil, path, {}, {}, {}
assert_not_equal ast, routes.ast
end
def test_simulator_changes
routes = Routes.new
path = Path::Pattern.from_string '/hello'
routes.add_route nil, path, {}, {}, {}
sim = routes.simulator
routes.add_route nil, path, {}, {}, {}
assert_not_equal sim, routes.simulator
end
def test_first_name_wins
#def add_route app, path, conditions, defaults, name = nil
routes = Routes.new
one = Path::Pattern.from_string '/hello'
two = Path::Pattern.from_string '/aaron'
routes.add_route nil, one, {}, {}, 'aaron'
routes.add_route nil, two, {}, {}, 'aaron'
assert_equal '/hello', routes.named_routes['aaron'].path.spec.to_s
end
end
end
end
Remove unneeded comment. [ci skip]
require 'abstract_unit'
module ActionDispatch
module Journey
class TestRoutes < ActiveSupport::TestCase
def test_clear
routes = Routes.new
exp = Router::Strexp.build '/foo(/:id)', {}, ['/.?']
path = Path::Pattern.new exp
requirements = { :hello => /world/ }
routes.add_route nil, path, requirements, {:id => nil}, {}
assert_equal 1, routes.length
routes.clear
assert_equal 0, routes.length
end
def test_ast
routes = Routes.new
path = Path::Pattern.from_string '/hello'
routes.add_route nil, path, {}, {}, {}
ast = routes.ast
routes.add_route nil, path, {}, {}, {}
assert_not_equal ast, routes.ast
end
def test_simulator_changes
routes = Routes.new
path = Path::Pattern.from_string '/hello'
routes.add_route nil, path, {}, {}, {}
sim = routes.simulator
routes.add_route nil, path, {}, {}, {}
assert_not_equal sim, routes.simulator
end
def test_first_name_wins
routes = Routes.new
one = Path::Pattern.from_string '/hello'
two = Path::Pattern.from_string '/aaron'
routes.add_route nil, one, {}, {}, 'aaron'
routes.add_route nil, two, {}, {}, 'aaron'
assert_equal '/hello', routes.named_routes['aaron'].path.spec.to_s
end
end
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{always_verify_ssl_certificates}
s.version = "0.2.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["James Golick"]
s.date = %q{2010-12-09}
s.description = %q{Ruby’s net/http is setup to never verify SSL certificates by default. Most ruby libraries do the same. That means that you’re not verifying the identity of the server you’re communicating with and are therefore exposed to man in the middle attacks. This gem monkey-patches net/http to force certificate verification and make turning it off impossible.}
s.email = %q{jamesgolick@gmail.com}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"always_verify_ssl_certificates.gemspec",
"lib/always_verify_ssl_certificates.rb",
"test/helper.rb",
"test/test_always_verify_ssl_certificates.rb"
]
s.homepage = %q{http://github.com/jamesgolick/always_verify_ssl_certificates}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{Force net/http to always verify SSL certificates.}
s.test_files = [
"test/helper.rb",
"test/test_always_verify_ssl_certificates.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
Regenerated gemspec for version 0.3.0
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{always_verify_ssl_certificates}
s.version = "0.3.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["James Golick"]
s.date = %q{2011-03-17}
s.description = %q{Ruby’s net/http is setup to never verify SSL certificates by default. Most ruby libraries do the same. That means that you’re not verifying the identity of the server you’re communicating with and are therefore exposed to man in the middle attacks. This gem monkey-patches net/http to force certificate verification and make turning it off impossible.}
s.email = %q{jamesgolick@gmail.com}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
".document",
".gitignore",
"LICENSE",
"README.rdoc",
"Rakefile",
"VERSION",
"always_verify_ssl_certificates.gemspec",
"lib/always_verify_ssl_certificates.rb",
"test/helper.rb",
"test/test_always_verify_ssl_certificates.rb"
]
s.homepage = %q{http://github.com/jamesgolick/always_verify_ssl_certificates}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.5.2}
s.summary = %q{Force net/http to always verify SSL certificates.}
s.test_files = [
"test/helper.rb",
"test/test_always_verify_ssl_certificates.rb"
]
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
class Entity < SessionResource
self.site = APP_CONFIG['api_base']
end
Entity base needs to be interpreted.
class Entity < SessionResource
self.site = "#{APP_CONFIG['api_base']}"
end
|
Gem::Specification.new do |s|
s.name = 'logstash-input-http_poller'
s.version = '1.1.2'
s.licenses = ['Apache License (2.0)']
s.summary = "Poll HTTP endpoints with Logstash."
s.description = "This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/plugin install gemname. This gem is not a stand-alone program."
s.authors = ["andrewvc"]
s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
s.require_paths = ["lib"]
# Files
s.files = `git ls-files`.split($\)
# Tests
s.test_files = s.files.grep(%r{^(test|spec|features)/})
# Special flag to let us know this is actually a logstash plugin
s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" }
# Gem dependencies
s.add_runtime_dependency "logstash-core", '>= 1.5.0', '< 2.0.0'
s.add_runtime_dependency 'logstash-codec-plain'
s.add_runtime_dependency 'logstash-codec-json'
s.add_runtime_dependency 'logstash-mixin-http_client', ">= 1.0.1"
s.add_runtime_dependency 'stud'
s.add_runtime_dependency 'manticore'
s.add_development_dependency 'logstash-devutils'
s.add_development_dependency 'flores'
end
remove git ls-files from gemspec
Gem::Specification.new do |s|
s.name = 'logstash-input-http_poller'
s.version = '1.1.2'
s.licenses = ['Apache License (2.0)']
s.summary = "Poll HTTP endpoints with Logstash."
s.description = "This gem is a logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/plugin install gemname. This gem is not a stand-alone program."
s.authors = ["andrewvc"]
s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
s.require_paths = ["lib"]
# Files
s.files = Dir['lib/**/*','spec/**/*','vendor/**/*','*.gemspec','*.md','CONTRIBUTORS','Gemfile','LICENSE','NOTICE.TXT']
# Tests
s.test_files = s.files.grep(%r{^(test|spec|features)/})
# Special flag to let us know this is actually a logstash plugin
s.metadata = { "logstash_plugin" => "true", "logstash_group" => "input" }
# Gem dependencies
s.add_runtime_dependency "logstash-core", '>= 1.5.0', '< 2.0.0'
s.add_runtime_dependency 'logstash-codec-plain'
s.add_runtime_dependency 'logstash-codec-json'
s.add_runtime_dependency 'logstash-mixin-http_client', ">= 1.0.1"
s.add_runtime_dependency 'stud'
s.add_runtime_dependency 'manticore'
s.add_development_dependency 'logstash-devutils'
s.add_development_dependency 'flores'
end
|
module CouchDB
# The Server class provides methods to retrieve information and statistics
# of a CouchDB server.
class Server
attr_accessor :host
attr_accessor :port
attr_accessor :username
attr_accessor :password
attr_accessor :password_salt
def initialize(host = "localhost", port = 5984, username = nil, password = nil)
@host, @port, @username, @password = host, port, username, password
end
def ==(other)
other.is_a?(self.class) && @host == other.host && @port == other.port
end
def information
Transport::JSON.request :get, url + "/", options
end
def statistics
Transport::JSON.request :get, url + "/_stats", options
end
def database_names
Transport::JSON.request :get, url + "/_all_dbs", options
end
def uuids(count = 1)
response = Transport::JSON.request :get, url + "/_uuids", options.merge(:parameters => { :count => count })
response["uuids"]
end
def user_database
@user_database ||= UserDatabase.new self
end
def url
"http://#{@host}:#{@port}"
end
def authentication_options
@username && @password ? { :auth_type => :basic, :username => @username, :password => @password } : { }
end
private
def options
authentication_options.merge :expected_status_code => 200
end
end
end
changed server constructor
module CouchDB
# The Server class provides methods to retrieve information and statistics
# of a CouchDB server.
class Server
attr_writer :host
attr_writer :port
attr_accessor :username
attr_accessor :password
attr_accessor :password_salt
def initialize(host = nil, port = nil, username = nil, password = nil)
@host, @port, @username, @password = host, port, username, password
end
def host
@host || "localhost"
end
def port
@port || 5984
end
def ==(other)
other.is_a?(self.class) && self.host == other.host && self.port == other.port
end
def information
Transport::JSON.request :get, url + "/", options
end
def statistics
Transport::JSON.request :get, url + "/_stats", options
end
def database_names
Transport::JSON.request :get, url + "/_all_dbs", options
end
def uuids(count = 1)
response = Transport::JSON.request :get, url + "/_uuids", options.merge(:parameters => { :count => count })
response["uuids"]
end
def user_database
@user_database ||= UserDatabase.new self
end
def url
"http://#{self.host}:#{self.port}"
end
def authentication_options
self.username && self.password ? { :auth_type => :basic, :username => self.username, :password => self.password } : { }
end
private
def options
authentication_options.merge :expected_status_code => 200
end
end
end
|
Write test which fails when `:mailing_address` in email tracking template.
When tracking email is received, `:mailing_address` will be interpreted as
**recipient's** address, asking her to send a specimen to herself.
require "test_helper"
# Tests which supplement controller/name_controller_test.rb
class NameControllerSupplementalTest < IntegrationTestCase
# Email tracking template should not contain ":mailing_address"
# because, when email is sent, that will be interpreted as
# recipient's mailing_address
def test_email_tracking_template_no_email_address_symbol
visit("/account/login")
fill_in("User name or Email address:", with: "rolf")
fill_in("Password:", with: "testpassword")
click_button("Login")
visit("/name/email_tracking/#{names(:boletus_edulis).id}")
template = find("#notification_note_template")
template.assert_no_text(":mailing_address")
end
end
|
module Cronofy
# Public: Primary class for interacting with the Cronofy API.
class Client
include TimeEncoding
# Public: The scope to request if none is explicitly specified by the
# caller.
DEFAULT_OAUTH_SCOPE = %w{
read_account
read_events
create_event
delete_event
}.freeze
# Public: Initialize a new Cronofy::Client.
#
# options - A Hash of options used to initialize the client (default: {}):
# :access_token - An existing access token String for the user's
# account (optional).
# :client_id - The client ID String of your Cronofy OAuth
# application (default:
# ENV["CRONOFY_CLIENT_ID"]).
# :client_secret - The client secret String of your Cronofy OAuth
# application (default:
# ENV["CRONOFY_CLIENT_SECRET"]).
# :refresh_token - An existing refresh token String for the user's
# account (optional).
# :data_centre - An identifier to override the default data
# centre (optional).
def initialize(options = {})
access_token = options[:access_token]
refresh_token = options[:refresh_token]
@client_id = options.fetch(:client_id, ENV["CRONOFY_CLIENT_ID"])
@client_secret = options.fetch(:client_secret, ENV["CRONOFY_CLIENT_SECRET"])
@data_centre = options[:data_centre]
@auth = Auth.new(
client_id: @client_id,
client_secret: @client_secret,
access_token: access_token,
refresh_token: refresh_token,
data_centre: @data_centre,
)
end
# Public: Creates a new calendar for the profile.
#
# profile_id - The String ID of the profile to create the calendar within.
# name - The String to use as the name of the calendar.
# options - The Hash options used to customize the calendar
# (default: {}):
# :color - The color to make the calendar (optional).
#
# See https://www.cronofy.com/developers/api/#create-calendar for reference.
#
# Returns the created Calendar
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::AccountLockedError if the profile is not in a writable
# state and so a calendar cannot be created.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def create_calendar(profile_id, name, options = {})
request = options.merge(profile_id: profile_id, name: name)
response = post("/v1/calendars", request)
parse_json(Calendar, "calendar", response)
end
# Public: Lists all the calendars for the account.
#
# See http://www.cronofy.com/developers/api#calendars for reference.
#
# Returns an Array of Calendars
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def list_calendars
response = get("/v1/calendars")
parse_collection(Calendar, "calendars", response)
end
# Public: Creates or updates an event for the event_id in the calendar
# relating to the given calendar_id.
#
# calendar_id - The String Cronofy ID for the calendar to upsert the event
# to.
# event - A Hash describing the event with symbolized keys:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :start - The Time or Date the event starts.
# :end - The Time or Date the event ends.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :color - The color of the event (optional).
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
#
# Examples
#
# client.upsert_event(
# "cal_n23kjnwrw2_jsdfjksn234",
# event_id: "qTtZdczOccgaPncGJaCiLg",
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# start: Time.utc(2014, 8, 5, 15, 30),
# end: Time.utc(2014, 8, 5, 17, 30),
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# })
#
# See http://www.cronofy.com/developers/api#upsert-event for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def upsert_event(calendar_id, event)
body = event.dup
body[:start] = encode_event_time(body[:start])
body[:end] = encode_event_time(body[:end])
post("/v1/calendars/#{calendar_id}/events", body)
nil
end
# Public: Alias for #upsert_event
alias_method :create_or_update_event, :upsert_event
# Public: Returns a lazily-evaluated Enumerable of Events that satisfy the
# given query criteria.
#
# options - The Hash options used to refine the selection (default: {}):
# :from - The minimum Date from which to return events
# (optional).
# :to - The Date to return events up until (optional).
# :tzid - A String representing a known time zone
# identifier from the IANA Time Zone Database
# (default: Etc/UTC).
# :include_deleted - A Boolean specifying whether events that have
# been deleted should be included or excluded
# from the results (optional).
# :include_moved - A Boolean specifying whether events that have
# ever existed within the given window should
# be included or excluded from the results
# (optional).
# :include_managed - A Boolean specifying whether events that you
# are managing for the account should be
# included or excluded from the results
# (optional).
# :only_managed - A Boolean specifying whether only events that
# you are managing for the account should
# trigger notifications (optional).
# :localized_times - A Boolean specifying whether the start and
# end times should be returned with any
# available localization information
# (optional).
# :last_modified - The Time that events must be modified on or
# after in order to be returned (optional).
# :calendar_ids - An Array of calendar ids for restricting the
# returned events (optional).
# :include_geo - A Boolean specifying whether the events should
# have their location.lat and location.long
# returned where available (optional).
#
# The first page will be retrieved eagerly so that common errors will happen
# inline. However, subsequent pages (if any) will be requested lazily.
#
# See http://www.cronofy.com/developers/api#read-events for reference.
#
# Returns a lazily-evaluated Enumerable of Events
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def read_events(options = {})
params = READ_EVENTS_DEFAULT_PARAMS.merge(options)
READ_EVENTS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
params[tp] = to_iso8601(params[tp])
end
url = api_url + "/v1/events"
PagedResultIterator.new(PagedEventsResult, :events, access_token!, url, params)
end
# Public: Returns a lazily-evaluated Enumerable of FreeBusy that satisfy the
# given query criteria.
#
# options - The Hash options used to refine the selection (default: {}):
# :from - The minimum Date from which to return events
# (optional).
# :to - The Date to return events up until (optional).
# :tzid - A String representing a known time zone
# identifier from the IANA Time Zone Database
# (default: Etc/UTC).
# :include_managed - A Boolean specifying whether events that you
# are managing for the account should be
# included or excluded from the results
# (optional).
# :localized_times - A Boolean specifying whether the start and
# end times should be returned with any
# available localization information
# (optional).
# :calendar_ids - An Array of calendar ids for restricting the
# returned events (optional).
#
# The first page will be retrieved eagerly so that common errors will happen
# inline. However, subsequent pages (if any) will be requested lazily.
#
# See http://www.cronofy.com/developers/api/#free-busy for reference.
#
# Returns a lazily-evaluated Enumerable of FreeBusy
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def free_busy(options = {})
params = FREE_BUSY_DEFAULT_PARAMS.merge(options)
FREE_BUSY_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
params[tp] = to_iso8601(params[tp])
end
url = api_url + "/v1/free_busy"
PagedResultIterator.new(PagedFreeBusyResult, :free_busy, access_token!, url, params)
end
# Public: Deletes an event from the specified calendar
#
# calendar_id - The String Cronofy ID for the calendar to delete the event
# from.
# event_id - A String uniquely identifying the event for your application
# (note: this is NOT an ID generated by Cronofy).
#
# See http://www.cronofy.com/developers/api#delete-event for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def delete_event(calendar_id, event_id)
delete("/v1/calendars/#{calendar_id}/events", event_id: event_id)
nil
end
class BatchBuilder
include TimeEncoding
def initialize
@entries = []
end
def upsert_event(calendar_id, event)
data = event.dup
data[:start] = encode_event_time(data[:start])
data[:end] = encode_event_time(data[:end])
post "/v1/calendars/#{calendar_id}/events", data
end
alias_method :create_or_update_event, :upsert_event
def delete_event(calendar_id, event_id)
delete "/v1/calendars/#{calendar_id}/events", event_id: event_id
end
def delete_external_event(calendar_id, event_uid)
delete "/v1/calendars/#{calendar_id}/events", event_uid: event_uid
end
def add_entry(args)
@entries << BatchEntryRequest.new(args)
nil
end
def build
@entries.dup
end
private
def delete(relative_url, data)
add_entry(method: "DELETE", relative_url: relative_url, data: data)
end
def post(relative_url, data)
add_entry(method: "POST", relative_url: relative_url, data: data)
end
end
def batch
yield builder = BatchBuilder.new
requests = builder.build
response = post("/v1/batch", batch: requests)
responses = parse_collection(BatchEntryResponse, "batch", response)
entries = requests.zip(responses).map do |request, response|
response.request = request
response
end
result = BatchResponse.new(entries)
if result.errors?
msg = "Batch contains #{result.errors.count} errors"
raise BatchResponse::PartialSuccessError.new(msg, result)
end
result
end
# Public: Deletes an external event from the specified calendar
#
# calendar_id - The String Cronofy ID for the calendar to delete the event
# from.
# event_uid - The unique ID of the event to delete.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope or the client has not been granted elevated
# permissions to the calendar.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def delete_external_event(calendar_id, event_uid)
delete("/v1/calendars/#{calendar_id}/events", event_uid: event_uid)
nil
end
# Public: Deletes all events you are managing for the account.
#
# See https://www.cronofy.com/developers/api/#bulk-delete-events for
# reference.
#
# options - The Hash options used to refine the selection (optional):
# :calendar_ids - An Array of calendar ids to delete managed
# events from returned events.
#
# If no options are specified it defaults to deleting all the events you are
# managing.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def delete_all_events(options = nil)
options ||= { delete_all: true }
delete("/v1/events", options)
nil
end
# Public: Creates a notification channel with a callback URL
#
# callback_url - A String specifing the callback URL for the channel.
# options - The Hash options used to refine the notifications of the
# channel (default: {}):
# :filters - A Hash of filters to use for the notification
# channel (optional):
# :calendar_ids - An Array of calendar ID strings
# to restrict the returned events
# to (optional).
# :only_managed - A Boolean specifying whether
# only events that you are
# managing for the account should
# trigger notifications
# (optional).
#
# See http://www.cronofy.com/developers/api#create-channel for reference.
#
# Returns a Channel.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def create_channel(callback_url, options = {})
params = options.merge(callback_url: callback_url)
response = post("/v1/channels", params)
parse_json(Channel, "channel", response)
end
# Public: Verifies a HMAC from a push notification using the client secret.
#
# args - A Hash containing the details of the push notification:
# :body - A String of the body of the notification.
# :hmac - A String of the HMAC of the notification taken from the
# Cronofy-HMAC-SHA256 header.
#
# Returns true if the HMAC provided matches the one calculated using the
# client secret, otherwise false.
def hmac_match?(args)
body = args[:body]
hmac = args[:hmac]
sha256 = OpenSSL::Digest.new('sha256')
digest = OpenSSL::HMAC.digest(sha256, @client_secret, body)
calculated = Base64.encode64(digest).strip
calculated == hmac
end
# Public: Lists all the notification channels for the account.
#
# See http://www.cronofy.com/developers/api#list-channels for reference.
#
# Returns an Array of Channels.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def list_channels
response = get("/v1/channels")
parse_collection(Channel, "channels", response)
end
# Public: Closes a notification channel.
#
# channel_id - The String Cronofy ID for the channel to close.
#
# See http://www.cronofy.com/developers/api#close-channel for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the channel does not exist.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def close_channel(channel_id)
delete("/v1/channels/#{channel_id}")
nil
end
# Public: Retrieves the details of the account.
#
# See http://www.cronofy.com/developers/api#account for reference.
#
# Returns an Account.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def account
response = get("/v1/account")
parse_json(Account, "account", response)
end
# Public: Lists all the profiles for the account.
#
# See https://www.cronofy.com/developers/api/#profiles for reference.
#
# Returns an Array of Profiles
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def list_profiles
response = get("/v1/profiles")
parse_collection(Profile, "profiles", response)
end
# Public: Retrieves the userinfo for the account
#
# See http://openid.net/specs/openid-connect-core-1_0.html#UserInfo for
# reference.
#
# Returns an UserInfo.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def userinfo
response = get("/v1/userinfo")
parse_json(UserInfo, nil, response)
end
# Public: Changes the participation status for a calendar event
#
# calendar_id - The String Cronofy ID for the calendar to delete the event
# from.
# event_uid - A String uniquely identifying the event for your application
# (note: this is NOT an ID generated by Cronofy).
# status - A String or Symbol to set the participation status of the
# invite to
#
#
# See http://www.cronofy.com/developers/api#delete-event for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def change_participation_status(calendar_id, event_uid, status)
body = {
status: status.to_s,
}
url = "/v1/calendars/#{calendar_id}/events/#{event_uid}/participation_status"
post(url, body)
end
# Public: Attempts to authorize the email with impersonation from a service
# account
#
# email - the email address to impersonate
# scope - Array or String of scopes describing the access to
# request from the user to the users calendars (required).
# callback_url - the url to callback to
#
# Returns nothing
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def authorize_with_service_account(email, scope, callback_url)
if scope.respond_to?(:join)
scope = scope.join(' ')
end
params = {
email: email,
scope: scope,
callback_url: callback_url
}
post("/v1/service_account_authorizations", params)
nil
end
# Public: Generates a URL to send the user to in order to perform the OAuth
# 2.0 authorization process.
#
# redirect_uri - A String specifing the URI to return the user to once they
# have completed the authorization steps.
# options - The Hash options used to refine the selection
# (default: {}):
# :scope - Array or String of scopes describing the access to
# request from the user to the users calendars
# (default: DEFAULT_OAUTH_SCOPE).
# :state - Array of states to retain during the OAuth
# authorization process (optional).
#
# See http://www.cronofy.com/developers/api#authorization for reference.
#
# Returns the URL as a String.
def user_auth_link(redirect_url, options = {})
options = { scope: DEFAULT_OAUTH_SCOPE }.merge(options)
@auth.user_auth_link(redirect_url, options)
end
# Public: Retrieves the OAuth credentials authorized for the given code and
# redirect URL pair.
#
# code - String code returned to redirect_url after authorization.
# redirect_url - A String specifing the URL the user returned to once they
# had completed the authorization steps.
#
# See http://www.cronofy.com/developers/api#token-issue for reference.
#
# Returns a set of Cronofy::Credentials for the account.
#
# Raises Cronofy::BadRequestError if the code is unknown, has been revoked,
# or the code and redirect URL do not match.
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
def get_token_from_code(code, redirect_url)
@auth.get_token_from_code(code, redirect_url)
end
# Public: Refreshes the credentials for the account's access token.
#
# Usually called in response to a Cronofy::AuthenticationFailureError as
# these usually occur when the access token has expired and needs
# refreshing.
#
# See http://www.cronofy.com/developers/api#token-refresh for reference.
#
# Returns a set of Cronofy::Credentials for the account.
#
# Raises Cronofy::BadRequestError if refresh token code is unknown or has
# been revoked.
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
# Raises Cronofy::CredentialsMissingError if no credentials available.
def refresh_access_token
@auth.refresh!
end
# Public: Obtains access to an application calendar
#
# See http://www.cronofy.com/developers/alpha/api#application-calendar for reference.
#
# Returns a set of Cronofy::Credentials for the account.
#
# Raises Cronofy::BadRequestError if refresh token code is unknown or has
# been revoked.
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
# Raises Cronofy::CredentialsMissingError if no credentials available.
def application_calendar(application_calendar_id)
@auth.application_calendar(application_calendar_id)
end
# Public: Revokes the account's refresh token and access token.
#
# After making this call the Client will become unusable. You should also
# delete the stored credentials used to create this instance.
#
# See http://www.cronofy.com/developers/api#revoke-authorization for
# reference.
#
# Returns nothing.
#
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
# Raises Cronofy::CredentialsMissingError if no credentials available.
def revoke_authorization
@auth.revoke!
end
# Public: Requests elevated permissions for a set of calendars.
#
# args - A Hash of options used to initialize the request (default: {}):
# :permissions - An Array of calendar permission hashes to set on
# the each hash must contain symbols for both
# `calendar_id` and `permission_level`
# :redirect_uri - A uri to redirect the end user back to after they
# have either granted or rejected the request for
# elevated permission.
#
# In the case of normal accounts:
# After making this call the end user will have to grant the extended
# permissions to their calendar via rhe url returned from the response.
#
# In the case of service accounts:
# After making this call the exteneded permissions will be granted provided
# the relevant scope has been granted to the account
#
# Returns a extended permissions response.
#
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
def elevated_permissions(args = {})
filtered_permissions = args[:permissions].map do |permission|
{ calendar_id: permission[:calendar_id], permission_level: permission[:permission_level] }
end
body = { permissions: filtered_permissions }
body[:redirect_uri] = args[:redirect_uri] if args[:redirect_uri]
response = post("/v1/permissions", body)
parse_json(PermissionsResponse, "permissions_request", response)
end
# Public: Lists all the resources for the service account.
#
# Returns an Array of Resources.
#
# Raises Cronofy::CredentialsMissingError if no credentials available
# or if non-service account credentials are provided.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def resources
response = get("/v1/resources")
parse_collection(Resource, "resources", response)
end
# Public: Performs an availability query.
#
# options - The Hash options used to refine the selection (default: {}):
# :participants - An Array of participant groups or a Hash
# for a single participant group.
# :required_duration - An Integer representing the minimum number
# of minutes of availability required.
# :available_periods - An Array of available time periods Hashes,
# each must specify a start and end Time.
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
#
# Returns an Array of AvailablePeriods.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def availability(options = {})
options[:participants] = map_availability_participants(options[:participants])
options[:required_duration] = map_availability_required_duration(options[:required_duration])
if options[:start_interval]
options[:start_interval] = map_availability_required_duration(options[:start_interval])
end
if buffer = options[:buffer]
options[:buffer] = map_availability_buffer(buffer)
end
translate_available_periods(options[:available_periods])
response = post("/v1/availability", options)
parse_collections(
response,
available_periods: AvailablePeriod,
available_slots: AvailableSlot,
)
end
# Public: Performs an sequenced availability query.
#
# options - The Hash options used to refine the selection (default: {}):
# :sequence - An Array of sequence defintions containing
# a Hash of:
# :sequence_id - A String to uniquely identify this part
# of the proposed sequence.
# :ordinal - An integer to define the ordering of the
# proposed sequence. (Optional)
# :participants - An Array of participant groups or a Hash
# for a single participant group.
# :required_duration - An Integer representing the minimum
# number of minutes of availability required.
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
# :available_periods - An Array of available time periods Hashes,
# each must specify a start and end Time.
#
# Returns an Array of Sequences.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def sequenced_availability(options = {})
options[:sequence] = map_availability_sequence(options[:sequence])
translate_available_periods(options[:available_periods])
response = post("/v1/sequenced_availability", options)
parse_collection(Sequence, "sequences", response)
end
# Public: Generates an add to calendar link to start the OAuth process with
# an event to be automatically upserted
#
# oauth - A Hash describing the OAuth flow required:
# :scope - A String representing the scopes to ask for
# within the OAuth flow
# :redirect_uri - A String containing a url to redirect the
# user to after completing the OAuth flow.
# :scope - A String representing additional state to
# be passed within the OAuth flow.
#
# event - A Hash describing the event with symbolized keys:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :start - The Time or Date the event starts.
# :end - The Time or Date the event ends.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
#
# Example
#
# client.add_to_calendar(
# oauth: {
# scopes: 'read_events delete_events',
# redirect_uri: 'http://www.example.com',
# state: 'example_state'
# },
# event: {
# event_id: "qTtZdczOccgaPncGJaCiLg",
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# start: Time.utc(2014, 8, 5, 15, 30),
# end: Time.utc(2014, 8, 5, 17, 30),
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# })
#
# See http://www.cronofy.com/developers/api#upsert-event for reference.
#
# Returns a AddToCalendarResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def add_to_calendar(args = {})
body = args.merge(client_id: @client_id, client_secret: @client_secret)
body[:event][:start] = encode_event_time(body[:event][:start])
body[:event][:end] = encode_event_time(body[:event][:end])
response = post("/v1/add_to_calendar", body)
parse_json(AddToCalendarResponse, nil , response)
end
# Public: Generates an real time scheduling link to start the OAuth process with
# an event to be automatically upserted
#
# oauth - A Hash describing the OAuth flow required:
# :scope - A String representing the scopes to ask for
# within the OAuth flow
# :redirect_uri - A String containing a url to redirect the
# user to after completing the OAuth flow.
# :scope - A String representing additional state to
# be passed within the OAuth flow.
#
# event - A Hash describing the event with symbolized keys:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
# availability - A Hash describing the availability details for the event:
# :participants - A hash stating who is required for the availability
# call
# :required_duration - A hash stating the length of time the event will
# last for
# :available_periods - A hash stating the available periods for the event
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
# target_calendars - An array of hashes stating into which calendars to insert the created
# event
#
# Examples
#
# - Availability example
# client.add_to_calendar(
# oauth: {
# redirect_uri: 'http://www.example.com'
# },
# event: {
# event_id: "qTtZdczOccgaPncGJaCiLg",
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# }
# },
# availability: {
# participants: [
# {
# members: [{
# sub: "acc_567236000909002",
# calendar_ids: ["cal_n23kjnwrw2_jsdfjksn234"]
# }],
# required: 'all'
# }
# ],
# required_duration: { minutes: 60 },
# available_periods: [{
# start: Time.utc(2017, 1, 1, 9, 00),
# end: Time.utc(2017, 1, 1, 17, 00),
# }]
# },
# target_calendars: [{
# sub: "acc_567236000909002",
# calendar_id: "cal_n23kjnwrw2_jsdfjksn234"
# }]
# )
#
# See http://www.cronofy.com/developers/api#real-time-scheduling for reference.
#
# Returns a AddToCalendarResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def real_time_scheduling(args = {})
body = args.merge(client_id: @client_id, client_secret: @client_secret)
if availability = args[:availability]
availability[:participants] = map_availability_participants(availability[:participants])
availability[:required_duration] = map_availability_required_duration(availability[:required_duration])
if value = availability[:start_interval]
availability[:start_interval] = map_availability_required_duration(value)
end
if buffer = availability[:buffer]
availability[:buffer] = map_availability_buffer(buffer)
end
end
translate_available_periods(availability[:available_periods])
body[:availability] = availability
response = raw_post("/v1/real_time_scheduling", body)
parse_json(AddToCalendarResponse, nil , response)
end
# Public: Generates an real time sequencing link to start the OAuth process with
# an event to be automatically upserted
#
# oauth - A Hash describing the OAuth flow required:
# :scope - A String representing the scopes to ask for
# within the OAuth flow
# :redirect_uri - A String containing a url to redirect the
# user to after completing the OAuth flow.
# :scope - A String representing additional state to
# be passed within the OAuth flow.
#
# availability - A Hash describing the availability details for the event:
# :sequence - An Array of sequence defintions containing
# a Hash of:
# :sequence_id - A String to uniquely identify this part
# of the proposed sequence.
# :ordinal - An integer to define the ordering of the
# proposed sequence. (Optional)
# :participants - An Array of participant groups or a Hash
# for a single participant group.
# :required_duration - An Integer representing the minimum
# number of minutes of availability required.
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
# :event - A Hash describing the event:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
# :available_periods - A hash stating the available periods for the event
# target_calendars - An array of hashes stating into which calendars to insert the created
# event
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def real_time_sequencing(args)
body = args.merge(client_id: @client_id, client_secret: @client_secret)
if availability = args[:availability]
availability[:sequence] = map_availability_sequence(availability[:sequence])
translate_available_periods(availability[:available_periods]) if availability[:available_periods]
end
body[:availability] = availability
response = raw_post("/v1/real_time_sequencing", body)
parse_json(AddToCalendarResponse, nil , response)
end
# Public: Creates a link_token to allow explicitly linking of an account
#
# See https://www.cronofy.com/developers/api/alpha/#auth-explicit-linking for
# reference.
#
# Returns a link token
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def link_token
response = post("/v1/link_tokens", nil)
parse_json(String, 'link_token', response)
end
# Public: Revokes the authorization to the given profile.
#
# See https://www.cronofy.com/developers/api/alpha/#revoke-profile for
# reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
def revoke_profile_authorization(profile_id)
post("/v1/profiles/#{profile_id}/revoke", nil)
nil
end
# Public: Creates or updates smart invite.
#
# smart_invite_id - A String uniquely identifying the event for your
# application (note: this is NOT an ID generated
# by Cronofy).
# callback_url - The URL within your application you want Cronofy to
# send notifications to about user interactions with
# the Smart Invite.
# recipient - A Hash containing the intended recipient of the invite
# :email - A String for the email address you are
# going to send the Smart Invite to.
# event - A Hash describing the event with symbolized keys:
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :start - The Time or Date the event starts.
# :end - The Time or Date the event ends.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :color - The color of the event (optional).
#
# organizer - A Hash containing the details of the organizer.
# :name - A String value for the display name of the
# event organizer
# Examples
#
# client.upsert_smart_invite(
# smart_invite_id: "qTtZdczOccgaPncGJaCiLg",
# callback_url: "http://www.example.com",
# recipient: {
# email: "example@example.com"
# },
# event: {
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# start: Time.utc(2014, 8, 5, 15, 30),
# end: Time.utc(2014, 8, 5, 17, 30),
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# },
# organizer: {
# name: "Smart invite application"
# }
# )
#
# See http://www.cronofy.com/developers/alpha/api#smart-invite for reference.
#
# Returns a SmartInviteResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def upsert_smart_invite(body={})
body[:event][:start] = encode_event_time(body[:event][:start])
body[:event][:end] = encode_event_time(body[:event][:end])
response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
parse_json(SmartInviteResponse, nil, response)
end
# Public: Cancels a smart invite
#
# smart_invite_id - A String uniquely identifying the event for your
# application (note: this is NOT an ID generated
# by Cronofy).
# recipient - A Hash containing the intended recipient of the invite
# :email - A String for thee email address you are
# going to send the Smart Invite to.
#
# See http://www.cronofy.com/developers/alpha/api#smart-invite for reference.
#
# Returns a SmartInviteResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def cancel_smart_invite(body={})
body[:method] = 'cancel'
response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
parse_json(SmartInviteResponse, nil, response)
end
# Public: Gets the details for a smart invite.
#
# smart_invite_id - A String uniquely identifying the event for your
# application (note: this is NOT an ID generated
# by Cronofy).
# recipient_email - The email address for the recipient to get details for.
#
# See http://www.cronofy.com/developers/alpha/api#smart-invite for reference.
#
# Returns a SmartInviteResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def get_smart_invite(smart_invite_id, recipient_email)
response = wrapped_request { api_key!.get("/v1/smart_invites?recipient_email=#{recipient_email}&smart_invite_id=#{smart_invite_id}") }
parse_json(SmartInviteResponse, nil, response)
end
# Public: Creates an element_token to pass to a UI Element
#
# options - A Hash of options for the token
# :permissions - An Array of strings describing the
# permissions required for the token
# :subs - An Array of sub values for the account(s)
# the element will be accessing
# :origin - The scheme://hostname where the token will
# be used.
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
#
# See https://docs.cronofy.com/developers/ui-elements/authentication for
# reference.
#
# Returns an element token
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def element_token(options)
response = wrapped_request { api_key!.post("/v1/element_tokens", json_request_args(options)) }
parse_json(ElementToken, "element_token", response)
end
# Public: Creates a scheduling conversation
#
def create_scheduling_conversation(body)
response = wrapped_request { post("/v1/scheduling_conversations", body) }
parse_json(SchedulingConversation, nil, response)
end
# Public: List available slots for a scheduling conversation
#
def list_scheduling_conversation_participant_slots(url)
response = wrapped_request { get(url) }
parse_collection(SchedulingConversationSlot, "available_slots", response )
end
# Public: Choose one or more slots for a scheduling conversation
def select_scheduling_conversation_participant_slots(url, args)
response = wrapped_request { post(url, args)}
parse_json(SchedulingConversation, nil, response)
end
private
def translate_available_periods(periods)
periods.each do |params|
AVAILABLE_PERIODS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
params[tp] = to_iso8601(params[tp])
end
end
end
def map_availability_participants(participants)
case participants
when Hash
# Allow one group to be specified without being nested
[map_availability_participants_group(participants)]
when Enumerable
participants.map do |group|
map_availability_participants_group(group)
end
else
participants
end
end
def map_availability_participants_group(participants)
case participants
when Hash
participants[:members].map! do |member|
map_availability_member(member)
end
unless participants.key?(:required)
participants[:required] = :all
end
participants
when Array
participants.map do |group|
map_availability_participants(group)
end
else
participants
end
end
def map_availability_member(member)
case member
when String
{ sub: member }
when Hash
if member[:available_periods]
translate_available_periods(member[:available_periods])
end
member
else
member
end
end
def map_availability_required_duration(required_duration)
case required_duration
when Integer
{ minutes: required_duration }
else
required_duration
end
end
def map_availability_buffer(buffer)
result = {}
unless buffer.is_a?(Hash)
return result
end
if before_buffer = buffer[:before]
result[:before] = map_buffer_details(before_buffer)
end
if after_buffer = buffer[:after]
result[:after] = map_buffer_details(after_buffer)
end
result
end
def map_buffer_details(buffer)
result = map_availability_required_duration(buffer)
if minimum_buffer = buffer[:minimum]
result[:minimum] = map_availability_required_duration(minimum_buffer)
end
if maximum_buffer = buffer[:maximum]
result[:maximum] = map_availability_required_duration(maximum_buffer)
end
result
end
def map_availability_sequence(sequence)
case sequence
when Enumerable
sequence.map do |sequence_item|
hash = {}
if value = sequence_item[:participants]
hash[:participants] = map_availability_participants(value)
end
if value = sequence_item[:required_duration]
hash[:required_duration] = map_availability_required_duration(value)
end
if sequence_item[:available_periods]
translate_available_periods(sequence_item[:available_periods])
end
if value = sequence_item[:start_interval]
hash[:start_interval] = map_availability_required_duration(value)
end
if buffer = sequence_item[:buffer]
hash[:buffer] = map_availability_buffer(buffer)
end
sequence_item.merge(hash)
end
else
sequence
end
end
AVAILABLE_PERIODS_TIME_PARAMS = %i{
start
end
}.freeze
FREE_BUSY_DEFAULT_PARAMS = { tzid: "Etc/UTC" }.freeze
FREE_BUSY_TIME_PARAMS = %i{
from
to
}.freeze
READ_EVENTS_DEFAULT_PARAMS = { tzid: "Etc/UTC" }.freeze
READ_EVENTS_TIME_PARAMS = %i{
from
to
last_modified
}.freeze
def access_token!
raise CredentialsMissingError.new unless @auth.access_token
@auth.access_token
end
def api_key!
raise CredentialsMissingError.new unless @auth.api_key
@auth.api_key
end
def get(url, opts = {})
wrapped_request { access_token!.get(url, opts) }
end
def post(url, body)
wrapped_request { access_token!.post(url, json_request_args(body)) }
end
def delete(url, body = nil)
wrapped_request { access_token!.delete(url, json_request_args(body)) }
end
def raw_post(url, body)
wrapped_request { @auth.api_client.request(:post, url, json_request_args(body)) }
end
def wrapped_request
yield
rescue OAuth2::Error => e
raise Errors.map_error(e)
end
def parse_collection(type, attr, response)
ResponseParser.new(response).parse_collection(type, attr)
end
def parse_collections(response, mappings)
ResponseParser.new(response).parse_collections(mappings)
end
def parse_json(type, attr = nil, response)
ResponseParser.new(response).parse_json(type, attr)
end
def json_request_args(body_hash)
if body_hash
{
body: JSON.generate(body_hash),
headers: { "Content-Type" => "application/json; charset=utf-8" },
}
else
{}
end
end
class PagedResultIterator
include Enumerable
def initialize(page_parser, items_key, access_token, url, params)
@page_parser = page_parser
@items_key = items_key
@access_token = access_token
@url = url
@params = params
@first_page = get_page(url, params)
end
def each
page = @first_page
page[@items_key].each do |item|
yield item
end
while page.pages.next_page?
page = get_page(page.pages.next_page)
page[@items_key].each do |item|
yield item
end
end
end
private
attr_reader :access_token
attr_reader :params
attr_reader :url
def get_page(url, params = {})
response = http_get(url, params)
parse_page(response)
end
def http_get(url, params = {})
response = Faraday.get(url, params, oauth_headers)
Errors.raise_if_error(response)
response
end
def oauth_headers
{
"Authorization" => "Bearer #{access_token.token}",
"User-Agent" => "Cronofy Ruby #{::Cronofy::VERSION}",
}
end
def parse_page(response)
ResponseParser.new(response).parse_json(@page_parser)
end
end
def api_url
::Cronofy.api_url(@data_centre)
end
end
# Deprecated: Alias for Client for backwards compatibility.
class Cronofy < Client
end
end
document scheduling conversation methods as pre-release
module Cronofy
# Public: Primary class for interacting with the Cronofy API.
class Client
include TimeEncoding
# Public: The scope to request if none is explicitly specified by the
# caller.
DEFAULT_OAUTH_SCOPE = %w{
read_account
read_events
create_event
delete_event
}.freeze
# Public: Initialize a new Cronofy::Client.
#
# options - A Hash of options used to initialize the client (default: {}):
# :access_token - An existing access token String for the user's
# account (optional).
# :client_id - The client ID String of your Cronofy OAuth
# application (default:
# ENV["CRONOFY_CLIENT_ID"]).
# :client_secret - The client secret String of your Cronofy OAuth
# application (default:
# ENV["CRONOFY_CLIENT_SECRET"]).
# :refresh_token - An existing refresh token String for the user's
# account (optional).
# :data_centre - An identifier to override the default data
# centre (optional).
def initialize(options = {})
access_token = options[:access_token]
refresh_token = options[:refresh_token]
@client_id = options.fetch(:client_id, ENV["CRONOFY_CLIENT_ID"])
@client_secret = options.fetch(:client_secret, ENV["CRONOFY_CLIENT_SECRET"])
@data_centre = options[:data_centre]
@auth = Auth.new(
client_id: @client_id,
client_secret: @client_secret,
access_token: access_token,
refresh_token: refresh_token,
data_centre: @data_centre,
)
end
# Public: Creates a new calendar for the profile.
#
# profile_id - The String ID of the profile to create the calendar within.
# name - The String to use as the name of the calendar.
# options - The Hash options used to customize the calendar
# (default: {}):
# :color - The color to make the calendar (optional).
#
# See https://www.cronofy.com/developers/api/#create-calendar for reference.
#
# Returns the created Calendar
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::AccountLockedError if the profile is not in a writable
# state and so a calendar cannot be created.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def create_calendar(profile_id, name, options = {})
request = options.merge(profile_id: profile_id, name: name)
response = post("/v1/calendars", request)
parse_json(Calendar, "calendar", response)
end
# Public: Lists all the calendars for the account.
#
# See http://www.cronofy.com/developers/api#calendars for reference.
#
# Returns an Array of Calendars
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def list_calendars
response = get("/v1/calendars")
parse_collection(Calendar, "calendars", response)
end
# Public: Creates or updates an event for the event_id in the calendar
# relating to the given calendar_id.
#
# calendar_id - The String Cronofy ID for the calendar to upsert the event
# to.
# event - A Hash describing the event with symbolized keys:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :start - The Time or Date the event starts.
# :end - The Time or Date the event ends.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :color - The color of the event (optional).
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
#
# Examples
#
# client.upsert_event(
# "cal_n23kjnwrw2_jsdfjksn234",
# event_id: "qTtZdczOccgaPncGJaCiLg",
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# start: Time.utc(2014, 8, 5, 15, 30),
# end: Time.utc(2014, 8, 5, 17, 30),
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# })
#
# See http://www.cronofy.com/developers/api#upsert-event for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def upsert_event(calendar_id, event)
body = event.dup
body[:start] = encode_event_time(body[:start])
body[:end] = encode_event_time(body[:end])
post("/v1/calendars/#{calendar_id}/events", body)
nil
end
# Public: Alias for #upsert_event
alias_method :create_or_update_event, :upsert_event
# Public: Returns a lazily-evaluated Enumerable of Events that satisfy the
# given query criteria.
#
# options - The Hash options used to refine the selection (default: {}):
# :from - The minimum Date from which to return events
# (optional).
# :to - The Date to return events up until (optional).
# :tzid - A String representing a known time zone
# identifier from the IANA Time Zone Database
# (default: Etc/UTC).
# :include_deleted - A Boolean specifying whether events that have
# been deleted should be included or excluded
# from the results (optional).
# :include_moved - A Boolean specifying whether events that have
# ever existed within the given window should
# be included or excluded from the results
# (optional).
# :include_managed - A Boolean specifying whether events that you
# are managing for the account should be
# included or excluded from the results
# (optional).
# :only_managed - A Boolean specifying whether only events that
# you are managing for the account should
# trigger notifications (optional).
# :localized_times - A Boolean specifying whether the start and
# end times should be returned with any
# available localization information
# (optional).
# :last_modified - The Time that events must be modified on or
# after in order to be returned (optional).
# :calendar_ids - An Array of calendar ids for restricting the
# returned events (optional).
# :include_geo - A Boolean specifying whether the events should
# have their location.lat and location.long
# returned where available (optional).
#
# The first page will be retrieved eagerly so that common errors will happen
# inline. However, subsequent pages (if any) will be requested lazily.
#
# See http://www.cronofy.com/developers/api#read-events for reference.
#
# Returns a lazily-evaluated Enumerable of Events
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def read_events(options = {})
params = READ_EVENTS_DEFAULT_PARAMS.merge(options)
READ_EVENTS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
params[tp] = to_iso8601(params[tp])
end
url = api_url + "/v1/events"
PagedResultIterator.new(PagedEventsResult, :events, access_token!, url, params)
end
# Public: Returns a lazily-evaluated Enumerable of FreeBusy that satisfy the
# given query criteria.
#
# options - The Hash options used to refine the selection (default: {}):
# :from - The minimum Date from which to return events
# (optional).
# :to - The Date to return events up until (optional).
# :tzid - A String representing a known time zone
# identifier from the IANA Time Zone Database
# (default: Etc/UTC).
# :include_managed - A Boolean specifying whether events that you
# are managing for the account should be
# included or excluded from the results
# (optional).
# :localized_times - A Boolean specifying whether the start and
# end times should be returned with any
# available localization information
# (optional).
# :calendar_ids - An Array of calendar ids for restricting the
# returned events (optional).
#
# The first page will be retrieved eagerly so that common errors will happen
# inline. However, subsequent pages (if any) will be requested lazily.
#
# See http://www.cronofy.com/developers/api/#free-busy for reference.
#
# Returns a lazily-evaluated Enumerable of FreeBusy
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def free_busy(options = {})
params = FREE_BUSY_DEFAULT_PARAMS.merge(options)
FREE_BUSY_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
params[tp] = to_iso8601(params[tp])
end
url = api_url + "/v1/free_busy"
PagedResultIterator.new(PagedFreeBusyResult, :free_busy, access_token!, url, params)
end
# Public: Deletes an event from the specified calendar
#
# calendar_id - The String Cronofy ID for the calendar to delete the event
# from.
# event_id - A String uniquely identifying the event for your application
# (note: this is NOT an ID generated by Cronofy).
#
# See http://www.cronofy.com/developers/api#delete-event for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def delete_event(calendar_id, event_id)
delete("/v1/calendars/#{calendar_id}/events", event_id: event_id)
nil
end
class BatchBuilder
include TimeEncoding
def initialize
@entries = []
end
def upsert_event(calendar_id, event)
data = event.dup
data[:start] = encode_event_time(data[:start])
data[:end] = encode_event_time(data[:end])
post "/v1/calendars/#{calendar_id}/events", data
end
alias_method :create_or_update_event, :upsert_event
def delete_event(calendar_id, event_id)
delete "/v1/calendars/#{calendar_id}/events", event_id: event_id
end
def delete_external_event(calendar_id, event_uid)
delete "/v1/calendars/#{calendar_id}/events", event_uid: event_uid
end
def add_entry(args)
@entries << BatchEntryRequest.new(args)
nil
end
def build
@entries.dup
end
private
def delete(relative_url, data)
add_entry(method: "DELETE", relative_url: relative_url, data: data)
end
def post(relative_url, data)
add_entry(method: "POST", relative_url: relative_url, data: data)
end
end
def batch
yield builder = BatchBuilder.new
requests = builder.build
response = post("/v1/batch", batch: requests)
responses = parse_collection(BatchEntryResponse, "batch", response)
entries = requests.zip(responses).map do |request, response|
response.request = request
response
end
result = BatchResponse.new(entries)
if result.errors?
msg = "Batch contains #{result.errors.count} errors"
raise BatchResponse::PartialSuccessError.new(msg, result)
end
result
end
# Public: Deletes an external event from the specified calendar
#
# calendar_id - The String Cronofy ID for the calendar to delete the event
# from.
# event_uid - The unique ID of the event to delete.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope or the client has not been granted elevated
# permissions to the calendar.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def delete_external_event(calendar_id, event_uid)
delete("/v1/calendars/#{calendar_id}/events", event_uid: event_uid)
nil
end
# Public: Deletes all events you are managing for the account.
#
# See https://www.cronofy.com/developers/api/#bulk-delete-events for
# reference.
#
# options - The Hash options used to refine the selection (optional):
# :calendar_ids - An Array of calendar ids to delete managed
# events from returned events.
#
# If no options are specified it defaults to deleting all the events you are
# managing.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def delete_all_events(options = nil)
options ||= { delete_all: true }
delete("/v1/events", options)
nil
end
# Public: Creates a notification channel with a callback URL
#
# callback_url - A String specifing the callback URL for the channel.
# options - The Hash options used to refine the notifications of the
# channel (default: {}):
# :filters - A Hash of filters to use for the notification
# channel (optional):
# :calendar_ids - An Array of calendar ID strings
# to restrict the returned events
# to (optional).
# :only_managed - A Boolean specifying whether
# only events that you are
# managing for the account should
# trigger notifications
# (optional).
#
# See http://www.cronofy.com/developers/api#create-channel for reference.
#
# Returns a Channel.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def create_channel(callback_url, options = {})
params = options.merge(callback_url: callback_url)
response = post("/v1/channels", params)
parse_json(Channel, "channel", response)
end
# Public: Verifies a HMAC from a push notification using the client secret.
#
# args - A Hash containing the details of the push notification:
# :body - A String of the body of the notification.
# :hmac - A String of the HMAC of the notification taken from the
# Cronofy-HMAC-SHA256 header.
#
# Returns true if the HMAC provided matches the one calculated using the
# client secret, otherwise false.
def hmac_match?(args)
body = args[:body]
hmac = args[:hmac]
sha256 = OpenSSL::Digest.new('sha256')
digest = OpenSSL::HMAC.digest(sha256, @client_secret, body)
calculated = Base64.encode64(digest).strip
calculated == hmac
end
# Public: Lists all the notification channels for the account.
#
# See http://www.cronofy.com/developers/api#list-channels for reference.
#
# Returns an Array of Channels.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def list_channels
response = get("/v1/channels")
parse_collection(Channel, "channels", response)
end
# Public: Closes a notification channel.
#
# channel_id - The String Cronofy ID for the channel to close.
#
# See http://www.cronofy.com/developers/api#close-channel for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the channel does not exist.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def close_channel(channel_id)
delete("/v1/channels/#{channel_id}")
nil
end
# Public: Retrieves the details of the account.
#
# See http://www.cronofy.com/developers/api#account for reference.
#
# Returns an Account.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def account
response = get("/v1/account")
parse_json(Account, "account", response)
end
# Public: Lists all the profiles for the account.
#
# See https://www.cronofy.com/developers/api/#profiles for reference.
#
# Returns an Array of Profiles
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def list_profiles
response = get("/v1/profiles")
parse_collection(Profile, "profiles", response)
end
# Public: Retrieves the userinfo for the account
#
# See http://openid.net/specs/openid-connect-core-1_0.html#UserInfo for
# reference.
#
# Returns an UserInfo.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def userinfo
response = get("/v1/userinfo")
parse_json(UserInfo, nil, response)
end
# Public: Changes the participation status for a calendar event
#
# calendar_id - The String Cronofy ID for the calendar to delete the event
# from.
# event_uid - A String uniquely identifying the event for your application
# (note: this is NOT an ID generated by Cronofy).
# status - A String or Symbol to set the participation status of the
# invite to
#
#
# See http://www.cronofy.com/developers/api#delete-event for reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def change_participation_status(calendar_id, event_uid, status)
body = {
status: status.to_s,
}
url = "/v1/calendars/#{calendar_id}/events/#{event_uid}/participation_status"
post(url, body)
end
# Public: Attempts to authorize the email with impersonation from a service
# account
#
# email - the email address to impersonate
# scope - Array or String of scopes describing the access to
# request from the user to the users calendars (required).
# callback_url - the url to callback to
#
# Returns nothing
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def authorize_with_service_account(email, scope, callback_url)
if scope.respond_to?(:join)
scope = scope.join(' ')
end
params = {
email: email,
scope: scope,
callback_url: callback_url
}
post("/v1/service_account_authorizations", params)
nil
end
# Public: Generates a URL to send the user to in order to perform the OAuth
# 2.0 authorization process.
#
# redirect_uri - A String specifing the URI to return the user to once they
# have completed the authorization steps.
# options - The Hash options used to refine the selection
# (default: {}):
# :scope - Array or String of scopes describing the access to
# request from the user to the users calendars
# (default: DEFAULT_OAUTH_SCOPE).
# :state - Array of states to retain during the OAuth
# authorization process (optional).
#
# See http://www.cronofy.com/developers/api#authorization for reference.
#
# Returns the URL as a String.
def user_auth_link(redirect_url, options = {})
options = { scope: DEFAULT_OAUTH_SCOPE }.merge(options)
@auth.user_auth_link(redirect_url, options)
end
# Public: Retrieves the OAuth credentials authorized for the given code and
# redirect URL pair.
#
# code - String code returned to redirect_url after authorization.
# redirect_url - A String specifing the URL the user returned to once they
# had completed the authorization steps.
#
# See http://www.cronofy.com/developers/api#token-issue for reference.
#
# Returns a set of Cronofy::Credentials for the account.
#
# Raises Cronofy::BadRequestError if the code is unknown, has been revoked,
# or the code and redirect URL do not match.
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
def get_token_from_code(code, redirect_url)
@auth.get_token_from_code(code, redirect_url)
end
# Public: Refreshes the credentials for the account's access token.
#
# Usually called in response to a Cronofy::AuthenticationFailureError as
# these usually occur when the access token has expired and needs
# refreshing.
#
# See http://www.cronofy.com/developers/api#token-refresh for reference.
#
# Returns a set of Cronofy::Credentials for the account.
#
# Raises Cronofy::BadRequestError if refresh token code is unknown or has
# been revoked.
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
# Raises Cronofy::CredentialsMissingError if no credentials available.
def refresh_access_token
@auth.refresh!
end
# Public: Obtains access to an application calendar
#
# See http://www.cronofy.com/developers/alpha/api#application-calendar for reference.
#
# Returns a set of Cronofy::Credentials for the account.
#
# Raises Cronofy::BadRequestError if refresh token code is unknown or has
# been revoked.
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
# Raises Cronofy::CredentialsMissingError if no credentials available.
def application_calendar(application_calendar_id)
@auth.application_calendar(application_calendar_id)
end
# Public: Revokes the account's refresh token and access token.
#
# After making this call the Client will become unusable. You should also
# delete the stored credentials used to create this instance.
#
# See http://www.cronofy.com/developers/api#revoke-authorization for
# reference.
#
# Returns nothing.
#
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
# Raises Cronofy::CredentialsMissingError if no credentials available.
def revoke_authorization
@auth.revoke!
end
# Public: Requests elevated permissions for a set of calendars.
#
# args - A Hash of options used to initialize the request (default: {}):
# :permissions - An Array of calendar permission hashes to set on
# the each hash must contain symbols for both
# `calendar_id` and `permission_level`
# :redirect_uri - A uri to redirect the end user back to after they
# have either granted or rejected the request for
# elevated permission.
#
# In the case of normal accounts:
# After making this call the end user will have to grant the extended
# permissions to their calendar via rhe url returned from the response.
#
# In the case of service accounts:
# After making this call the exteneded permissions will be granted provided
# the relevant scope has been granted to the account
#
# Returns a extended permissions response.
#
# Raises Cronofy::AuthenticationFailureError if the client ID and secret are
# not valid.
def elevated_permissions(args = {})
filtered_permissions = args[:permissions].map do |permission|
{ calendar_id: permission[:calendar_id], permission_level: permission[:permission_level] }
end
body = { permissions: filtered_permissions }
body[:redirect_uri] = args[:redirect_uri] if args[:redirect_uri]
response = post("/v1/permissions", body)
parse_json(PermissionsResponse, "permissions_request", response)
end
# Public: Lists all the resources for the service account.
#
# Returns an Array of Resources.
#
# Raises Cronofy::CredentialsMissingError if no credentials available
# or if non-service account credentials are provided.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def resources
response = get("/v1/resources")
parse_collection(Resource, "resources", response)
end
# Public: Performs an availability query.
#
# options - The Hash options used to refine the selection (default: {}):
# :participants - An Array of participant groups or a Hash
# for a single participant group.
# :required_duration - An Integer representing the minimum number
# of minutes of availability required.
# :available_periods - An Array of available time periods Hashes,
# each must specify a start and end Time.
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
#
# Returns an Array of AvailablePeriods.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def availability(options = {})
options[:participants] = map_availability_participants(options[:participants])
options[:required_duration] = map_availability_required_duration(options[:required_duration])
if options[:start_interval]
options[:start_interval] = map_availability_required_duration(options[:start_interval])
end
if buffer = options[:buffer]
options[:buffer] = map_availability_buffer(buffer)
end
translate_available_periods(options[:available_periods])
response = post("/v1/availability", options)
parse_collections(
response,
available_periods: AvailablePeriod,
available_slots: AvailableSlot,
)
end
# Public: Performs an sequenced availability query.
#
# options - The Hash options used to refine the selection (default: {}):
# :sequence - An Array of sequence defintions containing
# a Hash of:
# :sequence_id - A String to uniquely identify this part
# of the proposed sequence.
# :ordinal - An integer to define the ordering of the
# proposed sequence. (Optional)
# :participants - An Array of participant groups or a Hash
# for a single participant group.
# :required_duration - An Integer representing the minimum
# number of minutes of availability required.
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
# :available_periods - An Array of available time periods Hashes,
# each must specify a start and end Time.
#
# Returns an Array of Sequences.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def sequenced_availability(options = {})
options[:sequence] = map_availability_sequence(options[:sequence])
translate_available_periods(options[:available_periods])
response = post("/v1/sequenced_availability", options)
parse_collection(Sequence, "sequences", response)
end
# Public: Generates an add to calendar link to start the OAuth process with
# an event to be automatically upserted
#
# oauth - A Hash describing the OAuth flow required:
# :scope - A String representing the scopes to ask for
# within the OAuth flow
# :redirect_uri - A String containing a url to redirect the
# user to after completing the OAuth flow.
# :scope - A String representing additional state to
# be passed within the OAuth flow.
#
# event - A Hash describing the event with symbolized keys:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :start - The Time or Date the event starts.
# :end - The Time or Date the event ends.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
#
# Example
#
# client.add_to_calendar(
# oauth: {
# scopes: 'read_events delete_events',
# redirect_uri: 'http://www.example.com',
# state: 'example_state'
# },
# event: {
# event_id: "qTtZdczOccgaPncGJaCiLg",
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# start: Time.utc(2014, 8, 5, 15, 30),
# end: Time.utc(2014, 8, 5, 17, 30),
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# })
#
# See http://www.cronofy.com/developers/api#upsert-event for reference.
#
# Returns a AddToCalendarResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def add_to_calendar(args = {})
body = args.merge(client_id: @client_id, client_secret: @client_secret)
body[:event][:start] = encode_event_time(body[:event][:start])
body[:event][:end] = encode_event_time(body[:event][:end])
response = post("/v1/add_to_calendar", body)
parse_json(AddToCalendarResponse, nil , response)
end
# Public: Generates an real time scheduling link to start the OAuth process with
# an event to be automatically upserted
#
# oauth - A Hash describing the OAuth flow required:
# :scope - A String representing the scopes to ask for
# within the OAuth flow
# :redirect_uri - A String containing a url to redirect the
# user to after completing the OAuth flow.
# :scope - A String representing additional state to
# be passed within the OAuth flow.
#
# event - A Hash describing the event with symbolized keys:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
# availability - A Hash describing the availability details for the event:
# :participants - A hash stating who is required for the availability
# call
# :required_duration - A hash stating the length of time the event will
# last for
# :available_periods - A hash stating the available periods for the event
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
# target_calendars - An array of hashes stating into which calendars to insert the created
# event
#
# Examples
#
# - Availability example
# client.add_to_calendar(
# oauth: {
# redirect_uri: 'http://www.example.com'
# },
# event: {
# event_id: "qTtZdczOccgaPncGJaCiLg",
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# }
# },
# availability: {
# participants: [
# {
# members: [{
# sub: "acc_567236000909002",
# calendar_ids: ["cal_n23kjnwrw2_jsdfjksn234"]
# }],
# required: 'all'
# }
# ],
# required_duration: { minutes: 60 },
# available_periods: [{
# start: Time.utc(2017, 1, 1, 9, 00),
# end: Time.utc(2017, 1, 1, 17, 00),
# }]
# },
# target_calendars: [{
# sub: "acc_567236000909002",
# calendar_id: "cal_n23kjnwrw2_jsdfjksn234"
# }]
# )
#
# See http://www.cronofy.com/developers/api#real-time-scheduling for reference.
#
# Returns a AddToCalendarResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def real_time_scheduling(args = {})
body = args.merge(client_id: @client_id, client_secret: @client_secret)
if availability = args[:availability]
availability[:participants] = map_availability_participants(availability[:participants])
availability[:required_duration] = map_availability_required_duration(availability[:required_duration])
if value = availability[:start_interval]
availability[:start_interval] = map_availability_required_duration(value)
end
if buffer = availability[:buffer]
availability[:buffer] = map_availability_buffer(buffer)
end
end
translate_available_periods(availability[:available_periods])
body[:availability] = availability
response = raw_post("/v1/real_time_scheduling", body)
parse_json(AddToCalendarResponse, nil , response)
end
# Public: Generates an real time sequencing link to start the OAuth process with
# an event to be automatically upserted
#
# oauth - A Hash describing the OAuth flow required:
# :scope - A String representing the scopes to ask for
# within the OAuth flow
# :redirect_uri - A String containing a url to redirect the
# user to after completing the OAuth flow.
# :scope - A String representing additional state to
# be passed within the OAuth flow.
#
# availability - A Hash describing the availability details for the event:
# :sequence - An Array of sequence defintions containing
# a Hash of:
# :sequence_id - A String to uniquely identify this part
# of the proposed sequence.
# :ordinal - An integer to define the ordering of the
# proposed sequence. (Optional)
# :participants - An Array of participant groups or a Hash
# for a single participant group.
# :required_duration - An Integer representing the minimum
# number of minutes of availability required.
# :start_interval - An Integer representing the start interval
# of minutes for the availability query.
# :buffer - An Hash containing the buffer to apply to
# the availability query.
# :event - A Hash describing the event:
# :event_id - A String uniquely identifying the event for
# your application (note: this is NOT an ID
# generated by Cronofy).
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :attendees - A Hash of :invite and :reject, each of which is
# an array of invitees to invite to or reject from
# the event. Invitees are represented by a hash of
# :email and :display_name (optional).
# :available_periods - A hash stating the available periods for the event
# target_calendars - An array of hashes stating into which calendars to insert the created
# event
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::AuthorizationFailureError if the access token does not
# include the required scope.
# Raises Cronofy::NotFoundError if the calendar does not exist.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def real_time_sequencing(args)
body = args.merge(client_id: @client_id, client_secret: @client_secret)
if availability = args[:availability]
availability[:sequence] = map_availability_sequence(availability[:sequence])
translate_available_periods(availability[:available_periods]) if availability[:available_periods]
end
body[:availability] = availability
response = raw_post("/v1/real_time_sequencing", body)
parse_json(AddToCalendarResponse, nil , response)
end
# Public: Creates a link_token to allow explicitly linking of an account
#
# See https://www.cronofy.com/developers/api/alpha/#auth-explicit-linking for
# reference.
#
# Returns a link token
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def link_token
response = post("/v1/link_tokens", nil)
parse_json(String, 'link_token', response)
end
# Public: Revokes the authorization to the given profile.
#
# See https://www.cronofy.com/developers/api/alpha/#revoke-profile for
# reference.
#
# Returns nothing.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
def revoke_profile_authorization(profile_id)
post("/v1/profiles/#{profile_id}/revoke", nil)
nil
end
# Public: Creates or updates smart invite.
#
# smart_invite_id - A String uniquely identifying the event for your
# application (note: this is NOT an ID generated
# by Cronofy).
# callback_url - The URL within your application you want Cronofy to
# send notifications to about user interactions with
# the Smart Invite.
# recipient - A Hash containing the intended recipient of the invite
# :email - A String for the email address you are
# going to send the Smart Invite to.
# event - A Hash describing the event with symbolized keys:
# :summary - A String to use as the summary, sometimes
# referred to as the name or title, of the
# event.
# :description - A String to use as the description, sometimes
# referred to as the notes or body, of the
# event.
# :start - The Time or Date the event starts.
# :end - The Time or Date the event ends.
# :url - The URL associated with the event.
# :location - A Hash describing the location of the event
# with symbolized keys (optional):
# :description - A String describing the
# location.
# :lat - A String of the location's latitude.
# :long - A String of the location's longitude.
# :reminders - An Array of Hashes describing the desired
# reminders for the event. Reminders should be
# specified in priority order as, for example,
# when the underlying provider only supports a
# single reminder then the first reminder will
# be used.
# :minutes - An Integer specifying the number
# of minutes before the start of the
# event that the reminder should
# occur.
# :transparency - The transparency state for the event (optional).
# Accepted values are "transparent" and "opaque".
# :color - The color of the event (optional).
#
# organizer - A Hash containing the details of the organizer.
# :name - A String value for the display name of the
# event organizer
# Examples
#
# client.upsert_smart_invite(
# smart_invite_id: "qTtZdczOccgaPncGJaCiLg",
# callback_url: "http://www.example.com",
# recipient: {
# email: "example@example.com"
# },
# event: {
# summary: "Board meeting",
# description: "Discuss plans for the next quarter.",
# start: Time.utc(2014, 8, 5, 15, 30),
# end: Time.utc(2014, 8, 5, 17, 30),
# location: {
# description: "Board room",
# lat: "1.2345",
# long: "0.1234"
# },
# organizer: {
# name: "Smart invite application"
# }
# )
#
# See http://www.cronofy.com/developers/alpha/api#smart-invite for reference.
#
# Returns a SmartInviteResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def upsert_smart_invite(body={})
body[:event][:start] = encode_event_time(body[:event][:start])
body[:event][:end] = encode_event_time(body[:event][:end])
response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
parse_json(SmartInviteResponse, nil, response)
end
# Public: Cancels a smart invite
#
# smart_invite_id - A String uniquely identifying the event for your
# application (note: this is NOT an ID generated
# by Cronofy).
# recipient - A Hash containing the intended recipient of the invite
# :email - A String for thee email address you are
# going to send the Smart Invite to.
#
# See http://www.cronofy.com/developers/alpha/api#smart-invite for reference.
#
# Returns a SmartInviteResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def cancel_smart_invite(body={})
body[:method] = 'cancel'
response = wrapped_request { api_key!.post("/v1/smart_invites", json_request_args(body)) }
parse_json(SmartInviteResponse, nil, response)
end
# Public: Gets the details for a smart invite.
#
# smart_invite_id - A String uniquely identifying the event for your
# application (note: this is NOT an ID generated
# by Cronofy).
# recipient_email - The email address for the recipient to get details for.
#
# See http://www.cronofy.com/developers/alpha/api#smart-invite for reference.
#
# Returns a SmartInviteResponse.
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::InvalidRequestError if the request contains invalid
# parameters.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def get_smart_invite(smart_invite_id, recipient_email)
response = wrapped_request { api_key!.get("/v1/smart_invites?recipient_email=#{recipient_email}&smart_invite_id=#{smart_invite_id}") }
parse_json(SmartInviteResponse, nil, response)
end
# Public: Creates an element_token to pass to a UI Element
#
# options - A Hash of options for the token
# :permissions - An Array of strings describing the
# permissions required for the token
# :subs - An Array of sub values for the account(s)
# the element will be accessing
# :origin - The scheme://hostname where the token will
# be used.
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
#
# See https://docs.cronofy.com/developers/ui-elements/authentication for
# reference.
#
# Returns an element token
#
# Raises Cronofy::CredentialsMissingError if no credentials available.
# Raises Cronofy::AuthenticationFailureError if the access token is no
# longer valid.
# Raises Cronofy::TooManyRequestsError if the request exceeds the rate
# limits for the application.
def element_token(options)
response = wrapped_request { api_key!.post("/v1/element_tokens", json_request_args(options)) }
parse_json(ElementToken, "element_token", response)
end
# Public: Creates a scheduling conversation
#
# pre release end-point documentation to follow
#
def create_scheduling_conversation(body)
response = wrapped_request { post("/v1/scheduling_conversations", body) }
parse_json(SchedulingConversation, nil, response)
end
# Public: List available slots for a scheduling conversation
#
# pre release end-point documentation to follow
#
def list_scheduling_conversation_participant_slots(url)
response = wrapped_request { get(url) }
parse_collection(SchedulingConversationSlot, "available_slots", response )
end
# Public: Choose one or more slots for a scheduling conversation
#
# pre release end-point documentation to follow
#
def select_scheduling_conversation_participant_slots(url, args)
response = wrapped_request { post(url, args)}
parse_json(SchedulingConversation, nil, response)
end
private
def translate_available_periods(periods)
periods.each do |params|
AVAILABLE_PERIODS_TIME_PARAMS.select { |tp| params.key?(tp) }.each do |tp|
params[tp] = to_iso8601(params[tp])
end
end
end
def map_availability_participants(participants)
case participants
when Hash
# Allow one group to be specified without being nested
[map_availability_participants_group(participants)]
when Enumerable
participants.map do |group|
map_availability_participants_group(group)
end
else
participants
end
end
def map_availability_participants_group(participants)
case participants
when Hash
participants[:members].map! do |member|
map_availability_member(member)
end
unless participants.key?(:required)
participants[:required] = :all
end
participants
when Array
participants.map do |group|
map_availability_participants(group)
end
else
participants
end
end
def map_availability_member(member)
case member
when String
{ sub: member }
when Hash
if member[:available_periods]
translate_available_periods(member[:available_periods])
end
member
else
member
end
end
def map_availability_required_duration(required_duration)
case required_duration
when Integer
{ minutes: required_duration }
else
required_duration
end
end
def map_availability_buffer(buffer)
result = {}
unless buffer.is_a?(Hash)
return result
end
if before_buffer = buffer[:before]
result[:before] = map_buffer_details(before_buffer)
end
if after_buffer = buffer[:after]
result[:after] = map_buffer_details(after_buffer)
end
result
end
def map_buffer_details(buffer)
result = map_availability_required_duration(buffer)
if minimum_buffer = buffer[:minimum]
result[:minimum] = map_availability_required_duration(minimum_buffer)
end
if maximum_buffer = buffer[:maximum]
result[:maximum] = map_availability_required_duration(maximum_buffer)
end
result
end
def map_availability_sequence(sequence)
case sequence
when Enumerable
sequence.map do |sequence_item|
hash = {}
if value = sequence_item[:participants]
hash[:participants] = map_availability_participants(value)
end
if value = sequence_item[:required_duration]
hash[:required_duration] = map_availability_required_duration(value)
end
if sequence_item[:available_periods]
translate_available_periods(sequence_item[:available_periods])
end
if value = sequence_item[:start_interval]
hash[:start_interval] = map_availability_required_duration(value)
end
if buffer = sequence_item[:buffer]
hash[:buffer] = map_availability_buffer(buffer)
end
sequence_item.merge(hash)
end
else
sequence
end
end
AVAILABLE_PERIODS_TIME_PARAMS = %i{
start
end
}.freeze
FREE_BUSY_DEFAULT_PARAMS = { tzid: "Etc/UTC" }.freeze
FREE_BUSY_TIME_PARAMS = %i{
from
to
}.freeze
READ_EVENTS_DEFAULT_PARAMS = { tzid: "Etc/UTC" }.freeze
READ_EVENTS_TIME_PARAMS = %i{
from
to
last_modified
}.freeze
def access_token!
raise CredentialsMissingError.new unless @auth.access_token
@auth.access_token
end
def api_key!
raise CredentialsMissingError.new unless @auth.api_key
@auth.api_key
end
def get(url, opts = {})
wrapped_request { access_token!.get(url, opts) }
end
def post(url, body)
wrapped_request { access_token!.post(url, json_request_args(body)) }
end
def delete(url, body = nil)
wrapped_request { access_token!.delete(url, json_request_args(body)) }
end
def raw_post(url, body)
wrapped_request { @auth.api_client.request(:post, url, json_request_args(body)) }
end
def wrapped_request
yield
rescue OAuth2::Error => e
raise Errors.map_error(e)
end
def parse_collection(type, attr, response)
ResponseParser.new(response).parse_collection(type, attr)
end
def parse_collections(response, mappings)
ResponseParser.new(response).parse_collections(mappings)
end
def parse_json(type, attr = nil, response)
ResponseParser.new(response).parse_json(type, attr)
end
def json_request_args(body_hash)
if body_hash
{
body: JSON.generate(body_hash),
headers: { "Content-Type" => "application/json; charset=utf-8" },
}
else
{}
end
end
class PagedResultIterator
include Enumerable
def initialize(page_parser, items_key, access_token, url, params)
@page_parser = page_parser
@items_key = items_key
@access_token = access_token
@url = url
@params = params
@first_page = get_page(url, params)
end
def each
page = @first_page
page[@items_key].each do |item|
yield item
end
while page.pages.next_page?
page = get_page(page.pages.next_page)
page[@items_key].each do |item|
yield item
end
end
end
private
attr_reader :access_token
attr_reader :params
attr_reader :url
def get_page(url, params = {})
response = http_get(url, params)
parse_page(response)
end
def http_get(url, params = {})
response = Faraday.get(url, params, oauth_headers)
Errors.raise_if_error(response)
response
end
def oauth_headers
{
"Authorization" => "Bearer #{access_token.token}",
"User-Agent" => "Cronofy Ruby #{::Cronofy::VERSION}",
}
end
def parse_page(response)
ResponseParser.new(response).parse_json(@page_parser)
end
end
def api_url
::Cronofy.api_url(@data_centre)
end
end
# Deprecated: Alias for Client for backwards compatibility.
class Cronofy < Client
end
end
|
module Daberu
VERSION = "0.0.4"
end
バージョン番号を0.0.5に修正 [modified version number to 0.0.5]
module Daberu
VERSION = "0.0.5"
end
|
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 'spec_helper'
klass = OneviewSDK::API500::Synergy::SASInterconnect
RSpec.describe klass, integration: true, type: UPDATE do
let(:current_client) { $client_500_synergy }
include_examples 'SASInterconnectUpdateExample', 'integration api500 context'
end
Removing comment
require 'spec_helper'
klass = OneviewSDK::API500::Synergy::SASInterconnect
RSpec.describe klass, integration: true, type: UPDATE do
let(:current_client) { $client_500_synergy }
include_examples 'SASInterconnectUpdateExample', 'integration api500 context'
end
|
require_relative 'subtitle'
require 'net/http'
require 'nokogiri'
require 'open-uri'
require 'securerandom'
module LegendasTV
module Net
def self.GET(url, params = {})
uri = URI.parse(URI.encode(url))
uri.query = URI.encode_www_form(params)
::Net::HTTP.get_response(uri)
end
def self.POST(url, params = {})
uri = URI.parse(url)
::Net::HTTP.post_form(uri, params)
end
def self.Download(url, token, &block)
uri = URI.parse(url)
request = ::Net::HTTP::Get.new(uri.path)
request.add_field('Cookie', "au=#{token};")
response = ::Net::HTTP.new(uri.host, uri.port).start do |http|
http.request(request)
end
if response.is_a?(::Net::HTTPRedirection)
# Follow redirect
Download(response['location'], token, &block)
else
file = Tempfile.new([::SecureRandom.uuid, Pathname.new(url).extname])
file.write(response.body)
block.call(file.path)
file.close
file.unlink
end
end
def self.Parse(url)
uri = URI.encode(url)
results = Nokogiri::HTML(open(uri)).xpath('//article/div')
results.map do |r|
next if r.attr('class') =~ /banner/
Subtitle.new(r)
end.compact
end
end
end
Optimize search with XHR request
require_relative 'subtitle'
require 'net/http'
require 'nokogiri'
require 'securerandom'
module LegendasTV
module Net
def self.GET(url, params = {}, headers = {})
uri = URI.parse(URI.encode(url))
uri.query = URI.encode_www_form(params)
request = ::Net::HTTP::Get.new(uri)
headers.each { |k, v| request[k] = v }
::Net::HTTP.start(uri.hostname) do |http|
http.request(request)
end
end
def self.POST(url, params = {})
uri = URI.parse(url)
::Net::HTTP.post_form(uri, params)
end
def self.Download(url, token, &block)
uri = URI.parse(url)
request = ::Net::HTTP::Get.new(uri.path)
request.add_field('Cookie', "au=#{token};")
response = ::Net::HTTP.new(uri.host, uri.port).start do |http|
http.request(request)
end
if response.is_a?(::Net::HTTPRedirection)
# Follow redirect
Download(response['location'], token, &block)
else
file = Tempfile.new([::SecureRandom.uuid, Pathname.new(url).extname])
file.write(response.body)
block.call(file.path)
file.close
file.unlink
end
end
def self.Parse(url)
body = GET(url, {}, { 'X-Requested-With' => 'XMLHttpRequest' }).body
results = Nokogiri::HTML(body).xpath('//article/div')
results.map do |r|
next if r.attr('class') =~ /banner/
Subtitle.new(r)
end.compact
end
end
end
|
module BOAST
class DataType
include Intrinsics
include PrivateStateAccessor
def self.inherited(child)
child.extend( VarFunctor)
end
end
class Sizet < DataType
attr_reader :signed
attr_reader :size
attr_reader :vector_length
def initialize(hash={})
if hash[:signed] != nil then
@signed = hash[:signed]
end
@size = nil
@vector_length = 1
end
def to_hash
return { :signed => @signed }
end
def copy(options={})
hash = to_hash
options.each { |k,v|
hash[k] = v
}
return Sizet::new(hash)
end
def decl
return "integer(kind=#{get_default_int_size})" if lang == FORTRAN
if not @signed then
return "size_t" if [C, CL, CUDA].include?( lang )
else
return "ptrdiff_t" if [C, CL, CUDA].include?( lang )
end
end
def decl_ffi
return :size_t
end
def signed?
return !!signed
end
def suffix
s = ""
return s
end
end
class Real < DataType
attr_reader :size
attr_reader :signed
attr_reader :vector_length
attr_reader :total_size
attr_reader :getters
attr_reader :setters
def ==(t)
return true if t.class == self.class and t.size == size and t.vector_length == vector_length
return false
end
def initialize(hash={})
if hash[:size] then
@size = hash[:size]
else
@size = get_default_real_size
end
# @getters = {}
# @setters = {}
if hash[:vector_length] and hash[:vector_length] > 1 then
@vector_length = hash[:vector_length]
# @vector_length.times{ |indx|
# @getters["s#{indx}"] = indx
# @setters["s#{indx}="] = indx
# }
else
@vector_length = 1
end
@total_size = @size*@vector_length
@signed = true
end
def signed?
return !!signed
end
def to_hash
return { :size => @size, :vector_length => @vector_length }
end
def copy(options={})
hash = to_hash
options.each { |k,v|
hash[k] = v
}
return Real::new(hash)
end
def decl
return "real(kind=#{@size})" if lang == FORTRAN
if [C, CL, CUDA].include?( lang ) and @vector_length == 1 then
return "float" if @size == 4
return "double" if @size == 8
elsif lang == C and @vector_length > 1 then
return get_vector_decl(self)
elsif [CL, CUDA].include?( lang ) and @vector_length > 1 then
return "float#{@vector_length}" if @size == 4
return "double#{@vector_length}" if @size == 8
end
end
def decl_ffi
return :float if @size == 4
return :double if @size == 8
end
def suffix
s = ""
if [C, CL, CUDA].include?( lang ) then
s += "f" if @size == 4
elsif lang == FORTRAN then
s += "_wp" if @size == 8
end
return s
end
end
class Int < DataType
attr_reader :size
attr_reader :signed
attr_reader :vector_length
attr_reader :total_size
def ==(t)
return true if t.class == self.class and t.signed == signed and t.size == size and t.vector_length == vector_length
return false
end
def initialize(hash={})
if hash[:size] then
@size = hash[:size]
else
@size = get_default_int_size
end
if hash[:signed] != nil then
@signed = hash[:signed]
else
@signed = get_default_int_signed
end
if hash[:vector_length] and hash[:vector_length] > 1 then
@vector_length = hash[:vector_length]
raise "Vectors need to have their element size specified!" if not @size
else
@vector_length = 1
end
@total_size = @size*@vector_length
end
def to_hash
return { :size => @size, :vector_length => @vector_length, :signed => @signed }
end
def copy(options={})
hash = to_hash
options.each { |k,v|
hash[k] = v
}
return Int::new(hash)
end
def signed?
return !!@signed
end
def decl
if lang == FORTRAN then
return "integer(kind=#{@size})" if @size
return "integer"
end
if lang == C then
if @vector_length == 1 then
s = ""
s += "u" if not @signed
return s+"int#{8*@size}_t" if @size
return s+"int"
elsif @vector_length > 1 then
return get_vector_decl(self)
end
else
s =""
s += "u" if not @signed
s += "nsigned " if not @signed and lang == CUDA and @vector_length == 1
case @size
when 1
s += "char"
when 2
s += "short"
when 4
s += "int"
when 8
if lang == CUDA
case @vector_length
when 1
s += "long long"
else
s += "longlong"
end
else
s += "long"
end
when nil
s += "int"
else
raise "Unsupported integer size!"
end
if @vector_length > 1 then
s += "#{@vector_length}"
end
return s
end
end
def decl_ffi
t = ""
t += "u" if not @signed
t += "int"
t += "#{@size*8}" if @size
return t.to_sym
end
def suffix
s = ""
return s
end
end
class CStruct < DataType
attr_reader :name, :members, :members_array
def initialize(hash={})
@name = hash[:type_name]
@members = {}
@members_array = []
hash[:members].each { |m|
mc = m.copy
@members_array.push(mc)
@members[mc.name] = mc
}
end
def decl_c
return "struct #{@name}" if [C, CL, CUDA].include?( lang )
end
def decl_fortran
return "TYPE(#{@name})" if lang == FORTRAN
end
def decl
return decl_c if [C, CL, CUDA].include?( lang )
return decl_fortran if lang == FORTRAN
end
def finalize
s = ""
s += ";" if [C, CL, CUDA].include?( lang )
s+="\n"
return s
end
def define
return define_c if [C, CL, CUDA].include?( lang )
return define_fortran if lang == FORTRAN
end
def define_c
s = indent
s += decl_c + " {"
output.puts s
increment_indent_level
@members_array.each { |value|
value.decl
}
decrement_indent_level
s = indent
s += "}"
s += finalize
output.print s
return self
end
def define_fortran
s = indent
s += "TYPE :: #{@name}\n"
output.puts s
increment_indent_level
@members_array.each { |value|
value.decl
}
decrement_indent_level
s = indent
s += "END TYPE #{@name}"
s += finalize
output.print s
return self
end
end
class CustomType < DataType
attr_reader :size, :name, :vector_length
def initialize(hash={})
@name = hash[:type_name]
@size = hash[:size]
@size = 0 if @size.nil?
@vector_length = hash[:vector_length]
@vector_length = 1 if @vector_length.nil?
@total_size = @vector_length*@size
end
def decl
return "#{@name}" if [C, CL, CUDA].include?( lang )
end
end
end
Removed dead code.
module BOAST
class DataType
include Intrinsics
include PrivateStateAccessor
def self.inherited(child)
child.extend( VarFunctor)
end
end
class Sizet < DataType
attr_reader :signed
attr_reader :size
attr_reader :vector_length
def initialize(hash={})
if hash[:signed] != nil then
@signed = hash[:signed]
end
@size = nil
@vector_length = 1
end
def to_hash
return { :signed => @signed }
end
def copy(options={})
hash = to_hash
options.each { |k,v|
hash[k] = v
}
return Sizet::new(hash)
end
def decl
return "integer(kind=#{get_default_int_size})" if lang == FORTRAN
if not @signed then
return "size_t" if [C, CL, CUDA].include?( lang )
else
return "ptrdiff_t" if [C, CL, CUDA].include?( lang )
end
end
def decl_ffi
return :size_t
end
def signed?
return !!signed
end
def suffix
s = ""
return s
end
end
class Real < DataType
attr_reader :size
attr_reader :signed
attr_reader :vector_length
attr_reader :total_size
attr_reader :getters
attr_reader :setters
def ==(t)
return true if t.class == self.class and t.size == size and t.vector_length == vector_length
return false
end
def initialize(hash={})
if hash[:size] then
@size = hash[:size]
else
@size = get_default_real_size
end
if hash[:vector_length] and hash[:vector_length] > 1 then
@vector_length = hash[:vector_length]
else
@vector_length = 1
end
@total_size = @size*@vector_length
@signed = true
end
def signed?
return !!signed
end
def to_hash
return { :size => @size, :vector_length => @vector_length }
end
def copy(options={})
hash = to_hash
options.each { |k,v|
hash[k] = v
}
return Real::new(hash)
end
def decl
return "real(kind=#{@size})" if lang == FORTRAN
if [C, CL, CUDA].include?( lang ) and @vector_length == 1 then
return "float" if @size == 4
return "double" if @size == 8
elsif lang == C and @vector_length > 1 then
return get_vector_decl(self)
elsif [CL, CUDA].include?( lang ) and @vector_length > 1 then
return "float#{@vector_length}" if @size == 4
return "double#{@vector_length}" if @size == 8
end
end
def decl_ffi
return :float if @size == 4
return :double if @size == 8
end
def suffix
s = ""
if [C, CL, CUDA].include?( lang ) then
s += "f" if @size == 4
elsif lang == FORTRAN then
s += "_wp" if @size == 8
end
return s
end
end
class Int < DataType
attr_reader :size
attr_reader :signed
attr_reader :vector_length
attr_reader :total_size
def ==(t)
return true if t.class == self.class and t.signed == signed and t.size == size and t.vector_length == vector_length
return false
end
def initialize(hash={})
if hash[:size] then
@size = hash[:size]
else
@size = get_default_int_size
end
if hash[:signed] != nil then
@signed = hash[:signed]
else
@signed = get_default_int_signed
end
if hash[:vector_length] and hash[:vector_length] > 1 then
@vector_length = hash[:vector_length]
raise "Vectors need to have their element size specified!" if not @size
else
@vector_length = 1
end
@total_size = @size*@vector_length
end
def to_hash
return { :size => @size, :vector_length => @vector_length, :signed => @signed }
end
def copy(options={})
hash = to_hash
options.each { |k,v|
hash[k] = v
}
return Int::new(hash)
end
def signed?
return !!@signed
end
def decl
if lang == FORTRAN then
return "integer(kind=#{@size})" if @size
return "integer"
end
if lang == C then
if @vector_length == 1 then
s = ""
s += "u" if not @signed
return s+"int#{8*@size}_t" if @size
return s+"int"
elsif @vector_length > 1 then
return get_vector_decl(self)
end
else
s =""
s += "u" if not @signed
s += "nsigned " if not @signed and lang == CUDA and @vector_length == 1
case @size
when 1
s += "char"
when 2
s += "short"
when 4
s += "int"
when 8
if lang == CUDA
case @vector_length
when 1
s += "long long"
else
s += "longlong"
end
else
s += "long"
end
when nil
s += "int"
else
raise "Unsupported integer size!"
end
if @vector_length > 1 then
s += "#{@vector_length}"
end
return s
end
end
def decl_ffi
t = ""
t += "u" if not @signed
t += "int"
t += "#{@size*8}" if @size
return t.to_sym
end
def suffix
s = ""
return s
end
end
class CStruct < DataType
attr_reader :name, :members, :members_array
def initialize(hash={})
@name = hash[:type_name]
@members = {}
@members_array = []
hash[:members].each { |m|
mc = m.copy
@members_array.push(mc)
@members[mc.name] = mc
}
end
def decl_c
return "struct #{@name}" if [C, CL, CUDA].include?( lang )
end
def decl_fortran
return "TYPE(#{@name})" if lang == FORTRAN
end
def decl
return decl_c if [C, CL, CUDA].include?( lang )
return decl_fortran if lang == FORTRAN
end
def finalize
s = ""
s += ";" if [C, CL, CUDA].include?( lang )
s+="\n"
return s
end
def define
return define_c if [C, CL, CUDA].include?( lang )
return define_fortran if lang == FORTRAN
end
def define_c
s = indent
s += decl_c + " {"
output.puts s
increment_indent_level
@members_array.each { |value|
value.decl
}
decrement_indent_level
s = indent
s += "}"
s += finalize
output.print s
return self
end
def define_fortran
s = indent
s += "TYPE :: #{@name}\n"
output.puts s
increment_indent_level
@members_array.each { |value|
value.decl
}
decrement_indent_level
s = indent
s += "END TYPE #{@name}"
s += finalize
output.print s
return self
end
end
class CustomType < DataType
attr_reader :size, :name, :vector_length
def initialize(hash={})
@name = hash[:type_name]
@size = hash[:size]
@size = 0 if @size.nil?
@vector_length = hash[:vector_length]
@vector_length = 1 if @vector_length.nil?
@total_size = @vector_length*@size
end
def decl
return "#{@name}" if [C, CL, CUDA].include?( lang )
end
end
end
|
module BOAST
class OperatorError < Error
end
class Operator
extend PrivateStateAccessor
extend Intrinsics
DISCARD_OPTIONS = { :const => nil, :constant => nil, :direction => nil, :dir => nil, :align => nil }
def Operator.inspect
return "#{name}"
end
def Operator.convert(arg, type)
return "#{arg}" if get_vector_name(arg.type) == get_vector_name(type) or lang == CUDA
return "convert_#{type.decl}( #{arg} )" if lang == CL
path = get_conversion_path(type, arg.type)
s = "#{arg}"
if path.length > 1 then
path.each_cons(2) { |slice|
instruction = intrinsics_by_vector_name(:CVT, slice[1], slice[0])
s = "#{instruction}( #{s} )"
}
end
return s
end
end
class BasicBinaryOperator < Operator
def BasicBinaryOperator.string(arg1, arg2, return_type)
if lang == C and (arg1.class == Variable and arg2.class == Variable) and (arg1.type.vector_length > 1 or arg2.type.vector_length > 1) then
instruction = intrinsics(intr_symbol, return_type.type)
a1 = convert(arg1, return_type.type)
a2 = convert(arg2, return_type.type)
return "#{instruction}( #{a1}, #{a2} )"
else
return basic_usage( arg1, arg2 )
end
end
end
class Minus < Operator
def Minus.string(arg1, arg2, return_type)
return " -(#{arg2})"
end
end
class Plus < Operator
def Plus.string(arg1, arg2, return_type)
return " +#{arg2}"
end
end
class Not < Operator
def Not.string(arg1, arg2, return_type)
return " (.not. (#{arg2}))" if lang == FORTRAN
return " !(#{arg2})"
end
end
class Reference < Operator
def Reference.string(arg1, arg2, return_type)
return " #{arg2}" if lang == FORTRAN
return " &#{arg2}"
end
end
class Dereference < Operator
def Dereference.string(arg1, arg2, return_type)
return " *(#{arg2})"
end
end
class Equal < Operator
def Equal.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Equal.basic_usage(arg1, arg2)
return "#{arg1} == #{arg2}"
end
end
class Different < Operator
def Different.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Different.basic_usage(arg1, arg2)
return "#{arg1} /= #{arg2}" if lang == FORTRAN
return "#{arg1} != #{arg2}"
end
end
class Greater < Operator
def Greater.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Greater.basic_usage(arg1, arg2)
return "#{arg1} > #{arg2}"
end
end
class Less < Operator
def Less.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Less.basic_usage(arg1, arg2)
return "#{arg1} < #{arg2}"
end
end
class GreaterOrEqual < Operator
def GreaterOrEqual.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def GreaterOrEqual.basic_usage(arg1, arg2)
return "#{arg1} >= #{arg2}"
end
end
class LessOrEqual < Operator
def LessOrEqual.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def LessOrEqual.basic_usage(arg1, arg2)
return "#{arg1} <= #{arg2}"
end
end
class And < Operator
def And.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def And.basic_usage(arg1, arg2)
return "#{arg1} .and. #{arg2}" if lang == FORTRAN
return "#{arg1} && #{arg2}"
end
end
class Or < Operator
def Or.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Or.basic_usage(arg1, arg2)
return "#{arg1} .or. #{arg2}" if lang == FORTRAN
return "#{arg1} || #{arg2}"
end
end
class Affectation < Operator
def Affectation.string(arg1, arg2, return_type)
if arg1.class == Variable and arg1.type.vector_length > 1 then
return "#{arg1} = #{Load(arg2, arg1)}"
elsif arg2.class == Variable and arg2.type.vector_length > 1 then
return "#{Store(arg1, arg2, return_type)}"
end
return basic_usage(arg1, arg2)
end
def Affectation.basic_usage(arg1, arg2)
return "#{arg1} = #{arg2}"
end
end
class Exponentiation < BasicBinaryOperator
class << self
def symbol
return "**"
end
def intr_symbol
return :POW
end
def basic_usage(arg1, arg2)
return "(#{arg1})**(#{arg2})" if lang == FORTRAN
return "pow(#{arg1}, #{arg2})"
end
end
end
class Multiplication < BasicBinaryOperator
class << self
def symbol
return "*"
end
def intr_symbol
return :MUL
end
def basic_usage(arg1, arg2)
return "(#{arg1}) * (#{arg2})"
end
end
end
class Addition < BasicBinaryOperator
class << self
def symbol
return "+"
end
def intr_symbol
return :ADD
end
def basic_usage(arg1, arg2)
return "#{arg1} + #{arg2}"
end
end
end
class Substraction < BasicBinaryOperator
class << self
def symbol
return "-"
end
def intr_symbol
return :SUB
end
def basic_usage(arg1, arg2)
return "#{arg1} - (#{arg2})"
end
end
end
class Division < BasicBinaryOperator
class << self
def symbol
return "/"
end
def intr_symbol
return :DIV
end
def basic_usage(arg1, arg2)
return "(#{arg1}) / (#{arg2})"
end
end
end
class Set < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :source
attr_reader :return_type
def initialize(source, return_type)
@source = source
@return_type = return_type
end
def type
return @return_type.type
end
def to_var
if lang == C or lang == CL and @return_type.type.vector_length > 1 then
if @source.kind_of?( Array ) then
raise OperatorError, "Invalid array length!" unless @source.length == @return_type.type.vector_length
return @return_type.copy("(#{@return_type.type.decl})( #{@source.join(", ")} )", DISCARD_OPTIONS) if lang == CL
begin
instruction = intrinsics(:SET, @return_type.type)
return @return_type.copy("#{instruction}( #{@source.join(", ")} )", DISCARD_OPTIONS)
rescue IntrinsicsError
instruction = intrinsics(:SET_LANE, @return_type.type)
s = Set(0, @return_type).to_s
@source.each_with_index { |v,i|
s = "#{instruction}(#{v}, #{s}, #{i})"
}
return @return_type.copy(s, DISCARD_OPTIONS)
end
elsif @source.class != Variable or @source.type.vector_length == 1 then
return @return_type.copy("(#{@return_type.type.decl})( #{@source} )", DISCARD_OPTIONS) if lang == CL
instruction = intrinsics(:SET1, @return_type.type)
return @return_type.copy("#{instruction}( #{@source} )", DISCARD_OPTIONS)
elsif @return_type.type != @source.type
return @return_type.copy("#{Operator.convert(@source, @return_type.type)}", DISCARD_OPTIONS)
end
end
return @return_type.copy("#{@source}", DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class Load < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :source
attr_reader :return_type
def initialize(source, return_type)
@source = source
@return_type = return_type
end
def type
return @return_type.type
end
def to_var
if lang == C or lang == CL then
if @source.kind_of?(Array) then
return Set(@source, @return_type).to_var
elsif @source.class == Variable or @source.respond_to?(:to_var) then
if @source.to_var.type == @return_type.type
return @source.to_var
elsif @source.to_var.type.vector_length == 1 then
a2 = "#{@source}"
if a2[0] != "*" then
a2 = "&" + a2
else
a2 = a2[1..-1]
end
return @return_type.copy("vload#{@return_type.type.vector_length}(0, #{a2})", DISCARD_OPTIONS) if lang == CL
return @return_type.copy("_m_from_int64( *((int64_t * ) #{a2} ) )", DISCARD_OPTIONS) if get_architecture == X86 and @return_type.type.total_size*8 == 64
if @source.alignment == @return_type.type.total_size then
instruction = intrinsics(:LOADA, @return_type.type)
else
instruction = intrinsics(:LOAD, @return_type.type)
end
return @return_type.copy("#{instruction}( #{a2} )", DISCARD_OPTIONS)
else
return @return_type.copy("#{Operator.convert(@source, @return_type.type)}", DISCARD_OPTIONS)
end
end
end
return @return_type.copy("#{@source}", DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class MaskLoad < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :source
attr_reader :mask
attr_reader :return_type
def initialize(source, mask, return_type)
@source = source
@mask = mask
@return_type = return_type
end
def get_mask
raise OperatorError, "Mask size is wrong: #{@mask.length} for #{@return_type.type.vector_length}!" if @mask.length != @return_type.type.vector_length
return Load(@mask.collect { |m| ( m and m != 0 ) ? -1 : 0 }, Int("mask", :size => @return_type.type.size, :vector_length => @return_type.type.vector_length ) )
end
private :get_mask
def type
return @return_type.type
end
def to_var
raise OperatorError, "Cannot load unknown type!" unless @return_type
raise LanguageError, "Unsupported language!" unless lang == C
instruction = intrinsics(:MASKLOAD, @return_type.type)
s = ""
src = "#{@source}"
if src[0] != "*" then
src = "&" + src
else
src = src[1..-1]
end
p_type = @return_type.type.copy(:vector_length => 1)
s += "#{instruction}((#{p_type.decl} * )#{src}, #{get_mask})"
return @return_type.copy( s, DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class Store < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :dest
attr_reader :source
attr_reader :store_type
def initialize(dest, source, mask, store_type = nil)
@dest = dest
@source = source
@store_type = store_type
@store_type = source unless @store_type
end
def to_s
if lang == C or lang == CL then
dst = "#{@dest}"
if dst[0] != "*" then
dst = "&" + dst
else
dst = dst[1..-1]
end
return "vstore#{@source.type.vector_length}(#{@source}, 0, #{dst})" if lang == CL
return "*((int64_t * ) #{dst}) = _m_to_int64( #{@source} )" if get_architecture == X86 and @source.type.total_size*8 == 64
if @dest.alignment == @source.type.total_size then
instruction = intrinsics(:STOREA, @source.type)
else
instruction = intrinsics(:STORE, @source.type)
end
p_type = @source.type.copy(:vector_length => 1)
p_type = @source.type if get_architecture == X86 and @source.type.kind_of?(Int)
return "#{instruction}( (#{p_type.decl} * ) #{dst}, #{@source} )"
end
return Affectation.basic_usage(@dest, @source)
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class MaskStore < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :dest
attr_reader :source
attr_reader :mask
attr_reader :store_type
def initialize(dest, source, mask, store_type = nil)
@dest = dest
@source = source
@mask = mask
@store_type = store_type
@store_type = source unless @store_type
end
def get_mask
raise OperatorError, "Mask size is wrong: #{@mask.length} for #{@store_type.type.vector_length}!" if @mask.length != @store_type.type.vector_length
return Load.to_s(@mask.collect { |m| ( m and m != 0 ) ? -1 : 0 }, Int("mask", :size => @store_type.type.size, :vector_length => @store_type.type.vector_length ) )
end
private :get_mask
def to_s
raise OperatorError, "Cannot store unknown type!" unless @store_type
raise LanguageError, "Unsupported language!" unless lang == C
instruction = intrinsics(:MASKSTORE, @store_type.type)
s = ""
dst = "#{@dest}"
if dst[0] != "*" then
dst = "&" + dst
else
dst = dst[1..-1]
end
p_type = @store_type.type.copy(:vector_length => 1)
return s += "#{instruction}((#{p_type.decl} * )#{dst}, #{get_mask}, #{Operator.convert(@source, @store_type.type)})"
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class FMA < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :operand1
attr_reader :operand2
attr_reader :operand3
attr_reader :return_type
def initialize(a,b,c)
@operand1 = a
@operand2 = b
@operand3 = c
@return_type = nil
@return_type = @operand3.to_var unless @return_type
end
def convert_operand(op)
return "#{Operator.convert(op, @return_type.type)}"
end
private :convert_operand
def type
return @return_type.type
end
def to_var
instruction = nil
begin
instruction = intrinsics(:FMADD,@return_type.type)
rescue
end
return (@operand3 + @operand1 * @operand2).to_var unless lang != FORTRAN and @return_type and ( instruction or ( [CL, CUDA].include?(lang) ) )
op1 = convert_operand(@operand1)
op2 = convert_operand(@operand2)
op3 = convert_operand(@operand3)
if [CL, CUDA].include?(lang)
ret_name = "fma( #{op1}, #{op2}, #{op3} )"
else
case architecture
when X86
ret_name = "#{instruction}( #{op1}, #{op2}, #{op3} )"
when ARM
ret_name = "#{instruction}( #{op3}, #{op1}, #{op2} )"
else
return (@operand3 + @operand1 * @operand2).to_var
end
end
return @return_type.copy( ret_name, DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class FMS < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :operand1
attr_reader :operand2
attr_reader :operand3
attr_reader :return_type
def initialize(a,b,c)
@operand1 = a
@operand2 = b
@operand3 = c
@return_type = nil
@return_type = @operand3.to_var unless @return_type
end
def convert_operand(op)
return "#{Operator.convert(op, @return_type.type)}"
end
private :convert_operand
def type
return @return_type.type
end
def to_var
instruction = nil
begin
instruction = intrinsics(:FNMADD,@return_type.type)
rescue
end
return (@operand3 - @operand1 * @operand2).to_var unless lang != FORTRAN and @return_type and ( instruction or ( [CL, CUDA].include?(lang) ) )
op1 = convert_operand(@operand1)
op2 = convert_operand(@operand2)
op3 = convert_operand(@operand3)
if [CL, CUDA].include?(lang)
ret_name = "fma( #{op1}, -#{op2}, #{op3} )"
else
case architecture
when X86
ret_name = "#{instruction}( #{op1}, #{op2}, #{op3} )"
when ARM
ret_name = "#{instruction}( #{op3}, #{op1}, #{op2} )"
else
return (@operand3 - @operand1 * @operand2).to_var
end
end
return @return_type.copy( ret_name, DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class Ternary
extend Functor
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :operand1
attr_reader :operand2
attr_reader :operand3
def initialize(x,y,z)
@operand1 = x
@operand2 = y
@operand3 = z
end
def op_to_var
op1 = @operand1.respond_to?(:to_var) ? @operand1.to_var : @operand1
op1 = @operand1 unless op1
op2 = @operand2.respond_to?(:to_var) ? @operand2.to_var : @operand2
op2 = @operand2 unless op2
op3 = @operand3.respond_to?(:to_var) ? @operand3.to_var : @operand3
op3 = @operand3 unless op3
return [op1, op2, op3]
end
private :op_to_var
def to_s
return to_s_fortran if lang == FORTRAN
return to_s_c if [C, CL, CUDA].include?( lang )
end
def to_s_fortran
op1, op2, op3 = op_to_var
"merge(#{op2}, #{op3}, #{op1})"
end
def to_s_c
op1, op2, op3 = op_to_var
"(#{op1} ? #{op2} : #{op3})"
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
end
Convert FMA and FMS operand to var in order to get their type if they are expressions.
module BOAST
class OperatorError < Error
end
class Operator
extend PrivateStateAccessor
extend Intrinsics
DISCARD_OPTIONS = { :const => nil, :constant => nil, :direction => nil, :dir => nil, :align => nil }
def Operator.inspect
return "#{name}"
end
def Operator.convert(arg, type)
return "#{arg}" if get_vector_name(arg.type) == get_vector_name(type) or lang == CUDA
return "convert_#{type.decl}( #{arg} )" if lang == CL
path = get_conversion_path(type, arg.type)
s = "#{arg}"
if path.length > 1 then
path.each_cons(2) { |slice|
instruction = intrinsics_by_vector_name(:CVT, slice[1], slice[0])
s = "#{instruction}( #{s} )"
}
end
return s
end
end
class BasicBinaryOperator < Operator
def BasicBinaryOperator.string(arg1, arg2, return_type)
if lang == C and (arg1.class == Variable and arg2.class == Variable) and (arg1.type.vector_length > 1 or arg2.type.vector_length > 1) then
instruction = intrinsics(intr_symbol, return_type.type)
a1 = convert(arg1, return_type.type)
a2 = convert(arg2, return_type.type)
return "#{instruction}( #{a1}, #{a2} )"
else
return basic_usage( arg1, arg2 )
end
end
end
class Minus < Operator
def Minus.string(arg1, arg2, return_type)
return " -(#{arg2})"
end
end
class Plus < Operator
def Plus.string(arg1, arg2, return_type)
return " +#{arg2}"
end
end
class Not < Operator
def Not.string(arg1, arg2, return_type)
return " (.not. (#{arg2}))" if lang == FORTRAN
return " !(#{arg2})"
end
end
class Reference < Operator
def Reference.string(arg1, arg2, return_type)
return " #{arg2}" if lang == FORTRAN
return " &#{arg2}"
end
end
class Dereference < Operator
def Dereference.string(arg1, arg2, return_type)
return " *(#{arg2})"
end
end
class Equal < Operator
def Equal.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Equal.basic_usage(arg1, arg2)
return "#{arg1} == #{arg2}"
end
end
class Different < Operator
def Different.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Different.basic_usage(arg1, arg2)
return "#{arg1} /= #{arg2}" if lang == FORTRAN
return "#{arg1} != #{arg2}"
end
end
class Greater < Operator
def Greater.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Greater.basic_usage(arg1, arg2)
return "#{arg1} > #{arg2}"
end
end
class Less < Operator
def Less.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Less.basic_usage(arg1, arg2)
return "#{arg1} < #{arg2}"
end
end
class GreaterOrEqual < Operator
def GreaterOrEqual.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def GreaterOrEqual.basic_usage(arg1, arg2)
return "#{arg1} >= #{arg2}"
end
end
class LessOrEqual < Operator
def LessOrEqual.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def LessOrEqual.basic_usage(arg1, arg2)
return "#{arg1} <= #{arg2}"
end
end
class And < Operator
def And.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def And.basic_usage(arg1, arg2)
return "#{arg1} .and. #{arg2}" if lang == FORTRAN
return "#{arg1} && #{arg2}"
end
end
class Or < Operator
def Or.string(arg1, arg2, return_type)
return basic_usage(arg1, arg2)
end
def Or.basic_usage(arg1, arg2)
return "#{arg1} .or. #{arg2}" if lang == FORTRAN
return "#{arg1} || #{arg2}"
end
end
class Affectation < Operator
def Affectation.string(arg1, arg2, return_type)
if arg1.class == Variable and arg1.type.vector_length > 1 then
return "#{arg1} = #{Load(arg2, arg1)}"
elsif arg2.class == Variable and arg2.type.vector_length > 1 then
return "#{Store(arg1, arg2, return_type)}"
end
return basic_usage(arg1, arg2)
end
def Affectation.basic_usage(arg1, arg2)
return "#{arg1} = #{arg2}"
end
end
class Exponentiation < BasicBinaryOperator
class << self
def symbol
return "**"
end
def intr_symbol
return :POW
end
def basic_usage(arg1, arg2)
return "(#{arg1})**(#{arg2})" if lang == FORTRAN
return "pow(#{arg1}, #{arg2})"
end
end
end
class Multiplication < BasicBinaryOperator
class << self
def symbol
return "*"
end
def intr_symbol
return :MUL
end
def basic_usage(arg1, arg2)
return "(#{arg1}) * (#{arg2})"
end
end
end
class Addition < BasicBinaryOperator
class << self
def symbol
return "+"
end
def intr_symbol
return :ADD
end
def basic_usage(arg1, arg2)
return "#{arg1} + #{arg2}"
end
end
end
class Substraction < BasicBinaryOperator
class << self
def symbol
return "-"
end
def intr_symbol
return :SUB
end
def basic_usage(arg1, arg2)
return "#{arg1} - (#{arg2})"
end
end
end
class Division < BasicBinaryOperator
class << self
def symbol
return "/"
end
def intr_symbol
return :DIV
end
def basic_usage(arg1, arg2)
return "(#{arg1}) / (#{arg2})"
end
end
end
class Set < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :source
attr_reader :return_type
def initialize(source, return_type)
@source = source
@return_type = return_type
end
def type
return @return_type.type
end
def to_var
if lang == C or lang == CL and @return_type.type.vector_length > 1 then
if @source.kind_of?( Array ) then
raise OperatorError, "Invalid array length!" unless @source.length == @return_type.type.vector_length
return @return_type.copy("(#{@return_type.type.decl})( #{@source.join(", ")} )", DISCARD_OPTIONS) if lang == CL
begin
instruction = intrinsics(:SET, @return_type.type)
return @return_type.copy("#{instruction}( #{@source.join(", ")} )", DISCARD_OPTIONS)
rescue IntrinsicsError
instruction = intrinsics(:SET_LANE, @return_type.type)
s = Set(0, @return_type).to_s
@source.each_with_index { |v,i|
s = "#{instruction}(#{v}, #{s}, #{i})"
}
return @return_type.copy(s, DISCARD_OPTIONS)
end
elsif @source.class != Variable or @source.type.vector_length == 1 then
return @return_type.copy("(#{@return_type.type.decl})( #{@source} )", DISCARD_OPTIONS) if lang == CL
instruction = intrinsics(:SET1, @return_type.type)
return @return_type.copy("#{instruction}( #{@source} )", DISCARD_OPTIONS)
elsif @return_type.type != @source.type
return @return_type.copy("#{Operator.convert(@source, @return_type.type)}", DISCARD_OPTIONS)
end
end
return @return_type.copy("#{@source}", DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class Load < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :source
attr_reader :return_type
def initialize(source, return_type)
@source = source
@return_type = return_type
end
def type
return @return_type.type
end
def to_var
if lang == C or lang == CL then
if @source.kind_of?(Array) then
return Set(@source, @return_type).to_var
elsif @source.class == Variable or @source.respond_to?(:to_var) then
if @source.to_var.type == @return_type.type
return @source.to_var
elsif @source.to_var.type.vector_length == 1 then
a2 = "#{@source}"
if a2[0] != "*" then
a2 = "&" + a2
else
a2 = a2[1..-1]
end
return @return_type.copy("vload#{@return_type.type.vector_length}(0, #{a2})", DISCARD_OPTIONS) if lang == CL
return @return_type.copy("_m_from_int64( *((int64_t * ) #{a2} ) )", DISCARD_OPTIONS) if get_architecture == X86 and @return_type.type.total_size*8 == 64
if @source.alignment == @return_type.type.total_size then
instruction = intrinsics(:LOADA, @return_type.type)
else
instruction = intrinsics(:LOAD, @return_type.type)
end
return @return_type.copy("#{instruction}( #{a2} )", DISCARD_OPTIONS)
else
return @return_type.copy("#{Operator.convert(@source, @return_type.type)}", DISCARD_OPTIONS)
end
end
end
return @return_type.copy("#{@source}", DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class MaskLoad < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :source
attr_reader :mask
attr_reader :return_type
def initialize(source, mask, return_type)
@source = source
@mask = mask
@return_type = return_type
end
def get_mask
raise OperatorError, "Mask size is wrong: #{@mask.length} for #{@return_type.type.vector_length}!" if @mask.length != @return_type.type.vector_length
return Load(@mask.collect { |m| ( m and m != 0 ) ? -1 : 0 }, Int("mask", :size => @return_type.type.size, :vector_length => @return_type.type.vector_length ) )
end
private :get_mask
def type
return @return_type.type
end
def to_var
raise OperatorError, "Cannot load unknown type!" unless @return_type
raise LanguageError, "Unsupported language!" unless lang == C
instruction = intrinsics(:MASKLOAD, @return_type.type)
s = ""
src = "#{@source}"
if src[0] != "*" then
src = "&" + src
else
src = src[1..-1]
end
p_type = @return_type.type.copy(:vector_length => 1)
s += "#{instruction}((#{p_type.decl} * )#{src}, #{get_mask})"
return @return_type.copy( s, DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class Store < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :dest
attr_reader :source
attr_reader :store_type
def initialize(dest, source, mask, store_type = nil)
@dest = dest
@source = source
@store_type = store_type
@store_type = source unless @store_type
end
def to_s
if lang == C or lang == CL then
dst = "#{@dest}"
if dst[0] != "*" then
dst = "&" + dst
else
dst = dst[1..-1]
end
return "vstore#{@source.type.vector_length}(#{@source}, 0, #{dst})" if lang == CL
return "*((int64_t * ) #{dst}) = _m_to_int64( #{@source} )" if get_architecture == X86 and @source.type.total_size*8 == 64
if @dest.alignment == @source.type.total_size then
instruction = intrinsics(:STOREA, @source.type)
else
instruction = intrinsics(:STORE, @source.type)
end
p_type = @source.type.copy(:vector_length => 1)
p_type = @source.type if get_architecture == X86 and @source.type.kind_of?(Int)
return "#{instruction}( (#{p_type.decl} * ) #{dst}, #{@source} )"
end
return Affectation.basic_usage(@dest, @source)
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class MaskStore < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :dest
attr_reader :source
attr_reader :mask
attr_reader :store_type
def initialize(dest, source, mask, store_type = nil)
@dest = dest
@source = source
@mask = mask
@store_type = store_type
@store_type = source unless @store_type
end
def get_mask
raise OperatorError, "Mask size is wrong: #{@mask.length} for #{@store_type.type.vector_length}!" if @mask.length != @store_type.type.vector_length
return Load.to_s(@mask.collect { |m| ( m and m != 0 ) ? -1 : 0 }, Int("mask", :size => @store_type.type.size, :vector_length => @store_type.type.vector_length ) )
end
private :get_mask
def to_s
raise OperatorError, "Cannot store unknown type!" unless @store_type
raise LanguageError, "Unsupported language!" unless lang == C
instruction = intrinsics(:MASKSTORE, @store_type.type)
s = ""
dst = "#{@dest}"
if dst[0] != "*" then
dst = "&" + dst
else
dst = dst[1..-1]
end
p_type = @store_type.type.copy(:vector_length => 1)
return s += "#{instruction}((#{p_type.decl} * )#{dst}, #{get_mask}, #{Operator.convert(@source, @store_type.type)})"
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class FMA < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :operand1
attr_reader :operand2
attr_reader :operand3
attr_reader :return_type
def initialize(a,b,c)
@operand1 = a
@operand2 = b
@operand3 = c
@return_type = nil
@return_type = @operand3.to_var unless @return_type
end
def convert_operand(op)
return "#{Operator.convert(op, @return_type.type)}"
end
private :convert_operand
def type
return @return_type.type
end
def to_var
instruction = nil
begin
instruction = intrinsics(:FMADD,@return_type.type)
rescue
end
return (@operand3 + @operand1 * @operand2).to_var unless lang != FORTRAN and @return_type and ( instruction or ( [CL, CUDA].include?(lang) ) )
op1 = convert_operand(@operand1.to_var)
op2 = convert_operand(@operand2.to_var)
op3 = convert_operand(@operand3.to_var)
if [CL, CUDA].include?(lang)
ret_name = "fma( #{op1}, #{op2}, #{op3} )"
else
case architecture
when X86
ret_name = "#{instruction}( #{op1}, #{op2}, #{op3} )"
when ARM
ret_name = "#{instruction}( #{op3}, #{op1}, #{op2} )"
else
return (@operand3 + @operand1 * @operand2).to_var
end
end
return @return_type.copy( ret_name, DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class FMS < Operator
extend Functor
include Intrinsics
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :operand1
attr_reader :operand2
attr_reader :operand3
attr_reader :return_type
def initialize(a,b,c)
@operand1 = a
@operand2 = b
@operand3 = c
@return_type = nil
@return_type = @operand3.to_var unless @return_type
end
def convert_operand(op)
return "#{Operator.convert(op, @return_type.type)}"
end
private :convert_operand
def type
return @return_type.type
end
def to_var
instruction = nil
begin
instruction = intrinsics(:FNMADD,@return_type.type)
rescue
end
return (@operand3 - @operand1 * @operand2).to_var unless lang != FORTRAN and @return_type and ( instruction or ( [CL, CUDA].include?(lang) ) )
op1 = convert_operand(@operand1.to_var)
op2 = convert_operand(@operand2.to_var)
op3 = convert_operand(@operand3.to_var)
if [CL, CUDA].include?(lang)
op1 = convert_operand((-@operand1).to_var)
ret_name = "fma( #{op1}, #{op2}, #{op3} )"
else
case architecture
when X86
ret_name = "#{instruction}( #{op1}, #{op2}, #{op3} )"
when ARM
ret_name = "#{instruction}( #{op3}, #{op1}, #{op2} )"
else
return (@operand3 - @operand1 * @operand2).to_var
end
end
return @return_type.copy( ret_name, DISCARD_OPTIONS)
end
def to_s
return to_var.to_s
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
class Ternary
extend Functor
include Arithmetic
include Inspectable
include PrivateStateAccessor
attr_reader :operand1
attr_reader :operand2
attr_reader :operand3
def initialize(x,y,z)
@operand1 = x
@operand2 = y
@operand3 = z
end
def op_to_var
op1 = @operand1.respond_to?(:to_var) ? @operand1.to_var : @operand1
op1 = @operand1 unless op1
op2 = @operand2.respond_to?(:to_var) ? @operand2.to_var : @operand2
op2 = @operand2 unless op2
op3 = @operand3.respond_to?(:to_var) ? @operand3.to_var : @operand3
op3 = @operand3 unless op3
return [op1, op2, op3]
end
private :op_to_var
def to_s
return to_s_fortran if lang == FORTRAN
return to_s_c if [C, CL, CUDA].include?( lang )
end
def to_s_fortran
op1, op2, op3 = op_to_var
"merge(#{op2}, #{op3}, #{op1})"
end
def to_s_c
op1, op2, op3 = op_to_var
"(#{op1} ? #{op2} : #{op3})"
end
def pr
s=""
s += indent
s += to_s
s += ";" if [C, CL, CUDA].include?( lang )
output.puts s
return self
end
end
end
|
module BOAST
class Procedure
include PrivateStateAccessor
include Inspectable
extend Functor
attr_reader :name
attr_reader :parameters
attr_reader :constants
attr_reader :properties
attr_reader :headers
def initialize(name, parameters=[], constants=[], properties={}, &block)
@name = name
@parameters = parameters
@constants = constants
@block = block
@properties = properties
@headers = properties[:headers]
@headers = [] if not @headers
end
def boast_header_s( lang=C )
s = ""
headers.each { |h|
s += "#include <#{h}>\n"
}
if lang == CL then
s += "__kernel "
wgs = @properties[:reqd_work_group_size]
if wgs then
s += "__attribute__((reqd_work_group_size(#{wgs[0]},#{wgs[1]},#{wgs[2]}))) "
end
end
trailer = ""
trailer += "_" if lang == FORTRAN
trailer += "_wrapper" if lang == CUDA
if @properties[:return] then
s += "#{@properties[:return].type.decl} "
elsif lang == CUDA
s += "unsigned long long int "
else
s += "void "
end
s += "#{@name}#{trailer}("
if parameters.first then
s += parameters.first.boast_header(lang)
parameters[1..-1].each { |p|
s += ", "
s += p.boast_header(lang)
}
end
if lang == CUDA then
s += ", " if parameters.first
s += "size_t *block_number, size_t *block_size"
end
s += ")"
return s
end
def boast_header(lang=C)
s = boast_header_s(lang)
s += ";\n"
output.print s
return self
end
def call(*parameters)
prefix = ""
prefix += "call " if lang==FORTRAN
f = FuncCall::new(@name, *parameters)
f.prefix = prefix
return f
end
def close
return close_fortran if lang==FORTRAN
return close_c if [C, CL, CUDA].include?( lang )
end
def ckernel
old_output = output
k = CKernel::new
k.procedure = self
self.pr
set_output( old_output )
return k
end
def close_c
s = ""
s += indent + "return #{@properties[:return]};\n" if @properties[:return]
decrement_indent_level
s += indent + "}"
output.puts s
return self
end
def close_fortran
s = ""
if @properties[:return] then
s += indent + "#{@name} = #{@properties[:return]}\n"
decrement_indent_level
s += indent + "END FUNCTION #{@name}"
else
decrement_indent_level
s += indent + "END SUBROUTINE #{@name}"
end
output.puts s
return self
end
def pr
open
if @block then
@block.call
close
end
return self
end
def decl
return decl_fortran if lang==FORTRAN
return decl_c if [C, CL, CUDA].include?( lang )
end
def decl_fortran
output.puts indent + "INTERFACE"
increment_indent_level
open_fortran
close_fortran
decrement_indent_level
output.puts indent + "END INTERFACE"
return self
end
def decl_c_s
s = ""
if lang == CL then
if @properties[:local] then
s += "#if __OPENCL_C_VERSION__ && __OPENCL_C_VERSION__ >= 120\n"
s += "static\n"
s += "#endif\n"
else
s += "__kernel "
wgs = @properties[:reqd_work_group_size]
if wgs then
s += "__attribute__((reqd_work_group_size(#{wgs[0]},#{wgs[1]},#{wgs[2]}))) "
end
end
elsif lang == CUDA then
if @properties[:local] then
s += "static __device__ "
else
s += "__global__ "
wgs = @properties[:reqd_work_group_size]
if wgs then
s += "__launch_bounds__(#{wgs[0]}*#{wgs[1]}*#{wgs[2]}) "
end
end
elsif lang == C then
if @properties[:local] then
s += "static "
end
if @properties[:inline] then
s+= "inline "
end
end
if @properties[:qualifiers] then
s += "#{@properties[:qualifiers]} "
end
if @properties[:return] then
s += "#{@properties[:return].type.decl} "
else
s += "void "
end
s += "#{@name}("
if parameters.first then
s += parameters.first.decl_c_s(@properties[:local])
parameters[1..-1].each { |p|
s += ", "+p.decl_c_s(@properties[:local])
}
end
s += ")"
return s
end
def decl_c
s = indent + decl_c_s + ";"
output.puts s
return self
end
def open
return open_fortran if lang==FORTRAN
return open_c if [C, CL, CUDA].include?( lang )
end
def to_s
return decl_c_s if [C, CL, CUDA].include?( lang )
return to_s_fortran if lang==FORTRAN
end
def to_s_fortran
s = ""
if @properties[:return] then
s += "#{@properties[:return].type.decl} FUNCTION "
else
s += "SUBROUTINE "
end
s += "#{@name}("
s += parameters.join(", ")
s += ")"
end
def open_c
s = decl_c_s + "{"
output.puts s
increment_indent_level
constants.each { |c|
c.decl
}
if lang == C then
parameters.each { |p|
p.pr_align
}
end
return self
end
def open_fortran
s = indent + to_s_fortran
s += "\n"
increment_indent_level
s += indent + "integer, parameter :: wp=kind(1.0d0)"
output.puts s
constants.each { |c|
c.decl
}
parameters.each { |p|
p.decl
p.pr_align
}
return self
end
end
end
FORTRAN can take procedure as argument.
module BOAST
class Procedure
include PrivateStateAccessor
include Inspectable
extend Functor
attr_reader :name
attr_reader :parameters
attr_reader :constants
attr_reader :properties
attr_reader :headers
def initialize(name, parameters=[], constants=[], properties={}, &block)
@name = name
@parameters = parameters
@constants = constants
@block = block
@properties = properties
@headers = properties[:headers]
@headers = [] if not @headers
end
def boast_header_s( lang=C )
s = ""
headers.each { |h|
s += "#include <#{h}>\n"
}
if lang == CL then
s += "__kernel "
wgs = @properties[:reqd_work_group_size]
if wgs then
s += "__attribute__((reqd_work_group_size(#{wgs[0]},#{wgs[1]},#{wgs[2]}))) "
end
end
trailer = ""
trailer += "_" if lang == FORTRAN
trailer += "_wrapper" if lang == CUDA
if @properties[:return] then
s += "#{@properties[:return].type.decl} "
elsif lang == CUDA
s += "unsigned long long int "
else
s += "void "
end
s += "#{@name}#{trailer}("
if parameters.first then
s += parameters.first.boast_header(lang)
parameters[1..-1].each { |p|
s += ", "
s += p.boast_header(lang)
}
end
if lang == CUDA then
s += ", " if parameters.first
s += "size_t *block_number, size_t *block_size"
end
s += ")"
return s
end
def boast_header(lang=C)
s = boast_header_s(lang)
s += ";\n"
output.print s
return self
end
def call(*parameters)
prefix = ""
prefix += "call " if lang==FORTRAN
f = FuncCall::new(@name, *parameters)
f.prefix = prefix
return f
end
def close
return close_fortran if lang==FORTRAN
return close_c if [C, CL, CUDA].include?( lang )
end
def ckernel
old_output = output
k = CKernel::new
k.procedure = self
self.pr
set_output( old_output )
return k
end
def close_c
s = ""
s += indent + "return #{@properties[:return]};\n" if @properties[:return]
decrement_indent_level
s += indent + "}"
output.puts s
return self
end
def close_fortran
s = ""
if @properties[:return] then
s += indent + "#{@name} = #{@properties[:return]}\n"
decrement_indent_level
s += indent + "END FUNCTION #{@name}"
else
decrement_indent_level
s += indent + "END SUBROUTINE #{@name}"
end
output.puts s
return self
end
def pr
open
if @block then
@block.call
close
end
return self
end
def decl
return decl_fortran if lang==FORTRAN
return decl_c if [C, CL, CUDA].include?( lang )
end
def decl_fortran
output.puts indent + "INTERFACE"
increment_indent_level
open_fortran
close_fortran
decrement_indent_level
output.puts indent + "END INTERFACE"
return self
end
def decl_c_s
s = ""
if lang == CL then
if @properties[:local] then
s += "#if __OPENCL_C_VERSION__ && __OPENCL_C_VERSION__ >= 120\n"
s += "static\n"
s += "#endif\n"
else
s += "__kernel "
wgs = @properties[:reqd_work_group_size]
if wgs then
s += "__attribute__((reqd_work_group_size(#{wgs[0]},#{wgs[1]},#{wgs[2]}))) "
end
end
elsif lang == CUDA then
if @properties[:local] then
s += "static __device__ "
else
s += "__global__ "
wgs = @properties[:reqd_work_group_size]
if wgs then
s += "__launch_bounds__(#{wgs[0]}*#{wgs[1]}*#{wgs[2]}) "
end
end
elsif lang == C then
if @properties[:local] then
s += "static "
end
if @properties[:inline] then
s+= "inline "
end
end
if @properties[:qualifiers] then
s += "#{@properties[:qualifiers]} "
end
if @properties[:return] then
s += "#{@properties[:return].type.decl} "
else
s += "void "
end
s += "#{@name}("
if parameters.first then
s += parameters.first.decl_c_s(@properties[:local])
parameters[1..-1].each { |p|
s += ", "+p.decl_c_s(@properties[:local])
}
end
s += ")"
return s
end
def decl_c
s = indent + decl_c_s + ";"
output.puts s
return self
end
def open
return open_fortran if lang==FORTRAN
return open_c if [C, CL, CUDA].include?( lang )
end
def to_s
return decl_c_s if [C, CL, CUDA].include?( lang )
return to_s_fortran if lang==FORTRAN
end
def to_s_fortran
s = ""
if @properties[:return] then
s += "#{@properties[:return].type.decl} FUNCTION "
else
s += "SUBROUTINE "
end
s += "#{@name}("
s += parameters.collect(&:name).join(", ")
s += ")"
end
def pr_align
end
def open_c
s = decl_c_s + "{"
output.puts s
increment_indent_level
constants.each { |c|
c.decl
}
if lang == C then
parameters.each { |p|
p.pr_align
}
end
return self
end
def open_fortran
s = indent + to_s_fortran
s += "\n"
increment_indent_level
s += indent + "integer, parameter :: wp=kind(1.0d0)"
output.puts s
constants.each { |c|
c.decl
}
parameters.each { |p|
p.decl
p.pr_align
}
return self
end
end
end
|
module Daun
##
# Produce git refs differences before and after fetch
class RefsDiff
attr_accessor :added_remotes
def initialize(before, after)
@before = before
@after = after
end
def added(type = nil)
keys = (@after.keys - @before.keys).collect(&:to_s)
filter(keys, type)
end
def updated(type = nil)
keys = (@after.keys + @before.keys)
.group_by { |k| k }
.select { |k, k_group| k_group.size > 1 && @before[k] != @after[k] }
.keys.collect(&:to_s)
filter(keys, type)
end
def deleted(type = nil)
keys = (@before.keys - @after.keys).collect(&:to_s)
filter(keys, type)
end
private
def filter(keys, type)
!type.nil? ? keys.select { |k| k.start_with? "refs/#{type}" } : keys
end
end
end
Add yardoc to refs_diff.
module Daun
##
# Produce git refs differences before and after fetch
class RefsDiff
attr_accessor :added_remotes
# Creates a new instance of `RefsDiff`.
#
# @param before [Hash] the refs hash with full refs format as key and commit id as value
# @param after [Hash] the refs hash with full refs format as key and commit id as value
def initialize(before, after)
@before = before
@after = after
end
# Returns all of the refs that have been added after the fetch. These are the refs
# that exists in `after` but not `before`.
#
# @param type [Symbol] :tag for tag refs, :remotes for remote branches, nil for everything
def added(type = nil)
keys = (@after.keys - @before.keys).collect(&:to_s)
filter(keys, type)
end
# Returns all of the refs that have been updated after the fetch. Updated refs
# are detected when refs exists in both `before` and `after` but is having a
# different commit id in the `Hash`.
#
# @param type [Symbol] :tag for tag refs, :remotes for remote branches, nil for everything
def updated(type = nil)
keys = (@after.keys + @before.keys)
.group_by { |k| k }
.select { |k, k_group| k_group.size > 1 && @before[k] != @after[k] }
.keys.collect(&:to_s)
filter(keys, type)
end
# Returns all of the refs that have been deleted after the fetch. These are the
# refs that exists in `before` but not `after`
#
# @param type [Symbol] :tag for tag refs, :remotes for remote branches, nil for everything
def deleted(type = nil)
keys = (@before.keys - @after.keys).collect(&:to_s)
filter(keys, type)
end
private
def filter(keys, type)
!type.nil? ? keys.select { |k| k.start_with? "refs/#{type}" } : keys
end
end
end
|
module Daybreak
# Thread safe job queue
# @api private
class Queue
# HACK: Dangerous optimization on MRI which has a
# global interpreter lock and makes the @queue array
# thread safe.
if !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby'
def initialize
@queue, @full, @empty = [], [], []
@stop = false
@heartbeat = Thread.new(&method(:heartbeat))
@heartbeat.priority = -9
end
def <<(x)
@queue << x
thread = @full.shift
thread.wakeup if thread
end
def pop
@queue.shift
if @queue.empty?
thread = @empty.shift
thread.wakeup if thread
end
end
def next
while @queue.empty?
begin
@full << Thread.current
# If a push happens before Thread.stop, the thread won't be woken up
Thread.stop if @queue.empty?
ensure
@full.delete(Thread.current)
end
end
@queue.first
end
def flush
until @queue.empty?
begin
@empty << Thread.current
# If a pop happens before Thread.stop, the thread won't be woken up
Thread.stop unless @queue.empty?
ensure
@empty.delete(Thread.current)
end
end
end
def stop
@stop = true
@heartbeat.join
end
private
# Check threads 10 times per second to avoid deadlocks
# since there is a race condition below
def heartbeat
until @stop
unless @full.empty? || @empty.empty?
warn 'Daybreak queue: Deadlock detected'
@full.each(&:wakeup)
@empty.each(&:wakeup)
end
sleep 0.1
end
end
else
def initialize
@mutex = Mutex.new
@full = ConditionVariable.new
@empty = ConditionVariable.new
@queue = []
end
def <<(x)
@mutex.synchronize do
@queue << x
@full.signal
end
end
def pop
@mutex.synchronize do
@queue.shift
@empty.signal if @queue.empty?
end
end
def next
@mutex.synchronize do
@full.wait(@mutex) while @queue.empty?
@queue.first
end
end
def flush
@mutex.synchronize do
@empty.wait(@mutex) until @queue.empty?
end
end
end
end
end
fix deadlock
close issue #16
module Daybreak
# Thread safe job queue
# @api private
class Queue
# HACK: Dangerous optimization on MRI which has a
# global interpreter lock and makes the @queue array
# thread safe.
if !defined?(RUBY_ENGINE) || RUBY_ENGINE == 'ruby'
def initialize
@queue, @full, @empty = [], [], []
@stop = false
@heartbeat = Thread.new(&method(:heartbeat))
@heartbeat.priority = -9
end
def <<(x)
@queue << x
thread = @full.first
thread.wakeup if thread
end
def pop
@queue.shift
if @queue.empty?
thread = @empty.first
thread.wakeup if thread
end
end
def next
while @queue.empty?
begin
@full << Thread.current
# If a push happens before Thread.stop, the thread won't be woken up
Thread.stop while @queue.empty?
ensure
@full.delete(Thread.current)
end
end
@queue.first
end
def flush
until @queue.empty?
begin
@empty << Thread.current
# If a pop happens before Thread.stop, the thread won't be woken up
Thread.stop until @queue.empty?
ensure
@empty.delete(Thread.current)
end
end
end
def stop
@stop = true
@heartbeat.join
end
private
# Check threads 10 times per second to avoid deadlocks
# since there is a race condition below
def heartbeat
until @stop
@empty.each(&:wakeup)
@full.each(&:wakeup)
sleep 0.1
end
end
else
def initialize
@mutex = Mutex.new
@full = ConditionVariable.new
@empty = ConditionVariable.new
@queue = []
end
def <<(x)
@mutex.synchronize do
@queue << x
@full.signal
end
end
def pop
@mutex.synchronize do
@queue.shift
@empty.signal if @queue.empty?
end
end
def next
@mutex.synchronize do
@full.wait(@mutex) while @queue.empty?
@queue.first
end
end
def flush
@mutex.synchronize do
@empty.wait(@mutex) until @queue.empty?
end
end
end
end
end
|
require 'thor/shell/color'
module DeploYML
#
# Provides common methods used by both {LocalShell} and {RemoteShell}.
#
module Shell
include Thor::Shell
def initialize
yield self if block_given?
end
#
# Place-holder method.
#
# @param [String] program
# The name or path of the program to run.
#
# @param [Array<String>] args
# Additional arguments for the program.
#
def run(program,*args)
end
#
# Place-holder method.
#
# @param [String] message
# Message to echo.
#
# @since 0.4.0
#
def echo(message)
end
#
# Executes a Rake task.
#
# @param [Symbol, String] task
# Name of the Rake task to run.
#
# @param [Array<String>] args
# Additional arguments for the Rake task.
#
def rake(task,*args)
run 'rake', rake_task(task,*args)
end
#
# Prints a status message.
#
# @param [String] message
# The message to print.
#
# @since 0.4.0
#
def status(message)
echo "#{Color::GREEN}>>> #{message}#{Color::CLEAR}"
end
protected
#
# Builds a `rake` task name.
#
# @param [String, Symbol] name
# The name of the `rake` task.
#
# @param [Array] args
# Additional arguments to pass to the `rake` task.
#
# @param [String]
# The `rake` task name to be called.
#
def rake_task(name,*args)
name = name.to_s
unless args.empty?
name += ('[' + args.join(',') + ']')
end
return name
end
end
end
Remove place holder methods from DeploYML::Shell.
require 'thor/shell/color'
module DeploYML
#
# Provides common methods used by both {LocalShell} and {RemoteShell}.
#
module Shell
include Thor::Shell
def initialize
yield self if block_given?
end
#
# Executes a Rake task.
#
# @param [Symbol, String] task
# Name of the Rake task to run.
#
# @param [Array<String>] args
# Additional arguments for the Rake task.
#
def rake(task,*args)
run 'rake', rake_task(task,*args)
end
#
# Prints a status message.
#
# @param [String] message
# The message to print.
#
# @since 0.4.0
#
def status(message)
echo "#{Color::GREEN}>>> #{message}#{Color::CLEAR}"
end
protected
#
# Builds a `rake` task name.
#
# @param [String, Symbol] name
# The name of the `rake` task.
#
# @param [Array] args
# Additional arguments to pass to the `rake` task.
#
# @param [String]
# The `rake` task name to be called.
#
def rake_task(name,*args)
name = name.to_s
unless args.empty?
name += ('[' + args.join(',') + ']')
end
return name
end
end
end
|
require 'devinstall'
require 'getopt/long'
require 'devinstall/settings'
module Devinstall
class Cli
include Utils
def get_config(fnames)
fnames.each do |f|
(@opt['config'] ||= (File.expand_path(f) if File.exist? f)) and break
end
@opt['config']
end
def initialize(*package)
begin
@opt = Getopt::Long.getopts(
['--config', '-c', Getopt::REQUIRED],
['--type', '-t', Getopt::REQUIRED],
['--env', '-e', Getopt::REQUIRED],
['--verbose', '-v'],
['--dry-run', '-d'],
)
rescue
puts 'Invalid option in command line'
help
end
#verbose and dry-run
$verbose ||= @opt['verbose']
$dry ||= @opt['dry-run']
# get config file
unless get_config(["./devinstall.yml"])
exit! 'You must specify the config file'
end
# parse config file
Settings.load!(@opt['config'])
# complete from default values
if Settings.defaults # We have to check for the defaults before (no autovivification :( )
%w"package env type".each { |o| @opt[o] ||= Settings.defaults[o.to_sym] if Settings.defaults[o.to_sym] }
end
# verify all informations
if package # a packege was supplied on commandline
package.each {|p| @opt['package'] << p }# this overrides all
end
%w"package type env".each do |k|
unless @opt[k]
puts "You must specify option '#{k}' either as default or in command line"
help
end
end
# create package
end
def build
@opt['packages'] do |package|
pk=Devinstall::Pkg.new(package)
pk.build(@opt['type'].to_sym)
end
end
def install
@opt['packages'] do |package|
pk=Devinstall::Pkg.new(package)
pk.build(@opt['type'].to_sym)
pk.install(@opt['env'].to_sym)
end
end
def upload
@opt['packages'].each do |package|
pk=Devinstall::Pkg.new(package)
pk.build(@opt['type'].to_sym)
pk.run_tests(@opt['env'].to_sym)
pk.upload(@opt['env'].to_sym)
end
end
def test
@opt['package'].each do |package|
pk=Devinstall::Pkg.new(package)
pk.run_tests(@opt['env'].to_sym)
end
end
def help
puts 'Usage:'
puts 'pkg-tool command [package_name ... ] --config|-c <file> --type|-t <package_type> --env|-e <environment>'
puts 'where command is one of the: build, install, upload, help, version'
exit! 0
end
def version
puts "devinstall version #{Devinstall::VERSION}"
puts "pkg-tool version #{Devinstall::VERSION}"
exit! 0
end
end
end
move misplaced comment
require 'devinstall'
require 'getopt/long'
require 'devinstall/settings'
module Devinstall
class Cli
include Utils
def get_config(fnames)
fnames.each do |f|
(@opt['config'] ||= (File.expand_path(f) if File.exist? f)) and break
end
@opt['config']
end
def initialize(*package)
begin
@opt = Getopt::Long.getopts(
['--config', '-c', Getopt::REQUIRED],
['--type', '-t', Getopt::REQUIRED],
['--env', '-e', Getopt::REQUIRED],
['--verbose', '-v'],
['--dry-run', '-d'],
)
rescue
puts 'Invalid option in command line'
help
end
#verbose and dry-run
$verbose ||= @opt['verbose']
$dry ||= @opt['dry-run']
# get config file
unless get_config(["./devinstall.yml"])
exit! 'You must specify the config file'
end
# parse config file
Settings.load!(@opt['config'])
# complete from default values
if Settings.defaults # We have to check for the defaults before (no autovivification :( )
%w"package env type".each { |o| @opt[o] ||= Settings.defaults[o.to_sym] if Settings.defaults[o.to_sym] }
end
# verify all informations
if package # a packege was supplied on commandline
package.each {|p| @opt['package'] << p }# this overrides all
end
%w"package type env".each do |k|
unless @opt[k]
puts "You must specify option '#{k}' either as default or in command line"
help
end
end
end
def build
# create package
@opt['packages'] do |package|
pk=Devinstall::Pkg.new(package)
pk.build(@opt['type'].to_sym)
end
end
def install
@opt['packages'] do |package|
pk=Devinstall::Pkg.new(package)
pk.build(@opt['type'].to_sym)
pk.install(@opt['env'].to_sym)
end
end
def upload
@opt['packages'].each do |package|
pk=Devinstall::Pkg.new(package)
pk.build(@opt['type'].to_sym)
pk.run_tests(@opt['env'].to_sym)
pk.upload(@opt['env'].to_sym)
end
end
def test
@opt['package'].each do |package|
pk=Devinstall::Pkg.new(package)
pk.run_tests(@opt['env'].to_sym)
end
end
def help
puts 'Usage:'
puts 'pkg-tool command [package_name ... ] --config|-c <file> --type|-t <package_type> --env|-e <environment>'
puts 'where command is one of the: build, install, upload, help, version'
exit! 0
end
def version
puts "devinstall version #{Devinstall::VERSION}"
puts "pkg-tool version #{Devinstall::VERSION}"
exit! 0
end
end
end
|
# frozen_string_literal: true
module Dome
class Terraform
include Dome::Shell
include Dome::Level
attr_reader :state
def initialize
case level
when 'environment'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.account}-#{@environment.environment}-plan.tf"
puts '--- Environment terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when 'ecosystem'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Ecosystem terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when 'product'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Product terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when 'roles'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Role terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when /^secrets-/
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Secrets terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
else
puts '[*] Dome is meant to run from either a product,ecosystem,environment,role or secrets level'
raise Dome::InvalidLevelError.new, level
end
end
# TODO: this method is a bit of a mess and needs looking at
# FIXME: Simplify *validate_environment*
# rubocop:disable Metrics/PerceivedComplexity
def validate_environment
case level
when 'environment'
puts '--- AWS credentials for accessing environment state ---'
environment = @environment.environment
account = @environment.account
@environment.invalid_account_message unless @environment.valid_account? account
@environment.invalid_environment_message unless @environment.valid_environment? environment
@environment.unset_aws_keys
@environment.aws_credentials
when 'ecosystem'
puts '--- AWS credentials for accessing ecosystem state ---'
@environment.unset_aws_keys
@environment.aws_credentials
when 'product'
puts '--- AWS credentials for accessing product state ---'
@environment.unset_aws_keys
@environment.aws_credentials
when 'roles'
puts '--- AWS credentials for accessing roles state ---'
environment = @environment.environment
account = @environment.account
@environment.invalid_account_message unless @environment.valid_account? account
@environment.invalid_environment_message unless @environment.valid_environment? environment
@environment.unset_aws_keys
@environment.aws_credentials
when /^secrets-/
puts '--- AWS credentials for accessing secrets state ---'
environment = @environment.environment
account = @environment.account
@environment.invalid_account_message unless @environment.valid_account? account
@environment.invalid_environment_message unless @environment.valid_environment? environment
@environment.unset_aws_keys
@environment.aws_credentials
puts '--- Vault login ---'
begin
require 'vault/helper'
rescue LoadError
raise '[!] Failed to load vault/helper. Please add \
"gem \'hiera-vault\', git: \'git@github.com:ITV/hiera-vault\', ref: \'v1.0.0\'" or later to your Gemfile'.colorize(:red)
end
product = ENV['TF_VAR_product']
environment_name = @environment.environment
Vault.address = "https://secrets.#{environment_name}.#{product}.itv.com:8200"
case level
when 'secrets-init'
role = 'service_administrator'
unless Vault::Helper.initialized?
init_user = ENV['VAULT_INIT_USER'] || 'tomclar'
keys = Vault::Helper.init(init_user: init_user, token_file: nil)
puts "[*] Root token for #{init_user}: #{keys[:root_token]}".colorize(:yellow)
puts "[*] Recovery key for #{init_user}: #{keys[:recovery_key]}".colorize(:yellow)
raise "Vault not initialized, send the keys printed above to #{init_user} to finish initialization."
end
when 'secrets-config'
role = 'content_administrator'
else
raise Dome::InvalidLevelError.new, level
end
if ENV['VAULT_TOKEN']
puts '[*] Using VAULT_TOKEN environment variable'.colorize(:yellow)
Vault.token = ENV['VAULT_TOKEN']
else
puts "[*] Logging in as: #{role}"
Vault::Helper.login(role)
end
puts ''
else
raise Dome::InvalidLevelError.new, level
end
end
# rubocop:enable Metrics/PerceivedComplexity
def plan
puts '--- Decrypting hiera secrets and pass them as TF_VARs ---'
@secrets.secret_env_vars
puts '--- Deleting old plans'
# delete_terraform_directory # Don't delete it
delete_plan_file
@state.s3_state
puts
puts '--- Terraform init & plan ---'
puts
terraform_init
puts
create_plan
puts
end
def apply
@secrets.secret_env_vars
command = "terraform apply #{@plan_file}"
failure_message = '[!] something went wrong when applying the TF plan'
@state.s3_state
execute_command(command, failure_message)
end
def refresh
command = 'terraform refresh'
failure_message = '[!] something went wrong when doing terraform refresh'
execute_command(command, failure_message)
end
def statecmd(arguments)
command = "terraform state #{arguments}"
failure_message = "[!] something went wrong when doing terraform state #{arguments}"
execute_command(command, failure_message)
end
def console
@secrets.secret_env_vars
command = 'terraform console'
failure_message = '[!] something went wrong when doing terraform console'
execute_command(command, failure_message)
end
def create_plan
case level
when 'environment'
@secrets.extract_certs
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file} -var-file=params/env.tfvars"
failure_message = '[!] something went wrong when creating the environment TF plan'
execute_command(command, failure_message)
when 'ecosystem'
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the ecosystem TF plan'
execute_command(command, failure_message)
when 'product'
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the product TF plan'
execute_command(command, failure_message)
when 'roles'
@secrets.extract_certs
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the role TF plan'
execute_command(command, failure_message)
when /^secrets-/
@secrets.extract_certs
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the role TF plan'
execute_command(command, failure_message)
else
raise Dome::InvalidLevelError.new, level
end
end
def delete_terraform_directory
puts '[*] Deleting terraform module cache dir ...'.colorize(:green)
terraform_directory = '.terraform'
FileUtils.rm_rf terraform_directory
end
def delete_plan_file
puts '[*] Deleting previous terraform plan ...'.colorize(:green)
FileUtils.rm_f @plan_file
end
def init
@state.s3_state
sleep 5
terraform_init
end
def terraform_init
command = 'terraform init'
failure_message = 'something went wrong when initialising TF'
execute_command(command, failure_message)
end
def output
command = 'terraform output'
failure_message = 'something went wrong when printing TF output variables'
execute_command(command, failure_message)
end
end
end
Remove token_file parameter.
# frozen_string_literal: true
module Dome
class Terraform
include Dome::Shell
include Dome::Level
attr_reader :state
def initialize
case level
when 'environment'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.account}-#{@environment.environment}-plan.tf"
puts '--- Environment terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when 'ecosystem'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Ecosystem terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when 'product'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Product terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when 'roles'
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Role terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
when /^secrets-/
@environment = Dome::Environment.new
@secrets = Dome::Secrets.new(@environment)
@state = Dome::State.new(@environment)
@plan_file = "plans/#{@environment.level}-plan.tf"
puts '--- Secrets terraform state location ---'
puts "[*] S3 bucket name: #{@state.state_bucket_name.colorize(:green)}"
puts "[*] S3 object name: #{@state.state_file_name.colorize(:green)}"
puts
else
puts '[*] Dome is meant to run from either a product,ecosystem,environment,role or secrets level'
raise Dome::InvalidLevelError.new, level
end
end
# TODO: this method is a bit of a mess and needs looking at
# FIXME: Simplify *validate_environment*
# rubocop:disable Metrics/PerceivedComplexity
def validate_environment
case level
when 'environment'
puts '--- AWS credentials for accessing environment state ---'
environment = @environment.environment
account = @environment.account
@environment.invalid_account_message unless @environment.valid_account? account
@environment.invalid_environment_message unless @environment.valid_environment? environment
@environment.unset_aws_keys
@environment.aws_credentials
when 'ecosystem'
puts '--- AWS credentials for accessing ecosystem state ---'
@environment.unset_aws_keys
@environment.aws_credentials
when 'product'
puts '--- AWS credentials for accessing product state ---'
@environment.unset_aws_keys
@environment.aws_credentials
when 'roles'
puts '--- AWS credentials for accessing roles state ---'
environment = @environment.environment
account = @environment.account
@environment.invalid_account_message unless @environment.valid_account? account
@environment.invalid_environment_message unless @environment.valid_environment? environment
@environment.unset_aws_keys
@environment.aws_credentials
when /^secrets-/
puts '--- AWS credentials for accessing secrets state ---'
environment = @environment.environment
account = @environment.account
@environment.invalid_account_message unless @environment.valid_account? account
@environment.invalid_environment_message unless @environment.valid_environment? environment
@environment.unset_aws_keys
@environment.aws_credentials
puts '--- Vault login ---'
begin
require 'vault/helper'
rescue LoadError
raise '[!] Failed to load vault/helper. Please add \
"gem \'hiera-vault\', git: \'git@github.com:ITV/hiera-vault\', ref: \'v1.0.0\'" or later to your Gemfile'.colorize(:red)
end
product = ENV['TF_VAR_product']
environment_name = @environment.environment
Vault.address = "https://secrets.#{environment_name}.#{product}.itv.com:8200"
case level
when 'secrets-init'
role = 'service_administrator'
unless Vault::Helper.initialized?
init_user = ENV['VAULT_INIT_USER'] || 'tomclar'
keys = Vault::Helper.init(init_user: init_user)
puts "[*] Root token for #{init_user}: #{keys[:root_token]}".colorize(:yellow)
puts "[*] Recovery key for #{init_user}: #{keys[:recovery_key]}".colorize(:yellow)
raise "Vault not initialized, send the keys printed above to #{init_user} to finish initialization."
end
when 'secrets-config'
role = 'content_administrator'
else
raise Dome::InvalidLevelError.new, level
end
if ENV['VAULT_TOKEN']
puts '[*] Using VAULT_TOKEN environment variable'.colorize(:yellow)
Vault.token = ENV['VAULT_TOKEN']
else
puts "[*] Logging in as: #{role}"
Vault::Helper.login(role)
end
puts ''
else
raise Dome::InvalidLevelError.new, level
end
end
# rubocop:enable Metrics/PerceivedComplexity
def plan
puts '--- Decrypting hiera secrets and pass them as TF_VARs ---'
@secrets.secret_env_vars
puts '--- Deleting old plans'
# delete_terraform_directory # Don't delete it
delete_plan_file
@state.s3_state
puts
puts '--- Terraform init & plan ---'
puts
terraform_init
puts
create_plan
puts
end
def apply
@secrets.secret_env_vars
command = "terraform apply #{@plan_file}"
failure_message = '[!] something went wrong when applying the TF plan'
@state.s3_state
execute_command(command, failure_message)
end
def refresh
command = 'terraform refresh'
failure_message = '[!] something went wrong when doing terraform refresh'
execute_command(command, failure_message)
end
def statecmd(arguments)
command = "terraform state #{arguments}"
failure_message = "[!] something went wrong when doing terraform state #{arguments}"
execute_command(command, failure_message)
end
def console
@secrets.secret_env_vars
command = 'terraform console'
failure_message = '[!] something went wrong when doing terraform console'
execute_command(command, failure_message)
end
def create_plan
case level
when 'environment'
@secrets.extract_certs
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file} -var-file=params/env.tfvars"
failure_message = '[!] something went wrong when creating the environment TF plan'
execute_command(command, failure_message)
when 'ecosystem'
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the ecosystem TF plan'
execute_command(command, failure_message)
when 'product'
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the product TF plan'
execute_command(command, failure_message)
when 'roles'
@secrets.extract_certs
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the role TF plan'
execute_command(command, failure_message)
when /^secrets-/
@secrets.extract_certs
FileUtils.mkdir_p 'plans'
command = "terraform plan -refresh=true -out=#{@plan_file}"
failure_message = '[!] something went wrong when creating the role TF plan'
execute_command(command, failure_message)
else
raise Dome::InvalidLevelError.new, level
end
end
def delete_terraform_directory
puts '[*] Deleting terraform module cache dir ...'.colorize(:green)
terraform_directory = '.terraform'
FileUtils.rm_rf terraform_directory
end
def delete_plan_file
puts '[*] Deleting previous terraform plan ...'.colorize(:green)
FileUtils.rm_f @plan_file
end
def init
@state.s3_state
sleep 5
terraform_init
end
def terraform_init
command = 'terraform init'
failure_message = 'something went wrong when initialising TF'
execute_command(command, failure_message)
end
def output
command = 'terraform output'
failure_message = 'something went wrong when printing TF output variables'
execute_command(command, failure_message)
end
end
end
|
module Dossier
class Result
include Enumerable
attr_accessor :report, :adapter_results
def initialize(adapter_results, report)
self.adapter_results = adapter_results
self.report = report
end
def headers
adapter_results.headers
end
def body
rows.first(rows.length - report.options[:footer].to_i)
end
def footers
rows.last(report.options[:footer].to_i)
end
def rows
@rows ||= to_a
end
def arrays
@arrays ||= [headers] + rows
end
def hashes
return @hashes if defined?(@hashes)
@hashes = rows.map { |row| Hash[headers.zip(row)] }
end
def each
raise NotImplementedError, "Every result class must define `each`"
end
class Formatted < Result
def each
adapter_results.rows.each do |row|
yield format(row)
end
end
def format(result_row)
unless result_row.kind_of?(Enumerable)
raise ArgumentError.new("#{result_row.inspect} must be a kind of Enumerable")
end
result_row.each_with_index.map do |field, i|
method = "format_#{headers[i]}"
report.respond_to?(method) ? report.public_send(method, field) : field
end
end
end
class Unformatted < Result
def each
adapter_results.rows.each { |row| yield row }
end
end
end
end
Send the row to the formatter if it expects it
module Dossier
class Result
include Enumerable
attr_accessor :report, :adapter_results
def initialize(adapter_results, report)
self.adapter_results = adapter_results
self.report = report
end
def headers
adapter_results.headers
end
def body
rows.first(rows.length - report.options[:footer].to_i)
end
def footers
rows.last(report.options[:footer].to_i)
end
def rows
@rows ||= to_a
end
def arrays
@arrays ||= [headers] + rows
end
def hashes
return @hashes if defined?(@hashes)
@hashes = rows.map { |row| Hash[headers.zip(row)] }
end
def each
raise NotImplementedError, "Every result class must define `each`"
end
class Formatted < Result
def each
adapter_results.rows.each do |row|
yield format(row)
end
end
def format(result_row)
unless result_row.kind_of?(Enumerable)
raise ArgumentError.new("#{result_row.inspect} must be a kind of Enumerable")
end
result_row.each_with_index.map do |field, i|
method_name = "format_#{headers[i]}"
if report.respond_to?(method_name)
# Provide the row as context if the formatter takes two arguments
if report.method(method_name).arity == 2
report.public_send(method_name, field, result_row)
else
report.public_send(method_name, field)
end
else
field
end
end
end
end
class Unformatted < Result
def each
adapter_results.rows.each { |row| yield row }
end
end
end
end
|
module Dumbo
class Function < PgObject
attr_accessor :name, :result_type, :definition, :type, :arg_types
identfied_by :name, :arg_types
def initialize(oid)
super
get
end
def get
if type == 'agg'
Aggregate.new(oid)
else
self
end
end
def drop
"DROP FUNCTION #{name}(#{arg_types});"
end
def migrate_to(other)
if other.identify != identify
fail 'Not the Same Objects!'
end
return nil if other.to_sql == to_sql
if other.result_type != result_type
<<-SQL.gsub(/^ {8}/, '')
#{drop}
#{other.to_sql}
SQL
else
other.to_sql
end
end
def load_attributes
result = execute <<-SQL
SELECT
p.proname as name,
pg_catalog.pg_get_function_result(p.oid) as result_type,
pg_catalog.pg_get_function_arguments(p.oid) as arg_types,
CASE
WHEN p.proisagg THEN 'agg'
WHEN p.proiswindow THEN 'window'
WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
ELSE 'normal'
END as "type",
CASE
WHEN p.provolatile = 'i' THEN 'immutable'
WHEN p.provolatile = 's' THEN 'stable'
WHEN p.provolatile = 'v' THEN 'volatile'
END as volatility,
proisstrict as is_strict,
l.lanname as language,
p.prosrc as "source",
pg_catalog.obj_description(p.oid, 'pg_proc') as description,
CASE WHEN p.proisagg THEN 'agg_dummy' ELSE pg_get_functiondef(p.oid) END as definition
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_language l ON l.oid = p.prolang
WHERE pg_catalog.pg_function_is_visible(p.oid)
AND p.oid = #{oid};
SQL
result.first.each do |k, v|
send("#{k}=", v) rescue nil
end
result.first
end
def to_sql
definition.gsub("public.#{name}", name).strip + ';'
end
end
end
better function migrations
module Dumbo
class Function < PgObject
attr_accessor :name, :result_type, :definition, :type, :arg_types
identfied_by :name, :arg_types
def initialize(oid)
super
get
end
def get
if type == 'agg'
Aggregate.new(oid)
else
self
end
end
def drop
"DROP FUNCTION #{name}(#{arg_types});"
end
def migrate_to(other)
if other.identify != identify
fail 'Not the Same Objects!'
end
return nil if other.to_sql == to_sql
if other.result_type != result_type
<<-SQL.gsub(/^ {8}/, '')
#{drop}
#{other.to_sql}
SQL
else
other.to_sql
end
end
def load_attributes
result = execute <<-SQL
SELECT
p.proname as name,
pg_catalog.pg_get_function_result(p.oid) as result_type,
pg_catalog.pg_get_function_arguments(p.oid) as args,
pg_catalog.pg_get_function_identity_arguments(p.oid) as arg_types,
CASE
WHEN p.proisagg THEN 'agg'
WHEN p.proiswindow THEN 'window'
WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
ELSE 'normal'
END as "type",
CASE
WHEN p.provolatile = 'i' THEN 'immutable'
WHEN p.provolatile = 's' THEN 'stable'
WHEN p.provolatile = 'v' THEN 'volatile'
END as volatility,
proisstrict as is_strict,
l.lanname as language,
p.prosrc as "source",
pg_catalog.obj_description(p.oid, 'pg_proc') as description,
CASE WHEN p.proisagg THEN 'agg_dummy' ELSE pg_get_functiondef(p.oid) END as definition
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_language l ON l.oid = p.prolang
WHERE pg_catalog.pg_function_is_visible(p.oid)
AND p.oid = #{oid};
SQL
result.first.each do |k, v|
send("#{k}=", v) rescue nil
end
result.first
end
def to_sql
definition.gsub("public.#{name}", name).strip + ';'
end
end
end
|
module DxfIO
VERSION = '0.1.0'
end
New gem version
module DxfIO
VERSION = '0.1.1'
end
|
require 'email/html_cleaner'
#
# Handles an incoming message
#
module Email
class Receiver
include ActionView::Helpers::NumberHelper
class ProcessingError < StandardError; end
class EmailUnparsableError < ProcessingError; end
class EmptyEmailError < ProcessingError; end
class UserNotFoundError < ProcessingError; end
class UserNotSufficientTrustLevelError < ProcessingError; end
class BadDestinationAddress < ProcessingError; end
class TopicNotFoundError < ProcessingError; end
class TopicClosedError < ProcessingError; end
class EmailLogNotFound < ProcessingError; end
class InvalidPost < ProcessingError; end
attr_reader :body, :email_log
def initialize(raw)
@raw = raw
end
def process
raise EmptyEmailError if @raw.blank?
message = Mail.new(@raw)
body = parse_body message
dest_info = {type: :invalid, obj: nil}
message.to.each do |to_address|
if dest_info[:type] == :invalid
dest_info = check_address to_address
end
end
raise BadDestinationAddress if dest_info[:type] == :invalid
raise TopicNotFoundError if message.header.to_s =~ /auto-generated/ || message.header.to_s =~ /auto-replied/
# TODO get to a state where we can remove this
@message = message
@body = body
if dest_info[:type] == :category
raise BadDestinationAddress unless SiteSetting.email_in
category = dest_info[:obj]
@category_id = category.id
@allow_strangers = category.email_in_allow_strangers
user_email = @message.from.first
@user = User.find_by_email(user_email)
if @user.blank? && @allow_strangers
wrap_body_in_quote user_email
# TODO This is WRONG it should register an account
# and email the user details on how to log in / activate
@user = Discourse.system_user
end
raise UserNotFoundError if @user.blank?
raise UserNotSufficientTrustLevelError.new @user unless @allow_strangers || @user.has_trust_level?(TrustLevel[SiteSetting.email_in_min_trust.to_i])
create_new_topic
else
@email_log = dest_info[:obj]
raise EmailLogNotFound if @email_log.blank?
raise TopicNotFoundError if Topic.find_by_id(@email_log.topic_id).nil?
raise TopicClosedError if Topic.find_by_id(@email_log.topic_id).closed?
create_reply
end
rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError => e
raise EmailUnparsableError.new(e)
end
def check_address(address)
category = Category.find_by_email(address)
return {type: :category, obj: category} if category
regex = Regexp.escape SiteSetting.reply_by_email_address
regex = regex.gsub(Regexp.escape('%{reply_key}'), "(.*)")
regex = Regexp.new regex
match = regex.match address
if match && match[1].present?
reply_key = match[1]
email_log = EmailLog.for(reply_key)
return {type: :reply, obj: email_log}
end
{type: :invalid, obj: nil}
end
def parse_body(message)
body = select_body message
encoding = body.encoding
raise EmptyEmailError if body.strip.blank?
body = discourse_email_trimmer body
raise EmptyEmailError if body.strip.blank?
body = EmailReplyParser.parse_reply body
raise EmptyEmailError if body.strip.blank?
body.force_encoding(encoding).encode("UTF-8")
end
def select_body(message)
html = nil
# If the message is multipart, return that part (favor html)
if message.multipart?
html = fix_charset message.html_part
text = fix_charset message.text_part
# prefer plain text
if text
return text
end
elsif message.content_type =~ /text\/html/
html = fix_charset message
end
if html
body = HtmlCleaner.new(html).output_html
else
body = fix_charset message
end
# Certain trigger phrases that means we didn't parse correctly
if body =~ /Content\-Type\:/ || body =~ /multipart\/alternative/ || body =~ /text\/plain/
raise EmptyEmailError
end
body
end
# Force encoding to UTF-8 on a Mail::Message or Mail::Part
def fix_charset(object)
return nil if object.nil?
if object.charset
object.body.decoded.force_encoding(object.charset).encode("UTF-8").to_s
else
object.body.to_s
end
end
REPLYING_HEADER_LABELS = ['From', 'Sent', 'To', 'Subject', 'Reply To', 'Cc', 'Bcc', 'Date']
REPLYING_HEADER_REGEX = Regexp.union(REPLYING_HEADER_LABELS.map { |lbl| "#{lbl}:" })
def discourse_email_trimmer(body)
lines = body.scrub.lines.to_a
range_end = 0
lines.each_with_index do |l, idx|
break if l =~ /\A\s*\-{3,80}\s*\z/ ||
l =~ Regexp.new("\\A\\s*" + I18n.t('user_notifications.previous_discussion') + "\\s*\\Z") ||
(l =~ /via #{SiteSetting.title}(.*)\:$/) ||
# This one might be controversial but so many reply lines have years, times and end with a colon.
# Let's try it and see how well it works.
(l =~ /\d{4}/ && l =~ /\d:\d\d/ && l =~ /\:$/) ||
(l =~ /On \w+ \d+,? \d+,?.*wrote:/)
# Headers on subsequent lines
break if (0..2).all? { |off| lines[idx+off] =~ REPLYING_HEADER_REGEX }
# Headers on the same line
break if REPLYING_HEADER_LABELS.count { |lbl| l.include? lbl } >= 3
range_end = idx
end
lines[0..range_end].join.strip
end
def wrap_body_in_quote(user_email)
@body = "[quote=\"#{user_email}\"]
#{@body}
[/quote]"
end
private
def create_reply
create_post_with_attachments(@email_log.user,
raw: @body,
topic_id: @email_log.topic_id,
reply_to_post_number: @email_log.post.post_number)
end
def create_new_topic
post = create_post_with_attachments(@user,
raw: @body,
title: @message.subject,
category: @category_id)
EmailLog.create(
email_type: "topic_via_incoming_email",
to_address: @message.from.first, # pick from address because we want the user's email
topic_id: post.topic.id,
user_id: @user.id,
)
post
end
def create_post_with_attachments(user, post_opts={})
options = {
cooking_options: { traditional_markdown_linebreaks: true },
}.merge(post_opts)
raw = options[:raw]
# deal with attachments
@message.attachments.each do |attachment|
tmp = Tempfile.new("discourse-email-attachment")
begin
# read attachment
File.open(tmp.path, "w+b") { |f| f.write attachment.body.decoded }
# create the upload for the user
upload = Upload.create_for(user.id, tmp, attachment.filename, File.size(tmp))
if upload && upload.errors.empty?
# TODO: should use the same code as the client to insert attachments
raw << "\n#{attachment_markdown(upload)}\n"
end
ensure
tmp.close!
end
end
options[:raw] = raw
create_post(user, options)
end
def attachment_markdown(upload)
if FileHelper.is_image?(upload.original_filename)
"<img src='#{upload.url}' width='#{upload.width}' height='#{upload.height}'>"
else
"<a class='attachment' href='#{upload.url}'>#{upload.original_filename}</a> (#{number_to_human_size(upload.filesize)})"
end
end
def create_post(user, options)
# Mark the reply as incoming via email
options[:via_email] = true
options[:raw_email] = @raw
creator = PostCreator.new(user, options)
post = creator.create
if creator.errors.present?
raise InvalidPost, creator.errors.full_messages.join("\n")
end
post
end
end
end
FIX: convert UTF8 charset to UTF-8
require 'email/html_cleaner'
#
# Handles an incoming message
#
module Email
class Receiver
include ActionView::Helpers::NumberHelper
class ProcessingError < StandardError; end
class EmailUnparsableError < ProcessingError; end
class EmptyEmailError < ProcessingError; end
class UserNotFoundError < ProcessingError; end
class UserNotSufficientTrustLevelError < ProcessingError; end
class BadDestinationAddress < ProcessingError; end
class TopicNotFoundError < ProcessingError; end
class TopicClosedError < ProcessingError; end
class EmailLogNotFound < ProcessingError; end
class InvalidPost < ProcessingError; end
attr_reader :body, :email_log
def initialize(raw)
@raw = raw
end
def process
raise EmptyEmailError if @raw.blank?
message = Mail.new(@raw)
body = parse_body message
dest_info = {type: :invalid, obj: nil}
message.to.each do |to_address|
if dest_info[:type] == :invalid
dest_info = check_address to_address
end
end
raise BadDestinationAddress if dest_info[:type] == :invalid
raise TopicNotFoundError if message.header.to_s =~ /auto-generated/ || message.header.to_s =~ /auto-replied/
# TODO get to a state where we can remove this
@message = message
@body = body
if dest_info[:type] == :category
raise BadDestinationAddress unless SiteSetting.email_in
category = dest_info[:obj]
@category_id = category.id
@allow_strangers = category.email_in_allow_strangers
user_email = @message.from.first
@user = User.find_by_email(user_email)
if @user.blank? && @allow_strangers
wrap_body_in_quote user_email
# TODO This is WRONG it should register an account
# and email the user details on how to log in / activate
@user = Discourse.system_user
end
raise UserNotFoundError if @user.blank?
raise UserNotSufficientTrustLevelError.new @user unless @allow_strangers || @user.has_trust_level?(TrustLevel[SiteSetting.email_in_min_trust.to_i])
create_new_topic
else
@email_log = dest_info[:obj]
raise EmailLogNotFound if @email_log.blank?
raise TopicNotFoundError if Topic.find_by_id(@email_log.topic_id).nil?
raise TopicClosedError if Topic.find_by_id(@email_log.topic_id).closed?
create_reply
end
rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError => e
raise EmailUnparsableError.new(e)
end
def check_address(address)
category = Category.find_by_email(address)
return {type: :category, obj: category} if category
regex = Regexp.escape SiteSetting.reply_by_email_address
regex = regex.gsub(Regexp.escape('%{reply_key}'), "(.*)")
regex = Regexp.new regex
match = regex.match address
if match && match[1].present?
reply_key = match[1]
email_log = EmailLog.for(reply_key)
return {type: :reply, obj: email_log}
end
{type: :invalid, obj: nil}
end
def parse_body(message)
body = select_body message
encoding = body.encoding
raise EmptyEmailError if body.strip.blank?
body = discourse_email_trimmer body
raise EmptyEmailError if body.strip.blank?
body = EmailReplyParser.parse_reply body
raise EmptyEmailError if body.strip.blank?
body.force_encoding(encoding).encode("UTF-8")
end
def select_body(message)
html = nil
# If the message is multipart, return that part (favor html)
if message.multipart?
html = fix_charset message.html_part
text = fix_charset message.text_part
# prefer plain text
if text
return text
end
elsif message.content_type =~ /text\/html/
html = fix_charset message
end
if html
body = HtmlCleaner.new(html).output_html
else
body = fix_charset message
end
# Certain trigger phrases that means we didn't parse correctly
if body =~ /Content\-Type\:/ || body =~ /multipart\/alternative/ || body =~ /text\/plain/
raise EmptyEmailError
end
body
end
# Force encoding to UTF-8 on a Mail::Message or Mail::Part
def fix_charset(object)
return nil if object.nil?
if object.charset
# convert UTF8 charset to UTF-8
object.charset = object.charset.gsub(/utf8/i, "UTF-8") if object.charset.downcase == "utf8"
object.body.decoded.force_encoding(object.charset).encode("UTF-8").to_s
else
object.body.to_s
end
end
REPLYING_HEADER_LABELS = ['From', 'Sent', 'To', 'Subject', 'Reply To', 'Cc', 'Bcc', 'Date']
REPLYING_HEADER_REGEX = Regexp.union(REPLYING_HEADER_LABELS.map { |lbl| "#{lbl}:" })
def discourse_email_trimmer(body)
lines = body.scrub.lines.to_a
range_end = 0
lines.each_with_index do |l, idx|
break if l =~ /\A\s*\-{3,80}\s*\z/ ||
l =~ Regexp.new("\\A\\s*" + I18n.t('user_notifications.previous_discussion') + "\\s*\\Z") ||
(l =~ /via #{SiteSetting.title}(.*)\:$/) ||
# This one might be controversial but so many reply lines have years, times and end with a colon.
# Let's try it and see how well it works.
(l =~ /\d{4}/ && l =~ /\d:\d\d/ && l =~ /\:$/) ||
(l =~ /On \w+ \d+,? \d+,?.*wrote:/)
# Headers on subsequent lines
break if (0..2).all? { |off| lines[idx+off] =~ REPLYING_HEADER_REGEX }
# Headers on the same line
break if REPLYING_HEADER_LABELS.count { |lbl| l.include? lbl } >= 3
range_end = idx
end
lines[0..range_end].join.strip
end
def wrap_body_in_quote(user_email)
@body = "[quote=\"#{user_email}\"]
#{@body}
[/quote]"
end
private
def create_reply
create_post_with_attachments(@email_log.user,
raw: @body,
topic_id: @email_log.topic_id,
reply_to_post_number: @email_log.post.post_number)
end
def create_new_topic
post = create_post_with_attachments(@user,
raw: @body,
title: @message.subject,
category: @category_id)
EmailLog.create(
email_type: "topic_via_incoming_email",
to_address: @message.from.first, # pick from address because we want the user's email
topic_id: post.topic.id,
user_id: @user.id,
)
post
end
def create_post_with_attachments(user, post_opts={})
options = {
cooking_options: { traditional_markdown_linebreaks: true },
}.merge(post_opts)
raw = options[:raw]
# deal with attachments
@message.attachments.each do |attachment|
tmp = Tempfile.new("discourse-email-attachment")
begin
# read attachment
File.open(tmp.path, "w+b") { |f| f.write attachment.body.decoded }
# create the upload for the user
upload = Upload.create_for(user.id, tmp, attachment.filename, File.size(tmp))
if upload && upload.errors.empty?
# TODO: should use the same code as the client to insert attachments
raw << "\n#{attachment_markdown(upload)}\n"
end
ensure
tmp.close!
end
end
options[:raw] = raw
create_post(user, options)
end
def attachment_markdown(upload)
if FileHelper.is_image?(upload.original_filename)
"<img src='#{upload.url}' width='#{upload.width}' height='#{upload.height}'>"
else
"<a class='attachment' href='#{upload.url}'>#{upload.original_filename}</a> (#{number_to_human_size(upload.filesize)})"
end
end
def create_post(user, options)
# Mark the reply as incoming via email
options[:via_email] = true
options[:raw_email] = @raw
creator = PostCreator.new(user, options)
post = creator.create
if creator.errors.present?
raise InvalidPost, creator.errors.full_messages.join("\n")
end
post
end
end
end
|
module Mollie
module API
module Object
class Method < Base
IDEAL = "ideal"
CREDITCARD = "creditcard"
MISTERCASH = "mistercash"
BANKTRANSFER = "banktransfer"
PAYPAL = "paypal"
PAYSAFECARD = "paysafecard"
BITCOIN = "bitcoin"
SOFORT = "sofort
attr_accessor :id,
:description,
:amount,
:image
def getMinimumAmount ()
@amount.minimum
end
def getMaximumAmount ()
@amount.maximum
end
end
end
end
end
Fixes missing quote trying to build and publish new gem.
module Mollie
module API
module Object
class Method < Base
IDEAL = "ideal"
CREDITCARD = "creditcard"
MISTERCASH = "mistercash"
BANKTRANSFER = "banktransfer"
PAYPAL = "paypal"
PAYSAFECARD = "paysafecard"
BITCOIN = "bitcoin"
SOFORT = "sofort"
attr_accessor :id,
:description,
:amount,
:image
def getMinimumAmount ()
@amount.minimum
end
def getMaximumAmount ()
@amount.maximum
end
end
end
end
end
|
module EnjuLeaf
module EnjuUser
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def enju_leaf_user_model
include InstanceMethods
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :current_password,
:remember_me, :email_confirmation, :library_id, :locale,
:keyword_list, :auto_generated_password
attr_accessible :email, :password, :password_confirmation, :username,
:current_password, :user_number, :remember_me,
:email_confirmation, :note, :user_group_id, :library_id, :locale,
:expired_at, :locked, :required_role_id, :role_id,
:keyword_list, :user_has_role_attributes, :auto_generated_password,
:as => :admin
scope :administrators, where('roles.name = ?', 'Administrator').includes(:role)
scope :librarians, where('roles.name = ? OR roles.name = ?', 'Administrator', 'Librarian').includes(:role)
scope :suspended, where('locked_at IS NOT NULL')
#has_one :agent, :dependent => :destroy
if defined?(EnjuBiblio)
has_many :import_requests
has_many :picture_files, :as => :picture_attachable, :dependent => :destroy
end
has_one :user_has_role, :dependent => :destroy
has_one :role, :through => :user_has_role
belongs_to :library, :validate => true
belongs_to :user_group
belongs_to :required_role, :class_name => 'Role', :foreign_key => 'required_role_id' #, :validate => true
has_many :export_files if defined?(EnjuExport)
#has_one :agent_import_result
accepts_nested_attributes_for :user_has_role
validates :username, :presence => true, :uniqueness => true, :format => {:with => /\A[0-9A-Za-z][0-9A-Za-z_\-]*[0-9A-Za-z]\Z/}, :allow_blank => true
validates_uniqueness_of :email, :allow_blank => true
validates :email, :format => Devise::email_regexp, :allow_blank => true
validates_date :expired_at, :allow_blank => true
with_options :if => :password_required? do |v|
v.validates_presence_of :password
v.validates_confirmation_of :password
v.validates_length_of :password, :allow_blank => true,
:within => Devise::password_length
end
validates_presence_of :email, :email_confirmation, :on => :create, :if => proc{|user| !user.operator.try(:has_role?, 'Librarian')}
validates_associated :user_group, :library #, :agent
validates_presence_of :user_group, :library, :locale #, :user_number
validates :user_number, :uniqueness => true, :format => {:with => /\A[0-9A-Za-z_]+\Z/}, :allow_blank => true
validates_confirmation_of :email, :on => :create, :if => proc{|user| !user.operator.try(:has_role?, 'Librarian')}
before_validation :set_role_and_agent, :on => :create
before_validation :set_lock_information
before_destroy :check_role_before_destroy
before_save :check_expiration
before_create :set_expired_at
after_destroy :remove_from_index
after_create :set_confirmation
extend FriendlyId
friendly_id :username
#has_paper_trail
normalize_attributes :username, :user_number
normalize_attributes :email, :with => :strip
searchable do
text :username, :email, :note, :user_number
text :name do
#agent.name if agent
end
string :username
string :email
string :user_number
integer :required_role_id
time :created_at
time :updated_at
boolean :active do
active_for_authentication?
end
time :confirmed_at
end
attr_accessor :first_name, :middle_name, :last_name, :full_name,
:first_name_transcription, :middle_name_transcription,
:last_name_transcription, :full_name_transcription,
:zip_code, :address, :telephone_number, :fax_number, :address_note,
:operator, :password_not_verified,
:update_own_account, :auto_generated_password,
:locked, :current_password #, :agent_id
paginates_per 10
def lock_expired_users
User.find_each do |user|
user.lock_access! if user.expired? and user.active_for_authentication?
end
end
def export(options = {format: :tsv})
header = %w(
username
email
user_number
role
user_group
library
locale
created_at
updated_at
expired_at
keyword_list
save_checkout_history
note
).join("\t")
users = User.all.map{|u|
lines = []
lines << u.username
lines << u.email
lines << u.user_number
lines << u.role.name
lines << u.user_group.name
lines << u.library.name
lines << u.locale
lines << u.user_group.created_at
lines << u.user_group.updated_at
lines << u.user_group.expired_at
lines << u.keyword_list.try(:split).try(:join, "//")
if defined?(EnjuCirculation)
lines << u.try(:save_checkout_history)
else
lines << nil
end
lines << u.note
}
if options[:format] == :tsv
users.map{|u| u.join("\t")}.unshift(header).join("\r\n")
else
users
end
end
end
end
module InstanceMethods
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
def has_role?(role_in_question)
return false unless role
return true if role.name == role_in_question
case role.name
when 'Administrator'
return true
when 'Librarian'
return true if role_in_question == 'User'
else
false
end
end
def set_role_and_agent
self.required_role = Role.where(:name => 'Librarian').first
self.locale = I18n.default_locale.to_s unless locale
#unless self.agent
# self.agent = Agent.create(:full_name => self.username) if self.username
#end
end
def set_lock_information
if locked == '1' and self.active_for_authentication?
lock_access!
elsif locked == '0' and !self.active_for_authentication?
unlock_access!
end
end
def set_confirmation
if operator and respond_to?(:confirm!)
reload
confirm!
end
end
def check_expiration
return if self.has_role?('Administrator')
if expired_at
if expired_at.beginning_of_day < Time.zone.now.beginning_of_day
lock_access! if active_for_authentication?
end
end
end
def check_role_before_destroy
if self.has_role?('Administrator')
raise 'This is the last administrator in this system.' if Role.where(:name => 'Administrator').first.users.size == 1
end
end
def set_auto_generated_password
password = Devise.friendly_token[0..7]
self.password = password
self.password_confirmation = password
end
def expired?
if expired_at
true if expired_at.beginning_of_day < Time.zone.now.beginning_of_day
end
end
def is_admin?
true if self.has_role?('Administrator')
end
def last_librarian?
if self.has_role?('Librarian')
role = Role.where(:name => 'Librarian').first
true if role.users.size == 1
end
end
def send_confirmation_instructions
unless self.operator
Devise::Mailer.confirmation_instructions(self).deliver if self.email.present?
end
end
def set_expired_at
if expired_at.blank?
if user_group.valid_period_for_new_user > 0
self.expired_at = user_group.valid_period_for_new_user.days.from_now.end_of_day
end
end
end
def deletable_by(current_user)
if defined?(EnjuCirculation)
# 未返却の資料のあるユーザを削除しようとした
if checkouts.count > 0
errors[:base] << I18n.t('user.this_user_has_checked_out_item')
end
end
if has_role?('Librarian')
# 管理者以外のユーザが図書館員を削除しようとした。図書館員の削除は管理者しかできない
unless current_user.has_role?('Administrator')
errors[:base] << I18n.t('user.only_administrator_can_destroy')
end
# 最後の図書館員を削除しようとした
if last_librarian?
errors[:base] << I18n.t('user.last_librarian')
end
end
# 最後の管理者を削除しようとした
if has_role?('Administrator')
if Role.where(:name => 'Administrator').first.users.size == 1
errors[:base] << I18n.t('user.last_administrator')
end
end
if errors[:base] == []
true
else
false
end
end
def patron
LocalPatron.new({:username => username})
end
def full_name
username
end
end
end
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# password_salt :string(255)
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# failed_attempts :integer default(0)
# unlock_token :string(255)
# locked_at :datetime
# authentication_token :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# deleted_at :datetime
# username :string(255) not null
# library_id :integer default(1), not null
# user_group_id :integer default(1), not null
# expired_at :datetime
# required_role_id :integer default(1), not null
# note :text
# keyword_list :text
# user_number :string(255)
# state :string(255)
# locale :string(255)
# enju_access_key :string(255)
# save_checkout_history :boolean
# checkout_icalendar_token :string(255)
# share_bookmarks :boolean
# save_search_history :boolean
# answer_feed_token :string(255)
#
fixed exporting users
module EnjuLeaf
module EnjuUser
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def enju_leaf_user_model
include InstanceMethods
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :current_password,
:remember_me, :email_confirmation, :library_id, :locale,
:keyword_list, :auto_generated_password
attr_accessible :email, :password, :password_confirmation, :username,
:current_password, :user_number, :remember_me,
:email_confirmation, :note, :user_group_id, :library_id, :locale,
:expired_at, :locked, :required_role_id, :role_id,
:keyword_list, :user_has_role_attributes, :auto_generated_password,
:as => :admin
scope :administrators, where('roles.name = ?', 'Administrator').includes(:role)
scope :librarians, where('roles.name = ? OR roles.name = ?', 'Administrator', 'Librarian').includes(:role)
scope :suspended, where('locked_at IS NOT NULL')
#has_one :agent, :dependent => :destroy
if defined?(EnjuBiblio)
has_many :import_requests
has_many :picture_files, :as => :picture_attachable, :dependent => :destroy
end
has_one :user_has_role, :dependent => :destroy
has_one :role, :through => :user_has_role
belongs_to :library, :validate => true
belongs_to :user_group
belongs_to :required_role, :class_name => 'Role', :foreign_key => 'required_role_id' #, :validate => true
has_many :export_files if defined?(EnjuExport)
#has_one :agent_import_result
accepts_nested_attributes_for :user_has_role
validates :username, :presence => true, :uniqueness => true, :format => {:with => /\A[0-9A-Za-z][0-9A-Za-z_\-]*[0-9A-Za-z]\Z/}, :allow_blank => true
validates_uniqueness_of :email, :allow_blank => true
validates :email, :format => Devise::email_regexp, :allow_blank => true
validates_date :expired_at, :allow_blank => true
with_options :if => :password_required? do |v|
v.validates_presence_of :password
v.validates_confirmation_of :password
v.validates_length_of :password, :allow_blank => true,
:within => Devise::password_length
end
validates_presence_of :email, :email_confirmation, :on => :create, :if => proc{|user| !user.operator.try(:has_role?, 'Librarian')}
validates_associated :user_group, :library #, :agent
validates_presence_of :user_group, :library, :locale #, :user_number
validates :user_number, :uniqueness => true, :format => {:with => /\A[0-9A-Za-z_]+\Z/}, :allow_blank => true
validates_confirmation_of :email, :on => :create, :if => proc{|user| !user.operator.try(:has_role?, 'Librarian')}
before_validation :set_role_and_agent, :on => :create
before_validation :set_lock_information
before_destroy :check_role_before_destroy
before_save :check_expiration
before_create :set_expired_at
after_destroy :remove_from_index
after_create :set_confirmation
extend FriendlyId
friendly_id :username
#has_paper_trail
normalize_attributes :username, :user_number
normalize_attributes :email, :with => :strip
searchable do
text :username, :email, :note, :user_number
text :name do
#agent.name if agent
end
string :username
string :email
string :user_number
integer :required_role_id
time :created_at
time :updated_at
boolean :active do
active_for_authentication?
end
time :confirmed_at
end
attr_accessor :first_name, :middle_name, :last_name, :full_name,
:first_name_transcription, :middle_name_transcription,
:last_name_transcription, :full_name_transcription,
:zip_code, :address, :telephone_number, :fax_number, :address_note,
:operator, :password_not_verified,
:update_own_account, :auto_generated_password,
:locked, :current_password #, :agent_id
paginates_per 10
def lock_expired_users
User.find_each do |user|
user.lock_access! if user.expired? and user.active_for_authentication?
end
end
def export(options = {format: :tsv})
header = %w(
username
email
user_number
role
user_group
library
locale
created_at
updated_at
expired_at
keyword_list
save_checkout_history
note
).join("\t")
users = User.all.map{|u|
lines = []
lines << u.username
lines << u.email
lines << u.user_number
lines << u.role.name
lines << u.user_group.try(:name)
lines << u.library.try(:name)
lines << u.locale
lines << u.created_at
lines << u.updated_at
lines << u.expired_at
lines << u.keyword_list.try(:split).try(:join, "//")
if defined?(EnjuCirculation)
lines << u.try(:save_checkout_history)
else
lines << nil
end
lines << u.note
}
if options[:format] == :tsv
users.map{|u| u.join("\t")}.unshift(header).join("\r\n")
else
users
end
end
end
end
module InstanceMethods
def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end
def has_role?(role_in_question)
return false unless role
return true if role.name == role_in_question
case role.name
when 'Administrator'
return true
when 'Librarian'
return true if role_in_question == 'User'
else
false
end
end
def set_role_and_agent
self.required_role = Role.where(:name => 'Librarian').first
self.locale = I18n.default_locale.to_s unless locale
#unless self.agent
# self.agent = Agent.create(:full_name => self.username) if self.username
#end
end
def set_lock_information
if locked == '1' and self.active_for_authentication?
lock_access!
elsif locked == '0' and !self.active_for_authentication?
unlock_access!
end
end
def set_confirmation
if operator and respond_to?(:confirm!)
reload
confirm!
end
end
def check_expiration
return if self.has_role?('Administrator')
if expired_at
if expired_at.beginning_of_day < Time.zone.now.beginning_of_day
lock_access! if active_for_authentication?
end
end
end
def check_role_before_destroy
if self.has_role?('Administrator')
raise 'This is the last administrator in this system.' if Role.where(:name => 'Administrator').first.users.size == 1
end
end
def set_auto_generated_password
password = Devise.friendly_token[0..7]
self.password = password
self.password_confirmation = password
end
def expired?
if expired_at
true if expired_at.beginning_of_day < Time.zone.now.beginning_of_day
end
end
def is_admin?
true if self.has_role?('Administrator')
end
def last_librarian?
if self.has_role?('Librarian')
role = Role.where(:name => 'Librarian').first
true if role.users.size == 1
end
end
def send_confirmation_instructions
unless self.operator
Devise::Mailer.confirmation_instructions(self).deliver if self.email.present?
end
end
def set_expired_at
if expired_at.blank?
if user_group.valid_period_for_new_user > 0
self.expired_at = user_group.valid_period_for_new_user.days.from_now.end_of_day
end
end
end
def deletable_by(current_user)
if defined?(EnjuCirculation)
# 未返却の資料のあるユーザを削除しようとした
if checkouts.count > 0
errors[:base] << I18n.t('user.this_user_has_checked_out_item')
end
end
if has_role?('Librarian')
# 管理者以外のユーザが図書館員を削除しようとした。図書館員の削除は管理者しかできない
unless current_user.has_role?('Administrator')
errors[:base] << I18n.t('user.only_administrator_can_destroy')
end
# 最後の図書館員を削除しようとした
if last_librarian?
errors[:base] << I18n.t('user.last_librarian')
end
end
# 最後の管理者を削除しようとした
if has_role?('Administrator')
if Role.where(:name => 'Administrator').first.users.size == 1
errors[:base] << I18n.t('user.last_administrator')
end
end
if errors[:base] == []
true
else
false
end
end
def patron
LocalPatron.new({:username => username})
end
def full_name
username
end
end
end
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255) default(""), not null
# encrypted_password :string(255) default(""), not null
# reset_password_token :string(255)
# reset_password_sent_at :datetime
# remember_created_at :datetime
# sign_in_count :integer default(0)
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# password_salt :string(255)
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
# unconfirmed_email :string(255)
# failed_attempts :integer default(0)
# unlock_token :string(255)
# locked_at :datetime
# authentication_token :string(255)
# created_at :datetime not null
# updated_at :datetime not null
# deleted_at :datetime
# username :string(255) not null
# library_id :integer default(1), not null
# user_group_id :integer default(1), not null
# expired_at :datetime
# required_role_id :integer default(1), not null
# note :text
# keyword_list :text
# user_number :string(255)
# state :string(255)
# locale :string(255)
# enju_access_key :string(255)
# save_checkout_history :boolean
# checkout_icalendar_token :string(255)
# share_bookmarks :boolean
# save_search_history :boolean
# answer_feed_token :string(255)
#
|
# TODO: check for uncommitted changes at the start of each task
# TODO: Should crap out if git error?
# TODO: Be able to config live branches in app?
namespace :git do
def version_file_path
Rails.root.join('config/initializers/version.rb')
end
def read_app_version
load version_file_path
APP_VERSION
end
def write_app_version(v)
File.open(version_file_path, 'w') { |f| f.write("APP_VERSION = '#{v}'") }
load version_file_path
end
def major_version_bump(current_version = read_app_version)
version_number_array = current_version.split('.')
version_number_array[0] = version_number_array[0].to_i + 1
version_number_array[1] = 0
version_number_array[2] = 0
version_number_array.join('.').to_s
end
def minor_version_bump(current_version = read_app_version)
version_number_array = current_version.split('.')
version_number_array[1] = version_number_array[1].to_i + 1
version_number_array[2] = 0 # When bumping minor version reset bugfix version
version_number_array.join('.').to_s
end
def hotfix_version_bump(current_version = read_app_version)
version_number_array = current_version.split('.')
version_number_array[2] = version_number_array[2].to_i + 1
version_number_array.join('.').to_s
end
def all_branches
`git branch -a`
end
def uncommited_changes?
!`git diff && git diff --cached`.blank?
end
def branch_exists?(live_branch)
all_branches =~ /[\s\/]#{live_branch}$/
end
def current_branch_name
`git rev-parse --abbrev-ref HEAD`
end
def current_branch?(branch)
current_branch_name =~ /^#{branch}-/
end
def confirm?(question)
print "\x1B[36m\033[1m#{question}\x1B[0m"
proceed = STDIN.gets[0..0] rescue nil
(proceed == 'y' || proceed == 'Y')
end
def error(message)
puts "\x1B[31mError: #{message}\x1B[0m"
end
def deploy?(server)
if confirm?("Would you like to deploy to the #{server} server? (y/n)")
`cap #{server} deploy:migrations`
end
end
def merge_and_tag(source, target, version)
print "Merging and tagging #{source} to #{target}... "
`git checkout #{target}`
`git pull`
`git merge #{source}`
`git tag -a v#{version} -m "Version #{version}"`
`git push origin #{target}`
puts "\x1B[32m OK \x1B[0m"
end
def uncommitted_changes?
!(`git diff-index HEAD`.blank?)
end
def can_create_tag?(branch)
branch != 'production' && branch != 'training'
end
desc "Run this task at the start to check your repository is set up correctly and create the necessary branches if they don't exist."
task setup: :environment do
print " - Checking git repo..."
if Dir.exist?('.git')
puts "\x1B[32m OK \x1B[0m"
branch = current_branch_name
puts " - Checking branch structure..."
required_branches = %w(master demo production qa)
existing_branches = all_branches.scan(/#{required_branches.join('|')}/).to_set
required_branches.each do |required_branch|
print " #{required_branch}..."
if existing_branches.member?(required_branch)
puts "\x1B[32m OK \x1B[0m"
else
`git checkout -b #{required_branch}`
`git push -u origin #{required_branch}`
puts "\x1B[32m created \x1B[0m"
end
end
`git checkout #{branch}` unless branch == current_branch_name
print " - Checking version file..."
unless File.exist?(version_file_path)
print "creating #{version_file_path}..."
write_app_version('0.0.0')
end
puts "\x1B[32m OK \x1B[0m"
else
error("Please init a repo with a master branch and push it to the server first.")
end
end
##
# This method is intended to handle the alternate workflow for ticket-based projects.
# This allows a project to deploy a specific branch to a specific demo site.
# Both arguments must be given for this to work correctly.
def demo_workflow(args)
error "Both the demo and the branch values must be given." unless args.demo && args.branch
demo_site = "demo#{args.demo}"
unless branch_exists? demo_site
if confirm?("The branch #{demo_site} does not exist. Do you want to create it now?")
`git checkout -b #{demo_site}`
`git push -u origin #{demo_site}`
puts "\x1B[32m created \x1B[0m"
else
error "The branch #{demo_site} does not exist and was not created."
end
end
if uncommitted_changes?
error "There are uncommitted changes on your current branch. Please commit these changes before continuing."
else
`git checkout #{args.branch}`
`git push origin #{demo_site} --force`
deploy? "#{demo_site}"
puts "\x1B[32m OK \x1B[0m"
end
end
def workflow_for(env_name)
if branch_exists? env_name
if uncommited_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
branch = current_branch_name
if can_create_tag?(env_name) && confirm?("Do you want to create a new tag? If not you can choose an existing one? (y/n)")
new_version = minor_version_bump
write_app_version new_version
selected = "v#{new_version}"
`git commit #{version_file_path} -m "Bumped to version #{new_version}"`
`git tag -a v#{new_version} -m "Version #{new_version}"`
`git push origin master --tags`
else
tags = `git tag`.split.sort_by { |ver| ver[/[\d.]+/].split('.').map(&:to_i) }.reverse
first_tag = tags.first
recent_tags = tags[1..5]
puts "The most recent tag is: #{first_tag}"
puts "Other recent tags are:"
puts recent_tags.map.with_index {|ver, i| "- #{ver}" }.join("\n")
selected = nil
while selected.nil? do
puts
puts "\x1B[36m\033[1mWhich tag do you want to deploy to #{env_name}?\x1B[0m (default: #{first_tag})"
puts
input = (STDIN.gets[/v[\.\d]+/] rescue nil) || first_tag
selected = tags.include?(input) ? input : nil
puts "Invalid tag selected" unless selected
end
puts
puts "\x1B[36m\033[1mDeploying tag #{selected} to #{env_name}...\x1B[0m"
end
`git checkout #{env_name}`
`git pull`
`git merge --no-edit --no-ff #{selected}`
`git push origin #{env_name}`
deploy? env_name
puts "\x1B[32m OK \x1B[0m"
`git checkout #{branch}` unless branch == current_branch_name
end
else
error "The #{env_name} branch does not exist."
end
end
namespace :production do
desc "When you're ready to deploy to production run this task. You will be prompted to choose which version (tag) to merge into the production branch and optionally deploy."
task release: :environment do
workflow_for('production')
end
end
namespace :training do
desc "When you're ready to deploy to training run this task. You will be prompted to choose which version (tag) to merge into the training branch and optionally deploy."
task release: :environment do
workflow_for('training')
end
end
namespace :qa do
desc "When you're ready to deploy to qa run this task. You will be prompted to choose which version (tag) to merge into the qa branch and optionally deploy."
task release: :environment do
workflow_for('qa')
end
end
namespace :demo do
desc "When you're ready to deploy to demo run this task. You will be prompted to choose which version (tag) to merge into the demo branch and optionally deploy."
task :release, [:demo, :branch] => [:environment] do |t, args|
if args.blank?
workflow_for('demo')
else
demo_workflow(args)
end
end
end
### HOTFIX BRANCHES ###
# May branch off from: a live branch
# Must merge back to: the live branch it was branched from and master
# Naming convention: hotfix-<live branch name>-<version number (bumped)>
# Hotfix branches are created from a live branch. For example, say version 1.2 is the current release running on
# production and causing troubles due to a severe bug, but changes on master are yet unstable. We may then make a hotfix
# branch from production and start fixing the problem.
desc "This will create a hotfix branch from the live branch specified and bump the version ready for you to implement the fix."
task :start_hotfix_for, [:live_branch] => :environment do |t, args|
if uncommitted_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
live_branch = args[:live_branch]
if branch_exists?(live_branch)
`git checkout #{live_branch}`
`git pull`
new_version = hotfix_version_bump
hotfix_branch = "hotfix-#{live_branch}-#{new_version}" # live_branch included in the name so we know where to merge when we apply the fix
`git checkout -b #{hotfix_branch} #{live_branch}`
print "Bumping app version to #{new_version}..."
write_app_version(new_version)
puts "\x1B[32m OK \x1B[0m"
print "Committing version bump..."
`git commit -am "Bumped to version #{new_version} for hotfix"`
puts "\x1B[32m OK \x1B[0m"
puts "You are now on branch #{hotfix_branch}. Fix the bug, commit, then run rake git:apply_hotfix"
else
error("The branch #{live_branch} does not exist.")
end
end
end
desc "This will merge your hotfix into the appropriate live branch and optionally deploy. You should then manually merge the hotfix into deploy and master if necessary and delete the hotfix branch. Note: you must be in the hotfix branch you wish to apply before running this task."
task apply_hotfix: :environment do
if uncommitted_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
if current_branch?(:hotfix)
version = read_app_version
hotfix_branch = current_branch_name
live_branch = hotfix_branch.match(/^hotfix-(?<live_branch>.*)-[^-]+$/)[:live_branch]
merge_and_tag(hotfix_branch, live_branch, version)
deploy?(live_branch)
puts "The hotfix has been applied to #{live_branch}."
puts "IMPORTANT: You should merge the hotfix branch into demo and master if necessary, then delete the hotfix branch."
else
error("Please checkout the hotfix branch you wish to apply.")
end
end
end
# Staging instead of demo (for MSCAA) - to be standardised at some point
namespace :staging do
desc "When you're ready to deploy a release to staging from master run this task. The minor version number will be bumped, the commit tagged and merged into staging (and pushed to origin). Optional deployment."
task release: :environment do
if branch_exists? 'staging'
if uncommited_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
if confirm?('This will merge the master branch to staging for a new release. Continue? (y/n)')
branch = current_branch_name
`git checkout master`
`git pull`
new_version = minor_version_bump
write_app_version new_version
`git commit #{version_file_path} -m "Bumped to version #{new_version}"`
`git tag -a v#{new_version} -m "Version #{new_version}"`
`git push origin master`
`git checkout staging`
`git pull`
`git merge --no-edit --no-ff v#{new_version}`
`git push origin staging`
deploy? 'staging'
puts "\x1B[32m OK \x1B[0m"
`git checkout #{branch}` unless branch == current_branch_name
end
end
else
error "The staging branch does not exist."
end
end
end
end
update to stop it carrying on without a branch
# TODO: check for uncommitted changes at the start of each task
# TODO: Should crap out if git error?
# TODO: Be able to config live branches in app?
namespace :git do
def version_file_path
Rails.root.join('config/initializers/version.rb')
end
def read_app_version
load version_file_path
APP_VERSION
end
def write_app_version(v)
File.open(version_file_path, 'w') { |f| f.write("APP_VERSION = '#{v}'") }
load version_file_path
end
def major_version_bump(current_version = read_app_version)
version_number_array = current_version.split('.')
version_number_array[0] = version_number_array[0].to_i + 1
version_number_array[1] = 0
version_number_array[2] = 0
version_number_array.join('.').to_s
end
def minor_version_bump(current_version = read_app_version)
version_number_array = current_version.split('.')
version_number_array[1] = version_number_array[1].to_i + 1
version_number_array[2] = 0 # When bumping minor version reset bugfix version
version_number_array.join('.').to_s
end
def hotfix_version_bump(current_version = read_app_version)
version_number_array = current_version.split('.')
version_number_array[2] = version_number_array[2].to_i + 1
version_number_array.join('.').to_s
end
def all_branches
`git branch -a`
end
def uncommited_changes?
!`git diff && git diff --cached`.blank?
end
def branch_exists?(live_branch)
all_branches =~ /[\s\/]#{live_branch}$/
end
def current_branch_name
`git rev-parse --abbrev-ref HEAD`
end
def current_branch?(branch)
current_branch_name =~ /^#{branch}-/
end
def confirm?(question)
print "\x1B[36m\033[1m#{question}\x1B[0m"
proceed = STDIN.gets[0..0] rescue nil
(proceed == 'y' || proceed == 'Y')
end
def error(message)
puts "\x1B[31mError: #{message}\x1B[0m"
end
def deploy?(server)
if confirm?("Would you like to deploy to the #{server} server? (y/n)")
`cap #{server} deploy:migrations`
end
end
def merge_and_tag(source, target, version)
print "Merging and tagging #{source} to #{target}... "
`git checkout #{target}`
`git pull`
`git merge #{source}`
`git tag -a v#{version} -m "Version #{version}"`
`git push origin #{target}`
puts "\x1B[32m OK \x1B[0m"
end
def uncommitted_changes?
!(`git diff-index HEAD`.blank?)
end
def can_create_tag?(branch)
branch != 'production' && branch != 'training'
end
desc "Run this task at the start to check your repository is set up correctly and create the necessary branches if they don't exist."
task setup: :environment do
print " - Checking git repo..."
if Dir.exist?('.git')
puts "\x1B[32m OK \x1B[0m"
branch = current_branch_name
puts " - Checking branch structure..."
required_branches = %w(master demo production qa)
existing_branches = all_branches.scan(/#{required_branches.join('|')}/).to_set
required_branches.each do |required_branch|
print " #{required_branch}..."
if existing_branches.member?(required_branch)
puts "\x1B[32m OK \x1B[0m"
else
`git checkout -b #{required_branch}`
`git push -u origin #{required_branch}`
puts "\x1B[32m created \x1B[0m"
end
end
`git checkout #{branch}` unless branch == current_branch_name
print " - Checking version file..."
unless File.exist?(version_file_path)
print "creating #{version_file_path}..."
write_app_version('0.0.0')
end
puts "\x1B[32m OK \x1B[0m"
else
error("Please init a repo with a master branch and push it to the server first.")
end
end
##
# This method is intended to handle the alternate workflow for ticket-based projects.
# This allows a project to deploy a specific branch to a specific demo site.
# Both arguments must be given for this to work correctly.
def demo_workflow(args)
error "Both the demo and the branch values must be given." unless args.demo && args.branch
demo_site = "demo#{args.demo}"
unless branch_exists? demo_site
if confirm?("The branch #{demo_site} does not exist. Do you want to create it now? (y/n)")
`git checkout -b #{demo_site}`
`git push -u origin #{demo_site}`
puts "\x1B[32m created \x1B[0m"
else
error "The branch #{demo_site} does not exist and was not created."
return
end
end
if uncommitted_changes?
error "There are uncommitted changes on your current branch. Please commit these changes before continuing."
else
`git checkout #{args.branch}`
`git push origin #{demo_site} --force`
deploy? "#{demo_site}"
puts "\x1B[32m OK \x1B[0m"
end
end
def workflow_for(env_name)
if branch_exists? env_name
if uncommited_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
branch = current_branch_name
if can_create_tag?(env_name) && confirm?("Do you want to create a new tag? If not you can choose an existing one? (y/n)")
new_version = minor_version_bump
write_app_version new_version
selected = "v#{new_version}"
`git commit #{version_file_path} -m "Bumped to version #{new_version}"`
`git tag -a v#{new_version} -m "Version #{new_version}"`
`git push origin master --tags`
else
tags = `git tag`.split.sort_by { |ver| ver[/[\d.]+/].split('.').map(&:to_i) }.reverse
first_tag = tags.first
recent_tags = tags[1..5]
puts "The most recent tag is: #{first_tag}"
puts "Other recent tags are:"
puts recent_tags.map.with_index {|ver, i| "- #{ver}" }.join("\n")
selected = nil
while selected.nil? do
puts
puts "\x1B[36m\033[1mWhich tag do you want to deploy to #{env_name}?\x1B[0m (default: #{first_tag})"
puts
input = (STDIN.gets[/v[\.\d]+/] rescue nil) || first_tag
selected = tags.include?(input) ? input : nil
puts "Invalid tag selected" unless selected
end
puts
puts "\x1B[36m\033[1mDeploying tag #{selected} to #{env_name}...\x1B[0m"
end
`git checkout #{env_name}`
`git pull`
`git merge --no-edit --no-ff #{selected}`
`git push origin #{env_name}`
deploy? env_name
puts "\x1B[32m OK \x1B[0m"
`git checkout #{branch}` unless branch == current_branch_name
end
else
error "The #{env_name} branch does not exist."
end
end
namespace :production do
desc "When you're ready to deploy to production run this task. You will be prompted to choose which version (tag) to merge into the production branch and optionally deploy."
task release: :environment do
workflow_for('production')
end
end
namespace :training do
desc "When you're ready to deploy to training run this task. You will be prompted to choose which version (tag) to merge into the training branch and optionally deploy."
task release: :environment do
workflow_for('training')
end
end
namespace :qa do
desc "When you're ready to deploy to qa run this task. You will be prompted to choose which version (tag) to merge into the qa branch and optionally deploy."
task release: :environment do
workflow_for('qa')
end
end
namespace :demo do
desc "When you're ready to deploy to demo run this task. You will be prompted to choose which version (tag) to merge into the demo branch and optionally deploy."
task :release, [:demo, :branch] => [:environment] do |t, args|
if args.blank?
workflow_for('demo')
else
demo_workflow(args)
end
end
end
### HOTFIX BRANCHES ###
# May branch off from: a live branch
# Must merge back to: the live branch it was branched from and master
# Naming convention: hotfix-<live branch name>-<version number (bumped)>
# Hotfix branches are created from a live branch. For example, say version 1.2 is the current release running on
# production and causing troubles due to a severe bug, but changes on master are yet unstable. We may then make a hotfix
# branch from production and start fixing the problem.
desc "This will create a hotfix branch from the live branch specified and bump the version ready for you to implement the fix."
task :start_hotfix_for, [:live_branch] => :environment do |t, args|
if uncommitted_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
live_branch = args[:live_branch]
if branch_exists?(live_branch)
`git checkout #{live_branch}`
`git pull`
new_version = hotfix_version_bump
hotfix_branch = "hotfix-#{live_branch}-#{new_version}" # live_branch included in the name so we know where to merge when we apply the fix
`git checkout -b #{hotfix_branch} #{live_branch}`
print "Bumping app version to #{new_version}..."
write_app_version(new_version)
puts "\x1B[32m OK \x1B[0m"
print "Committing version bump..."
`git commit -am "Bumped to version #{new_version} for hotfix"`
puts "\x1B[32m OK \x1B[0m"
puts "You are now on branch #{hotfix_branch}. Fix the bug, commit, then run rake git:apply_hotfix"
else
error("The branch #{live_branch} does not exist.")
end
end
end
desc "This will merge your hotfix into the appropriate live branch and optionally deploy. You should then manually merge the hotfix into deploy and master if necessary and delete the hotfix branch. Note: you must be in the hotfix branch you wish to apply before running this task."
task apply_hotfix: :environment do
if uncommitted_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
if current_branch?(:hotfix)
version = read_app_version
hotfix_branch = current_branch_name
live_branch = hotfix_branch.match(/^hotfix-(?<live_branch>.*)-[^-]+$/)[:live_branch]
merge_and_tag(hotfix_branch, live_branch, version)
deploy?(live_branch)
puts "The hotfix has been applied to #{live_branch}."
puts "IMPORTANT: You should merge the hotfix branch into demo and master if necessary, then delete the hotfix branch."
else
error("Please checkout the hotfix branch you wish to apply.")
end
end
end
# Staging instead of demo (for MSCAA) - to be standardised at some point
namespace :staging do
desc "When you're ready to deploy a release to staging from master run this task. The minor version number will be bumped, the commit tagged and merged into staging (and pushed to origin). Optional deployment."
task release: :environment do
if branch_exists? 'staging'
if uncommited_changes?
error "There are uncommited changes on your current branch. Please commit these changes before continuing."
else
if confirm?('This will merge the master branch to staging for a new release. Continue? (y/n)')
branch = current_branch_name
`git checkout master`
`git pull`
new_version = minor_version_bump
write_app_version new_version
`git commit #{version_file_path} -m "Bumped to version #{new_version}"`
`git tag -a v#{new_version} -m "Version #{new_version}"`
`git push origin master`
`git checkout staging`
`git pull`
`git merge --no-edit --no-ff v#{new_version}`
`git push origin staging`
deploy? 'staging'
puts "\x1B[32m OK \x1B[0m"
`git checkout #{branch}` unless branch == current_branch_name
end
end
else
error "The staging branch does not exist."
end
end
end
end
|
# -*- encoding : ascii-8bit -*-
require 'forwardable'
module Ethereum
##
# A block.
#
# All attributes from the block header are accessible via properties (i.e.
# `block.prevhash` is equivalent to `block.header.prevhash`). It is ensured
# that no discrepancies between header and the block occur.
#
class Block
include RLP::Sedes::Serializable
HeaderGetters = (BlockHeader.serializable_fields.keys - %i(state_root receipts_root tx_list_root)).freeze
HeaderSetters = HeaderGetters.map {|field| :"#{field}=" }.freeze
set_serializable_fields(
header: BlockHeader,
transaction_list: RLP::Sedes::CountableList.new(Transaction),
uncles: RLP::Sedes::CountableList.new(BlockHeader)
)
extend Forwardable
def_delegators :header, *HeaderGetters, *HeaderSetters
attr :env, :db, :config
attr_accessor :state, :transactions, :receipts, :refunds, :suicides, :ether_delta, :ancestor_hashes, :logs, :log_listeners
class <<self
##
# Assumption: blocks loaded from the db are not manipulated -> can be
# cached including hash.
def find(env, hash)
raise ArgumentError, "env must be instance of Env" unless env.instance_of?(Env)
blk = RLP.decode env.db.get(hash), sedes: Block, env: env
CachedBlock.create_cached blk
end
lru_cache :find, 1024
def verify(block, parent)
block2 = RLP.decode RLP.encode(block), sedes: Block, env: parent.env, parent: parent
raise "block not match" unless block == block2
true
rescue InvalidBlock
false
end
##
# Create a block without specifying transactions or uncles.
#
# @param header_rlp [String] the RLP encoded block header
# @param env [Env] provide database for the block
#
# @return [Block]
#
def build_from_header(header_rlp, env)
header = RLP.decode header_rlp, sedes: BlockHeader
new header, transaction_list: nil, uncles: [], env: env
end
##
# Create a new block based on a parent block.
#
# The block will not include any transactions and will not be finalized.
#
def build_from_parent(parent, coinbase, nonce: Constant::BYTE_EMPTY, extra_data: Constant::BYTE_EMPTY, timestamp: Time.now.to_i, uncles: [], env: nil)
env ||= parent.env
header = BlockHeader.new(
prevhash: parent.full_hash,
uncles_hash: Utils.keccak256_rlp(uncles),
coinbase: coinbase,
state_root: parent.state_root,
tx_list_root: Trie::BLANK_ROOT,
receipts_root: Trie::BLANK_ROOT,
bloom: 0,
difficulty: calc_difficulty(parent, timestamp),
mixhash: Constant::BYTE_EMPTY,
number: parent.number+1,
gas_limit: calc_gaslimit(parent),
gas_used: 0,
timestamp: timestamp,
extra_data: extra_data,
nonce: nonce
)
Block.new(
header,
transaction_list: [],
uncles: uncles,
env: env,
parent: parent,
making: true
).tap do |blk|
blk.ancestor_hashes = [parent.full_hash] + parent.ancestor_hashes
blk.log_listeners = parent.log_listeners
end
end
def calc_difficulty(parent, ts)
config = parent.config
offset = parent.difficulty / config[:block_diff_factor]
if parent.number >= (config[:homestead_fork_blknum] - 1)
sign = [1 - ((ts - parent.timestamp) / config[:homestead_diff_adjustment_cutoff]), -99].max
else
sign = (ts - parent.timestamp) < config[:diff_adjustment_cutoff] ? 1 : -1
end
# If we enter a special mode where the genesis difficulty starts off
# below the minimal difficulty, we allow low-difficulty blocks (this will
# never happen in the official protocol)
o = [parent.difficulty + offset*sign, [parent.difficulty, config[:min_diff]].min].max
period_count = (parent.number + 1) / config[:expdiff_period]
if period_count >= config[:expdiff_free_periods]
o = [o + 2**(period_count - config[:expdiff_free_periods]), config[:min_diff]].max
end
o
end
def calc_gaslimit(parent)
config = parent.config
decay = parent.gas_limit / config[:gaslimit_ema_factor]
new_contribution = ((parent.gas_used * config[:blklim_factor_nom]) / config[:blklim_factor_den] / config[:gaslimit_ema_factor])
gl = [parent.gas_limit - decay + new_contribution, config[:min_gas_limit]].max
if gl < config[:genesis_gas_limit]
gl2 = parent.gas_limit + decay
gl = [config[:genesis_gas_limit], gl2].min
end
raise ValueError, "invalid gas limit" unless check_gaslimit(parent, gl)
gl
end
def check_gaslimit(parent, gas_limit)
config = parent.config
adjmax = parent.gas_limit / config[:gaslimit_adjmax_factor]
(gas_limit - parent.gas_limit).abs <= adjmax && gas_limit >= parent.config[:min_gas_limit]
end
##
# Build the genesis block.
#
def genesis(env, options={})
allowed_args = %i(start_alloc bloom prevhash coinbase difficulty gas_limit gas_used timestamp extra_data mixhash nonce)
invalid_options = options.keys - allowed_args
raise ArgumentError, "invalid options: #{invalid_options}" unless invalid_options.empty?
start_alloc = options[:start_alloc] || env.config[:genesis_initial_alloc]
header = BlockHeader.new(
prevhash: options[:prevhash] || env.config[:genesis_prevhash],
uncles_hash: Utils.keccak256_rlp([]),
coinbase: options[:coinbase] || env.config[:genesis_coinbase],
state_root: Trie::BLANK_ROOT,
tx_list_root: Trie::BLANK_ROOT,
receipts_root: Trie::BLANK_ROOT,
bloom: options[:bloom] || 0,
difficulty: options[:difficulty] || env.config[:genesis_difficulty],
number: 0,
gas_limit: options[:gas_limit] || env.config[:genesis_gas_limit],
gas_used: options[:gas_used] || 0,
timestamp: options[:timestamp] || 0,
extra_data: options[:extra_data] || env.config[:genesis_extra_data],
mixhash: options[:mixhash] || env.config[:genesis_mixhash],
nonce: options[:nonce] || env.config[:genesis_nonce]
)
block = Block.new header, transaction_list: [], uncles: [], env: env
start_alloc.each do |addr, data|
addr = Utils.normalize_address addr
block.set_balance addr, Utils.parse_int_or_hex(data[:wei]) if data[:wei]
block.set_balance addr, Utils.parse_int_or_hex(data[:balance]) if data[:balance]
block.set_code addr, Utils.decode_hex(Utils.remove_0x_head(data[:code])) if data[:code]
block.set_nonce addr, Utils.parse_int_or_hex(data[:nonce]) if data[:nonce]
if data[:storage]
data[:storage].each do |k, v|
k = Utils.big_endian_to_int Utils.decode_hex(Utils.remove_0x_head(k))
v = Utils.big_endian_to_int Utils.decode_hex(Utils.remove_0x_head(v))
block.set_storage_data addr, k, v
end
end
end
block.commit_state
block.commit_state_db
# genesis block has predefined state root (so no additional
# finalization necessary)
block
end
end
##
# Arguments in format of:
# `header, transaction_list=[], uncles=[], env=nil, parent=nil,
# making=false`
#
# @param args [Array] mix of arguments:
#
# * header {BlockHeader} optional. if given, will be used as block
# header. if not given, you must specify header by `options[:header]`
# * options (Hash) optional.
# - transaction_list {Array[Transaction]} a list of transactions
# which are replayed if the state given by the header is not known.
# If the state is known, `nil` can be used instead of the empty
# list.
# - uncles {Array[BlockHeader]} a list of the headers of the uncles
# of this block
# - env {Env} env including db in which the block's state,
# transactions and receipts are stored (required)
# - parent {Block} optional parent which if not given may have to be
# loaded from the database for replay
#
def initialize(*args)
header = args.first.instance_of?(BlockHeader) ? args.first : nil
options = args.last.instance_of?(Hash) ? args.last : {}
header = options.delete(:header) if options.has_key?(:header)
transaction_list = options.has_key?(:transaction_list) ? options[:transaction_list] : []
uncles = options.has_key?(:uncles) ? options[:uncles] : []
env = options.delete(:env)
parent = options.delete(:parent)
making = options.has_key?(:making) ? options.delete(:making) : false
raise ArgumentError, "No Env object given" unless env.instance_of?(Env)
raise ArgumentError, "No database object given. db=#{env.db}" unless env.db.is_a?(DB::BaseDB)
@env = env
@db = env.db
@config = env.config
_set_field :header, header
_set_field :uncles, uncles
reset_cache
@get_transactions_cache = []
self.suicides = []
self.logs = []
self.log_listeners = []
self.refunds = 0
self.ether_delta = 0
self.ancestor_hashes = number > 0 ? [prevhash] : [nil]*256
validate_parent!(parent) if parent
original_values = {
bloom: bloom,
gas_used: gas_used,
timestamp: timestamp,
difficulty: difficulty,
uncles_hash: uncles_hash,
header_mutable: header.mutable?
}
make_mutable!
header.make_mutable!
@transactions = PruningTrie.new db
@receipts = PruningTrie.new db
initialize_state(transaction_list, parent, making)
validate_block!(original_values)
unless db.has_key?("validated:#{full_hash}")
if number == 0
db.put "validated:#{full_hash}", '1'
else
db.put_temporarily "validated:#{full_hash}", '1'
end
end
header.block = self
header.instance_variable_set :@_mutable, original_values[:header_mutable]
end
def add_listener(l)
log_listeners.push l
end
##
# The binary block hash. This is equivalent to `header.full_hash`.
#
def full_hash
Utils.keccak256_rlp header
end
##
# The hex encoded block hash. This is equivalent to `header.full_hash_hex`.
#
def full_hash_hex
Utils.encode_hex full_hash
end
def tx_list_root
@transactions.root_hash
end
def tx_list_root=(v)
@transactions = PruningTrie.new db, v
end
def receipts_root
@receipts.root_hash
end
def receipts_root=(v)
@receipts = PruningTrie.new db, v
end
def state_root
commit_state
@state.root_hash
end
def state_root=(v)
@state = SecureTrie.new PruningTrie.new(db, v)
reset_cache
end
def transaction_list
@transaction_count.times.map {|i| get_transaction(i) }
end
def uncles_hash
Utils.keccak256_rlp(uncles)
end
##
# Validate the uncles of this block.
#
def validate_uncles
return false if Utils.keccak256_rlp(uncles) != uncles_hash
return false if uncles.size > config[:max_uncles]
uncles.each do |uncle|
raise InvalidUncles, "Cannot find uncle prevhash in db" unless db.include?(uncle.prevhash)
if uncle.number == number
logger.error "uncle at same block height", block: self
return false
end
end
max_uncle_depth = config[:max_uncle_depth]
ancestor_chain = [self] + get_ancestor_list(max_uncle_depth+1)
raise ValueError, "invalid ancestor chain" unless ancestor_chain.size == [number+1, max_uncle_depth+2].min
# Uncles of this block cannot be direct ancestors and cannot also be
# uncles included 1-6 blocks ago.
ineligible = []
ancestor_chain.safe_slice(1..-1).each {|a| ineligible.concat a.uncles }
ineligible.concat(ancestor_chain.map {|a| a.header })
eligible_ancestor_hashes = ancestor_chain.safe_slice(2..-1).map(&:full_hash)
uncles.each do |uncle|
parent = Block.find env, uncle.prevhash
return false if uncle.difficulty != Block.calc_difficulty(parent, uncle.timestamp)
return false if uncle.number != parent.number + 1
return false if uncle.timestamp < parent.timestamp
return false unless uncle.check_pow
unless eligible_ancestor_hashes.include?(uncle.prevhash)
eligible = eligible_ancestor_hashes.map {|h| Utils.encode_hex(h) }
logger.error "Uncle does not have a valid ancestor", block: self, eligible: eligible, uncle_prevhash: Utils.encode_hex(uncle.prevhash)
return false
end
if ineligible.include?(uncle)
logger.error "Duplicate uncle", block: self, uncle: Utils.encode_hex(Utils.keccak256_rlp(uncle))
return false
end
# FIXME: what if uncles include previously rewarded uncle?
ineligible.push uncle
end
true
end
def add_refund(x)
self.refunds += x
end
##
# Add a transaction to the transaction trie.
#
# Note that this does not execute anything, i.e. the state is not updated.
#
def add_transaction_to_list(tx)
k = RLP.encode @transaction_count
@transactions[k] = RLP.encode(tx)
r = mk_transaction_receipt tx
@receipts[k] = RLP.encode(r)
self.bloom |= r.bloom
@transaction_count += 1
end
def build_external_call(tx)
ExternalCall.new self, tx
end
def apply_transaction(tx)
validate_transaction tx
intrinsic_gas = get_intrinsic_gas tx
logger.debug "apply transaction", tx: tx.log_dict
increment_nonce tx.sender
# buy startgas
delta_balance tx.sender, -tx.startgas*tx.gasprice
message_gas = tx.startgas - intrinsic_gas
message_data = VM::CallData.new tx.data.bytes, 0, tx.data.size
message = VM::Message.new tx.sender, tx.to, tx.value, message_gas, message_data, code_address: tx.to
ec = build_external_call tx
if tx.to.true? && tx.to != Address::CREATE_CONTRACT
result, gas_remained, data = ec.apply_msg message
logger.debug "_res_", result: result, gas_remained: gas_remained, data: data
else # CREATE
result, gas_remained, data = ec.create message
raise ValueError, "gas remained is not numeric" unless gas_remained.is_a?(Numeric)
logger.debug "_create_", result: result, gas_remained: gas_remained, data: data
end
raise ValueError, "gas remained cannot be negative" unless gas_remained >= 0
logger.debug "TX APPLIED", result: result, gas_remained: gas_remained, data: data
if result.true?
logger.debug "TX SUCCESS", data: data
gas_used = tx.startgas - gas_remained
self.refunds += self.suicides.uniq.size * Opcodes::GSUICIDEREFUND
if refunds > 0
gas_refund = [refunds, gas_used/2].min
logger.debug "Refunding", gas_refunded: gas_refund
gas_remained += gas_refund
gas_used -= gas_refund
self.refunds = 0
end
delta_balance tx.sender, tx.gasprice * gas_remained
delta_balance coinbase, tx.gasprice * gas_used
self.gas_used += gas_used
output = tx.to.true? ? Utils.int_array_to_bytes(data) : data
success = 1
else # 0 = OOG failure in both cases
logger.debug "TX FAILED", reason: 'out of gas', startgas: tx.startgas, gas_remained: gas_remained
self.gas_used += tx.startgas
delta_balance coinbase, tx.gasprice*tx.startgas
output = Constant::BYTE_EMPTY
success = 0
end
commit_state
suicides.each do |s|
self.ether_delta -= get_balance(s)
set_balance s, 0 # TODO: redundant with code in SUICIDE op?
del_account s
end
self.suicides = []
add_transaction_to_list tx
self.logs = []
# TODO: change success to Bool type
return success, output
end
def get_intrinsic_gas(tx)
intrinsic_gas = tx.intrinsic_gas_used
if number >= config[:homestead_fork_blknum]
intrinsic_gas += Opcodes::CREATE[3] if tx.to.false? || tx.to == Address::CREATE_CONTRACT
end
intrinsic_gas
end
##
# Get the `num`th transaction in this block.
#
# @raise [IndexError] if the transaction does not exist
#
def get_transaction(num)
index = RLP.encode num
tx = @transactions.get index
raise IndexError, "Transaction does not exist" if tx == Trie::BLANK_NODE
RLP.decode tx, sedes: Transaction
end
##
# Build a list of all transactions in this block.
#
def get_transactions
# FIXME: such memoization is potentially buggy - what if pop b from and
# push a to the cache? size will not change while content changed.
if @get_transactions_cache.size != @transaction_count
@get_transactions_cache = transaction_list
end
@get_transactions_cache
end
##
# helper to check if block contains a tx.
#
def get_transaction_hashes
@transaction_count.times.map do |i|
Utils.keccak256 @transactions[RLP.encode(i)]
end
end
def include_transaction?(tx_hash)
raise ArgumentError, "argument must be transaction hash in bytes" unless tx_hash.size == 32
get_transaction_hashes.include?(tx_hash)
end
def transaction_count
@transaction_count
end
##
# Apply rewards and commit.
#
def finalize
delta = @config[:block_reward] + @config[:nephew_reward] * uncles.size
delta_balance coinbase, delta
self.ether_delta += delta
uncles.each do |uncle|
r = @config[:block_reward] * (@config[:uncle_depth_penalty_factor] + uncle.number - number) / @config[:uncle_depth_penalty_factor]
delta_balance uncle.coinbase, r
self.ether_delta += r
end
commit_state
end
##
# Serialize the block to a readable hash.
#
# @param with_state [Bool] include state for all accounts
# @param full_transactions [Bool] include serialized transactions (hashes
# otherwise)
# @param with_storage_roots [Bool] if account states are included also
# include their storage roots
# @param with_uncles [Bool] include uncle hashes
#
# @return [Hash] a hash represents the block
#
def to_h(with_state: false, full_transactions: false, with_storage_roots: false, with_uncles: false)
b = { header: header.to_h }
txlist = []
get_transactions.each_with_index do |tx, i|
receipt_rlp = @receipts[RLP.encode(i)]
receipt = RLP.decode receipt_rlp, sedes: Receipt
txjson = full_transactions ? tx.to_h : tx.full_hash
logs = receipt.logs.map {|l| Log.serialize(l) }
txlist.push(
tx: txjson,
medstate: Utils.encode_hex(receipt.state_root),
gas: receipt.gas_used.to_s,
logs: logs,
bloom: Sedes.int256.serialize(receipt.bloom)
)
end
b[:transactions] = txlist
if with_state
state_dump = {}
@state.each do |address, v|
state_dump[Utils.encode_hex(address)] = account_to_dict(address, with_storage_root: with_storage_roots)
end
b[:state] = state_dump
end
if with_uncles
b[:uncles] = uncles.map {|u| RLP.decode(u, sedes: BlockHeader) }
end
b
end
def mining_hash
header.mining_hash
end
##
# `true` if this block has a known parent, otherwise `false`.
#
def has_parent?
get_parent
true
rescue UnknownParentError
false
end
def get_parent_header
raise UnknownParentError, "Genesis block has no parent" if number == 0
BlockHeader.find db, prevhash
rescue KeyError
raise UnknownParentError, Utils.encode_hex(prevhash)
end
##
# Get the parent of this block.
#
def get_parent
raise UnknownParentError, "Genesis block has no parent" if number == 0
Block.find env, prevhash
rescue KeyError
raise UnknownParentError, Utils.encode_hex(prevhash)
end
##
# Get the summarized difficulty.
#
# If the summarized difficulty is not stored in the database, it will be
# calculated recursively and put int the database.
#
def chain_difficulty
return difficulty if genesis?
k = "difficulty:#{Utils.encode_hex(full_hash)}"
return Utils.decode_int(db.get(k)) if db.has_key?(k)
o = difficulty + get_parent.chain_difficulty
@state.db.put_temporarily k, Utils.encode_int(o)
o
end
##
# Commit account caches. Write the account caches on the corresponding
# tries.
#
def commit_state
return if @journal.empty?
changes = []
addresses = @caches[:all].keys.sort
addresses.each do |addr|
acct = get_account addr
%i(balance nonce code storage).each do |field|
if v = @caches[field][addr]
changes.push [field, addr, v]
acct.send :"#{field}=", v
end
end
t = SecureTrie.new PruningTrie.new(db, acct.storage)
@caches.fetch("storage:#{addr}", {}).each do |k, v|
enckey = Utils.zpad Utils.coerce_to_bytes(k), 32
val = RLP.encode v
changes.push ['storage', addr, k, v]
v.true? ? t.set(enckey, val) : t.delete(enckey)
end
acct.storage = t.root_hash
@state[addr] = RLP.encode(acct)
end
logger.debug "delta changes=#{changes}"
reset_cache
db.put_temporarily "validated:#{full_hash}", '1'
end
def commit_state_db
@state.db.commit
end
def account_exists(address)
address = Utils.normalize_address address
@state[address].size > 0 || @caches[:all].has_key?(address)
end
def add_log(log)
logs.push log
log_listeners.each {|l| l.call log }
end
##
# Increase the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] can be positive or negative
#
# @return [Bool] return `true` if successful, otherwise `false`
#
def delta_balance(address, value)
delta_account_item(address, :balance, value)
end
##
# Reset cache and journal without commiting any changes.
#
def reset_cache
@caches = {
all: {},
balance: {},
nonce: {},
code: {},
storage: {}
}
@journal = []
end
##
# Make a snapshot of the current state to enable later reverting.
#
def snapshot
{ state: @state.root_hash,
gas: gas_used,
txs: @transactions,
txcount: @transaction_count,
refunds: refunds,
suicides: suicides,
suicides_size: suicides.size,
logs: logs,
logs_size: logs.size,
journal: @journal, # pointer to reference, so is not static
journal_size: @journal.size,
ether_delta: ether_delta
}
end
##
# Revert to a previously made snapshot.
#
# Reverting is for example neccessary when a contract runs out of gas
# during execution.
#
def revert(mysnapshot)
logger.debug "REVERTING"
@journal = mysnapshot[:journal]
# if @journal changed after snapshot
while @journal.size > mysnapshot[:journal_size]
cache, index, prev, post = @journal.pop
logger.debug "revert journal", cache: cache, index: index, prev: prev, post: post
if prev
@caches[cache][index] = prev
else
@caches[cache].delete index
end
end
self.suicides = mysnapshot[:suicides]
suicides.pop while suicides.size > mysnapshot[:suicides_size]
self.logs = mysnapshot[:logs]
logs.pop while logs.size > mysnapshot[:logs_size]
self.refunds = mysnapshot[:refunds]
self.gas_used = mysnapshot[:gas]
self.ether_delta = mysnapshot[:ether_delta]
@transactions = mysnapshot[:txs]
@transaction_count = mysnapshot[:txcount]
@state.set_root_hash mysnapshot[:state]
@get_transactions_cache = []
end
##
# Get the receipt of the `num`th transaction.
#
# @raise [IndexError] if receipt at index is not found
#
# @return [Receipt]
#
def get_receipt(num)
index = RLP.encode num
receipt = @receipts[index]
if receipt == Trie::BLANK_NODE
raise IndexError, "Receipt does not exist"
else
RLP.decode receipt, sedes: Receipt
end
end
##
# Build a list of all receipts in this block.
#
def get_receipts
receipts = []
i = 0
loop do
begin
receipts.push get_receipt(i)
i += 1
rescue IndexError
return receipts
end
end
end
##
# Get the nonce of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Integer] the nonce value
#
def get_nonce(address)
get_account_item address, :nonce
end
##
# Set the nonce of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] the new nonce
#
# @return [Bool] `true` if successful, otherwise `false`
#
def set_nonce(address, value)
set_account_item address, :nonce, value
end
##
# Increment the nonce of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Bool] `true` if successful, otherwise `false`
#
def increment_nonce(address)
if get_nonce(address) == 0
delta_account_item address, :nonce, config[:account_initial_nonce]+1
else
delta_account_item address, :nonce, 1
end
end
##
# Get the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Integer] balance value
#
def get_balance(address)
get_account_item address, :balance
end
##
# Set the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] the new balance value
#
# @return [Bool] `true` if successful, otherwise `false`
#
def set_balance(address, value)
set_account_item address, :balance, value
end
##
# Increase the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] can be positive or negative
#
# @return [Bool] `true` if successful, otherwise `false`
#
def delta_balance(address, value)
delta_account_item address, :balance, value
end
##
# Transfer a value between two account balance.
#
# @param from [String] the address of the sending account (binary or hex
# string)
# @param to [String] the address of the receiving account (binary or hex
# string)
# @param value [Integer] the (positive) value to send
#
# @return [Bool] `true` if successful, otherwise `false`
#
def transfer_value(from, to, value)
raise ArgumentError, "value must be greater or equal than zero" unless value >= 0
delta_balance(from, -value) && delta_balance(to, value)
end
##
# Get the code of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [String] account code
#
def get_code(address)
get_account_item address, :code
end
##
# Set the code of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [String] the new code bytes
#
# @return [Bool] `true` if successful, otherwise `false`
#
def set_code(address, value)
set_account_item address, :code, value
end
##
# Get the trie holding an account's storage.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Trie] the storage trie of account
#
def get_storage(address)
storage_root = get_account_item address, :storage
SecureTrie.new PruningTrie.new(db, storage_root)
end
def reset_storage(address)
set_account_item address, :storage, Constant::BYTE_EMPTY
cache_key = "storage:#{address}"
if @caches.has_key?(cache_key)
@caches[cache_key].each {|k, v| set_and_journal cache_key, k, 0 }
end
end
##
# Get a specific item in the storage of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param index [Integer] the index of the requested item in the storage
#
# @return [Integer] the value at storage index
#
def get_storage_data(address, index)
address = Utils.normalize_address address
cache = @caches["storage:#{address}"]
return cache[index] if cache && cache.has_key?(index)
key = Utils.zpad Utils.coerce_to_bytes(index), 32
value = get_storage(address)[key]
value.true? ? RLP.decode(value, sedes: Sedes.big_endian_int) : 0
end
##
# Set a specific item in the storage of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param index [Integer] the index of the requested item in the storage
# @param value [Integer] the new value of the item
#
def set_storage_data(address, index, value)
address = Utils.normalize_address address
cache_key = "storage:#{address}"
unless @caches.has_key?(cache_key)
@caches[cache_key] = {}
set_and_journal :all, address, true
end
set_and_journal cache_key, index, value
end
##
# Delete an account.
#
# @param address [String] the address of the account (binary or hex string)
#
def del_account(address)
address = Utils.normalize_address address
commit_state
@state.delete address
end
##
# Serialize an account to a hash with human readable entries.
#
# @param address [String] the account address
# @param with_storage_root [Bool] include the account's storage root
# @param with_storage [Bool] include the whole account's storage
#
# @return [Hash] hash represent the account
#
def account_to_dict(address, with_storage_root: false, with_storage: true)
address = Utils.normalize_address address
# if there are uncommited account changes the current storage root is
# meaningless
raise ArgumentError, "cannot include storage root with uncommited account changes" if with_storage_root && !@journal.empty?
h = {}
account = get_account address
h[:nonce] = (@caches[:nonce][address] || account.nonce).to_s
h[:balance] = (@caches[:balance][address] || account.balance).to_s
code = @caches[:code][address] || account.code
h[:code] = "0x#{Utils.encode_hex code}"
storage_trie = SecureTrie.new PruningTrie.new(db, account.storage)
h[:storage_root] = Utils.encode_hex storage_trie.root_hash if with_storage_root
if with_storage
h[:storage] = {}
sh = storage_trie.to_h
cache = @caches["storage:#{address}"] || {}
keys = cache.keys.map {|k| Utils.zpad Utils.coerce_to_bytes(k), 32 }
(sh.keys + keys).each do |k|
hexkey = "0x#{Utils.encode_hex Utils.zunpad(k)}"
v = cache[Utils.big_endian_to_int(k)]
if v.true?
h[:storage][hexkey] = "0x#{Utils.encode_hex Utils.int_to_big_endian(v)}"
else
v = sh[k]
h[:storage][hexkey] = "0x#{Utils.encode_hex RLP.decode(v)}" if v
end
end
end
h
end
##
# Return `n` ancestors of this block.
#
# @return [Array] array of ancestors in format of `[parent, parent.parent, ...]
#
def get_ancestor_list(n)
raise ArgumentError, "n must be greater or equal than zero" unless n >= 0
return [] if n == 0 || number == 0
parent = get_parent
[parent] + parent.get_ancestor_list(n-1)
end
def get_ancestor_hash(n)
raise ArgumentError, "n must be greater than 0 and less or equal than 256" unless n > 0 && n <= 256
while ancestor_hashes.size < n
if number == ancestor_hashes.size - 1
ancestor_hashes.push nil
else
ancestor_hashes.push self.class.find(env, ancestor_hashes[-1]).get_parent().full_hash
end
end
ancestor_hashes[n-1]
end
def genesis?
number == 0
end
##
# Two blocks are equal iff they have the same hash.
#
def ==(other)
(other.instance_of?(Block) || other.instance_of?(CachedBlock)) &&
full_hash == other.full_hash
end
def hash
Utils.big_endian_to_int full_hash
end
def >(other)
number > other.number
end
def <(other)
number < other.number
end
def to_s
"#<#{self.class.name}:#{object_id} ##{number} #{Utils.encode_hex full_hash[0,8]}>"
end
alias :inspect :to_s
def validate_transaction(tx)
unless tx.sender
if number >= config[:metropolis_fork_blknum]
tx.sender = Utils.normalize_address(config[:metropolis_entry_point])
else
raise UnsignedTransactionError.new(tx)
end
end
acct_nonce = get_nonce tx.sender
raise InvalidNonce, "#{tx}: nonce actual: #{tx.nonce} target: #{acct_nonce}" if acct_nonce != tx.nonce
min_gas = get_intrinsic_gas tx
raise InsufficientStartGas, "#{tx}: startgas actual: #{tx.startgas} target: #{min_gas}" if tx.startgas < min_gas
total_cost = tx.value + tx.gasprice * tx.startgas
balance = get_balance tx.sender
raise InsufficientBalance, "#{tx}: balance actual: #{balance} target: #{total_cost}" if balance < total_cost
accum_gas = gas_used + tx.startgas
raise BlockGasLimitReached, "#{tx}: gaslimit actual: #{accum_gas} target: #{gas_limit}" if accum_gas > gas_limit
tx.check_low_s if number >= config[:homestead_fork_blknum]
true
end
private
def logger
@logger ||= Logger.new 'eth.block'
end
def initialize_state(transaction_list, parent, making)
state_unknown =
prevhash != @config[:genesis_prevhash] &&
number != 0 &&
header.state_root != PruningTrie::BLANK_ROOT &&
(header.state_root.size != 32 || !db.has_key?("validated:#{full_hash}")) &&
!making
if state_unknown
raise ArgumentError, "transaction list cannot be nil" unless transaction_list
parent ||= get_parent_header
@state = SecureTrie.new PruningTrie.new(db, parent.state_root)
@transaction_count = 0 # TODO - should always equal @transactions.size
self.gas_used = 0
transaction_list.each {|tx| apply_transaction tx }
finalize
else # trust the state root in the header
@state = SecureTrie.new PruningTrie.new(db, header._state_root)
@transaction_count = 0
transaction_list.each {|tx| add_transaction_to_list(tx) } if transaction_list
raise ValidationError, "Transaction list root hash does not match" if @transactions.root_hash != header.tx_list_root
# receipts trie populated by add_transaction_to_list is incorrect (it
# doesn't know intermediate states), so reset it
@receipts = PruningTrie.new db, header.receipts_root
end
end
##
# Validate block (header) against previous block.
#
def validate_parent!(parent)
raise ValidationError, "Parent lives in different database" if parent && db != parent.db && db.db != parent.db # TODO: refactor the db.db mess
raise ValidationError, "Block's prevhash and parent's hash do not match" if prevhash != parent.full_hash
raise ValidationError, "Block's number is not the successor of its parent number" if number != parent.number+1
raise ValidationError, "Block's gaslimit is inconsistent with its parent's gaslimit" unless Block.check_gaslimit(parent, gas_limit)
raise ValidationError, "Block's difficulty is inconsistent with its parent's difficulty" if difficulty != Block.calc_difficulty(parent, timestamp)
raise ValidationError, "Gas used exceeds gas limit" if gas_used > gas_limit
raise ValidationError, "Timestamp equal to or before parent" if timestamp <= parent.timestamp
raise ValidationError, "Timestamp way too large" if timestamp > Constant::UINT_MAX
end
##
# Validate (transaction applied) block against its header, plus fields and
# value check.
#
def validate_block!(original_values)
raise InvalidBlock, "gas_used mistmatch actual: #{gas_used} target: #{original_values[:gas_used]}" if gas_used != original_values[:gas_used]
raise InvalidBlock, "timestamp mistmatch actual: #{timestamp} target: #{original_values[:timestamp]}" if timestamp != original_values[:timestamp]
raise InvalidBlock, "difficulty mistmatch actual: #{difficulty} target: #{original_values[:difficulty]}" if difficulty != original_values[:difficulty]
raise InvalidBlock, "bloom mistmatch actual: #{bloom} target: #{original_values[:bloom]}" if bloom != original_values[:bloom]
uh = Utils.keccak256_rlp uncles
raise InvalidBlock, "uncles_hash mistmatch actual: #{uh} target: #{original_values[:uncles_hash]}" if uh != original_values[:uncles_hash]
raise InvalidBlock, "header must reference no block" unless header.block.nil?
raise InvalidBlock, "state_root mistmatch actual: #{Utils.encode_hex @state.root_hash} target: #{Utils.encode_hex header.state_root}" if @state.root_hash != header.state_root
raise InvalidBlock, "tx_list_root mistmatch actual: #{@transactions.root_hash} target: #{header.tx_list_root}" if @transactions.root_hash != header.tx_list_root
raise InvalidBlock, "receipts_root mistmatch actual: #{@receipts.root_hash} target: #{header.receipts_root}" if @receipts.root_hash != header.receipts_root
raise ValueError, "Block is invalid" unless validate_fields
raise ValueError, "Extra data cannot exceed #{config[:max_extradata_length]} bytes" if header.extra_data.size > config[:max_extradata_length]
raise ValueError, "Coinbase cannot be empty address" if header.coinbase.false?
raise ValueError, "State merkle root of block #{self} not found in database" unless @state.root_hash_valid?
raise InvalidNonce, "PoW check failed" if !genesis? && nonce.true? && !header.check_pow
end
##
# Check that the values of all fields are well formed.
#
# Serialize and deserialize and check that the values didn't change.
#
def validate_fields
l = Block.serialize self
RLP.decode(RLP.encode(l)) == l
end
##
# Add a value to an account item.
#
# If the resulting value would be negative, it is left unchanged and
# `false` is returned.
#
# @param address [String] the address of the account (binary or hex string)
# @param param [Symbol] the parameter to increase or decrease (`:nonce`,
# `:balance`, `:storage`, or `:code`)
# @param value [Integer] can be positive or negative
#
# @return [Bool] `true` if the operation was successful, `false` if not
#
def delta_account_item(address, param, value)
new_value = get_account_item(address, param) + value
return false if new_value < 0
set_account_item(address, param, new_value % 2**256)
true
end
##
# Get a specific parameter of a specific account.
#
# @param address [String] the address of the account (binary or hex string)
# @param param [Symbol] the requested parameter (`:nonce`, `:balance`,
# `:storage` or `:code`)
#
# @return [Object] the value
#
def get_account_item(address, param)
address = Utils.normalize_address address, allow_blank: true
return @caches[param][address] if @caches[param].has_key?(address)
account = get_account address
v = account.send param
@caches[param][address] = v
v
end
##
# Set a specific parameter of a specific account.
#
# @param address [String] the address of the account (binary or hex string)
# @param param [Symbol] the requested parameter (`:nonce`, `:balance`,
# `:storage` or `:code`)
# @param value [Object] the new value
#
def set_account_item(address, param, value)
raise ArgumentError, "invalid address: #{address}" unless address.size == 20 || address.size == 40
address = Utils.decode_hex(address) if address.size == 40
set_and_journal(param, address, value)
set_and_journal(:all, address, true)
end
##
# Get the account with the given address.
#
# Note that this method ignores cached account items.
#
def get_account(address)
address = Utils.normalize_address address, allow_blank: true
rlpdata = @state[address]
if rlpdata == Trie::BLANK_NODE
Account.build_blank db, config[:account_initial_nonce]
else
RLP.decode(rlpdata, sedes: Account, db: db).tap do |acct|
acct.make_mutable!
acct._cached_rlp = nil
end
end
end
##
# @param ns [Symbol] cache namespace
# @param k [String] cache key
# @param v [Object] cache value
#
def set_and_journal(ns, k, v)
prev = @caches[ns][k]
if prev != v
@journal.push [ns, k, prev, v]
@caches[ns][k] = v
end
end
def mk_transaction_receipt(tx)
Receipt.new state_root, gas_used, logs
end
end
end
EIP 98
# -*- encoding : ascii-8bit -*-
require 'forwardable'
module Ethereum
##
# A block.
#
# All attributes from the block header are accessible via properties (i.e.
# `block.prevhash` is equivalent to `block.header.prevhash`). It is ensured
# that no discrepancies between header and the block occur.
#
class Block
include RLP::Sedes::Serializable
HeaderGetters = (BlockHeader.serializable_fields.keys - %i(state_root receipts_root tx_list_root)).freeze
HeaderSetters = HeaderGetters.map {|field| :"#{field}=" }.freeze
set_serializable_fields(
header: BlockHeader,
transaction_list: RLP::Sedes::CountableList.new(Transaction),
uncles: RLP::Sedes::CountableList.new(BlockHeader)
)
extend Forwardable
def_delegators :header, *HeaderGetters, *HeaderSetters
attr :env, :db, :config
attr_accessor :state, :transactions, :receipts, :refunds, :suicides, :ether_delta, :ancestor_hashes, :logs, :log_listeners
class <<self
##
# Assumption: blocks loaded from the db are not manipulated -> can be
# cached including hash.
def find(env, hash)
raise ArgumentError, "env must be instance of Env" unless env.instance_of?(Env)
blk = RLP.decode env.db.get(hash), sedes: Block, env: env
CachedBlock.create_cached blk
end
lru_cache :find, 1024
def verify(block, parent)
block2 = RLP.decode RLP.encode(block), sedes: Block, env: parent.env, parent: parent
raise "block not match" unless block == block2
true
rescue InvalidBlock
false
end
##
# Create a block without specifying transactions or uncles.
#
# @param header_rlp [String] the RLP encoded block header
# @param env [Env] provide database for the block
#
# @return [Block]
#
def build_from_header(header_rlp, env)
header = RLP.decode header_rlp, sedes: BlockHeader
new header, transaction_list: nil, uncles: [], env: env
end
##
# Create a new block based on a parent block.
#
# The block will not include any transactions and will not be finalized.
#
def build_from_parent(parent, coinbase, nonce: Constant::BYTE_EMPTY, extra_data: Constant::BYTE_EMPTY, timestamp: Time.now.to_i, uncles: [], env: nil)
env ||= parent.env
header = BlockHeader.new(
prevhash: parent.full_hash,
uncles_hash: Utils.keccak256_rlp(uncles),
coinbase: coinbase,
state_root: parent.state_root,
tx_list_root: Trie::BLANK_ROOT,
receipts_root: Trie::BLANK_ROOT,
bloom: 0,
difficulty: calc_difficulty(parent, timestamp),
mixhash: Constant::BYTE_EMPTY,
number: parent.number+1,
gas_limit: calc_gaslimit(parent),
gas_used: 0,
timestamp: timestamp,
extra_data: extra_data,
nonce: nonce
)
Block.new(
header,
transaction_list: [],
uncles: uncles,
env: env,
parent: parent,
making: true
).tap do |blk|
blk.ancestor_hashes = [parent.full_hash] + parent.ancestor_hashes
blk.log_listeners = parent.log_listeners
end
end
def calc_difficulty(parent, ts)
config = parent.config
offset = parent.difficulty / config[:block_diff_factor]
if parent.number >= (config[:homestead_fork_blknum] - 1)
sign = [1 - ((ts - parent.timestamp) / config[:homestead_diff_adjustment_cutoff]), -99].max
else
sign = (ts - parent.timestamp) < config[:diff_adjustment_cutoff] ? 1 : -1
end
# If we enter a special mode where the genesis difficulty starts off
# below the minimal difficulty, we allow low-difficulty blocks (this will
# never happen in the official protocol)
o = [parent.difficulty + offset*sign, [parent.difficulty, config[:min_diff]].min].max
period_count = (parent.number + 1) / config[:expdiff_period]
if period_count >= config[:expdiff_free_periods]
o = [o + 2**(period_count - config[:expdiff_free_periods]), config[:min_diff]].max
end
o
end
def calc_gaslimit(parent)
config = parent.config
decay = parent.gas_limit / config[:gaslimit_ema_factor]
new_contribution = ((parent.gas_used * config[:blklim_factor_nom]) / config[:blklim_factor_den] / config[:gaslimit_ema_factor])
gl = [parent.gas_limit - decay + new_contribution, config[:min_gas_limit]].max
if gl < config[:genesis_gas_limit]
gl2 = parent.gas_limit + decay
gl = [config[:genesis_gas_limit], gl2].min
end
raise ValueError, "invalid gas limit" unless check_gaslimit(parent, gl)
gl
end
def check_gaslimit(parent, gas_limit)
config = parent.config
adjmax = parent.gas_limit / config[:gaslimit_adjmax_factor]
(gas_limit - parent.gas_limit).abs <= adjmax && gas_limit >= parent.config[:min_gas_limit]
end
##
# Build the genesis block.
#
def genesis(env, options={})
allowed_args = %i(start_alloc bloom prevhash coinbase difficulty gas_limit gas_used timestamp extra_data mixhash nonce)
invalid_options = options.keys - allowed_args
raise ArgumentError, "invalid options: #{invalid_options}" unless invalid_options.empty?
start_alloc = options[:start_alloc] || env.config[:genesis_initial_alloc]
header = BlockHeader.new(
prevhash: options[:prevhash] || env.config[:genesis_prevhash],
uncles_hash: Utils.keccak256_rlp([]),
coinbase: options[:coinbase] || env.config[:genesis_coinbase],
state_root: Trie::BLANK_ROOT,
tx_list_root: Trie::BLANK_ROOT,
receipts_root: Trie::BLANK_ROOT,
bloom: options[:bloom] || 0,
difficulty: options[:difficulty] || env.config[:genesis_difficulty],
number: 0,
gas_limit: options[:gas_limit] || env.config[:genesis_gas_limit],
gas_used: options[:gas_used] || 0,
timestamp: options[:timestamp] || 0,
extra_data: options[:extra_data] || env.config[:genesis_extra_data],
mixhash: options[:mixhash] || env.config[:genesis_mixhash],
nonce: options[:nonce] || env.config[:genesis_nonce]
)
block = Block.new header, transaction_list: [], uncles: [], env: env
start_alloc.each do |addr, data|
addr = Utils.normalize_address addr
block.set_balance addr, Utils.parse_int_or_hex(data[:wei]) if data[:wei]
block.set_balance addr, Utils.parse_int_or_hex(data[:balance]) if data[:balance]
block.set_code addr, Utils.decode_hex(Utils.remove_0x_head(data[:code])) if data[:code]
block.set_nonce addr, Utils.parse_int_or_hex(data[:nonce]) if data[:nonce]
if data[:storage]
data[:storage].each do |k, v|
k = Utils.big_endian_to_int Utils.decode_hex(Utils.remove_0x_head(k))
v = Utils.big_endian_to_int Utils.decode_hex(Utils.remove_0x_head(v))
block.set_storage_data addr, k, v
end
end
end
block.commit_state
block.commit_state_db
# genesis block has predefined state root (so no additional
# finalization necessary)
block
end
end
##
# Arguments in format of:
# `header, transaction_list=[], uncles=[], env=nil, parent=nil,
# making=false`
#
# @param args [Array] mix of arguments:
#
# * header {BlockHeader} optional. if given, will be used as block
# header. if not given, you must specify header by `options[:header]`
# * options (Hash) optional.
# - transaction_list {Array[Transaction]} a list of transactions
# which are replayed if the state given by the header is not known.
# If the state is known, `nil` can be used instead of the empty
# list.
# - uncles {Array[BlockHeader]} a list of the headers of the uncles
# of this block
# - env {Env} env including db in which the block's state,
# transactions and receipts are stored (required)
# - parent {Block} optional parent which if not given may have to be
# loaded from the database for replay
#
def initialize(*args)
header = args.first.instance_of?(BlockHeader) ? args.first : nil
options = args.last.instance_of?(Hash) ? args.last : {}
header = options.delete(:header) if options.has_key?(:header)
transaction_list = options.has_key?(:transaction_list) ? options[:transaction_list] : []
uncles = options.has_key?(:uncles) ? options[:uncles] : []
env = options.delete(:env)
parent = options.delete(:parent)
making = options.has_key?(:making) ? options.delete(:making) : false
raise ArgumentError, "No Env object given" unless env.instance_of?(Env)
raise ArgumentError, "No database object given. db=#{env.db}" unless env.db.is_a?(DB::BaseDB)
@env = env
@db = env.db
@config = env.config
_set_field :header, header
_set_field :uncles, uncles
reset_cache
@get_transactions_cache = []
self.suicides = []
self.logs = []
self.log_listeners = []
self.refunds = 0
self.ether_delta = 0
self.ancestor_hashes = number > 0 ? [prevhash] : [nil]*256
validate_parent!(parent) if parent
original_values = {
bloom: bloom,
gas_used: gas_used,
timestamp: timestamp,
difficulty: difficulty,
uncles_hash: uncles_hash,
header_mutable: header.mutable?
}
make_mutable!
header.make_mutable!
@transactions = PruningTrie.new db
@receipts = PruningTrie.new db
initialize_state(transaction_list, parent, making)
validate_block!(original_values)
unless db.has_key?("validated:#{full_hash}")
if number == 0
db.put "validated:#{full_hash}", '1'
else
db.put_temporarily "validated:#{full_hash}", '1'
end
end
header.block = self
header.instance_variable_set :@_mutable, original_values[:header_mutable]
end
def add_listener(l)
log_listeners.push l
end
##
# The binary block hash. This is equivalent to `header.full_hash`.
#
def full_hash
Utils.keccak256_rlp header
end
##
# The hex encoded block hash. This is equivalent to `header.full_hash_hex`.
#
def full_hash_hex
Utils.encode_hex full_hash
end
def tx_list_root
@transactions.root_hash
end
def tx_list_root=(v)
@transactions = PruningTrie.new db, v
end
def receipts_root
@receipts.root_hash
end
def receipts_root=(v)
@receipts = PruningTrie.new db, v
end
def state_root
commit_state
@state.root_hash
end
def state_root=(v)
@state = SecureTrie.new PruningTrie.new(db, v)
reset_cache
end
def transaction_list
@transaction_count.times.map {|i| get_transaction(i) }
end
def uncles_hash
Utils.keccak256_rlp(uncles)
end
##
# Validate the uncles of this block.
#
def validate_uncles
return false if Utils.keccak256_rlp(uncles) != uncles_hash
return false if uncles.size > config[:max_uncles]
uncles.each do |uncle|
raise InvalidUncles, "Cannot find uncle prevhash in db" unless db.include?(uncle.prevhash)
if uncle.number == number
logger.error "uncle at same block height", block: self
return false
end
end
max_uncle_depth = config[:max_uncle_depth]
ancestor_chain = [self] + get_ancestor_list(max_uncle_depth+1)
raise ValueError, "invalid ancestor chain" unless ancestor_chain.size == [number+1, max_uncle_depth+2].min
# Uncles of this block cannot be direct ancestors and cannot also be
# uncles included 1-6 blocks ago.
ineligible = []
ancestor_chain.safe_slice(1..-1).each {|a| ineligible.concat a.uncles }
ineligible.concat(ancestor_chain.map {|a| a.header })
eligible_ancestor_hashes = ancestor_chain.safe_slice(2..-1).map(&:full_hash)
uncles.each do |uncle|
parent = Block.find env, uncle.prevhash
return false if uncle.difficulty != Block.calc_difficulty(parent, uncle.timestamp)
return false if uncle.number != parent.number + 1
return false if uncle.timestamp < parent.timestamp
return false unless uncle.check_pow
unless eligible_ancestor_hashes.include?(uncle.prevhash)
eligible = eligible_ancestor_hashes.map {|h| Utils.encode_hex(h) }
logger.error "Uncle does not have a valid ancestor", block: self, eligible: eligible, uncle_prevhash: Utils.encode_hex(uncle.prevhash)
return false
end
if ineligible.include?(uncle)
logger.error "Duplicate uncle", block: self, uncle: Utils.encode_hex(Utils.keccak256_rlp(uncle))
return false
end
# FIXME: what if uncles include previously rewarded uncle?
ineligible.push uncle
end
true
end
def add_refund(x)
self.refunds += x
end
##
# Add a transaction to the transaction trie.
#
# Note that this does not execute anything, i.e. the state is not updated.
#
def add_transaction_to_list(tx)
k = RLP.encode @transaction_count
@transactions[k] = RLP.encode(tx)
r = mk_transaction_receipt tx
@receipts[k] = RLP.encode(r)
self.bloom |= r.bloom
@transaction_count += 1
end
def build_external_call(tx)
ExternalCall.new self, tx
end
def apply_transaction(tx)
validate_transaction tx
intrinsic_gas = get_intrinsic_gas tx
logger.debug "apply transaction", tx: tx.log_dict
increment_nonce tx.sender
# buy startgas
delta_balance tx.sender, -tx.startgas*tx.gasprice
message_gas = tx.startgas - intrinsic_gas
message_data = VM::CallData.new tx.data.bytes, 0, tx.data.size
message = VM::Message.new tx.sender, tx.to, tx.value, message_gas, message_data, code_address: tx.to
ec = build_external_call tx
if tx.to.true? && tx.to != Address::CREATE_CONTRACT
result, gas_remained, data = ec.apply_msg message
logger.debug "_res_", result: result, gas_remained: gas_remained, data: data
else # CREATE
result, gas_remained, data = ec.create message
raise ValueError, "gas remained is not numeric" unless gas_remained.is_a?(Numeric)
logger.debug "_create_", result: result, gas_remained: gas_remained, data: data
end
raise ValueError, "gas remained cannot be negative" unless gas_remained >= 0
logger.debug "TX APPLIED", result: result, gas_remained: gas_remained, data: data
if result.true?
logger.debug "TX SUCCESS", data: data
gas_used = tx.startgas - gas_remained
self.refunds += self.suicides.uniq.size * Opcodes::GSUICIDEREFUND
if refunds > 0
gas_refund = [refunds, gas_used/2].min
logger.debug "Refunding", gas_refunded: gas_refund
gas_remained += gas_refund
gas_used -= gas_refund
self.refunds = 0
end
delta_balance tx.sender, tx.gasprice * gas_remained
delta_balance coinbase, tx.gasprice * gas_used
self.gas_used += gas_used
output = tx.to.true? ? Utils.int_array_to_bytes(data) : data
success = 1
else # 0 = OOG failure in both cases
logger.debug "TX FAILED", reason: 'out of gas', startgas: tx.startgas, gas_remained: gas_remained
self.gas_used += tx.startgas
delta_balance coinbase, tx.gasprice*tx.startgas
output = Constant::BYTE_EMPTY
success = 0
end
commit_state
suicides.each do |s|
self.ether_delta -= get_balance(s)
set_balance s, 0 # TODO: redundant with code in SUICIDE op?
del_account s
end
self.suicides = []
add_transaction_to_list tx
self.logs = []
# TODO: change success to Bool type
return success, output
end
def get_intrinsic_gas(tx)
intrinsic_gas = tx.intrinsic_gas_used
if number >= config[:homestead_fork_blknum]
intrinsic_gas += Opcodes::CREATE[3] if tx.to.false? || tx.to == Address::CREATE_CONTRACT
end
intrinsic_gas
end
##
# Get the `num`th transaction in this block.
#
# @raise [IndexError] if the transaction does not exist
#
def get_transaction(num)
index = RLP.encode num
tx = @transactions.get index
raise IndexError, "Transaction does not exist" if tx == Trie::BLANK_NODE
RLP.decode tx, sedes: Transaction
end
##
# Build a list of all transactions in this block.
#
def get_transactions
# FIXME: such memoization is potentially buggy - what if pop b from and
# push a to the cache? size will not change while content changed.
if @get_transactions_cache.size != @transaction_count
@get_transactions_cache = transaction_list
end
@get_transactions_cache
end
##
# helper to check if block contains a tx.
#
def get_transaction_hashes
@transaction_count.times.map do |i|
Utils.keccak256 @transactions[RLP.encode(i)]
end
end
def include_transaction?(tx_hash)
raise ArgumentError, "argument must be transaction hash in bytes" unless tx_hash.size == 32
get_transaction_hashes.include?(tx_hash)
end
def transaction_count
@transaction_count
end
##
# Apply rewards and commit.
#
def finalize
delta = @config[:block_reward] + @config[:nephew_reward] * uncles.size
delta_balance coinbase, delta
self.ether_delta += delta
uncles.each do |uncle|
r = @config[:block_reward] * (@config[:uncle_depth_penalty_factor] + uncle.number - number) / @config[:uncle_depth_penalty_factor]
delta_balance uncle.coinbase, r
self.ether_delta += r
end
commit_state
end
##
# Serialize the block to a readable hash.
#
# @param with_state [Bool] include state for all accounts
# @param full_transactions [Bool] include serialized transactions (hashes
# otherwise)
# @param with_storage_roots [Bool] if account states are included also
# include their storage roots
# @param with_uncles [Bool] include uncle hashes
#
# @return [Hash] a hash represents the block
#
def to_h(with_state: false, full_transactions: false, with_storage_roots: false, with_uncles: false)
b = { header: header.to_h }
txlist = []
get_transactions.each_with_index do |tx, i|
receipt_rlp = @receipts[RLP.encode(i)]
receipt = RLP.decode receipt_rlp, sedes: Receipt
txjson = full_transactions ? tx.to_h : tx.full_hash
logs = receipt.logs.map {|l| Log.serialize(l) }
txlist.push(
tx: txjson,
medstate: Utils.encode_hex(receipt.state_root),
gas: receipt.gas_used.to_s,
logs: logs,
bloom: Sedes.int256.serialize(receipt.bloom)
)
end
b[:transactions] = txlist
if with_state
state_dump = {}
@state.each do |address, v|
state_dump[Utils.encode_hex(address)] = account_to_dict(address, with_storage_root: with_storage_roots)
end
b[:state] = state_dump
end
if with_uncles
b[:uncles] = uncles.map {|u| RLP.decode(u, sedes: BlockHeader) }
end
b
end
def mining_hash
header.mining_hash
end
##
# `true` if this block has a known parent, otherwise `false`.
#
def has_parent?
get_parent
true
rescue UnknownParentError
false
end
def get_parent_header
raise UnknownParentError, "Genesis block has no parent" if number == 0
BlockHeader.find db, prevhash
rescue KeyError
raise UnknownParentError, Utils.encode_hex(prevhash)
end
##
# Get the parent of this block.
#
def get_parent
raise UnknownParentError, "Genesis block has no parent" if number == 0
Block.find env, prevhash
rescue KeyError
raise UnknownParentError, Utils.encode_hex(prevhash)
end
##
# Get the summarized difficulty.
#
# If the summarized difficulty is not stored in the database, it will be
# calculated recursively and put int the database.
#
def chain_difficulty
return difficulty if genesis?
k = "difficulty:#{Utils.encode_hex(full_hash)}"
return Utils.decode_int(db.get(k)) if db.has_key?(k)
o = difficulty + get_parent.chain_difficulty
@state.db.put_temporarily k, Utils.encode_int(o)
o
end
##
# Commit account caches. Write the account caches on the corresponding
# tries.
#
def commit_state
return if @journal.empty?
changes = []
addresses = @caches[:all].keys.sort
addresses.each do |addr|
acct = get_account addr
%i(balance nonce code storage).each do |field|
if v = @caches[field][addr]
changes.push [field, addr, v]
acct.send :"#{field}=", v
end
end
t = SecureTrie.new PruningTrie.new(db, acct.storage)
@caches.fetch("storage:#{addr}", {}).each do |k, v|
enckey = Utils.zpad Utils.coerce_to_bytes(k), 32
val = RLP.encode v
changes.push ['storage', addr, k, v]
v.true? ? t.set(enckey, val) : t.delete(enckey)
end
acct.storage = t.root_hash
@state[addr] = RLP.encode(acct)
end
logger.debug "delta changes=#{changes}"
reset_cache
db.put_temporarily "validated:#{full_hash}", '1'
end
def commit_state_db
@state.db.commit
end
def account_exists(address)
address = Utils.normalize_address address
@state[address].size > 0 || @caches[:all].has_key?(address)
end
def add_log(log)
logs.push log
log_listeners.each {|l| l.call log }
end
##
# Increase the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] can be positive or negative
#
# @return [Bool] return `true` if successful, otherwise `false`
#
def delta_balance(address, value)
delta_account_item(address, :balance, value)
end
##
# Reset cache and journal without commiting any changes.
#
def reset_cache
@caches = {
all: {},
balance: {},
nonce: {},
code: {},
storage: {}
}
@journal = []
end
##
# Make a snapshot of the current state to enable later reverting.
#
def snapshot
{ state: @state.root_hash,
gas: gas_used,
txs: @transactions,
txcount: @transaction_count,
refunds: refunds,
suicides: suicides,
suicides_size: suicides.size,
logs: logs,
logs_size: logs.size,
journal: @journal, # pointer to reference, so is not static
journal_size: @journal.size,
ether_delta: ether_delta
}
end
##
# Revert to a previously made snapshot.
#
# Reverting is for example neccessary when a contract runs out of gas
# during execution.
#
def revert(mysnapshot)
logger.debug "REVERTING"
@journal = mysnapshot[:journal]
# if @journal changed after snapshot
while @journal.size > mysnapshot[:journal_size]
cache, index, prev, post = @journal.pop
logger.debug "revert journal", cache: cache, index: index, prev: prev, post: post
if prev
@caches[cache][index] = prev
else
@caches[cache].delete index
end
end
self.suicides = mysnapshot[:suicides]
suicides.pop while suicides.size > mysnapshot[:suicides_size]
self.logs = mysnapshot[:logs]
logs.pop while logs.size > mysnapshot[:logs_size]
self.refunds = mysnapshot[:refunds]
self.gas_used = mysnapshot[:gas]
self.ether_delta = mysnapshot[:ether_delta]
@transactions = mysnapshot[:txs]
@transaction_count = mysnapshot[:txcount]
@state.set_root_hash mysnapshot[:state]
@get_transactions_cache = []
end
##
# Get the receipt of the `num`th transaction.
#
# @raise [IndexError] if receipt at index is not found
#
# @return [Receipt]
#
def get_receipt(num)
index = RLP.encode num
receipt = @receipts[index]
if receipt == Trie::BLANK_NODE
raise IndexError, "Receipt does not exist"
else
RLP.decode receipt, sedes: Receipt
end
end
##
# Build a list of all receipts in this block.
#
def get_receipts
receipts = []
i = 0
loop do
begin
receipts.push get_receipt(i)
i += 1
rescue IndexError
return receipts
end
end
end
##
# Get the nonce of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Integer] the nonce value
#
def get_nonce(address)
get_account_item address, :nonce
end
##
# Set the nonce of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] the new nonce
#
# @return [Bool] `true` if successful, otherwise `false`
#
def set_nonce(address, value)
set_account_item address, :nonce, value
end
##
# Increment the nonce of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Bool] `true` if successful, otherwise `false`
#
def increment_nonce(address)
if get_nonce(address) == 0
delta_account_item address, :nonce, config[:account_initial_nonce]+1
else
delta_account_item address, :nonce, 1
end
end
##
# Get the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Integer] balance value
#
def get_balance(address)
get_account_item address, :balance
end
##
# Set the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] the new balance value
#
# @return [Bool] `true` if successful, otherwise `false`
#
def set_balance(address, value)
set_account_item address, :balance, value
end
##
# Increase the balance of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [Integer] can be positive or negative
#
# @return [Bool] `true` if successful, otherwise `false`
#
def delta_balance(address, value)
delta_account_item address, :balance, value
end
##
# Transfer a value between two account balance.
#
# @param from [String] the address of the sending account (binary or hex
# string)
# @param to [String] the address of the receiving account (binary or hex
# string)
# @param value [Integer] the (positive) value to send
#
# @return [Bool] `true` if successful, otherwise `false`
#
def transfer_value(from, to, value)
raise ArgumentError, "value must be greater or equal than zero" unless value >= 0
delta_balance(from, -value) && delta_balance(to, value)
end
##
# Get the code of an account.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [String] account code
#
def get_code(address)
get_account_item address, :code
end
##
# Set the code of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param value [String] the new code bytes
#
# @return [Bool] `true` if successful, otherwise `false`
#
def set_code(address, value)
set_account_item address, :code, value
end
##
# Get the trie holding an account's storage.
#
# @param address [String] the address of the account (binary or hex string)
#
# @return [Trie] the storage trie of account
#
def get_storage(address)
storage_root = get_account_item address, :storage
SecureTrie.new PruningTrie.new(db, storage_root)
end
def reset_storage(address)
set_account_item address, :storage, Constant::BYTE_EMPTY
cache_key = "storage:#{address}"
if @caches.has_key?(cache_key)
@caches[cache_key].each {|k, v| set_and_journal cache_key, k, 0 }
end
end
##
# Get a specific item in the storage of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param index [Integer] the index of the requested item in the storage
#
# @return [Integer] the value at storage index
#
def get_storage_data(address, index)
address = Utils.normalize_address address
cache = @caches["storage:#{address}"]
return cache[index] if cache && cache.has_key?(index)
key = Utils.zpad Utils.coerce_to_bytes(index), 32
value = get_storage(address)[key]
value.true? ? RLP.decode(value, sedes: Sedes.big_endian_int) : 0
end
##
# Set a specific item in the storage of an account.
#
# @param address [String] the address of the account (binary or hex string)
# @param index [Integer] the index of the requested item in the storage
# @param value [Integer] the new value of the item
#
def set_storage_data(address, index, value)
address = Utils.normalize_address address
cache_key = "storage:#{address}"
unless @caches.has_key?(cache_key)
@caches[cache_key] = {}
set_and_journal :all, address, true
end
set_and_journal cache_key, index, value
end
##
# Delete an account.
#
# @param address [String] the address of the account (binary or hex string)
#
def del_account(address)
address = Utils.normalize_address address
commit_state
@state.delete address
end
##
# Serialize an account to a hash with human readable entries.
#
# @param address [String] the account address
# @param with_storage_root [Bool] include the account's storage root
# @param with_storage [Bool] include the whole account's storage
#
# @return [Hash] hash represent the account
#
def account_to_dict(address, with_storage_root: false, with_storage: true)
address = Utils.normalize_address address
# if there are uncommited account changes the current storage root is
# meaningless
raise ArgumentError, "cannot include storage root with uncommited account changes" if with_storage_root && !@journal.empty?
h = {}
account = get_account address
h[:nonce] = (@caches[:nonce][address] || account.nonce).to_s
h[:balance] = (@caches[:balance][address] || account.balance).to_s
code = @caches[:code][address] || account.code
h[:code] = "0x#{Utils.encode_hex code}"
storage_trie = SecureTrie.new PruningTrie.new(db, account.storage)
h[:storage_root] = Utils.encode_hex storage_trie.root_hash if with_storage_root
if with_storage
h[:storage] = {}
sh = storage_trie.to_h
cache = @caches["storage:#{address}"] || {}
keys = cache.keys.map {|k| Utils.zpad Utils.coerce_to_bytes(k), 32 }
(sh.keys + keys).each do |k|
hexkey = "0x#{Utils.encode_hex Utils.zunpad(k)}"
v = cache[Utils.big_endian_to_int(k)]
if v.true?
h[:storage][hexkey] = "0x#{Utils.encode_hex Utils.int_to_big_endian(v)}"
else
v = sh[k]
h[:storage][hexkey] = "0x#{Utils.encode_hex RLP.decode(v)}" if v
end
end
end
h
end
##
# Return `n` ancestors of this block.
#
# @return [Array] array of ancestors in format of `[parent, parent.parent, ...]
#
def get_ancestor_list(n)
raise ArgumentError, "n must be greater or equal than zero" unless n >= 0
return [] if n == 0 || number == 0
parent = get_parent
[parent] + parent.get_ancestor_list(n-1)
end
def get_ancestor_hash(n)
raise ArgumentError, "n must be greater than 0 and less or equal than 256" unless n > 0 && n <= 256
while ancestor_hashes.size < n
if number == ancestor_hashes.size - 1
ancestor_hashes.push nil
else
ancestor_hashes.push self.class.find(env, ancestor_hashes[-1]).get_parent().full_hash
end
end
ancestor_hashes[n-1]
end
def genesis?
number == 0
end
##
# Two blocks are equal iff they have the same hash.
#
def ==(other)
(other.instance_of?(Block) || other.instance_of?(CachedBlock)) &&
full_hash == other.full_hash
end
def hash
Utils.big_endian_to_int full_hash
end
def >(other)
number > other.number
end
def <(other)
number < other.number
end
def to_s
"#<#{self.class.name}:#{object_id} ##{number} #{Utils.encode_hex full_hash[0,8]}>"
end
alias :inspect :to_s
def validate_transaction(tx)
unless tx.sender
if number >= config[:metropolis_fork_blknum]
tx.sender = Utils.normalize_address(config[:metropolis_entry_point])
else
raise UnsignedTransactionError.new(tx)
end
end
acct_nonce = get_nonce tx.sender
raise InvalidNonce, "#{tx}: nonce actual: #{tx.nonce} target: #{acct_nonce}" if acct_nonce != tx.nonce
min_gas = get_intrinsic_gas tx
raise InsufficientStartGas, "#{tx}: startgas actual: #{tx.startgas} target: #{min_gas}" if tx.startgas < min_gas
total_cost = tx.value + tx.gasprice * tx.startgas
balance = get_balance tx.sender
raise InsufficientBalance, "#{tx}: balance actual: #{balance} target: #{total_cost}" if balance < total_cost
accum_gas = gas_used + tx.startgas
raise BlockGasLimitReached, "#{tx}: gaslimit actual: #{accum_gas} target: #{gas_limit}" if accum_gas > gas_limit
tx.check_low_s if number >= config[:homestead_fork_blknum]
true
end
private
def logger
@logger ||= Logger.new 'eth.block'
end
def initialize_state(transaction_list, parent, making)
state_unknown =
prevhash != @config[:genesis_prevhash] &&
number != 0 &&
header.state_root != PruningTrie::BLANK_ROOT &&
(header.state_root.size != 32 || !db.has_key?("validated:#{full_hash}")) &&
!making
if state_unknown
raise ArgumentError, "transaction list cannot be nil" unless transaction_list
parent ||= get_parent_header
@state = SecureTrie.new PruningTrie.new(db, parent.state_root)
@transaction_count = 0 # TODO - should always equal @transactions.size
self.gas_used = 0
transaction_list.each {|tx| apply_transaction tx }
finalize
else # trust the state root in the header
@state = SecureTrie.new PruningTrie.new(db, header._state_root)
@transaction_count = 0
transaction_list.each {|tx| add_transaction_to_list(tx) } if transaction_list
raise ValidationError, "Transaction list root hash does not match" if @transactions.root_hash != header.tx_list_root
# receipts trie populated by add_transaction_to_list is incorrect (it
# doesn't know intermediate states), so reset it
@receipts = PruningTrie.new db, header.receipts_root
end
end
##
# Validate block (header) against previous block.
#
def validate_parent!(parent)
raise ValidationError, "Parent lives in different database" if parent && db != parent.db && db.db != parent.db # TODO: refactor the db.db mess
raise ValidationError, "Block's prevhash and parent's hash do not match" if prevhash != parent.full_hash
raise ValidationError, "Block's number is not the successor of its parent number" if number != parent.number+1
raise ValidationError, "Block's gaslimit is inconsistent with its parent's gaslimit" unless Block.check_gaslimit(parent, gas_limit)
raise ValidationError, "Block's difficulty is inconsistent with its parent's difficulty" if difficulty != Block.calc_difficulty(parent, timestamp)
raise ValidationError, "Gas used exceeds gas limit" if gas_used > gas_limit
raise ValidationError, "Timestamp equal to or before parent" if timestamp <= parent.timestamp
raise ValidationError, "Timestamp way too large" if timestamp > Constant::UINT_MAX
end
##
# Validate (transaction applied) block against its header, plus fields and
# value check.
#
def validate_block!(original_values)
raise InvalidBlock, "gas_used mistmatch actual: #{gas_used} target: #{original_values[:gas_used]}" if gas_used != original_values[:gas_used]
raise InvalidBlock, "timestamp mistmatch actual: #{timestamp} target: #{original_values[:timestamp]}" if timestamp != original_values[:timestamp]
raise InvalidBlock, "difficulty mistmatch actual: #{difficulty} target: #{original_values[:difficulty]}" if difficulty != original_values[:difficulty]
raise InvalidBlock, "bloom mistmatch actual: #{bloom} target: #{original_values[:bloom]}" if bloom != original_values[:bloom]
uh = Utils.keccak256_rlp uncles
raise InvalidBlock, "uncles_hash mistmatch actual: #{uh} target: #{original_values[:uncles_hash]}" if uh != original_values[:uncles_hash]
raise InvalidBlock, "header must reference no block" unless header.block.nil?
raise InvalidBlock, "state_root mistmatch actual: #{Utils.encode_hex @state.root_hash} target: #{Utils.encode_hex header.state_root}" if @state.root_hash != header.state_root
raise InvalidBlock, "tx_list_root mistmatch actual: #{@transactions.root_hash} target: #{header.tx_list_root}" if @transactions.root_hash != header.tx_list_root
raise InvalidBlock, "receipts_root mistmatch actual: #{@receipts.root_hash} target: #{header.receipts_root}" if @receipts.root_hash != header.receipts_root
raise ValueError, "Block is invalid" unless validate_fields
raise ValueError, "Extra data cannot exceed #{config[:max_extradata_length]} bytes" if header.extra_data.size > config[:max_extradata_length]
raise ValueError, "Coinbase cannot be empty address" if header.coinbase.false?
raise ValueError, "State merkle root of block #{self} not found in database" unless @state.root_hash_valid?
raise InvalidNonce, "PoW check failed" if !genesis? && nonce.true? && !header.check_pow
end
##
# Check that the values of all fields are well formed.
#
# Serialize and deserialize and check that the values didn't change.
#
def validate_fields
l = Block.serialize self
RLP.decode(RLP.encode(l)) == l
end
##
# Add a value to an account item.
#
# If the resulting value would be negative, it is left unchanged and
# `false` is returned.
#
# @param address [String] the address of the account (binary or hex string)
# @param param [Symbol] the parameter to increase or decrease (`:nonce`,
# `:balance`, `:storage`, or `:code`)
# @param value [Integer] can be positive or negative
#
# @return [Bool] `true` if the operation was successful, `false` if not
#
def delta_account_item(address, param, value)
new_value = get_account_item(address, param) + value
return false if new_value < 0
set_account_item(address, param, new_value % 2**256)
true
end
##
# Get a specific parameter of a specific account.
#
# @param address [String] the address of the account (binary or hex string)
# @param param [Symbol] the requested parameter (`:nonce`, `:balance`,
# `:storage` or `:code`)
#
# @return [Object] the value
#
def get_account_item(address, param)
address = Utils.normalize_address address, allow_blank: true
return @caches[param][address] if @caches[param].has_key?(address)
account = get_account address
v = account.send param
@caches[param][address] = v
v
end
##
# Set a specific parameter of a specific account.
#
# @param address [String] the address of the account (binary or hex string)
# @param param [Symbol] the requested parameter (`:nonce`, `:balance`,
# `:storage` or `:code`)
# @param value [Object] the new value
#
def set_account_item(address, param, value)
raise ArgumentError, "invalid address: #{address}" unless address.size == 20 || address.size == 40
address = Utils.decode_hex(address) if address.size == 40
set_and_journal(param, address, value)
set_and_journal(:all, address, true)
end
##
# Get the account with the given address.
#
# Note that this method ignores cached account items.
#
def get_account(address)
address = Utils.normalize_address address, allow_blank: true
rlpdata = @state[address]
if rlpdata == Trie::BLANK_NODE
Account.build_blank db, config[:account_initial_nonce]
else
RLP.decode(rlpdata, sedes: Account, db: db).tap do |acct|
acct.make_mutable!
acct._cached_rlp = nil
end
end
end
##
# @param ns [Symbol] cache namespace
# @param k [String] cache key
# @param v [Object] cache value
#
def set_and_journal(ns, k, v)
prev = @caches[ns][k]
if prev != v
@journal.push [ns, k, prev, v]
@caches[ns][k] = v
end
end
def mk_transaction_receipt(tx)
if number >= @config[:metropolis_fork_blknum]
Receipt.new Constant::HASH_ZERO, gas_used, logs
else
Receipt.new state_root, gas_used, logs
end
end
end
end
|
module EventCalendar
module PluginMethods
def has_event_calendar
ClassMethods.setup_event_calendar_on self
end
end
# class Methods
module ClassMethods
def self.setup_event_calendar_on(recipient)
recipient.extend ClassMethods
recipient.class_eval do
include InstanceMethods
end
end
# For the given month, find the start and end dates
# Find all the events within this range, and create event strips for them
def event_strips_for_month(shown_date)
strip_start, strip_end = get_start_and_end_dates(shown_date)
events = events_for_date_range(strip_start, strip_end)
event_strips = create_event_strips(strip_start, strip_end, events)
event_strips
end
# Expand start and end dates to show the previous month and next month's days,
# that overlap with the shown months display
def get_start_and_end_dates(shown_date)
# the end of last month
strip_start = beginning_of_week(shown_date)
# the beginning of next month
strip_end = beginning_of_week(shown_date.next_month + 7) - 1
[strip_start, strip_end]
end
# Get the events overlapping the given start and end dates
def events_for_date_range(start_d, end_d)
self.find(
:all,
:conditions => [ '(? <= end_at) AND (start_at <= ?)', start_d, end_d ],
:order => 'start_at ASC'
)
end
# Create the various strips that show evetns
def create_event_strips(strip_start, strip_end, events)
# create an inital event strip, with a nil entry for every day of the displayed days
event_strips = [[nil] * (strip_end - strip_start + 1)]
events.each do |event|
cur_date = event.start_at.to_date
end_date = event.end_at.to_date
cur_date, end_date = event.clip_range(strip_start, strip_end)
start_range = (cur_date - strip_start).to_i
end_range = (end_date - strip_start).to_i
# make sure the event is within our viewing range
if (start_range <= end_range) and (end_range >= 0)
range = start_range..end_range
open_strip = space_in_current_strips?(event_strips, range)
if open_strip.nil?
# no strips open, make a new one
new_strip = [nil] * (strip_end - strip_start + 1)
range.each {|r| new_strip[r] = event}
event_strips << new_strip
else
# found an open strip, add this event to it
range.each {|r| open_strip[r] = event}
end
end
end
event_strips
end
def space_in_current_strips?(event_strips, range)
open_strip = nil
for strip in event_strips
strip_is_open = true
range.each do |r|
# overlapping events on this strip
if !strip[r].nil?
strip_is_open = false
break
end
end
if strip_is_open
open_strip = strip
break
end
end
open_strip
end
def days_between(first, second)
if first > second
second + (7 - first)
else
second - first
end
end
def beginning_of_week(date, start = 0)
days_to_beg = days_between(start, date.wday)
date - days_to_beg
end
end
# Instance Methods
module InstanceMethods
def year
date.year
end
def month
date.month
end
def day
date.day
end
def color
self[:color] || '#9aa4ad'
end
def days
end_at.to_date - start_at.to_date
end
def clip_range(start_d, end_d)
# Clip start date, make sure it also ends on or after the start range
if (start_at < start_d and end_at >= start_d)
clipped_start = start_d
else
clipped_start = start_at.to_date
end
# Clip end date
if (end_at > end_d)
clipped_end = end_d
else
clipped_end = end_at.to_date
end
[clipped_start, clipped_end]
end
end
end
Show the calendar month for any passed in date. Don't assume it's the first of the month.
module EventCalendar
module PluginMethods
def has_event_calendar
ClassMethods.setup_event_calendar_on self
end
end
# class Methods
module ClassMethods
def self.setup_event_calendar_on(recipient)
recipient.extend ClassMethods
recipient.class_eval do
include InstanceMethods
end
end
# For the given month, find the start and end dates
# Find all the events within this range, and create event strips for them
def event_strips_for_month(shown_date)
strip_start, strip_end = get_start_and_end_dates(shown_date)
events = events_for_date_range(strip_start, strip_end)
event_strips = create_event_strips(strip_start, strip_end, events)
event_strips
end
# Expand start and end dates to show the previous month and next month's days,
# that overlap with the shown months display
def get_start_and_end_dates(shown_date)
# start with the first day of the given month
start_of_month = Date.civil(shown_date.year, shown_date.month, 1)
# the end of last month
strip_start = beginning_of_week(start_of_month)
# the beginning of next month
strip_end = beginning_of_week(start_of_month.next_month + 7) - 1
[strip_start, strip_end]
end
# Get the events overlapping the given start and end dates
def events_for_date_range(start_d, end_d)
self.find(
:all,
:conditions => [ '(? <= end_at) AND (start_at <= ?)', start_d, end_d ],
:order => 'start_at ASC'
)
end
# Create the various strips that show evetns
def create_event_strips(strip_start, strip_end, events)
# create an inital event strip, with a nil entry for every day of the displayed days
event_strips = [[nil] * (strip_end - strip_start + 1)]
events.each do |event|
cur_date = event.start_at.to_date
end_date = event.end_at.to_date
cur_date, end_date = event.clip_range(strip_start, strip_end)
start_range = (cur_date - strip_start).to_i
end_range = (end_date - strip_start).to_i
# make sure the event is within our viewing range
if (start_range <= end_range) and (end_range >= 0)
range = start_range..end_range
open_strip = space_in_current_strips?(event_strips, range)
if open_strip.nil?
# no strips open, make a new one
new_strip = [nil] * (strip_end - strip_start + 1)
range.each {|r| new_strip[r] = event}
event_strips << new_strip
else
# found an open strip, add this event to it
range.each {|r| open_strip[r] = event}
end
end
end
event_strips
end
def space_in_current_strips?(event_strips, range)
open_strip = nil
for strip in event_strips
strip_is_open = true
range.each do |r|
# overlapping events on this strip
if !strip[r].nil?
strip_is_open = false
break
end
end
if strip_is_open
open_strip = strip
break
end
end
open_strip
end
def days_between(first, second)
if first > second
second + (7 - first)
else
second - first
end
end
def beginning_of_week(date, start = 0)
days_to_beg = days_between(start, date.wday)
date - days_to_beg
end
end
# Instance Methods
module InstanceMethods
def year
date.year
end
def month
date.month
end
def day
date.day
end
def color
self[:color] || '#9aa4ad'
end
def days
end_at.to_date - start_at.to_date
end
def clip_range(start_d, end_d)
# Clip start date, make sure it also ends on or after the start range
if (start_at < start_d and end_at >= start_d)
clipped_start = start_d
else
clipped_start = start_at.to_date
end
# Clip end date
if (end_at > end_d)
clipped_end = end_d
else
clipped_end = end_at.to_date
end
[clipped_start, clipped_end]
end
end
end |
module Viewpoint::EWS::Types
module Item
include Viewpoint::EWS
include Viewpoint::EWS::Types
include ItemFieldUriMap
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def init_simple_item(ews, id, change_key = nil, parent = nil)
ews_item = {item_id: {attribs: {id: id, change_key: change_key}}}
self.new ews, ews_item, parent
end
end
ITEM_KEY_PATHS = {
item_id: [:item_id, :attribs],
id: [:item_id, :attribs, :id],
change_key: [:item_id, :attribs, :change_key],
subject: [:subject, :text],
sensitivity: [:sensitivity, :text],
size: [:size, :text],
date_time_sent: [:date_time_sent, :text],
date_time_created: [:date_time_created, :text],
last_modified_time: [:last_modified_time, :text],
mime_content: [:mime_content, :text],
has_attachments?:[:has_attachments, :text],
is_associated?: [:is_associated, :text],
is_read?: [:is_read, :text],
is_draft?: [:is_draft, :text],
is_submitted?: [:is_submitted, :text],
conversation_id:[:conversation_id, :attribs, :id],
categories: [:categories, :elems],
internet_message_id:[:internet_message_id, :text],
internet_message_headers:[:internet_message_headers, :elems],
sender: [:sender, :elems, 0, :mailbox, :elems],
from: [:from, :elems, 0, :mailbox, :elems],
to_recipients: [:to_recipients, :elems],
cc_recipients: [:cc_recipients, :elems],
attachments: [:attachments, :elems],
importance: [:importance, :text],
conversation_index: [:conversation_index, :text],
conversation_topic: [:conversation_topic, :text],
body_type: [:body, :attribs, :body_type],
body: [:body, :text]
}
ITEM_KEY_TYPES = {
size: ->(str){str.to_i},
date_time_sent: ->(str){DateTime.parse(str)},
date_time_created: ->(str){DateTime.parse(str)},
last_modified_time: ->(str){DateTime.parse(str)},
has_attachments?: ->(str){str.downcase == 'true'},
is_associated?: ->(str){str.downcase == 'true'},
is_read?: ->(str){str.downcase == 'true'},
is_draft?: ->(str){str.downcase == 'true'},
is_submitted?: ->(str){str.downcase == 'true'},
categories: ->(obj){obj.collect{|s| s[:string][:text]}},
internet_message_headers: ->(obj){obj.collect{|h|
{h[:internet_message_header][:attribs][:header_name] =>
h[:internet_message_header][:text]} } },
sender: :build_mailbox_user,
from: :build_mailbox_user,
to_recipients: :build_mailbox_users,
cc_recipients: :build_mailbox_users,
attachments: :build_attachments,
}
ITEM_KEY_ALIAS = {
:read? => :is_read?,
:draft? => :is_draft?,
:submitted? => :is_submitted?,
:associated? => :is_associated?,
}
attr_reader :ews_item, :parent
# @param ews [SOAP::ExchangeWebService] the EWS reference
# @param ews_item [Hash] the EWS parsed response document
# @param parent [GenericFolder] an optional parent object
def initialize(ews, ews_item, parent = nil)
super(ews, ews_item)
@parent = parent
@body_type = false
simplify!
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# Specify a body_type to fetch this item with if it hasn't already been fetched.
# @param body_type [String, Symbol, FalseClass] must be :best, :text, or
# :html. You can also set it to false to make it use the default.
def default_body_type=(body_type)
@body_type = body_type
end
def delete!(deltype = :hard, opts = {})
opts = {
:delete_type => delete_type(deltype),
:item_ids => [{:item_id => {:id => id}}]
}.merge(opts)
resp = @ews.delete_item(opts)
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "Could not delete #{self.class}. #{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def recycle!
delete! :recycle
end
def get_all_properties!
@ews_item = get_item(base_shape: 'AllProperties')
simplify!
end
# Mark an item as read
def mark_read!
update_is_read_status true
end
# Mark an item as unread
def mark_unread!
update_is_read_status false
end
# Move this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the moved item
def move!(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
move_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.move_item(move_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not move item. #{resp.code}: #{resp.message}"
end
end
# Copy this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the copied item
def copy(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
copy_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.copy_item(copy_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}"
end
end
def add_file_attachment(file)
fa = OpenStruct.new
fa.name = File.basename(file.path)
fa.content = Base64.encode64(file.read)
@new_file_attachments << fa
end
def add_item_attachment(other_item, name = nil)
ia = OpenStruct.new
ia.name = (name ? name : other_item.subject)
ia.item = {id: other_item.id, change_key: other_item.change_key}
@new_item_attachments << ia
end
def add_inline_attachment(file)
fi = OpenStruct.new
fi.name = File.basename(file.path)
fi.content = Base64.encode64(file.read)
@new_inline_attachments << fi
end
def submit!
if draft?
submit_attachments!
resp = ews.send_item(item_ids: [{item_id: {id: self.id, change_key: self.change_key}}])
rm = resp.response_messages[0]
if rm.success?
true
else
raise EwsSendItemError, "#{rm.code}: #{rm.message_text}"
end
else
false
end
end
def submit_attachments!
return false unless draft? && !(@new_file_attachments.empty? && @new_item_attachments.empty? && @new_inline_attachments.empty?)
opts = {
parent_id: {id: self.id, change_key: self.change_key},
files: @new_file_attachments,
items: @new_item_attachments,
inline_files: @new_inline_attachments
}
resp = ews.create_attachment(opts)
set_change_key resp.response_messages[0].attachments[0].parent_change_key
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# If you want to add to the body set #new_body_content. If you set #body
# it will override the body that is there.
# @see MessageAccessors#send_message for options
# additional options:
# :new_body_content, :new_body_type
# @example
# item.forward do |i|
# i.new_body_content = "Add this to the top"
# i.to_recipients << 'test@example.com'
# end
def forward(opts = {})
msg = Template::ForwardItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to_all(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
msg.ews_type = :reply_all_to_item
dispatch_create_item! msg
end
private
def key_paths
super.merge(ITEM_KEY_PATHS)
end
def key_types
super.merge(ITEM_KEY_TYPES)
end
def key_alias
super.merge(ITEM_KEY_ALIAS)
end
def update_is_read_status(read)
field = :is_read
opts = {item_changes:
[
{ item_id: {id: id, change_key: change_key},
updates: [
{set_item_field: {field_uRI: {field_uRI: FIELD_URIS[field][:text]},
message: {sub_elements: [{field => {text: read}}]}}}
]
}
]
}
resp = ews.update_item({conflict_resolution: 'AutoResolve'}.merge(opts))
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "#{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def simplify!
return unless @ews_item.has_key?(:elems)
@ews_item = @ews_item[:elems].inject({}) do |o,i|
key = i.keys.first
if o.has_key?(key)
if o[key].is_a?(Array)
o[key] << i[key]
else
o[key] = [o.delete(key), i[key]]
end
else
o[key] = i[key]
end
o
end
end
# Get a specific item by its ID.
# @param [Hash] opts Misc options to control request
# @option opts [String] :base_shape IdOnly/Default/AllProperties
# @raise [EwsError] raised when the backend SOAP method returns an error.
def get_item(opts = {})
args = get_item_args(opts)
resp = ews.get_item(args)
get_item_parser(resp)
end
# Build up the arguements for #get_item
# @todo: should we really pass the ChangeKey or do we want the freshest obj?
def get_item_args(opts)
opts[:base_shape] ||= 'Default'
default_args = {
item_shape: {base_shape: opts[:base_shape]},
item_ids: [{item_id:{id: id, change_key: change_key}}]
}
default_args[:item_shape][:body_type] = @body_type if @body_type
default_args
end
def get_item_parser(resp)
rm = resp.response_messages[0]
if(rm.status == 'Success')
rm.items[0].values.first
else
raise EwsError, "Could not retrieve #{self.class}. #{rm.code}: #{rm.message_text}"
end
end
# Map a delete type to what EWS expects
# @param [Symbol] type. Must be :hard, :soft, or :recycle
def delete_type(type)
case type
when :hard then 'HardDelete'
when :soft then 'SoftDelete'
when :recycle then 'MoveToDeletedItems'
else 'MoveToDeletedItems'
end
end
def build_deleted_occurrences(occurrences)
occurrences.collect{|a| DateTime.parse a[:deleted_occurrence][:elems][0][:start][:text]}
end
def build_modified_occurrences(occurrences)
{}.tap do |h|
occurrences.collect do |a|
elems = a[:occurrence][:elems]
h[DateTime.parse(elems.find{|e| e[:original_start]}[:original_start][:text])] = {
start: elems.find{|e| e[:start]}[:start][:text],
end: elems.find{|e| e[:end]}[:end][:text]
}
end
end
end
def build_mailbox_user(mbox_ews)
MailboxUser.new(ews, mbox_ews)
end
def build_mailbox_users(users)
return [] if users.nil?
users.collect{|u| build_mailbox_user(u[:mailbox][:elems])}
end
def build_attendees_users(users)
return [] if users.nil?
users.collect do |u|
u[:attendee][:elems].collect do |a|
mbox=build_mailbox_user(a[:mailbox][:elems]) if a[:mailbox]
a[:mailbox]=mbox
a
end
end.flatten.compact
end
def build_attachments(attachments)
return [] if attachments.nil?
attachments.collect do |att|
key = att.keys.first
class_by_name(key).new(self, att[key])
end
end
def set_change_key(ck)
p = resolve_key_path(ews_item, key_paths[:change_key][0..-2])
p[:change_key] = ck
end
# Handles the CreateItem call for Forward, ReplyTo, and ReplyAllTo
# It will handle the neccessary actions for adding attachments.
def dispatch_create_item!(msg)
if msg.has_attachments?
draft = msg.draft
msg.draft = true
resp = validate_created_item(ews.create_item(msg.to_ews))
msg.file_attachments.each do |f|
next unless f.kind_of?(File)
resp.add_file_attachment(f)
end
if draft
resp.submit_attachments!
resp
else
resp.submit!
end
else
resp = ews.create_item(msg.to_ews)
validate_created_item resp
end
end
# validate the CreateItem response.
# @return [Boolean, Item] returns true if items is empty and status is
# "Success" if items is not empty it will return the first Item since
# we are only dealing with single items here.
# @raise EwsCreateItemError on failure
def validate_created_item(response)
msg = response.response_messages[0]
if(msg.status == 'Success')
msg.items.empty? ? true : parse_created_item(msg.items.first)
else
raise EwsCreateItemError, "#{msg.code}: #{msg.message_text}"
end
end
def parse_created_item(msg)
mtype = msg.keys.first
message = class_by_name(mtype).new(ews, msg[mtype])
end
end
end
no message
module Viewpoint::EWS::Types
module Item
include Viewpoint::EWS
include Viewpoint::EWS::Types
include ItemFieldUriMap
def self.included(klass)
klass.extend ClassMethods
end
module ClassMethods
def init_simple_item(ews, id, change_key = nil, parent = nil)
ews_item = {item_id: {attribs: {id: id, change_key: change_key}}}
self.new ews, ews_item, parent
end
end
ITEM_KEY_PATHS = {
item_id: [:item_id, :attribs],
id: [:item_id, :attribs, :id],
change_key: [:item_id, :attribs, :change_key],
subject: [:subject, :text],
sensitivity: [:sensitivity, :text],
size: [:size, :text],
date_time_sent: [:date_time_sent, :text],
date_time_created: [:date_time_created, :text],
last_modified_time: [:last_modified_time, :text],
mime_content: [:mime_content, :text],
has_attachments?:[:has_attachments, :text],
is_associated?: [:is_associated, :text],
is_read?: [:is_read, :text],
is_draft?: [:is_draft, :text],
is_submitted?: [:is_submitted, :text],
conversation_id:[:conversation_id, :attribs, :id],
categories: [:categories, :elems],
internet_message_id:[:internet_message_id, :text],
internet_message_headers:[:internet_message_headers, :elems],
sender: [:sender, :elems, 0, :mailbox, :elems],
from: [:from, :elems, 0, :mailbox, :elems],
to_recipients: [:to_recipients, :elems],
cc_recipients: [:cc_recipients, :elems],
attachments: [:attachments, :elems],
importance: [:importance, :text],
conversation_index: [:conversation_index, :text],
conversation_topic: [:conversation_topic, :text],
body_type: [:body, :attribs, :body_type],
body: [:body, :text]
}
ITEM_KEY_TYPES = {
size: ->(str){str.to_i},
date_time_sent: ->(str){DateTime.parse(str)},
date_time_created: ->(str){DateTime.parse(str)},
last_modified_time: ->(str){DateTime.parse(str)},
has_attachments?: ->(str){str.downcase == 'true'},
is_associated?: ->(str){str.downcase == 'true'},
is_read?: ->(str){str.downcase == 'true'},
is_draft?: ->(str){str.downcase == 'true'},
is_submitted?: ->(str){str.downcase == 'true'},
categories: ->(obj){obj.collect{|s| s[:string][:text]}},
internet_message_headers: ->(obj){obj.collect{|h|
{h[:internet_message_header][:attribs][:header_name] =>
h[:internet_message_header][:text]} } },
sender: :build_mailbox_user,
from: :build_mailbox_user,
to_recipients: :build_mailbox_users,
cc_recipients: :build_mailbox_users,
attachments: :build_attachments,
}
ITEM_KEY_ALIAS = {
:read? => :is_read?,
:draft? => :is_draft?,
:submitted? => :is_submitted?,
:associated? => :is_associated?,
}
attr_reader :ews_item, :parent
# @param ews [SOAP::ExchangeWebService] the EWS reference
# @param ews_item [Hash] the EWS parsed response document
# @param parent [GenericFolder] an optional parent object
def initialize(ews, ews_item, parent = nil)
super(ews, ews_item)
@parent = parent
@body_type = false
simplify!
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# Specify a body_type to fetch this item with if it hasn't already been fetched.
# @param body_type [String, Symbol, FalseClass] must be :best, :text, or
# :html. You can also set it to false to make it use the default.
def default_body_type=(body_type)
@body_type = body_type
end
def delete!(deltype = :hard, opts = {})
opts = {
:delete_type => delete_type(deltype),
:item_ids => [{:item_id => {:id => id}}]
}.merge(opts)
resp = @ews.delete_item(opts)
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "Could not delete #{self.class}. #{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def recycle!
delete! :recycle
end
def get_all_properties!
@ews_item = get_item(base_shape: 'AllProperties')
simplify!
end
# Mark an item as read
def mark_read!
update_is_read_status true
end
# Mark an item as unread
def mark_unread!
update_is_read_status false
end
# Move this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the moved item
def move!(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
move_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.move_item(move_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not move item. #{resp.code}: #{resp.message}"
end
end
# Copy this item to a new folder
# @param [String,Symbol,GenericFolder] new_folder The new folder to move it to. This should
# be a subclass of GenericFolder, a DistinguishedFolderId (must me a Symbol) or a FolderId (String)
# @return [String] the new Id of the copied item
def copy(new_folder)
new_folder = new_folder.id if new_folder.kind_of?(GenericFolder)
copy_opts = {
:to_folder_id => {:id => new_folder},
:item_ids => [{:item_id => {:id => self.id}}]
}
resp = @ews.copy_item(copy_opts)
rmsg = resp.response_messages[0]
if rmsg.success?
obj = rmsg.items.first
itype = obj.keys.first
obj[itype][:elems][0][:item_id][:attribs][:id]
else
raise EwsError, "Could not copy item. #{rmsg.response_code}: #{rmsg.message_text}"
end
end
def add_file_attachment(file)
fa = OpenStruct.new
fa.name = File.basename(file.path)
fa.content = Base64.encode64(file.read)
@new_file_attachments << fa
end
def add_item_attachment(other_item, name = nil)
ia = OpenStruct.new
ia.name = (name ? name : other_item.subject)
ia.item = {id: other_item.id, change_key: other_item.change_key}
@new_item_attachments << ia
end
def add_inline_attachment(file)
fi = OpenStruct.new
fi.name = File.basename(file.path)
fi.content = Base64.encode64(file.read)
@new_inline_attachments << fi
end
def submit!
if draft?
submit_attachments!
resp = ews.send_item(item_ids: [{item_id: {id: self.id, change_key: self.change_key}}])
rm = resp.response_messages[0]
if rm.success?
true
else
raise EwsSendItemError, "#{rm.code}: #{rm.message_text}"
end
else
false
end
end
def submit_attachments!
return false unless draft? && !(@new_file_attachments.empty? && @new_item_attachments.empty? && @new_inline_attachments.empty?)
opts = {
parent_id: {id: self.id, change_key: self.change_key},
files: @new_file_attachments,
items: @new_item_attachments,
inline_files: @new_inline_attachments
}
resp = ews.create_attachment(opts)
set_change_key resp.response_messages[0].attachments[0].parent_change_key
@new_file_attachments = []
@new_item_attachments = []
@new_inline_attachments = []
end
# If you want to add to the body set #new_body_content. If you set #body
# it will override the body that is there.
# @see MessageAccessors#send_message for options
# additional options:
# :new_body_content, :new_body_type
# @example
# item.forward do |i|
# i.new_body_content = "Add this to the top"
# i.to_recipients << 'test@example.com'
# end
def forward(opts = {})
msg = Template::ForwardItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
dispatch_create_item! msg
end
def reply_to_all(opts = {})
msg = Template::ReplyToItem.new opts.clone
yield msg if block_given?
msg.reference_item_id = {id: self.id, change_key: self.change_key}
msg.ews_type = :reply_all_to_item
dispatch_create_item! msg
end
private
def key_paths
super.merge(ITEM_KEY_PATHS)
end
def key_types
super.merge(ITEM_KEY_TYPES)
end
def key_alias
super.merge(ITEM_KEY_ALIAS)
end
def update_is_read_status(read)
field = :is_read
opts = {item_changes:
[
{ item_id: {id: id, change_key: change_key},
updates: [
{set_item_field: {field_uRI: {field_uRI: FIELD_URIS[field][:text]},
message: {sub_elements: [{field => {text: read}}]}}}
]
}
]
}
resp = ews.update_item({conflict_resolution: 'AutoResolve'}.merge(opts))
rmsg = resp.response_messages[0]
unless rmsg.success?
raise EwsError, "#{rmsg.response_code}: #{rmsg.message_text}"
end
true
end
def simplify!
return unless @ews_item.has_key?(:elems)
@ews_item = @ews_item[:elems].inject({}) do |o,i|
key = i.keys.first
if o.has_key?(key)
if o[key].is_a?(Array)
o[key] << i[key]
else
o[key] = [o.delete(key), i[key]]
end
else
o[key] = i[key]
end
o
end
end
# Get a specific item by its ID.
# @param [Hash] opts Misc options to control request
# @option opts [String] :base_shape IdOnly/Default/AllProperties
# @raise [EwsError] raised when the backend SOAP method returns an error.
def get_item(opts = {})
args = get_item_args(opts)
resp = ews.get_item(args)
get_item_parser(resp)
end
# Build up the arguements for #get_item
# @todo: should we really pass the ChangeKey or do we want the freshest obj?
def get_item_args(opts)
opts[:base_shape] ||= 'Default'
default_args = {
item_shape: {base_shape: opts[:base_shape]},
item_ids: [{item_id:{id: id, change_key: change_key}}]
}
default_args[:item_shape][:body_type] = @body_type if @body_type
default_args
end
def get_item_parser(resp)
rm = resp.response_messages[0]
if(rm.status == 'Success')
rm.items[0].values.first
else
raise EwsError, "Could not retrieve #{self.class}. #{rm.code}: #{rm.message_text}"
end
end
# Map a delete type to what EWS expects
# @param [Symbol] type. Must be :hard, :soft, or :recycle
def delete_type(type)
case type
when :hard then 'HardDelete'
when :soft then 'SoftDelete'
when :recycle then 'MoveToDeletedItems'
else 'MoveToDeletedItems'
end
end
def build_deleted_occurrences(occurrences)
occurrences.collect{|a| DateTime.parse a[:deleted_occurrence][:elems][0][:start][:text]}
end
def build_modified_occurrences(occurrences)
{}.tap do |h|
occurrences.collect do |a|
elems = a[:occurrence][:elems]
h[DateTime.parse(elems.find{|e| e[:original_start]}[:original_start][:text])] = {
start: elems.find{|e| e[:start]}[:start][:text],
end: elems.find{|e| e[:end]}[:end][:text]
}
end
end
end
def build_mailbox_user(mbox_ews)
MailboxUser.new(ews, mbox_ews)
end
def build_mailbox_users(users)
return [] if users.nil?
users.collect{|u| build_mailbox_user(u[:mailbox][:elems])}
end
def build_attendees_users(users)
return [] if users.nil?
users.collect do |u|
u[:attendee][:elems].collect do |a|
rtype=a[:response_type]
rtime=a[:last_response_time]
mbox=build_mailbox_user(a[:mailbox][:elems]) if a[:mailbox]
{mailbox: mbox, response_type: rtype, response_time: rtime}
end
end.flatten.compact
end
def build_attachments(attachments)
return [] if attachments.nil?
attachments.collect do |att|
key = att.keys.first
class_by_name(key).new(self, att[key])
end
end
def set_change_key(ck)
p = resolve_key_path(ews_item, key_paths[:change_key][0..-2])
p[:change_key] = ck
end
# Handles the CreateItem call for Forward, ReplyTo, and ReplyAllTo
# It will handle the neccessary actions for adding attachments.
def dispatch_create_item!(msg)
if msg.has_attachments?
draft = msg.draft
msg.draft = true
resp = validate_created_item(ews.create_item(msg.to_ews))
msg.file_attachments.each do |f|
next unless f.kind_of?(File)
resp.add_file_attachment(f)
end
if draft
resp.submit_attachments!
resp
else
resp.submit!
end
else
resp = ews.create_item(msg.to_ews)
validate_created_item resp
end
end
# validate the CreateItem response.
# @return [Boolean, Item] returns true if items is empty and status is
# "Success" if items is not empty it will return the first Item since
# we are only dealing with single items here.
# @raise EwsCreateItemError on failure
def validate_created_item(response)
msg = response.response_messages[0]
if(msg.status == 'Success')
msg.items.empty? ? true : parse_created_item(msg.items.first)
else
raise EwsCreateItemError, "#{msg.code}: #{msg.message_text}"
end
end
def parse_created_item(msg)
mtype = msg.keys.first
message = class_by_name(mtype).new(ews, msg[mtype])
end
end
end
|
module Excon
class Response
attr_accessor :data
# backwards compatability reader/writers
def body=(new_body)
@data[:body] = new_body
end
def body
@data[:body]
end
def headers=(new_headers)
@data[:headers] = new_headers
end
def headers
@data[:headers]
end
def status=(new_status)
@data[:status] = new_status
end
def status
@data[:status]
end
def reason_phrase=(new_reason_phrase)
@data[:reason_phrase] = new_reason_phrase
end
def reason_phrase
@data[:reason_phrase]
end
def remote_ip=(new_remote_ip)
@data[:remote_ip] = new_remote_ip
end
def remote_ip
@data[:remote_ip]
end
def local_port
@data[:local_port]
end
def local_address
@data[:local_address]
end
def self.parse(socket, datum)
# this will discard any trailing lines from the previous response if any.
begin
full_status = socket.readline[9..-1]
end until status = full_status.to_i
reason_phrase = full_status.sub("#{status} ", "").chomp
datum[:response] = {
:body => '',
:headers => Excon::Headers.new,
:status => status,
:reason_phrase => reason_phrase
}
unix_proxy = datum[:proxy] ? datum[:proxy][:scheme] == UNIX : false
unless datum[:scheme] == UNIX || unix_proxy
datum[:response].merge!(
:remote_ip => socket.remote_ip,
:local_port => socket.local_port,
:local_address => socket.local_address
)
end
parse_headers(socket, datum)
unless (['HEAD', 'CONNECT'].include?(datum[:method].to_s.upcase)) || NO_ENTITY.include?(datum[:response][:status])
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Transfer-Encoding') == 0 }
encodings = Utils.split_header_value(datum[:response][:headers][key])
if (encoding = encodings.last) && encoding.casecmp('chunked') == 0
transfer_encoding_chunked = true
if encodings.length == 1
datum[:response][:headers].delete(key)
else
datum[:response][:headers][key] = encodings[0...-1].join(', ')
end
end
end
# use :response_block unless :expects would fail
if response_block = datum[:response_block]
if datum[:middlewares].include?(Excon::Middleware::Expects) && datum[:expects] &&
!Array(datum[:expects]).include?(datum[:response][:status])
response_block = nil
end
end
if transfer_encoding_chunked
if response_block
while (chunk_size = socket.readline.chomp!.to_i(16)) > 0
while chunk_size > 0
chunk = socket.read(chunk_size)
chunk_size -= chunk.bytesize
response_block.call(chunk, nil, nil)
end
new_line_size = 2 # 2 == "\r\n".length
while new_line_size > 0
new_line_size -= socket.read(new_line_size).length
end
end
else
while (chunk_size = socket.readline.chomp!.to_i(16)) > 0
while chunk_size > 0
chunk = socket.read(chunk_size)
chunk_size -= chunk.bytesize
datum[:response][:body] << chunk
end
new_line_size = 2 # 2 == "\r\n".length
while new_line_size > 0
new_line_size -= socket.read(new_line_size).length
end
end
end
parse_headers(socket, datum) # merge trailers into headers
else
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Content-Length') == 0 }
content_length = datum[:response][:headers][key].to_i
end
if remaining = content_length
if response_block
while remaining > 0
chunk = socket.read([datum[:chunk_size], remaining].min)
response_block.call(chunk, [remaining - chunk.bytesize, 0].max, content_length)
remaining -= chunk.bytesize
end
else
while remaining > 0
chunk = socket.read([datum[:chunk_size], remaining].min)
datum[:response][:body] << chunk
remaining -= chunk.bytesize
end
end
else
if response_block
while chunk = socket.read(datum[:chunk_size])
response_block.call(chunk, nil, nil)
end
else
while chunk = socket.read(datum[:chunk_size])
datum[:response][:body] << chunk
end
end
end
end
end
datum
end
def self.parse_headers(socket, datum)
last_key = nil
until (data = socket.readline.chomp!).empty?
if !data.lstrip!.nil?
raise Excon::Errors::ResponseParseError, 'malformed header' unless last_key
# append to last_key's last value
datum[:response][:headers][last_key] << ' ' << data.rstrip
else
key, value = data.split(':', 2)
raise Excon::Errors::ResponseParseError, 'malformed header' unless value
# add key/value or append value to existing values
datum[:response][:headers][key] = ([datum[:response][:headers][key]] << value.strip).compact.join(', ')
last_key = key
end
end
end
def initialize(params={})
@data = {
:body => ''
}.merge(params)
@data[:headers] = Excon::Headers.new.merge!(params[:headers] || {})
@body = @data[:body]
@headers = @data[:headers]
@status = @data[:status]
@remote_ip = @data[:remote_ip]
@local_port = @data[:local_port]
@local_address = @data[:local_address]
end
def [](key)
@data[key]
end
def params
Excon.display_warning('Excon::Response#params is deprecated use Excon::Response#data instead.')
data
end
def pp
Excon::PrettyPrinter.pp($stdout, @data)
end
# Retrieve a specific header value. Header names are treated case-insensitively.
# @param [String] name Header name
def get_header(name)
headers[name]
end
end # class Response
end # module Excon
Refactors reason phrase parsing
This is easier to understand and performs better too!
module Excon
class Response
attr_accessor :data
# backwards compatability reader/writers
def body=(new_body)
@data[:body] = new_body
end
def body
@data[:body]
end
def headers=(new_headers)
@data[:headers] = new_headers
end
def headers
@data[:headers]
end
def status=(new_status)
@data[:status] = new_status
end
def status
@data[:status]
end
def reason_phrase=(new_reason_phrase)
@data[:reason_phrase] = new_reason_phrase
end
def reason_phrase
@data[:reason_phrase]
end
def remote_ip=(new_remote_ip)
@data[:remote_ip] = new_remote_ip
end
def remote_ip
@data[:remote_ip]
end
def local_port
@data[:local_port]
end
def local_address
@data[:local_address]
end
def self.parse(socket, datum)
# this will discard any trailing lines from the previous response if any.
begin
line = socket.readline
end until status = line[9, 3].to_i
reason_phrase = line[13..-3] # -3 strips the trailing "\r\n"
datum[:response] = {
:body => '',
:headers => Excon::Headers.new,
:status => status,
:reason_phrase => reason_phrase
}
unix_proxy = datum[:proxy] ? datum[:proxy][:scheme] == UNIX : false
unless datum[:scheme] == UNIX || unix_proxy
datum[:response].merge!(
:remote_ip => socket.remote_ip,
:local_port => socket.local_port,
:local_address => socket.local_address
)
end
parse_headers(socket, datum)
unless (['HEAD', 'CONNECT'].include?(datum[:method].to_s.upcase)) || NO_ENTITY.include?(datum[:response][:status])
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Transfer-Encoding') == 0 }
encodings = Utils.split_header_value(datum[:response][:headers][key])
if (encoding = encodings.last) && encoding.casecmp('chunked') == 0
transfer_encoding_chunked = true
if encodings.length == 1
datum[:response][:headers].delete(key)
else
datum[:response][:headers][key] = encodings[0...-1].join(', ')
end
end
end
# use :response_block unless :expects would fail
if response_block = datum[:response_block]
if datum[:middlewares].include?(Excon::Middleware::Expects) && datum[:expects] &&
!Array(datum[:expects]).include?(datum[:response][:status])
response_block = nil
end
end
if transfer_encoding_chunked
if response_block
while (chunk_size = socket.readline.chomp!.to_i(16)) > 0
while chunk_size > 0
chunk = socket.read(chunk_size)
chunk_size -= chunk.bytesize
response_block.call(chunk, nil, nil)
end
new_line_size = 2 # 2 == "\r\n".length
while new_line_size > 0
new_line_size -= socket.read(new_line_size).length
end
end
else
while (chunk_size = socket.readline.chomp!.to_i(16)) > 0
while chunk_size > 0
chunk = socket.read(chunk_size)
chunk_size -= chunk.bytesize
datum[:response][:body] << chunk
end
new_line_size = 2 # 2 == "\r\n".length
while new_line_size > 0
new_line_size -= socket.read(new_line_size).length
end
end
end
parse_headers(socket, datum) # merge trailers into headers
else
if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Content-Length') == 0 }
content_length = datum[:response][:headers][key].to_i
end
if remaining = content_length
if response_block
while remaining > 0
chunk = socket.read([datum[:chunk_size], remaining].min)
response_block.call(chunk, [remaining - chunk.bytesize, 0].max, content_length)
remaining -= chunk.bytesize
end
else
while remaining > 0
chunk = socket.read([datum[:chunk_size], remaining].min)
datum[:response][:body] << chunk
remaining -= chunk.bytesize
end
end
else
if response_block
while chunk = socket.read(datum[:chunk_size])
response_block.call(chunk, nil, nil)
end
else
while chunk = socket.read(datum[:chunk_size])
datum[:response][:body] << chunk
end
end
end
end
end
datum
end
def self.parse_headers(socket, datum)
last_key = nil
until (data = socket.readline.chomp!).empty?
if !data.lstrip!.nil?
raise Excon::Errors::ResponseParseError, 'malformed header' unless last_key
# append to last_key's last value
datum[:response][:headers][last_key] << ' ' << data.rstrip
else
key, value = data.split(':', 2)
raise Excon::Errors::ResponseParseError, 'malformed header' unless value
# add key/value or append value to existing values
datum[:response][:headers][key] = ([datum[:response][:headers][key]] << value.strip).compact.join(', ')
last_key = key
end
end
end
def initialize(params={})
@data = {
:body => ''
}.merge(params)
@data[:headers] = Excon::Headers.new.merge!(params[:headers] || {})
@body = @data[:body]
@headers = @data[:headers]
@status = @data[:status]
@remote_ip = @data[:remote_ip]
@local_port = @data[:local_port]
@local_address = @data[:local_address]
end
def [](key)
@data[key]
end
def params
Excon.display_warning('Excon::Response#params is deprecated use Excon::Response#data instead.')
data
end
def pp
Excon::PrettyPrinter.pp($stdout, @data)
end
# Retrieve a specific header value. Header names are treated case-insensitively.
# @param [String] name Header name
def get_header(name)
headers[name]
end
end # class Response
end # module Excon
|
require 'celluloid'
require 'yaml'
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/numeric'
require 'active_support/core_ext/string/filters'
require_relative 'utils/leak_19'
Eye.send(:extend, Eye::Logger::Helpers)
class Eye::Controller
include Celluloid
autoload :Load, 'eye/controller/load'
autoload :Helpers, 'eye/controller/helpers'
autoload :Commands, 'eye/controller/commands'
autoload :Status, 'eye/controller/status'
autoload :SendCommand, 'eye/controller/send_command'
include Eye::Logger::Helpers
include Eye::Controller::Load
include Eye::Controller::Helpers
include Eye::Controller::Commands
include Eye::Controller::Status
include Eye::Controller::SendCommand
attr_reader :applications, :current_config
def initialize
@applications = []
@current_config = Eye::Dsl.initial_config
Eye.instance_variable_set(:@logger, Eye::Logger.new('eye'))
@logger = Eye.logger
Celluloid::logger = Eye.logger
Eye::SystemResources.setup
end
end
# log eye version, when started
require 'celluloid'
require 'yaml'
require 'active_support'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/object/try'
require 'active_support/core_ext/numeric'
require 'active_support/core_ext/string/filters'
require_relative 'utils/leak_19'
Eye.send(:extend, Eye::Logger::Helpers)
class Eye::Controller
include Celluloid
autoload :Load, 'eye/controller/load'
autoload :Helpers, 'eye/controller/helpers'
autoload :Commands, 'eye/controller/commands'
autoload :Status, 'eye/controller/status'
autoload :SendCommand, 'eye/controller/send_command'
include Eye::Logger::Helpers
include Eye::Controller::Load
include Eye::Controller::Helpers
include Eye::Controller::Commands
include Eye::Controller::Status
include Eye::Controller::SendCommand
attr_reader :applications, :current_config
def initialize
@applications = []
@current_config = Eye::Dsl.initial_config
Eye.instance_variable_set(:@logger, Eye::Logger.new('eye'))
@logger = Eye.logger
Celluloid::logger = Eye.logger
Eye::SystemResources.setup
info "starting #{Eye::ABOUT}"
end
end
|
# coding: utf-8
#* version.rb - The version string for fOOrth.
module XfOOrth
#The version string for fOOrth.
VERSION = "0.5.3"
end
Next version to be 0.6.0
# coding: utf-8
#* version.rb - The version string for fOOrth.
module XfOOrth
#The version string for fOOrth.
VERSION = "0.6.0"
end
|
module FakeS3
VERSION = "1.0.0-11"
end
Bump version to 1.0.0-12
module FakeS3
VERSION = "1.0.0-12"
end
|
require 'json'
require 'pathname'
require 'open-uri'
module Fauxhai
class Mocker
# The base URL for the GitHub project (raw)
RAW_BASE = 'https://raw.githubusercontent.com/customink/fauxhai/master'
# A message about where to find a list of platforms
PLATFORM_LIST_MESSAGE = "A list of available platforms is available at https://github.com/customink/fauxhai/blob/master/PLATFORMS.md".freeze
# @return [Hash] The raw ohai data for the given Mock
attr_reader :data
# Create a new Ohai Mock with fauxhai.
#
# @param [Hash] options
# the options for the mocker
# @option options [String] :platform
# the platform to mock
# @option options [String] :version
# the version of the platform to mock
# @option options [String] :path
# the path to a local JSON file
# @option options [Bool] :github_fetching
# whether to try loading from Github
def initialize(options = {}, &override_attributes)
@options = { github_fetching: true }.merge(options)
@data = fauxhai_data
yield(@data) if block_given?
if defined?(::ChefSpec) && ::ChefSpec::VERSION <= '0.9.0'
data = @data
::ChefSpec::ChefRunner.send :define_method, :fake_ohai do |ohai|
data.each_pair do |attribute, value|
ohai[attribute] = value
end
end
end
@data
end
private
def fauxhai_data
@fauxhai_data ||= lambda do
# If a path option was specified, use it
if @options[:path]
filepath = File.expand_path(@options[:path])
unless File.exist?(filepath)
raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'")
end
else
filepath = File.join(platform_path, "#{version}.json")
end
if File.exist?(filepath)
JSON.parse( File.read(filepath) )
elsif !@options[:github_fetching]
# Try loading from github (in case someone submitted a PR with a new file, but we haven't
# yet updated the gem version). Cache the response locally so it's faster next time.
begin
response = open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json")
rescue OpenURI::HTTPError
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' in any of the sources! #{PLATFORM_LIST_MESSAGE}")
end
if response.status.first.to_i == 200
response_body = response.read
path = Pathname.new(filepath)
FileUtils.mkdir_p(path.dirname)
File.open(filepath, 'w') { |f| f.write(response_body) }
return JSON.parse(response_body)
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' in any of the sources! #{PLATFORM_LIST_MESSAGE}")
end
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' in any of the sources!")
end
end.call
end
def platform
@options[:platform] ||= begin
STDERR.puts "WARNING: you must specify a 'platform' and 'version' to your ChefSpec Runner and/or Fauxhai constructor, in the future omitting these will become a hard error. #{PLATFORM_LIST_MESSAGE}"
'chefspec'
end
end
def platform_path
File.join(Fauxhai.root, 'lib', 'fauxhai', 'platforms', platform)
end
def version
@options[:version] ||= chefspec_version || raise(Fauxhai::Exception::InvalidVersion.new("Platform version not specified. #{PLATFORM_LIST_MESSAGE}"))
end
def chefspec_version
platform == 'chefspec' ? '0.6.1' : nil
end
end
end
The logic to enable/disable github fetching was backwards
Signed-off-by: Tim Smith <764ef62106582a09ed09dfa0b6bff7c05fd7d1e4@chef.io>
require 'json'
require 'pathname'
require 'open-uri'
module Fauxhai
class Mocker
# The base URL for the GitHub project (raw)
RAW_BASE = 'https://raw.githubusercontent.com/customink/fauxhai/master'
# A message about where to find a list of platforms
PLATFORM_LIST_MESSAGE = "A list of available platforms is available at https://github.com/customink/fauxhai/blob/master/PLATFORMS.md".freeze
# @return [Hash] The raw ohai data for the given Mock
attr_reader :data
# Create a new Ohai Mock with fauxhai.
#
# @param [Hash] options
# the options for the mocker
# @option options [String] :platform
# the platform to mock
# @option options [String] :version
# the version of the platform to mock
# @option options [String] :path
# the path to a local JSON file
# @option options [Bool] :github_fetching
# whether to try loading from Github
def initialize(options = {}, &override_attributes)
@options = { github_fetching: true }.merge(options)
@data = fauxhai_data
yield(@data) if block_given?
if defined?(::ChefSpec) && ::ChefSpec::VERSION <= '0.9.0'
data = @data
::ChefSpec::ChefRunner.send :define_method, :fake_ohai do |ohai|
data.each_pair do |attribute, value|
ohai[attribute] = value
end
end
end
@data
end
private
def fauxhai_data
@fauxhai_data ||= lambda do
# If a path option was specified, use it
if @options[:path]
filepath = File.expand_path(@options[:path])
unless File.exist?(filepath)
raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'")
end
else
filepath = File.join(platform_path, "#{version}.json")
end
if File.exist?(filepath)
JSON.parse( File.read(filepath) )
elsif @options[:github_fetching]
# Try loading from github (in case someone submitted a PR with a new file, but we haven't
# yet updated the gem version). Cache the response locally so it's faster next time.
begin
response = open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json")
rescue OpenURI::HTTPError
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' in any of the sources! #{PLATFORM_LIST_MESSAGE}")
end
if response.status.first.to_i == 200
response_body = response.read
path = Pathname.new(filepath)
FileUtils.mkdir_p(path.dirname)
File.open(filepath, 'w') { |f| f.write(response_body) }
return JSON.parse(response_body)
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' in any of the sources! #{PLATFORM_LIST_MESSAGE}")
end
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' in any of the sources! #{PLATFORM_LIST_MESSAGE}")
end
end.call
end
def platform
@options[:platform] ||= begin
STDERR.puts "WARNING: you must specify a 'platform' and 'version' to your ChefSpec Runner and/or Fauxhai constructor, in the future omitting these will become a hard error. #{PLATFORM_LIST_MESSAGE}"
'chefspec'
end
end
def platform_path
File.join(Fauxhai.root, 'lib', 'fauxhai', 'platforms', platform)
end
def version
@options[:version] ||= chefspec_version || raise(Fauxhai::Exception::InvalidVersion.new("Platform version not specified. #{PLATFORM_LIST_MESSAGE}"))
end
def chefspec_version
platform == 'chefspec' ? '0.6.1' : nil
end
end
end
|
module Fech
class Table
def initialize(cycle, opts={})
@cycle = cycle
@headers = opts[:headers]
@file = opts[:file]
@format = opts[:format]
@receiver = opts[:connection] || receiver
@parser = parser
end
def receiver
if @format == :csv
CSV.open("#{@file}#{@cycle.to_s[2..3]}.csv", 'a+', headers: @headers, write_headers: true)
else
[]
end
end
def retrieve_data
fetch_file { |row| enter_row(row) }
return @receiver
end
def enter_row(row)
case @format
when :db
table_exist? ? @receiver << row : create_table(row)
when :csv
@receiver << row.values
else
@receiver << row
end
end
# the @receiver obj is the database itself.
# This assumes the table needs to be created.
def fetch_file(&blk)
zip_file = "#{@file}#{@cycle.to_s[2..3]}.zip"
Net::FTP.open("ftp.fec.gov") do |ftp|
ftp.login
ftp.chdir("./FEC/#{@cycle}")
begin
ftp.get(zip_file, "./#{zip_file}")
rescue Net::FTPPermError
raise 'File not found - please try the other methods'
end
end
unzip(zip_file, &blk)
end
def parser
@headers.map.with_index do |h,i|
if h.to_s =~ /cash|amount|contributions|total|loan|transfer|debts|refund|expenditure/
[h, ->(line) { line[i].to_f }]
elsif h == :filing_id
[h, ->(line) { line[i].to_i }]
elsif h.to_s =~ /_date/
[h, ->(line) { parse_date(line[i]) }]
else
[h, ->(line) { line[i] }]
end
end
end
def format_row(line)
hash = {}
line = line.encode('UTF-8', invalid: :replace, replace: ' ').chomp.split("|")
@parser.each { |k,blk| hash[k] = blk.call(line) }
return hash
end
def parse_date(date)
if date.length == 8
Date.strptime(date, "%m%d%Y")
else
Date.parse(date)
end
end
def unzip(zip_file, &blk)
Zip::File.open(zip_file) do |zip|
zip.each do |entry|
entry.extract("./#{entry.name}") if !File.file?(entry.name)
File.delete(zip_file)
File.foreach(entry.name) do |row|
blk.call(format_row(row))
end
File.delete(entry.name)
end
end
end
end
end
fixed conflict
module Fech
class Table
def initialize(cycle, opts={})
@cycle = cycle
@headers = opts[:headers]
@file = opts[:file]
@format = opts[:format]
@receiver = opts[:connection] || receiver
@parser = parser
end
def receiver
if @format == :csv
CSV.open("#{@file}#{@cycle.to_s[2..3]}.csv", 'a+', headers: @headers, write_headers: true)
else
[]
end
end
def retrieve_data
fetch_file { |row| enter_row(row) }
return @receiver
end
def enter_row(row)
case @format
when :db
table_exist? ? @receiver << row : create_table(row)
when :csv
@receiver << row.values
else
@receiver << row
end
end
# the @receiver obj is the database itself.
# This assumes the table needs to be created.
def table_exist?
@receiver.respond_to? :columns
end
def create_table(row)
db, table = @receiver
table = table.to_s.pluralize.to_sym
db.create_table(table) { primary_key :id }
row.each do |k,v|
db.alter_table table do
add_column k, v.class
end
end
@receiver = db[table]
@receiver << row
end
def fetch_file(&blk)
zip_file = "#{@file}#{@cycle.to_s[2..3]}.zip"
Net::FTP.open("ftp.fec.gov") do |ftp|
ftp.login
ftp.chdir("./FEC/#{@cycle}")
begin
ftp.get(zip_file, "./#{zip_file}")
rescue Net::FTPPermError
raise 'File not found - please try the other methods'
end
end
unzip(zip_file, &blk)
end
def parser
@headers.map.with_index do |h,i|
if h.to_s =~ /cash|amount|contributions|total|loan|transfer|debts|refund|expenditure/
[h, ->(line) { line[i].to_f }]
elsif h == :filing_id
[h, ->(line) { line[i].to_i }]
elsif h.to_s =~ /_date/
[h, ->(line) { parse_date(line[i]) }]
else
[h, ->(line) { line[i] }]
end
end
end
def format_row(line)
hash = {}
line = line.encode('UTF-8', invalid: :replace, replace: ' ').chomp.split("|")
@parser.each { |k,blk| hash[k] = blk.call(line) }
return hash
end
def parse_date(date)
if date.length == 8
Date.strptime(date, "%m%d%Y")
else
Date.parse(date)
end
end
def unzip(zip_file, &blk)
Zip::File.open(zip_file) do |zip|
zip.each do |entry|
entry.extract("./#{entry.name}") if !File.file?(entry.name)
File.delete(zip_file)
File.foreach(entry.name) do |row|
blk.call(format_row(row))
end
File.delete(entry.name)
end
end
end
end
end |
module Ferver
VERSION = "1.0.0"
end
Bump version to 1.1.0 on account of sweet enhancements
module Ferver
VERSION = "1.1.0"
end
|
module Fetcha
VERSION = "0.2.1"
end
Version bump
module Fetcha
VERSION = "0.2.2"
end
|
require 'flash_flow/cmd_runner'
module FlashFlow
class Git
ATTRIBUTES = [:merge_remote, :merge_branch, :master_branch, :use_rerere]
attr_reader *ATTRIBUTES
attr_reader :working_branch
UNMERGED_STATUSES = %w{DD AU UD UA DU AA UU}
def initialize(config, logger=nil)
@cmd_runner = CmdRunner.new(logger: logger)
ATTRIBUTES.each do |attr|
unless config.has_key?(attr.to_s)
raise RuntimeError.new("git configuration missing. Required config parameters: #{ATTRIBUTES}")
end
instance_variable_set("@#{attr}", config[attr.to_s])
end
@working_branch = current_branch
end
def last_stdout
@cmd_runner.last_stdout
end
def last_command
@cmd_runner.last_command
end
def last_success?
@cmd_runner.last_success?
end
def run(cmd)
@cmd_runner.run("git #{cmd}")
end
def add_and_commit(files, message, opts={})
files = [files].flatten
run("add #{'-f ' if opts[:add] && opts[:add][:force]}#{files.join(' ')}")
run("commit -m '#{message}'")
end
def push(branch, options)
run("push #{'-f' if options[:force]} #{merge_remote} #{branch}")
end
def merge(branch)
run("merge #{branch}")
end
def fetch(remote)
run("fetch #{remote}")
end
def master_branch_contains?(ref)
run("branch --contains #{ref}")
last_stdout.split("\n").detect { |str| str[2..-1] == master_branch }
end
def in_original_merge_branch
begin
starting_branch = current_branch
run("checkout #{merge_remote}/#{merge_branch}")
yield
ensure
run("checkout #{starting_branch}")
end
end
def read_file_from_merge_branch(filename)
run("show #{merge_remote}/#{merge_branch}:#{filename}")
last_stdout
end
def initialize_rerere
return unless use_rerere
@cmd_runner.run('mkdir .git/rr-cache')
@cmd_runner.run('cp -R rr-cache/* .git/rr-cache/')
end
def commit_rerere(current_rereres)
return unless use_rerere
@cmd_runner.run('mkdir rr-cache')
@cmd_runner.run('rm -rf rr-cache/*')
current_rereres.each do |rerere|
@cmd_runner.run("cp -R .git/rr-cache/#{rerere} rr-cache/")
end
run('add rr-cache/')
run("commit -m 'Update rr-cache'")
end
def rerere_resolve!
return false unless use_rerere
merging_files = staged_and_working_dir_files.select { |s| UNMERGED_STATUSES.include?(s[0..1]) }.map { |s| s[3..-1] }
conflicts = merging_files.map do |file|
File.open(file) { |f| f.grep(/>>>>/) }
end
if conflicts.all? { |c| c.empty? }
run("add #{merging_files.join(" ")}")
run('commit --no-edit')
resolutions(merging_files)
else
false
end
end
def resolutions(files)
{}.tap do |hash|
files.map do |file|
hash[file] = resolution_candidates(file)
end.flatten
end
end
# git rerere doesn't give you a deterministic way to determine which resolution was used
def resolution_candidates(file)
@cmd_runner.run("diff -q --from-file #{file} .git/rr-cache/*/postimage")
different_files = split_diff_lines(@cmd_runner.last_stdout)
@cmd_runner.run('ls -la .git/rr-cache/*/postimage')
all_files = split_diff_lines(@cmd_runner.last_stdout)
all_files - different_files
end
def split_diff_lines(arr)
arr.split("\n").map { |s| s.split(".git/rr-cache/").last.split("/postimage").first }
end
def remotes
run('remote -v')
last_stdout.split("\n")
end
def remotes_hash
return @remotes_hash if @remotes_hash
@remotes_hash = {}
remotes.each do |r|
name = r.split[0]
url = r.split[1]
@remotes_hash[name] ||= url
end
@remotes_hash
end
def fetch_remote_for_url(url)
fetch_remotes = remotes.grep(Regexp.new(url)).grep(/ \(fetch\)/)
fetch_remotes.map { |remote| remote.to_s.split("\t").first }.first
end
def staged_and_working_dir_files
run("status --porcelain")
last_stdout.split("\n").reject { |line| line[0..1] == '??' }
end
def current_branch
run("rev-parse --abbrev-ref HEAD")
last_stdout.strip
end
def most_recent_commit
run("show -s --format=%cd head")
end
def reset_temp_merge_branch
in_branch(master_branch) do
run("fetch #{merge_remote}")
run("branch -D #{temp_merge_branch}")
run("checkout -b #{temp_merge_branch}")
run("reset --hard #{merge_remote}/#{master_branch}")
end
end
def push_merge_branch
run("push -f #{merge_remote} #{merge_branch}")
end
def copy_temp_to_merge_branch
run("checkout #{temp_merge_branch}")
run("merge --strategy=ours --no-edit #{merge_branch}")
run("checkout #{merge_branch}")
run("merge #{temp_merge_branch}")
run("log #{merge_remote}/#{merge_branch}..#{merge_branch}~3")
log = last_stdout
run("diff --name-only #{merge_remote}/#{merge_branch} #{merge_branch}")
files = last_stdout.split("\n")
run("reset #{merge_remote}/#{merge_branch}")
run("add #{files.join(" ")}")
run("commit -m '#{commit_message(log)}'")
# require 'byebug'; debugger
# puts 'hello'
end
def commit_message(log)
"Flash Flow run from branch: #{working_branch}\n\n#{log}"
end
def delete_temp_merge_branch
in_merge_branch do
run("branch -d #{temp_merge_branch}")
end
end
def in_temp_merge_branch(&block)
in_branch(temp_merge_branch, &block)
end
def in_merge_branch(&block)
in_branch(merge_branch, &block)
end
private
def temp_merge_branch
"flash_flow/#{merge_branch}"
end
def in_branch(branch)
begin
starting_branch = current_branch
run("checkout #{branch}")
yield
ensure
run("checkout #{starting_branch}")
end
end
end
end
Small refactor, remove commented out code
require 'flash_flow/cmd_runner'
module FlashFlow
class Git
ATTRIBUTES = [:merge_remote, :merge_branch, :master_branch, :use_rerere]
attr_reader *ATTRIBUTES
attr_reader :working_branch
UNMERGED_STATUSES = %w{DD AU UD UA DU AA UU}
def initialize(config, logger=nil)
@cmd_runner = CmdRunner.new(logger: logger)
ATTRIBUTES.each do |attr|
unless config.has_key?(attr.to_s)
raise RuntimeError.new("git configuration missing. Required config parameters: #{ATTRIBUTES}")
end
instance_variable_set("@#{attr}", config[attr.to_s])
end
@working_branch = current_branch
end
def last_stdout
@cmd_runner.last_stdout
end
def last_command
@cmd_runner.last_command
end
def last_success?
@cmd_runner.last_success?
end
def run(cmd)
@cmd_runner.run("git #{cmd}")
end
def add_and_commit(files, message, opts={})
files = [files].flatten
run("add #{'-f ' if opts[:add] && opts[:add][:force]}#{files.join(' ')}")
run("commit -m '#{message}'")
end
def push(branch, options)
run("push #{'-f' if options[:force]} #{merge_remote} #{branch}")
end
def merge(branch)
run("merge #{branch}")
end
def fetch(remote)
run("fetch #{remote}")
end
def master_branch_contains?(ref)
run("branch --contains #{ref}")
last_stdout.split("\n").detect { |str| str[2..-1] == master_branch }
end
def in_original_merge_branch
begin
starting_branch = current_branch
run("checkout #{merge_remote}/#{merge_branch}")
yield
ensure
run("checkout #{starting_branch}")
end
end
def read_file_from_merge_branch(filename)
run("show #{merge_remote}/#{merge_branch}:#{filename}")
last_stdout
end
def initialize_rerere
return unless use_rerere
@cmd_runner.run('mkdir .git/rr-cache')
@cmd_runner.run('cp -R rr-cache/* .git/rr-cache/')
end
def commit_rerere(current_rereres)
return unless use_rerere
@cmd_runner.run('mkdir rr-cache')
@cmd_runner.run('rm -rf rr-cache/*')
current_rereres.each do |rerere|
@cmd_runner.run("cp -R .git/rr-cache/#{rerere} rr-cache/")
end
run('add rr-cache/')
run("commit -m 'Update rr-cache'")
end
def rerere_resolve!
return false unless use_rerere
merging_files = staged_and_working_dir_files.select { |s| UNMERGED_STATUSES.include?(s[0..1]) }.map { |s| s[3..-1] }
conflicts = merging_files.map do |file|
File.open(file) { |f| f.grep(/>>>>/) }
end
if conflicts.all? { |c| c.empty? }
run("add #{merging_files.join(" ")}")
run('commit --no-edit')
resolutions(merging_files)
else
false
end
end
def resolutions(files)
{}.tap do |hash|
files.map do |file|
hash[file] = resolution_candidates(file)
end.flatten
end
end
# git rerere doesn't give you a deterministic way to determine which resolution was used
def resolution_candidates(file)
@cmd_runner.run("diff -q --from-file #{file} .git/rr-cache/*/postimage")
different_files = split_diff_lines(@cmd_runner.last_stdout)
@cmd_runner.run('ls -la .git/rr-cache/*/postimage')
all_files = split_diff_lines(@cmd_runner.last_stdout)
all_files - different_files
end
def split_diff_lines(arr)
arr.split("\n").map { |s| s.split(".git/rr-cache/").last.split("/postimage").first }
end
def remotes
run('remote -v')
last_stdout.split("\n")
end
def remotes_hash
return @remotes_hash if @remotes_hash
@remotes_hash = {}
remotes.each do |r|
name = r.split[0]
url = r.split[1]
@remotes_hash[name] ||= url
end
@remotes_hash
end
def fetch_remote_for_url(url)
fetch_remotes = remotes.grep(Regexp.new(url)).grep(/ \(fetch\)/)
fetch_remotes.map { |remote| remote.to_s.split("\t").first }.first
end
def staged_and_working_dir_files
run("status --porcelain")
last_stdout.split("\n").reject { |line| line[0..1] == '??' }
end
def current_branch
run("rev-parse --abbrev-ref HEAD")
last_stdout.strip
end
def most_recent_commit
run("show -s --format=%cd head")
end
def reset_temp_merge_branch
in_branch(master_branch) do
run("fetch #{merge_remote}")
run("branch -D #{temp_merge_branch}")
run("checkout -b #{temp_merge_branch}")
run("reset --hard #{merge_remote}/#{master_branch}")
end
end
def push_merge_branch
run("push -f #{merge_remote} #{merge_branch}")
end
def copy_temp_to_merge_branch
run("checkout #{temp_merge_branch}")
run("merge --strategy=ours --no-edit #{merge_branch}")
run("checkout #{merge_branch}")
run("merge #{temp_merge_branch}")
squash_commits
end
def commit_message(log)
"Flash Flow run from branch: #{working_branch}\n\n#{log}"
end
def delete_temp_merge_branch
in_merge_branch do
run("branch -d #{temp_merge_branch}")
end
end
def in_temp_merge_branch(&block)
in_branch(temp_merge_branch, &block)
end
def in_merge_branch(&block)
in_branch(merge_branch, &block)
end
private
def squash_commits
# There are three commits created by flash flow that we don't need in the message
run("log #{merge_remote}/#{merge_branch}..#{merge_branch}~3")
log = last_stdout
# Get all the files that differ between existing acceptance and new acceptance
run("diff --name-only #{merge_remote}/#{merge_branch} #{merge_branch}")
files = last_stdout.split("\n")
run("reset #{merge_remote}/#{merge_branch}")
run("add #{files.map { |f| "'#{f}'" }.join(" ")}")
run("commit -m '#{commit_message(log)}'")
end
def temp_merge_branch
"flash_flow/#{merge_branch}"
end
def in_branch(branch)
begin
starting_branch = current_branch
run("checkout #{branch}")
yield
ensure
run("checkout #{starting_branch}")
end
end
end
end
|
module Fleck
class Consumer
class << self
attr_accessor :logger, :configs, :consumers
end
def self.inherited(subclass)
super
init_consumer(subclass)
autostart(subclass)
Fleck.register_consumer(subclass)
end
def self.configure(opts = {})
self.configs.merge!(opts)
logger.debug "Consumer configurations updated."
end
def self.init_consumer(subclass)
subclass.logger = Fleck.logger.clone
subclass.logger.progname = subclass.to_s
subclass.logger.debug "Setting defaults for #{subclass.to_s.color(:yellow)} consumer"
subclass.configs = Fleck.config.default_options
subclass.consumers = []
end
def self.autostart(subclass)
# Use TracePoint to autostart the consumer when ready
trace = TracePoint.new(:end) do |tp|
if tp.self == subclass
# disable tracing when we reach the end of the subclass
trace.disable
# create a new instance of the subclass, in order to start the consumer
[subclass.configs[:concurrency].to_i, 1].max.times do |i|
subclass.consumers << subclass.new(i)
end
end
end
trace.enable
end
def initialize(thread_id)
@thread_id = thread_id
@connection = nil
@host = configs[:host]
@port = configs[:port]
@user = configs[:user] || 'guest'
@pass = configs[:password] || configs[:pass]
@vhost = configs[:vhost] || "/"
@queue_name = configs[:queue]
logger.info "Launching #{self.class.to_s.color(:yellow)} consumer ..."
connect!
create_channel!
subscribe!
at_exit do
terminate
end
end
def on_message(delivery_info, metadata, payload)
raise NotImplementedError.new("You must implement #on_message(delivery_info, metadata, payload) method")
end
def terminate
unless @channel.closed?
@channel.close
logger.info "Consumer successfully terminated."
end
end
def logger
return @logger if @logger
@logger = self.class.logger.clone
@logger.progname = "#{self.class.name}[#{@thread_id}]"
@logger
end
def configs
@configs ||= self.class.configs
end
protected
def connect!
@connection = Fleck.connection(host: @host, port: @port, user: @user, pass: @pass, vhost: @vhost)
end
def create_channel!
if @channel && !@channel.closed?
logger.info("Closing the opened channel...")
@channel.close
end
logger.debug "Creating a new channel for #{self.class.to_s.color(:yellow)} consumer"
@channel = @connection.create_channel
@channel.prefetch(1) # prevent from dispatching a new RabbitMQ message, until the previous message is not processed
@queue = @channel.queue(@queue_name, auto_delete: false)
@exchange = @channel.default_exchange
end
def subscribe!
logger.debug "Consuming from queue: #{@queue_name.color(:green)}"
@subscription = @queue.subscribe do |delivery_info, metadata, payload|
data = Oj.load(payload)
result = on_message(data["headers"], data["body"])
response = Oj.dump({"status" => 200, "body" => result})
logger.debug "Sending response: #{response}"
@exchange.publish(
response,
routing_key: metadata.reply_to,
correlation_id: metadata.correlation_id
)
end
end
def restart!
create_channel!
subscribe!
end
end
end
FIX: set default value for thread ID parameter of Fleck::Consumer
module Fleck
class Consumer
class << self
attr_accessor :logger, :configs, :consumers
end
def self.inherited(subclass)
super
init_consumer(subclass)
autostart(subclass)
Fleck.register_consumer(subclass)
end
def self.configure(opts = {})
self.configs.merge!(opts)
logger.debug "Consumer configurations updated."
end
def self.init_consumer(subclass)
subclass.logger = Fleck.logger.clone
subclass.logger.progname = subclass.to_s
subclass.logger.debug "Setting defaults for #{subclass.to_s.color(:yellow)} consumer"
subclass.configs = Fleck.config.default_options
subclass.consumers = []
end
def self.autostart(subclass)
# Use TracePoint to autostart the consumer when ready
trace = TracePoint.new(:end) do |tp|
if tp.self == subclass
# disable tracing when we reach the end of the subclass
trace.disable
# create a new instance of the subclass, in order to start the consumer
[subclass.configs[:concurrency].to_i, 1].max.times do |i|
subclass.consumers << subclass.new(i)
end
end
end
trace.enable
end
def initialize(thread_id = nil)
@thread_id = thread_id
@connection = nil
@host = configs[:host]
@port = configs[:port]
@user = configs[:user] || 'guest'
@pass = configs[:password] || configs[:pass]
@vhost = configs[:vhost] || "/"
@queue_name = configs[:queue]
logger.info "Launching #{self.class.to_s.color(:yellow)} consumer ..."
connect!
create_channel!
subscribe!
at_exit do
terminate
end
end
def on_message(delivery_info, metadata, payload)
raise NotImplementedError.new("You must implement #on_message(delivery_info, metadata, payload) method")
end
def terminate
unless @channel.closed?
@channel.close
logger.info "Consumer successfully terminated."
end
end
def logger
return @logger if @logger
@logger = self.class.logger.clone
@logger.progname = "#{self.class.name}" + (configs[:concurrency].to_i <= 1 ? "" : "[#{@thread_id}]")
@logger
end
def configs
@configs ||= self.class.configs
end
protected
def connect!
@connection = Fleck.connection(host: @host, port: @port, user: @user, pass: @pass, vhost: @vhost)
end
def create_channel!
if @channel && !@channel.closed?
logger.info("Closing the opened channel...")
@channel.close
end
logger.debug "Creating a new channel for #{self.class.to_s.color(:yellow)} consumer"
@channel = @connection.create_channel
@channel.prefetch(1) # prevent from dispatching a new RabbitMQ message, until the previous message is not processed
@queue = @channel.queue(@queue_name, auto_delete: false)
@exchange = @channel.default_exchange
end
def subscribe!
logger.debug "Consuming from queue: #{@queue_name.color(:green)}"
@subscription = @queue.subscribe do |delivery_info, metadata, payload|
data = Oj.load(payload)
result = on_message(data["headers"], data["body"])
response = Oj.dump({"status" => 200, "body" => result})
logger.debug "Sending response: #{response}"
@exchange.publish(
response,
routing_key: metadata.reply_to,
correlation_id: metadata.correlation_id
)
end
end
def restart!
create_channel!
subscribe!
end
end
end |
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'hp'))
require 'fog/storage'
module Fog
module Storage
class HP < Fog::Service
requires :hp_secret_key, :hp_account_id, :hp_tenant_id
recognizes :hp_auth_uri, :hp_servicenet, :hp_cdn_ssl, :hp_cdn_uri, :persistent, :connection_options, :hp_use_upass_auth_style, :hp_auth_version
model_path 'fog/hp/models/storage'
model :directory
collection :directories
model :file
collection :files
request_path 'fog/hp/requests/storage'
request :delete_container
request :delete_object
request :get_container
request :get_containers
request :get_object
request :head_container
request :head_containers
request :head_object
request :put_container
request :put_object
module Utils
def cdn
unless @hp_cdn_uri.nil?
@cdn ||= Fog::CDN.new(
:provider => 'HP',
:hp_account_id => @hp_account_id,
:hp_secret_key => @hp_secret_key,
:hp_auth_uri => @hp_auth_uri,
:hp_cdn_uri => @hp_cdn_uri,
:hp_tenant_id => @hp_tenant_id
)
if @cdn.enabled?
@cdn
end
else
nil
end
end
def url
"#{@scheme}://#{@host}:#{@port}#{@path}"
end
def acl_to_header(acl)
header = {}
case acl
when "private"
header['X-Container-Read'] = ""
header['X-Container-Write'] = ""
when "public-read"
header['X-Container-Read'] = ".r:*,.rlistings"
when "public-write"
header['X-Container-Write'] = "*"
when "public-read-write"
header['X-Container-Read'] = ".r:*,.rlistings"
header['X-Container-Write'] = "*"
end
header
end
def header_to_acl(read_header=nil, write_header=nil)
acl = nil
if read_header.nil? && write_header.nil?
acl = nil
elsif !read_header.nil? && read_header.include?(".r:*") && write_header.nil?
acl = "public-read"
elsif !write_header.nil? && write_header.include?("*") && read_header.nil?
acl = "public-write"
elsif !read_header.nil? && read_header.include?(".r:*") && !write_header.nil? && write_header.include?("*")
acl = "public-read-write"
end
end
end
class Mock
include Utils
def self.acls(type)
type
end
def self.data
@data ||= Hash.new do |hash, key|
hash[key] = {
:acls => {
:container => {},
:object => {}
},
:containers => {}
}
end
end
def self.reset
@data = nil
end
def initialize(options={})
require 'mime/types'
@hp_secret_key = options[:hp_secret_key]
@hp_account_id = options[:hp_account_id]
end
def data
self.class.data[@hp_account_id]
end
def reset_data
self.class.data.delete(@hp_account_id)
end
end
class Real
include Utils
attr_reader :hp_cdn_ssl
def initialize(options={})
require 'mime/types'
require 'multi_json'
@hp_secret_key = options[:hp_secret_key]
@hp_account_id = options[:hp_account_id]
@hp_auth_uri = options[:hp_auth_uri]
@hp_cdn_ssl = options[:hp_cdn_ssl]
@connection_options = options[:connection_options] || {}
### Set an option to use the style of authentication desired; :v1 or :v2 (default)
auth_version = options[:hp_auth_version] || :v2
### Pass the service type for object storage to the authentication call
options[:hp_service_type] = "object-store"
@hp_tenant_id = options[:hp_tenant_id]
### Make the authentication call
if (auth_version == :v2)
# Call the control services authentication
credentials = Fog::HP.authenticate_v2(options, @connection_options)
# the CS service catalog returns the cdn endpoint
@hp_storage_uri = credentials[:endpoint_url]
@hp_cdn_uri = credentials[:cdn_endpoint_url]
else
# Call the legacy v1.0/v1.1 authentication
credentials = Fog::HP.authenticate_v1(options, @connection_options)
# the user sends in the cdn endpoint
@hp_storage_uri = options[:hp_auth_uri]
@hp_cdn_uri = options[:hp_cdn_uri]
end
@auth_token = credentials[:auth_token]
uri = URI.parse(@hp_storage_uri)
@host = options[:hp_servicenet] == true ? "snet-#{uri.host}" : uri.host
@path = uri.path
@persistent = options[:persistent] || false
@port = uri.port
@scheme = uri.scheme
Excon.ssl_verify_peer = false if options[:hp_servicenet] == true
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options)
end
def reload
@connection.reset
end
def request(params, parse_json = true, &block)
begin
response = @connection.request(params.merge!({
:headers => {
'Content-Type' => 'application/json',
'X-Auth-Token' => @auth_token
}.merge!(params[:headers] || {}),
:host => @host,
:path => "#{@path}/#{params[:path]}",
}), &block)
rescue Excon::Errors::HTTPStatusError => error
raise case error
when Excon::Errors::NotFound
Fog::Storage::HP::NotFound.slurp(error)
else
error
end
end
if !response.body.empty? && parse_json && response.headers['Content-Type'] =~ %r{application/json}
response.body = MultiJson.decode(response.body)
end
response
end
end
end
end
end
Pass connection_options hash to the cdn connection in the storage provider.
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'hp'))
require 'fog/storage'
module Fog
module Storage
class HP < Fog::Service
requires :hp_secret_key, :hp_account_id, :hp_tenant_id
recognizes :hp_auth_uri, :hp_servicenet, :hp_cdn_ssl, :hp_cdn_uri, :persistent, :connection_options, :hp_use_upass_auth_style, :hp_auth_version
model_path 'fog/hp/models/storage'
model :directory
collection :directories
model :file
collection :files
request_path 'fog/hp/requests/storage'
request :delete_container
request :delete_object
request :get_container
request :get_containers
request :get_object
request :head_container
request :head_containers
request :head_object
request :put_container
request :put_object
module Utils
def cdn
unless @hp_cdn_uri.nil?
@cdn ||= Fog::CDN.new(
:provider => 'HP',
:hp_account_id => @hp_account_id,
:hp_secret_key => @hp_secret_key,
:hp_auth_uri => @hp_auth_uri,
:hp_cdn_uri => @hp_cdn_uri,
:hp_tenant_id => @hp_tenant_id,
:connection_options => @connection_options
)
if @cdn.enabled?
@cdn
end
else
nil
end
end
def url
"#{@scheme}://#{@host}:#{@port}#{@path}"
end
def acl_to_header(acl)
header = {}
case acl
when "private"
header['X-Container-Read'] = ""
header['X-Container-Write'] = ""
when "public-read"
header['X-Container-Read'] = ".r:*,.rlistings"
when "public-write"
header['X-Container-Write'] = "*"
when "public-read-write"
header['X-Container-Read'] = ".r:*,.rlistings"
header['X-Container-Write'] = "*"
end
header
end
def header_to_acl(read_header=nil, write_header=nil)
acl = nil
if read_header.nil? && write_header.nil?
acl = nil
elsif !read_header.nil? && read_header.include?(".r:*") && write_header.nil?
acl = "public-read"
elsif !write_header.nil? && write_header.include?("*") && read_header.nil?
acl = "public-write"
elsif !read_header.nil? && read_header.include?(".r:*") && !write_header.nil? && write_header.include?("*")
acl = "public-read-write"
end
end
end
class Mock
include Utils
def self.acls(type)
type
end
def self.data
@data ||= Hash.new do |hash, key|
hash[key] = {
:acls => {
:container => {},
:object => {}
},
:containers => {}
}
end
end
def self.reset
@data = nil
end
def initialize(options={})
require 'mime/types'
@hp_secret_key = options[:hp_secret_key]
@hp_account_id = options[:hp_account_id]
end
def data
self.class.data[@hp_account_id]
end
def reset_data
self.class.data.delete(@hp_account_id)
end
end
class Real
include Utils
attr_reader :hp_cdn_ssl
def initialize(options={})
require 'mime/types'
require 'multi_json'
@hp_secret_key = options[:hp_secret_key]
@hp_account_id = options[:hp_account_id]
@hp_auth_uri = options[:hp_auth_uri]
@hp_cdn_ssl = options[:hp_cdn_ssl]
@connection_options = options[:connection_options] || {}
### Set an option to use the style of authentication desired; :v1 or :v2 (default)
auth_version = options[:hp_auth_version] || :v2
### Pass the service type for object storage to the authentication call
options[:hp_service_type] = "object-store"
@hp_tenant_id = options[:hp_tenant_id]
### Make the authentication call
if (auth_version == :v2)
# Call the control services authentication
credentials = Fog::HP.authenticate_v2(options, @connection_options)
# the CS service catalog returns the cdn endpoint
@hp_storage_uri = credentials[:endpoint_url]
@hp_cdn_uri = credentials[:cdn_endpoint_url]
else
# Call the legacy v1.0/v1.1 authentication
credentials = Fog::HP.authenticate_v1(options, @connection_options)
# the user sends in the cdn endpoint
@hp_storage_uri = options[:hp_auth_uri]
@hp_cdn_uri = options[:hp_cdn_uri]
end
@auth_token = credentials[:auth_token]
uri = URI.parse(@hp_storage_uri)
@host = options[:hp_servicenet] == true ? "snet-#{uri.host}" : uri.host
@path = uri.path
@persistent = options[:persistent] || false
@port = uri.port
@scheme = uri.scheme
Excon.ssl_verify_peer = false if options[:hp_servicenet] == true
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent, @connection_options)
end
def reload
@connection.reset
end
def request(params, parse_json = true, &block)
begin
response = @connection.request(params.merge!({
:headers => {
'Content-Type' => 'application/json',
'X-Auth-Token' => @auth_token
}.merge!(params[:headers] || {}),
:host => @host,
:path => "#{@path}/#{params[:path]}",
}), &block)
rescue Excon::Errors::HTTPStatusError => error
raise case error
when Excon::Errors::NotFound
Fog::Storage::HP::NotFound.slurp(error)
else
error
end
end
if !response.body.empty? && parse_json && response.headers['Content-Type'] =~ %r{application/json}
response.body = MultiJson.decode(response.body)
end
response
end
end
end
end
end
|
require "foreman"
require "foreman/process"
require "foreman/procfile"
require "foreman/utils"
require "pty"
require "tempfile"
require "timeout"
require "term/ansicolor"
require "fileutils"
class Foreman::Engine
attr_reader :procfile
attr_reader :directory
attr_reader :environment
attr_reader :options
extend Term::ANSIColor
COLORS = [ cyan, yellow, green, magenta, red ]
def initialize(procfile, options={})
@procfile = Foreman::Procfile.new(procfile)
@directory = File.expand_path(File.dirname(procfile))
@options = options
@environment = read_environment_files(options[:env])
end
def start
proctitle "ruby: foreman master"
processes.each do |process|
process.color = next_color
fork process
end
trap("TERM") { puts "SIGTERM received"; terminate_gracefully }
trap("INT") { puts "SIGINT received"; terminate_gracefully }
watch_for_termination
end
def execute(name)
fork procfile[name]
trap("TERM") { puts "SIGTERM received"; terminate_gracefully }
trap("INT") { puts "SIGINT received"; terminate_gracefully }
watch_for_termination
end
def processes
procfile.processes
end
def port_for(process, num, base_port=nil)
base_port ||= 5000
offset = procfile.process_names.index(process.name) * 100
base_port.to_i + offset + num - 1
end
private ######################################################################
def fork(process)
concurrency = Foreman::Utils.parse_concurrency(@options[:concurrency])
1.upto(concurrency[process.name]) do |num|
fork_individual(process, num, port_for(process, num, @options[:port]))
end
end
def fork_individual(process, num, port)
@environment.each { |k,v| ENV[k] = v }
ENV["PORT"] = port.to_s
ENV["PS"] = "#{process.name}.#{num}"
pid = Process.fork do
run(process)
end
info "started with pid #{pid}", process
running_processes[pid] = process
end
def run(process)
proctitle "ruby: foreman #{process.name}"
trap("SIGINT", "IGNORE")
begin
Dir.chdir directory do
PTY.spawn(process.command) do |stdin, stdout, pid|
trap("SIGTERM") { Process.kill("SIGTERM", pid) }
until stdin.eof?
info stdin.gets, process
end
end
end
rescue PTY::ChildExited, Interrupt, Errno::EIO
begin
info "process exiting", process
rescue Interrupt
end
end
end
def kill_all(signal="SIGTERM")
running_processes.each do |pid, process|
Process.kill(signal, pid) rescue Errno::ESRCH
end
end
def terminate_gracefully
info "sending SIGTERM to all processes"
kill_all "SIGTERM"
Timeout.timeout(3) { Process.waitall }
rescue Timeout::Error
info "sending SIGKILL to all processes"
kill_all "SIGKILL"
end
def watch_for_termination
pid, status = Process.wait2
process = running_processes.delete(pid)
info "process terminated", process
terminate_gracefully
kill_all
rescue Errno::ECHILD
end
def info(message, process=nil)
print process.color if process
print "#{Time.now.strftime("%H:%M:%S")} #{pad_process_name(process)} | "
print Term::ANSIColor.reset
print message.chomp
puts
end
def error(message)
puts "ERROR: #{message}"
exit 1
end
def longest_process_name
@longest_process_name ||= begin
longest = procfile.process_names.map { |name| name.length }.sort.last
longest = 6 if longest < 6 # system
longest
end
end
def pad_process_name(process)
name = process ? "#{ENV["PS"]}" : "system"
name.ljust(longest_process_name + 3) # add 3 for process number padding
end
def proctitle(title)
$0 = title
end
def running_processes
@running_processes ||= {}
end
def next_color
@current_color ||= -1
@current_color += 1
@current_color >= COLORS.length ? "" : COLORS[@current_color]
end
def read_environment_files(filenames)
environment = {}
(filenames || "").split(",").map(&:strip).each do |filename|
error "No such file: #{filename}" unless File.exists?(filename)
environment.merge!(read_environment(filename))
end
environment.merge!(read_environment(".env")) unless filenames
environment
end
def read_environment(filename)
return {} unless File.exists?(filename)
File.read(filename).split("\n").inject({}) do |hash, line|
if line =~ /\A([A-Za-z_]+)=(.*)\z/
hash[$1] = $2
end
hash
end
end
end
- Controlling non-existing command in ruby1.9.3-HEAD
require "foreman"
require "foreman/process"
require "foreman/procfile"
require "foreman/utils"
require "pty"
require "tempfile"
require "timeout"
require "term/ansicolor"
require "fileutils"
class Foreman::Engine
attr_reader :procfile
attr_reader :directory
attr_reader :environment
attr_reader :options
extend Term::ANSIColor
COLORS = [ cyan, yellow, green, magenta, red ]
def initialize(procfile, options={})
@procfile = Foreman::Procfile.new(procfile)
@directory = File.expand_path(File.dirname(procfile))
@options = options
@environment = read_environment_files(options[:env])
end
def start
proctitle "ruby: foreman master"
processes.each do |process|
process.color = next_color
fork process
end
trap("TERM") { puts "SIGTERM received"; terminate_gracefully }
trap("INT") { puts "SIGINT received"; terminate_gracefully }
watch_for_termination
end
def execute(name)
fork procfile[name]
trap("TERM") { puts "SIGTERM received"; terminate_gracefully }
trap("INT") { puts "SIGINT received"; terminate_gracefully }
watch_for_termination
end
def processes
procfile.processes
end
def port_for(process, num, base_port=nil)
base_port ||= 5000
offset = procfile.process_names.index(process.name) * 100
base_port.to_i + offset + num - 1
end
private ######################################################################
def fork(process)
concurrency = Foreman::Utils.parse_concurrency(@options[:concurrency])
1.upto(concurrency[process.name]) do |num|
fork_individual(process, num, port_for(process, num, @options[:port]))
end
end
def fork_individual(process, num, port)
@environment.each { |k,v| ENV[k] = v }
ENV["PORT"] = port.to_s
ENV["PS"] = "#{process.name}.#{num}"
pid = Process.fork do
run(process)
end
info "started with pid #{pid}", process
running_processes[pid] = process
end
def run(process)
proctitle "ruby: foreman #{process.name}"
trap("SIGINT", "IGNORE")
begin
Dir.chdir directory do
PTY.spawn(process.command) do |stdin, stdout, pid|
trap("SIGTERM") { Process.kill("SIGTERM", pid) }
until stdin.eof?
info stdin.gets, process
end
end
end
rescue PTY::ChildExited, Interrupt, Errno::EIO, Errno::ENOENT
begin
info "process exiting", process
rescue Interrupt
end
end
end
def kill_all(signal="SIGTERM")
running_processes.each do |pid, process|
Process.kill(signal, pid) rescue Errno::ESRCH
end
end
def terminate_gracefully
info "sending SIGTERM to all processes"
kill_all "SIGTERM"
Timeout.timeout(3) { Process.waitall }
rescue Timeout::Error
info "sending SIGKILL to all processes"
kill_all "SIGKILL"
end
def watch_for_termination
pid, status = Process.wait2
process = running_processes.delete(pid)
info "process terminated", process
terminate_gracefully
kill_all
rescue Errno::ECHILD
end
def info(message, process=nil)
print process.color if process
print "#{Time.now.strftime("%H:%M:%S")} #{pad_process_name(process)} | "
print Term::ANSIColor.reset
print message.chomp
puts
end
def error(message)
puts "ERROR: #{message}"
exit 1
end
def longest_process_name
@longest_process_name ||= begin
longest = procfile.process_names.map { |name| name.length }.sort.last
longest = 6 if longest < 6 # system
longest
end
end
def pad_process_name(process)
name = process ? "#{ENV["PS"]}" : "system"
name.ljust(longest_process_name + 3) # add 3 for process number padding
end
def proctitle(title)
$0 = title
end
def running_processes
@running_processes ||= {}
end
def next_color
@current_color ||= -1
@current_color += 1
@current_color >= COLORS.length ? "" : COLORS[@current_color]
end
def read_environment_files(filenames)
environment = {}
(filenames || "").split(",").map(&:strip).each do |filename|
error "No such file: #{filename}" unless File.exists?(filename)
environment.merge!(read_environment(filename))
end
environment.merge!(read_environment(".env")) unless filenames
environment
end
def read_environment(filename)
return {} unless File.exists?(filename)
File.read(filename).split("\n").inject({}) do |hash, line|
if line =~ /\A([A-Za-z_]+)=(.*)\z/
hash[$1] = $2
end
hash
end
end
end
|
module Forest
VERSION = '0.120.1'
end
Version 0.121.0
module Forest
VERSION = '0.121.0'
end
|
%w(error builder collector helpers).each do |f|
require File.join(File.dirname(__FILE__), 'form_assistant', f)
end
# Developed by Ryan Heath (http://rpheath.com)
module RPH
# FormAssistant is currently made up of two custom FormBuilder's:
#
# 1) FormAssistant::FormBuilder
# - provides several convenient helpers (see helpers.rb)
# - method_missing hook to wrap content "on the fly"
# - labels automatically attached to field helpers
#
# 2) FormAssistant::InlineErrorFormBuilder
# - inherits from FormBuilder, so has all of the above functionality
# - provides errors inline with the field that wraps it
# - uses partials (in views/forms/) to style fields
#
# The idea is to make forms extremely less painful and a lot more DRY
module FormAssistant
# custom form builder
#
# <% form_for @project, :builder => RPH::FormAssistant::FormBuilder do |form| %>
# // form stuff
# <% end %>
#
# Note: see #form_assistant_for() below for an easier way to use this builder
class FormBuilder < ActionView::Helpers::FormBuilder
include RPH::FormAssistant::Helpers
class_inheritable_accessor :wrap_fields_with_paragraph_tag
# set to true if you want the <label> and the <field>
# to be automatically wrapped in a <p> tag
#
# Note: this can be set in config/initializers/form_assistant.rb ...
# RPH::FormAssistant::FormBuilder.wrap_fields_with_paragraph_tag = true
self.wrap_fields_with_paragraph_tag = false
public
# redefining all traditional form helpers so that they
# behave the way FormAssistant thinks they should behave
send(:form_helpers).each do |name|
define_method name do |field, *args|
# pull out the options
options = args.detect { |arg| arg.is_a?(Hash) } || {}
options[:label] ||= {}
# allow for a more convenient way to set common label options
%w(text class).each do |option|
label_option = "label_#{option}".to_sym
options[:label].merge!(option.to_sym => options.delete(label_option)) if options[label_option]
end
# return the fields
label_with_field = label(field, options[:label].delete(:text), options.delete(:label)) + super
self.class.wrap_fields_with_paragraph_tag ? @template.content_tag(:p, label_with_field) : label_with_field
end
end
end
# extends the custom form builder above to attach form errros to
# the fields themselves, avoiding the <%= error_messages_for :object %> way
#
# <% form_for @project, :builder => RPH::FormAssistant::InlineErrorFormBuilder do |form| %>
# // form stuff
# <% end %>
#
# Note: see #inline_error_form_assistant_for() below for an easier way to use this builder
class InlineErrorFormBuilder < FormBuilder
# override the field_error_proc so that it no longer wraps the field
# with <div class="fieldWithErrors">...</div>, but just returns the field
ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| html_tag }
# ensure that fields are NOT wrapped with <p> tags
# (handle markup formatting in forms/_partials)
self.wrap_fields_with_paragraph_tag = false
private
# get the error messages (if any) for a field
def error_message(field)
return unless has_errors?(field)
errors = object.errors.on(field)
errors.is_a?(Array) ? errors.to_sentence : errors
end
# returns true if a field is invalid or the object is missing
def has_errors?(field)
!(object.nil? || object.errors.on(field).blank?)
end
public
# redefining the custom FormBuilder's methods
send(:form_helpers).each do |name|
define_method name do |field, *args|
# use partials located in app/views/forms to
# handle the representation of the fields
render_partial_for(field) { super }
end
end
# render the appropriate partial based on whether or not
# the field has any errors
def render_partial_for(field)
@template.capture do
# get the field/label combo provided by FormBuilder
locals = { :field_with_label => yield }
# determine which partial to render based on if
# the field has any errors associated with it
if has_errors?(field)
locals.merge! :errors => error_message(field)
@template.render :partial => 'forms/field_with_errors', :locals => locals
else
@template.render :partial => 'forms/field_without_errors', :locals => locals
end
end
end
end
# methods that mix into ActionView::Base
module ActionView
private
# used to ensure that the desired builder gets set before calling form_for()
def form_for_with_builder(record_or_name_or_array, builder, *args, &proc)
options = (args.detect { |arg| arg.is_a?(Hash) } || {}).merge! :builder => builder
args << options
form_for(record_or_name_or_array, *args, &proc)
end
public
# easy way to make use of FormAssistant::FormBuilder
#
# <% form_assistant_for @project do |form| %>
# // form stuff
# <% end %>
def form_assistant_for(record_or_name_or_array, *args, &proc)
form_for_with_builder(record_or_name_or_array, RPH::FormAssistant::FormBuilder, *args, &proc)
end
# easy way to make use of FormAssistant::InlineErrorFormBuilder
#
# <% inline_error_form_assistant_for @project do |form| %>
# // form stuff
# <% end %>
def inline_error_form_assistant_for(record_or_name_or_array, *args, &proc)
form_for_with_builder(record_or_name_or_array, RPH::FormAssistant::InlineErrorFormBuilder, *args, &proc)
end
end
end
end
cleaning up comments
%w(error builder collector helpers).each do |f|
require File.join(File.dirname(__FILE__), 'form_assistant', f)
end
# Developed by Ryan Heath (http://rpheath.com)
module RPH
# FormAssistant is currently made up of two custom FormBuilder's:
#
# FormAssistant::FormBuilder
# - provides several convenient helpers (see helpers.rb)
# - method_missing hook to wrap content "on the fly"
# - labels automatically attached to field helpers
#
# FormAssistant::InlineErrorFormBuilder
# - inherits from FormBuilder, so has all of the above functionality
# - provides errors inline with the field that wraps it
# - uses partials (in views/forms/) to style fields
#
# The idea is to make forms extremely less painful and a lot more DRY
module FormAssistant
# custom form builder
#
# <% form_for @project, :builder => RPH::FormAssistant::FormBuilder do |form| %>
# // form stuff
# <% end %>
#
# Note: see #form_assistant_for() below for an easier way to use this builder
class FormBuilder < ActionView::Helpers::FormBuilder
include RPH::FormAssistant::Helpers
class_inheritable_accessor :wrap_fields_with_paragraph_tag
# set to true if you want the <label> and the <field>
# to be automatically wrapped in a <p> tag
#
# Note: this can be set in config/initializers/form_assistant.rb ...
# RPH::FormAssistant::FormBuilder.wrap_fields_with_paragraph_tag = true
self.wrap_fields_with_paragraph_tag = false
public
# redefining all traditional form helpers so that they
# behave the way FormAssistant thinks they should behave
send(:form_helpers).each do |name|
define_method name do |field, *args|
# pull out the options
options = args.detect { |arg| arg.is_a?(Hash) } || {}
options[:label] ||= {}
# allow for a more convenient way to set common label options
%w(text class).each do |option|
label_option = "label_#{option}".to_sym
options[:label].merge!(option.to_sym => options.delete(label_option)) if options[label_option]
end
# return the fields
label_with_field = label(field, options[:label].delete(:text), options.delete(:label)) + super
self.class.wrap_fields_with_paragraph_tag ? @template.content_tag(:p, label_with_field) : label_with_field
end
end
end
# extends the custom form builder above to attach form errros to
# the fields themselves, avoiding the <%= error_messages_for :object %> way
#
# <% form_for @project, :builder => RPH::FormAssistant::InlineErrorFormBuilder do |form| %>
# // form stuff
# <% end %>
#
# Note: see #inline_error_form_assistant_for() below for an easier way to use this builder
class InlineErrorFormBuilder < FormBuilder
# override the field_error_proc so that it no longer wraps the field
# with <div class="fieldWithErrors">...</div>, but just returns the field
ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| html_tag }
# ensure that fields are NOT wrapped with <p> tags
# (handle markup formatting in forms/_partials)
self.wrap_fields_with_paragraph_tag = false
private
# get the error messages (if any) for a field
def error_message(field)
return unless has_errors?(field)
errors = object.errors.on(field)
errors.is_a?(Array) ? errors.to_sentence : errors
end
# returns true if a field is invalid or the object is missing
def has_errors?(field)
!(object.nil? || object.errors.on(field).blank?)
end
public
# redefining the custom FormBuilder's methods
send(:form_helpers).each do |name|
define_method name do |field, *args|
# use partials located in app/views/forms to
# handle the representation of the fields
render_partial_for(field) { super }
end
end
# render the appropriate partial based on whether or not
# the field has any errors
def render_partial_for(field)
@template.capture do
# get the field/label combo provided by FormBuilder
locals = { :field_with_label => yield }
# determine which partial to render based on if
# the field has any errors associated with it
if has_errors?(field)
locals.merge! :errors => error_message(field)
@template.render :partial => 'forms/field_with_errors', :locals => locals
else
@template.render :partial => 'forms/field_without_errors', :locals => locals
end
end
end
end
# methods that mix into ActionView::Base
module ActionView
private
# used to ensure that the desired builder gets set before calling form_for()
def form_for_with_builder(record_or_name_or_array, builder, *args, &proc)
options = (args.detect { |arg| arg.is_a?(Hash) } || {}).merge! :builder => builder
args << options
form_for(record_or_name_or_array, *args, &proc)
end
public
# easy way to make use of FormAssistant::FormBuilder
#
# <% form_assistant_for @project do |form| %>
# // form stuff
# <% end %>
def form_assistant_for(record_or_name_or_array, *args, &proc)
form_for_with_builder(record_or_name_or_array, RPH::FormAssistant::FormBuilder, *args, &proc)
end
# easy way to make use of FormAssistant::InlineErrorFormBuilder
#
# <% inline_error_form_assistant_for @project do |form| %>
# // form stuff
# <% end %>
def inline_error_form_assistant_for(record_or_name_or_array, *args, &proc)
form_for_with_builder(record_or_name_or_array, RPH::FormAssistant::InlineErrorFormBuilder, *args, &proc)
end
end
end
end |
# frozen_string_literal: true
class Freddy
VERSION = '2.1.0'
end
Bump version to 2.2.0
# frozen_string_literal: true
class Freddy
VERSION = '2.2.0'
end
|
# Copyright (C) 2013, 2014 by Dmitry Maksyoma <ledestin@gmail.com>
require 'timeout'
require 'frugal_timeout/request'
require 'frugal_timeout/request_queue'
require 'frugal_timeout/timer'
#--
# {{{1 Rdoc
#++
# Timeout.timeout() replacement using only 1 thread
# = Example
#
# require 'frugal_timeout'
#
# begin
# FrugalTimeout.timeout(0.1) { sleep }
# rescue Timeout::Error
# puts 'it works!'
# end
#
# # Ensure that calling timeout() will use FrugalTimeout.timeout().
# FrugalTimeout.dropin!
#
# # Rescue frugal-specific exception if needed.
# begin
# timeout(0.1) { sleep }
# rescue FrugalTimeout::Error
# puts 'yay!'
# end
#--
# }}}1
module FrugalTimeout
# Each timeout() call produces a request that contains expiry time. All new
# requests are put into a queue, and when the nearest request expires, all
# expired requests raise exceptions and are removed from the queue.
#
# Timer is setup here to trigger exception raising (for expired requests) when
# the nearest request expires. And queue is setup to let Timer know of the
# nearest expiry time.
@requestQueue, timer = RequestQueue.new, Timer.new
@requestQueue.onNewNearestRequest { |request|
timer.notifyAt request.at
}
timer.onNotify { @requestQueue.enforceExpired }
# Ensure that calling ::timeout() will use FrugalTimeout.timeout()
def self.dropin!
Object.class_eval \
'def timeout t, klass=nil, &b
FrugalTimeout.timeout t, klass, &b
end'
end
def self.on_enforce &b #:nodoc:
@requestQueue.onEnforce &b
end
def self.on_ensure &b #:nodoc:
@onEnsure = b
end
# Same as Timeout.timeout()
def self.timeout sec, klass=nil
return yield sec if sec.nil? || sec <= 0
innerException = klass || Class.new(Timeout::ExitException)
begin
request = @requestQueue.queue(sec, innerException)
# 'defuse!' is here only for the case when exception comes from the yield
# block. Otherwise, when timeout exception is raised, the request is
# defused automatically.
#
# Now, if in ensure, timeout exception comes, the request has already been
# defused automatically, so even if ensure is interrupted, there's no
# problem.
begin
yield sec
ensure
request.defuse!
end
rescue innerException => e
# Respect user's choice of exception.
raise if klass
raise Error, e.message, e.backtrace
ensure
@onEnsure.call if @onEnsure
end
end
end
* More comments.
# Copyright (C) 2013, 2014 by Dmitry Maksyoma <ledestin@gmail.com>
require 'timeout'
require 'frugal_timeout/request'
require 'frugal_timeout/request_queue'
require 'frugal_timeout/timer'
#--
# {{{1 Rdoc
#++
# Timeout.timeout() replacement using only 1 thread
# = Example
#
# require 'frugal_timeout'
#
# begin
# FrugalTimeout.timeout(0.1) { sleep }
# rescue Timeout::Error
# puts 'it works!'
# end
#
# # Ensure that calling timeout() will use FrugalTimeout.timeout().
# FrugalTimeout.dropin!
#
# # Rescue frugal-specific exception if needed.
# begin
# timeout(0.1) { sleep }
# rescue FrugalTimeout::Error
# puts 'yay!'
# end
#--
# }}}1
module FrugalTimeout
# Each timeout() call produces a request that contains expiry time. All new
# requests are put into a queue, and when the nearest request expires, all
# expired requests raise exceptions and are removed from the queue.
#
# Timer is setup here to trigger exception raising (for expired requests) when
# the nearest request expires. And queue is setup to let Timer know of the
# nearest expiry time.
@requestQueue, timer = RequestQueue.new, Timer.new
@requestQueue.onNewNearestRequest { |request|
timer.notifyAt request.at
}
timer.onNotify { @requestQueue.enforceExpired }
# Ensure that calling ::timeout() will use FrugalTimeout.timeout()
def self.dropin!
Object.class_eval \
'def timeout t, klass=nil, &b
FrugalTimeout.timeout t, klass, &b
end'
end
def self.on_enforce &b #:nodoc:
@requestQueue.onEnforce &b
end
def self.on_ensure &b #:nodoc:
@onEnsure = b
end
# Same as Timeout.timeout()
def self.timeout sec, klass=nil
return yield sec if sec.nil? || sec <= 0
# Exception to raise on timeout expiry *inside* yield. A unique class is
# needed to prevent #timeout() calls within yield from rescuing it.
innerException = klass || Class.new(Timeout::ExitException)
begin
request = @requestQueue.queue(sec, innerException)
# 'defuse!' is here only for the case when exception comes from the yield
# block. Otherwise, when timeout exception is raised, the request is
# defused automatically.
#
# Now, if in ensure, timeout exception comes, the request has already been
# defused automatically, so even if ensure is interrupted, there's no
# problem.
begin
yield sec
ensure
request.defuse!
end
rescue innerException => e
# Respect user's choice of exception.
raise if klass
raise Error, e.message, e.backtrace
ensure
@onEnsure.call if @onEnsure
end
end
end
|
module Fusuma
VERSION = '0.4.0'.freeze
end
bump version
module Fusuma
VERSION = '0.4.1'.freeze
end
|
module Fusuma
VERSION = '0.3.3'.freeze
end
bump version
module Fusuma
VERSION = '0.3.4'.freeze
end
|
module Game
class Panellist
attr_accessor :index
attr_accessor :name1, :name2
attr_accessor :font, :buzzer, :score, :challenger
def initialize(window, index, config)
@window = window
@index = index
@challenger = false
init_name(config)
init_score
init_buzzer(config['buzzer'])
center = (window.x_size / 2)
gap = window.x_size / 4
if @window.config.reverse
# house left to house right
display_index = ((@index - 3) * -1)
else
# stage left to stage right
display_index = @index
end
@center = center + (gap * (display_index - 1.5))
end
def init_score
@score = 0
@score_font = Gosu::Font.new(@window.x_size / 5)
end
def init_name(config)
@name1 = config['name1']
@name2 = config['name2']
@name_font = Gosu::Font.new(@window.x_size / 15)
end
def init_buzzer(sample_name)
@buzzer = Gosu::Sample.new(
File.join(
File.dirname(__FILE__),
'..', '..', 'audio',
sample_name
)
)
end
def colour
if @challenger
Gosu::Color::CYAN
else
Gosu::Color::WHITE
end
end
def draw
@name_font.draw_rel(
name1,
@center,
(@window.y_size / 8) * 5,
0, 0.5, 0.5
)
@name_font.draw_rel(
name2,
@center,
(@window.y_size / 8) * 5.5,
0, 0.5, 0.5
)
@score_font.draw_rel(
score.to_s,
@center,
(@window.y_size / 8) * 7,
0, 0.5, 0.5,
1, 1, colour
)
end
def button_down(id)
case id
when KeyBinding.panellist(@index, :up)
@score += 1
@window.report
when KeyBinding.panellist(@index, :down)
@score -= 1
@window.report
when KeyBinding.panellist(@index, :buzz)
buzz
end
end
def buzz
if @window.timer.active
@challenger = true
@buzzer.play
@window.timer.stop
@window.report
end
end
end
end
Re-coloured the entire name, not just the score
module Game
class Panellist
attr_accessor :index
attr_accessor :name1, :name2
attr_accessor :font, :buzzer, :score, :challenger
def initialize(window, index, config)
@window = window
@index = index
@challenger = false
init_name(config)
init_score
init_buzzer(config['buzzer'])
center = (window.x_size / 2)
gap = window.x_size / 4
if @window.config.reverse
# house left to house right
display_index = ((@index - 3) * -1)
else
# stage left to stage right
display_index = @index
end
@center = center + (gap * (display_index - 1.5))
end
def init_score
@score = 0
@score_font = Gosu::Font.new(@window.x_size / 5)
end
def init_name(config)
@name1 = config['name1']
@name2 = config['name2']
@name_font = Gosu::Font.new(@window.x_size / 15)
end
def init_buzzer(sample_name)
@buzzer = Gosu::Sample.new(
File.join(
File.dirname(__FILE__),
'..', '..', 'audio',
sample_name
)
)
end
def colour
if @challenger
Gosu::Color::GREEN
else
Gosu::Color::WHITE
end
end
def draw
@name_font.draw_rel(
name1,
@center,
(@window.y_size / 8) * 5,
0, 0.5, 0.5,
1, 1, colour
)
@name_font.draw_rel(
name2,
@center,
(@window.y_size / 8) * 5.5,
0, 0.5, 0.5,
1, 1, colour
)
@score_font.draw_rel(
score.to_s,
@center,
(@window.y_size / 8) * 7,
0, 0.5, 0.5,
1, 1, colour
)
end
def button_down(id)
case id
when KeyBinding.panellist(@index, :up)
@score += 1
@window.report
when KeyBinding.panellist(@index, :down)
@score -= 1
@window.report
when KeyBinding.panellist(@index, :buzz)
buzz
end
end
def buzz
if @window.timer.active
@challenger = true
@buzzer.play
@window.timer.stop
@window.report
end
end
end
end |
module Garufa
VERSION = '0.0.1.beta.1'
end
Bump 0.0.1.beta.2.
module Garufa
VERSION = '0.0.1.beta.2'
end
|
module Geofsh
VERSION = "0.1.0-beta"
end
Increment gem version
module Geofsh
VERSION = "0.1.0"
end
|
require 'active_force/query'
require 'active_force/association/association'
require 'active_force/association/has_many_association'
require 'active_force/association/belongs_to_association'
module ActiveForce
module Association
module ClassMethods
def has_many relation_name, options = {}
HasManyAssociation.new(self, relation_name, options)
end
def belongs_to relation_name, options = {}
BelongsToAssociation.new(self, relation_name, options)
end
end
def self.included mod
mod.extend ClassMethods
end
end
end
Remove unused request.
require 'active_force/association/association'
require 'active_force/association/has_many_association'
require 'active_force/association/belongs_to_association'
module ActiveForce
module Association
module ClassMethods
def has_many relation_name, options = {}
HasManyAssociation.new(self, relation_name, options)
end
def belongs_to relation_name, options = {}
BelongsToAssociation.new(self, relation_name, options)
end
end
def self.included mod
mod.extend ClassMethods
end
end
end
|
module Geordi
VERSION = '0.12.8'
end
bump version to 0.13.0
module Geordi
VERSION = '0.13.0'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.