CombinedText
stringlengths
4
3.42M
module ActiveMerchant #:nodoc: module Billing #:nodoc: class MercadoPagoGateway < Gateway self.live_url = self.test_url = 'https://api.mercadopago.com/v1' self.supported_countries = ['AR', 'BR', 'CL', 'CO', 'MX', 'PE', 'UY'] self.supported_cardtypes = [:visa, :master, :american_express] self.homepage_url = 'https://www.mercadopago.com/' self.display_name = 'Mercado Pago' self.money_format = :dollars CARD_BRAND = { "american_express" => "amex", "diners_club" => "diners" } def initialize(options={}) requires!(options, :access_token) super end def purchase(money, payment, options={}) MultiResponse.run do |r| r.process { commit("tokenize", "card_tokens", card_token_request(money, payment, options)) } options.merge!(card_brand: (CARD_BRAND[payment.brand] || payment.brand)) options.merge!(card_token: r.authorization.split("|").first) r.process { commit("purchase", "payments", purchase_request(money, payment, options) ) } end end def authorize(money, payment, options={}) MultiResponse.run do |r| r.process { commit("tokenize", "card_tokens", card_token_request(money, payment, options)) } options.merge!(card_brand: (CARD_BRAND[payment.brand] || payment.brand)) options.merge!(card_token: r.authorization.split("|").first) r.process { commit("authorize", "payments", authorize_request(money, payment, options) ) } end end def capture(money, authorization, options={}) post = {} authorization, _ = authorization.split("|") post[:capture] = true post[:transaction_amount] = amount(money).to_f commit("capture", "payments/#{authorization}", post) end def refund(money, authorization, options={}) post = {} authorization, original_amount = authorization.split("|") post[:amount] = amount(money).to_f if original_amount && original_amount.to_f > amount(money).to_f commit("refund", "payments/#{authorization}/refunds", post) end def void(authorization, options={}) authorization, _ = authorization.split("|") post = { status: "cancelled" } commit("void", "payments/#{authorization}", post) end def verify(credit_card, options={}) MultiResponse.run(:use_first_response) do |r| r.process { authorize(100, credit_card, options) } r.process(:ignore_result) { void(r.authorization, options) } end end def supports_scrubbing? true end def scrub(transcript) transcript. gsub(%r((access_token=).*?([^\s]+)), '\1[FILTERED]'). gsub(%r((\"card_number\\\":\\\")\d+), '\1[FILTERED]'). gsub(%r((\"security_code\\\":\\\")\d+), '\1[FILTERED]') end private def card_token_request(money, payment, options = {}) post = {} post[:card_number] = payment.number post[:security_code] = payment.verification_value post[:expiration_month] = payment.month post[:expiration_year] = payment.year post[:cardholder] = { name: payment.name, identification: { type: options[:cardholder_identification_type], number: options[:cardholder_identification_number] } } post end def purchase_request(money, payment, options = {}) post = {} add_invoice(post, money, options) add_payment(post, options) add_additional_data(post, options) add_customer_data(post, payment, options) add_address(post, options) post[:binary_mode] = (options[:binary_mode].nil? ? true : options[:binary_mode]) post end def authorize_request(money, payment, options = {}) post = purchase_request(money, payment, options) post.merge!(capture: false) post end def add_additional_data(post, options) post[:sponsor_id] = options[:sponsor_id] post[:device_id] = options[:device_id] if options[:device_id] post[:additional_info] = { ip_address: options[:ip_address] }.merge(options[:additional_info] || {}) add_address(post, options) add_shipping_address(post, options) end def add_customer_data(post, payment, options) post[:payer] = { email: options[:email], first_name: payment.first_name, last_name: payment.last_name } end def add_address(post, options) if address = (options[:billing_address] || options[:address]) post[:additional_info].merge!({ payer: { address: { zip_code: address[:zip], street_name: "#{address[:address1]} #{address[:address2]}" } } }) end end def add_shipping_address(post, options) if address = options[:shipping_address] post[:additional_info].merge!({ shipments: { receiver_address: { zip_code: address[:zip], street_name: "#{address[:address1]} #{address[:address2]}" } } }) end end def split_street_address(address1) street_number = address1.split(" ").first if street_name = address1.split(" ")[1..-1] street_name = street_name.join(" ") else nil end [street_number, street_name] end def add_invoice(post, money, options) post[:transaction_amount] = amount(money).to_f post[:description] = options[:description] post[:installments] = options[:installments] ? options[:installments].to_i : 1 post[:statement_descriptor] = options[:statement_descriptor] if options[:statement_descriptor] post[:external_reference] = options[:order_id] || SecureRandom.hex(16) end def add_payment(post, options) post[:token] = options[:card_token] post[:payment_method_id] = options[:card_brand] end def parse(body) JSON.parse(body) end def commit(action, path, parameters) if ["capture", "void"].include?(action) response = parse(ssl_request(:put, url(path), post_data(parameters), headers)) else response = parse(ssl_post(url(path), post_data(parameters), headers(parameters))) end Response.new( success_from(action, response), message_from(response), response, authorization: authorization_from(response, parameters), test: test?, error_code: error_code_from(action, response) ) end def success_from(action, response) if action == "refund" response["error"].nil? else ["active", "approved", "authorized", "cancelled"].include?(response["status"]) end end def message_from(response) (response["status_detail"]) || (response["message"]) end def authorization_from(response, params) [response["id"], params[:transaction_amount]].join("|") end def post_data(parameters = {}) parameters.clone.tap { |p| p.delete(:device_id) }.to_json end def error_code_from(action, response) unless success_from(action, response) if cause = response["cause"] cause.empty? ? nil : cause.first["code"] else response["status"] end end end def url(action) full_url = (test? ? test_url : live_url) full_url + "/#{action}?access_token=#{CGI.escape(@options[:access_token])}" end def headers(options = {}) headers = { "Content-Type" => "application/json" } headers['X-Device-Session-ID'] = options[:device_id] if options[:device_id] headers end def handle_response(response) case response.code.to_i when 200..499 response.body else raise ResponseError.new(response) end end end end end Mercado Pago: Allow binary_mode to be changed Allows binary_mode to be set to a value rather than the current default of true. Loaded suite test/unit/gateways/mercado_pago_test Started ................... 19 tests, 95 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 100% passed Loaded suite test/remote/gateways/remote_mercado_pago_test Started ................. 17 tests, 46 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 100% passed module ActiveMerchant #:nodoc: module Billing #:nodoc: class MercadoPagoGateway < Gateway self.live_url = self.test_url = 'https://api.mercadopago.com/v1' self.supported_countries = ['AR', 'BR', 'CL', 'CO', 'MX', 'PE', 'UY'] self.supported_cardtypes = [:visa, :master, :american_express] self.homepage_url = 'https://www.mercadopago.com/' self.display_name = 'Mercado Pago' self.money_format = :dollars CARD_BRAND = { "american_express" => "amex", "diners_club" => "diners" } def initialize(options={}) requires!(options, :access_token) super end def purchase(money, payment, options={}) MultiResponse.run do |r| r.process { commit("tokenize", "card_tokens", card_token_request(money, payment, options)) } options.merge!(card_brand: (CARD_BRAND[payment.brand] || payment.brand)) options.merge!(card_token: r.authorization.split("|").first) r.process { commit("purchase", "payments", purchase_request(money, payment, options) ) } end end def authorize(money, payment, options={}) MultiResponse.run do |r| r.process { commit("tokenize", "card_tokens", card_token_request(money, payment, options)) } options.merge!(card_brand: (CARD_BRAND[payment.brand] || payment.brand)) options.merge!(card_token: r.authorization.split("|").first) r.process { commit("authorize", "payments", authorize_request(money, payment, options) ) } end end def capture(money, authorization, options={}) post = {} authorization, _ = authorization.split("|") post[:capture] = true post[:transaction_amount] = amount(money).to_f commit("capture", "payments/#{authorization}", post) end def refund(money, authorization, options={}) post = {} authorization, original_amount = authorization.split("|") post[:amount] = amount(money).to_f if original_amount && original_amount.to_f > amount(money).to_f commit("refund", "payments/#{authorization}/refunds", post) end def void(authorization, options={}) authorization, _ = authorization.split("|") post = { status: "cancelled" } commit("void", "payments/#{authorization}", post) end def verify(credit_card, options={}) MultiResponse.run(:use_first_response) do |r| r.process { authorize(100, credit_card, options) } r.process(:ignore_result) { void(r.authorization, options) } end end def supports_scrubbing? true end def scrub(transcript) transcript. gsub(%r((access_token=).*?([^\s]+)), '\1[FILTERED]'). gsub(%r((\"card_number\\\":\\\")\d+), '\1[FILTERED]'). gsub(%r((\"security_code\\\":\\\")\d+), '\1[FILTERED]') end private def card_token_request(money, payment, options = {}) post = {} post[:card_number] = payment.number post[:security_code] = payment.verification_value post[:expiration_month] = payment.month post[:expiration_year] = payment.year post[:cardholder] = { name: payment.name, identification: { type: options[:cardholder_identification_type], number: options[:cardholder_identification_number] } } post end def purchase_request(money, payment, options = {}) post = {} add_invoice(post, money, options) add_payment(post, options) add_additional_data(post, options) add_customer_data(post, payment, options) add_address(post, options) post[:binary_mode] = (options[:binary_mode].nil? ? true : options[:binary_mode]) post end def authorize_request(money, payment, options = {}) post = purchase_request(money, payment, options) post.merge!(capture: false) post end def add_additional_data(post, options) post[:sponsor_id] = options[:sponsor_id] post[:device_id] = options[:device_id] if options[:device_id] post[:additional_info] = { ip_address: options[:ip_address] }.merge(options[:additional_info] || {}) add_address(post, options) add_shipping_address(post, options) end def add_customer_data(post, payment, options) post[:payer] = { email: options[:email], first_name: payment.first_name, last_name: payment.last_name } end def add_address(post, options) if address = (options[:billing_address] || options[:address]) post[:additional_info].merge!({ payer: { address: { zip_code: address[:zip], street_name: "#{address[:address1]} #{address[:address2]}" } } }) end end def add_shipping_address(post, options) if address = options[:shipping_address] post[:additional_info].merge!({ shipments: { receiver_address: { zip_code: address[:zip], street_name: "#{address[:address1]} #{address[:address2]}" } } }) end end def split_street_address(address1) street_number = address1.split(" ").first if street_name = address1.split(" ")[1..-1] street_name = street_name.join(" ") else nil end [street_number, street_name] end def add_invoice(post, money, options) post[:transaction_amount] = amount(money).to_f post[:description] = options[:description] post[:installments] = options[:installments] ? options[:installments].to_i : 1 post[:statement_descriptor] = options[:statement_descriptor] if options[:statement_descriptor] post[:external_reference] = options[:order_id] || SecureRandom.hex(16) end def add_payment(post, options) post[:token] = options[:card_token] post[:payment_method_id] = options[:card_brand] end def parse(body) JSON.parse(body) end def commit(action, path, parameters) if ["capture", "void"].include?(action) response = parse(ssl_request(:put, url(path), post_data(parameters), headers)) else response = parse(ssl_post(url(path), post_data(parameters), headers(parameters))) end Response.new( success_from(action, response), message_from(response), response, authorization: authorization_from(response, parameters), test: test?, error_code: error_code_from(action, response) ) end def success_from(action, response) if action == "refund" response["error"].nil? else ["active", "approved", "authorized", "cancelled", "in_process"].include?(response["status"]) end end def message_from(response) (response["status_detail"]) || (response["message"]) end def authorization_from(response, params) [response["id"], params[:transaction_amount]].join("|") end def post_data(parameters = {}) parameters.clone.tap { |p| p.delete(:device_id) }.to_json end def error_code_from(action, response) unless success_from(action, response) if cause = response["cause"] cause.empty? ? nil : cause.first["code"] else response["status"] end end end def url(action) full_url = (test? ? test_url : live_url) full_url + "/#{action}?access_token=#{CGI.escape(@options[:access_token])}" end def headers(options = {}) headers = { "Content-Type" => "application/json" } headers['X-Device-Session-ID'] = options[:device_id] if options[:device_id] headers end def handle_response(response) case response.code.to_i when 200..499 response.body else raise ResponseError.new(response) end end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'at_most/version' Gem::Specification.new do |spec| spec.name = "at_most" spec.version = AtMost::VERSION spec.authors = ["Kristian Freeman"] spec.email = ["kristian@kristianfreeman.com"] spec.description = %q{TODO: Write a gem description} spec.summary = %q{TODO: Write a gem summary} 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_dependency "activerecord" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "coveralls" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "sqlite3" end Update Gemspec, getting prepared for version 0.0.1 release # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'at_most/version' Gem::Specification.new do |spec| spec.name = "at_most" spec.version = AtMost::VERSION spec.authors = ["Kristian Freeman"] spec.email = ["kristian@kristianfreeman.com"] spec.description = %q{Limit your ActiveRecord models} spec.summary = %q{A simple extension to ActiveRecord to allow limiting of model creation via validation. This gem was extracted out of a Rails app function that limited the number of users that could be created with CRUD access to a different AR model.} spec.homepage = "https://github.com/imkmf/at_most" spec.license = "MIT" spec.files = `git ls-files`.split($/) spec.test_files = spec.files.grep(%r{^(spec)/}) spec.require_paths = ["lib"] spec.add_dependency "activerecord" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "coveralls" spec.add_development_dependency "rake" spec.add_development_dependency "rspec" spec.add_development_dependency "sqlite3" end
module ActiveRecord module ActsAsRelation module AccessMethods protected def define_acts_as_accessors(attribs, model_name) # The weird order of the if-else branches is so that we query ourselves # before we query our superclass. class_eval <<-EndCode, __FILE__, __LINE__ + 1 def method_missing(method, *args, &proc) if #{model_name}.respond_to?(method) self.class_eval do delegate method, to: :#{model_name} end #{model_name}.send(method, *args, &proc) else super end end def read_attribute(attr_name, *args, &proc) if attribute_method?(attr_name.to_s) super(attr_name, *args) else #{model_name}.read_attribute(attr_name, *args, &proc) end end def touch(name = nil, *args, &proc) if attribute_method?(name.to_s) super(name, *args, &proc) else super(nil, *args, &proc) #{model_name}.touch(name, *args, &proc) end end private def write_attribute(attr_name, *args, &proc) if attribute_method?(attr_name.to_s) super(attr_name, *args) else #{model_name}.send(:write_attribute, attr_name, *args, &proc) end end EndCode end end end end When saving the record, ensure that the superclass is saved also. This is necessary if the child class is not timestamped. module ActiveRecord module ActsAsRelation module AccessMethods protected def define_acts_as_accessors(attribs, model_name) # The weird order of the if-else branches is so that we query ourselves # before we query our superclass. class_eval <<-EndCode, __FILE__, __LINE__ + 1 def method_missing(method, *args, &proc) if #{model_name}.respond_to?(method) self.class_eval do delegate method, to: :#{model_name} end #{model_name}.send(method, *args, &proc) else super end end def read_attribute(attr_name, *args, &proc) if attribute_method?(attr_name.to_s) super(attr_name, *args) else #{model_name}.read_attribute(attr_name, *args, &proc) end end def touch(name = nil, *args, &proc) if attribute_method?(name.to_s) super(name, *args, &proc) else super(nil, *args, &proc) #{model_name}.touch(name, *args, &proc) end end def save(*args) super(*args) && #{model_name}.save(*args) end def save!(*args) super(*args) && #{model_name}.save!(*args) end private def write_attribute(attr_name, *args, &proc) if attribute_method?(attr_name.to_s) super(attr_name, *args) else #{model_name}.send(:write_attribute, attr_name, *args, &proc) end end EndCode end end end end
require 'sinatra' require 'sinatra/param' require 'mongo' require 'json/ext' require 'date' mongo_uri = ENV['MONGOLAB_URI'] || 'mongodb://127.0.0.1:27017/twacker' configure do db = Mongo::Client.new(mongo_uri) set :mongo_db, db helpers Sinatra::Param end get '/' do p settings.public_folder send_file File.join(settings.public_folder, 'index.html') end get '/stats' do aggregated = Array.new days = settings.mongo_db[:twacker_stats].find({'date' => {'$gt' => Date::today - 30}}) days.each_with_index do |today, i| yesterday = days.to_a[i - 1] unless i == 0 aggregated << { date: today[:date].strftime('%Y-%m-%d'), followers_count: today[:followers].length, friends_count: today[:friends].length, followers_added: yesterday ? today[:followers] - yesterday[:followers] : [], followers_removed: yesterday ? yesterday[:followers] - today[:followers] : [], friends_added: yesterday ? today[:friends] - yesterday[:friends] : [], friends_removed: yesterday ? yesterday[:friends] - today[:friends] : [] } end content_type :json aggregated.to_json end get '/profile' do param :user_id, Integer, required: true content_type :json profile = settings.mongo_db[:profiles].find( {'user_id' => params[:user_id]} ).projection({'_id' => false}).first.to_json end Remove puts from get /. require 'sinatra' require 'sinatra/param' require 'mongo' require 'json/ext' require 'date' mongo_uri = ENV['MONGOLAB_URI'] || 'mongodb://127.0.0.1:27017/twacker' configure do db = Mongo::Client.new(mongo_uri) set :mongo_db, db helpers Sinatra::Param end get '/' do send_file File.join(settings.public_folder, 'index.html') end get '/stats' do aggregated = Array.new days = settings.mongo_db[:twacker_stats].find({'date' => {'$gt' => Date::today - 30}}) days.each_with_index do |today, i| yesterday = days.to_a[i - 1] unless i == 0 aggregated << { date: today[:date].strftime('%Y-%m-%d'), followers_count: today[:followers].length, friends_count: today[:friends].length, followers_added: yesterday ? today[:followers] - yesterday[:followers] : [], followers_removed: yesterday ? yesterday[:followers] - today[:followers] : [], friends_added: yesterday ? today[:friends] - yesterday[:friends] : [], friends_removed: yesterday ? yesterday[:friends] - today[:friends] : [] } end content_type :json aggregated.to_json end get '/profile' do param :user_id, Integer, required: true content_type :json profile = settings.mongo_db[:profiles].find( {'user_id' => params[:user_id]} ).projection({'_id' => false}).first.to_json end
require 'json' require 'logger' require 'socket' require './light' require './project' module BuildOrb DEBUG = false PORT = 0 NAME = 1 PROJECTS = 2 OFFICE_HOURS = 6..17 LOGGER = Logger.new(STDOUT) def main() # address:port for receiving updates address = "0.0.0.0" port = ARGV[PORT] ? ARGV[PORT] : 4712 LOGGER.debug("port is #{port}") # name of the light to control light_label = ARGV[NAME] ? ARGV[NAME] : "BBEBB" light = get_light(light_label, debug: DEBUG) LOGGER.debug("light is #{light}") projects_file_name = ARGV[PROJECTS] ? ARGV[PROJECTS] : "projects.json" projects = Projects.new(JSON.parse(File.read(projects_file_name))) LOGGER.debug("projects are #{projects}") socket = TCPServer.new(address, port) LOGGER.info("Listen to socket for messages...") loop do power_light_only_during_office_hours(light, Time.now, OFFICE_HOURS) readable, _, _ = IO.select([socket], [socket], nil, 600) if readable != nil LOGGER.debug("Receiving message...") msg = read_message(socket.accept) LOGGER.debug("Received: #{msg}") msg = JSON.parse(msg) project = projects[msg["name"]] status = msg["build"]["status"] if project && status project.actual_status = Status[status] end end status = projects.status LOGGER.info("the combined status of all projects is \"#{status.name}\".") light.set_color(status.color, duration: 0.2) end end def power_light_only_during_office_hours(light, time, office_hours) is_off_time = time.saturday? || time.sunday? || !office_hours.cover?(time.hour) if light.on? && is_off_time LOGGER.info("Office hours are over, turn off the light.") light.turn_off! end if light.off? && !is_off_time LOGGER.info("Time to work, turn on the lights.") light.turn_on! end end def read_message(connection) msg = "" while line = connection.gets msg << line end connection.close return msg end end include BuildOrb BuildOrb::main Update office hours require 'json' require 'logger' require 'socket' require './light' require './project' module BuildOrb DEBUG = false PORT = 0 NAME = 1 PROJECTS = 2 OFFICE_HOURS = 6..16 LOGGER = Logger.new(STDOUT) def main() # address:port for receiving updates address = "0.0.0.0" port = ARGV[PORT] ? ARGV[PORT] : 4712 LOGGER.debug("port is #{port}") # name of the light to control light_label = ARGV[NAME] ? ARGV[NAME] : "BBEBB" light = get_light(light_label, debug: DEBUG) LOGGER.debug("light is #{light}") projects_file_name = ARGV[PROJECTS] ? ARGV[PROJECTS] : "projects.json" projects = Projects.new(JSON.parse(File.read(projects_file_name))) LOGGER.debug("projects are #{projects}") socket = TCPServer.new(address, port) LOGGER.info("Listen to socket for messages...") loop do power_light_only_during_office_hours(light, Time.now, OFFICE_HOURS) readable, _, _ = IO.select([socket], [socket], nil, 600) if readable != nil LOGGER.debug("Receiving message...") msg = read_message(socket.accept) LOGGER.debug("Received: #{msg}") msg = JSON.parse(msg) project = projects[msg["name"]] status = msg["build"]["status"] if project && status project.actual_status = Status[status] end end status = projects.status LOGGER.info("the combined status of all projects is \"#{status.name}\".") light.set_color(status.color, duration: 0.2) end end def power_light_only_during_office_hours(light, time, office_hours) is_off_time = time.saturday? || time.sunday? || !office_hours.cover?(time.hour) if light.on? && is_off_time LOGGER.info("Office hours are over, turn off the light.") light.turn_off! end if light.off? && !is_off_time LOGGER.info("Time to work, turn on the lights.") light.turn_on! end end def read_message(connection) msg = "" while line = connection.gets msg << line end connection.close return msg end end include BuildOrb BuildOrb::main
#!/usr/bin/env ruby require 'sinatra' puts "Starting server..." require 'hallon' require 'hallon-openal' require 'json' configure do set :logged_in, false set :session, Hallon::Session.initialize(IO.read('./spotify_appkey.key')) set :player, Hallon::Player.new(Hallon::OpenAL) set :status, {:playing => false, :text => ""} Thread.new do while true do sleep 1 settings.session.process_events end end settings.session.on(:end_of_track) do settings.status[:playing] = false settings.status[:text] = "" end end post '/login' do begin if settings.logged_in == true r = "Already logged in!" puts r else puts "Connecting and logging in..." request.body.rewind request_body = JSON.parse(request.body.read) settings.session.login!(request_body["username"], request_body["password"]) settings.logged_in = true r = "Successfully logged in!" puts r end rescue r = "Login error!" puts r end r end post '/logout' do begin if settings.logged_in == true puts "Logging out..." settings.player.stop settings.session.logout settings.logged_in = false settings.status[:text] = "" settings.status[:playing] = false r = "Successfully logged out!" puts r else puts "No one logged in!" r = "No one logged in!" puts r end rescue puts "Logout error!" r = "Logout error!" puts r end r end get '/' do "This is the root" end get '/status' do r = JSON.generate(settings.status) puts r r end post '/play' do begin if settings.logged_in == true if request.body.length > 0 request.body.rewind request_body = JSON.parse(request.body.read) track = Hallon::Track.new(request_body["song"]).load if track r = "#{track.name} by #{track.artist.name}" settings.status[:text] = r settings.status[:playing] = true puts r else r = "No song found..." settings.status[:text] = "" settings.status[:playing] = false puts r end settings.player.stop settings.player.play(track) else settings.player.play settings.status[:playing] = true r = settings.status[:text] puts r end else r = "No one logged in!" puts r end rescue r = "Error playing song..." puts r end r end post '/pause' do begin if settings.logged_in == true settings.player.pause r = "Pausing #{settings.status[:text]}" settings.status[:playing] = false puts r else r = "No one logged in!" puts r end rescue r = "Error pausing song..." puts r end r end puts "Server started..." server file formatting changes #!/usr/bin/env ruby require 'sinatra' require 'hallon' require 'hallon-openal' require 'json' puts "Starting server..." configure do set :logged_in, false set :session, Hallon::Session.initialize(IO.read('./spotify_appkey.key')) set :player, Hallon::Player.new(Hallon::OpenAL) set :status, {:playing => false, :text => ""} Thread.new do while true do sleep 1 settings.session.process_events end end settings.session.on(:end_of_track) do settings.status[:playing] = false settings.status[:text] = "" end end post '/login' do begin if settings.logged_in == true r = "Already logged in!" puts r else puts "Connecting and logging in..." request.body.rewind request_body = JSON.parse(request.body.read) settings.session.login!(request_body["username"], request_body["password"]) settings.logged_in = true r = "Successfully logged in!" puts r end rescue r = "Login error!" puts r end r end post '/logout' do begin if settings.logged_in == true puts "Logging out..." settings.player.stop settings.session.logout settings.logged_in = false settings.status[:text] = "" settings.status[:playing] = false r = "Successfully logged out!" puts r else puts "No one logged in!" r = "No one logged in!" puts r end rescue puts "Logout error!" r = "Logout error!" puts r end r end get '/' do "This is the root" end get '/status' do r = JSON.generate(settings.status) puts r r end post '/play' do begin if settings.logged_in == true if request.body.length > 0 request.body.rewind request_body = JSON.parse(request.body.read) track = Hallon::Track.new(request_body["song"]).load if track r = "#{track.name} by #{track.artist.name}" settings.status[:text] = r settings.status[:playing] = true puts r else r = "No song found..." settings.status[:text] = "" settings.status[:playing] = false puts r end settings.player.stop settings.player.play(track) else settings.player.play settings.status[:playing] = true r = settings.status[:text] puts r end else r = "No one logged in!" puts r end rescue r = "Error playing song..." puts r end r end post '/pause' do begin if settings.logged_in == true settings.player.pause r = "Pausing #{settings.status[:text]}" settings.status[:playing] = false puts r else r = "No one logged in!" puts r end rescue r = "Error pausing song..." puts r end r end puts "Server started..."
require "sinatra" require "json" set :public_folder, 'public' get '/' do redirect '/index.html' end get "/kelvin-to-celsius/:name" do (params[:name].to_f - 272.15).round(2).to_s #{ "kelvin" => params[:name].to_f.round(2).to_s , "celsius" => (params[:name].to_f - 272.15).round(2).to_s }.to_json end get "/celsius-to-kelvin/:name" do #(params["name"].to_f + 272.15).round(2).to_s {"celsius" => params[:name].to_f.round(2).to_s , "kelvin" => (params["name"].to_f + 272.15).round(2).to_s}.to_json end get "/celsius-to-fahrenheit/:name" do #(((params["name"].to_i * 9) / 5) + 32).round(2).to_s {"celsius" => params[:name].to_f.round(2).to_s , "fahrenheit" => (((params["name"].to_i * 9) / 5) + 32).round(2).to_s }.to_json end get "/fahrenheit-to-celsius/:name" do #(((params["name"].to_f - 32 ) * 5) / 9).round(2).to_s {"fahrenheit" => params[:name].to_f.round(2).to_s , "celsius" => (((params["name"].to_f - 32 ) * 5) / 9).round(2).to_s }.to_json end get "/kelvin-to-fahrenheit/:name" do #(((params["name"].to_f * 9) / 5) - 459.67).round(2).to_s {"kelvin" => params[:name].to_f.round(2).to_s , "fahrenheit" => (((params["name"].to_f * 9) / 5) - 459.67).round(2).to_s }.to_json end get "/fahrenheit-to-kelvin/:name" do #(((params["name"].to_f + 459.67) * 5) / 9).round(2).to_s {"fahrenheit" => params[:name].to_f.round(2).to_s , "kelvin" => (((params["name"].to_f + 459.67) * 5) / 9).round(2).to_s }.to_json end using routing for changing differnt formats require "sinatra" require "json" require "nokogiri" set :public_folder, 'public' get '/' do redirect '/index.html' end get "/kelvin-to-celsius/:name/?:format?" do unless params[:format] (params[:name].to_f - 272.15).round(2).to_s else if params[:format] == "json" { "from_kelvin" => params[:name].to_f.round(2).to_s , "to_celsius" => (params[:name].to_f - 272.15).round(2).to_s }.to_json else params[:format] == "xml" output = { "from_kelvin" => params[:name].to_f.round(2).to_s , "to_celsius" => (params[:name].to_f - 272.15).round(2).to_s } builder = Nokogiri::XML::Builder.new do |xml| xml.response do xml.from_kelvin output["from_kelvin"] xml.to_celsius output["to_celsius"] end end content_type "text/xml" builder.to_xml.to_s end end end get "/celsius-to-kelvin/:name/?:format?" do unless params[:format] (params["name"].to_f + 272.15).round(2).to_s else if params[:format] == "json" {"from_celsius" => params[:name].to_f.round(2).to_s , "to_kelvin" => (params["name"].to_f + 272.15).round(2).to_s}.to_json elsif params[:format] == "xml" output = { "from_celsius" => params[:name].to_f.round(2).to_s , "to_kelvin" => (params["name"].to_f + 272.15).round(2).to_s } builder = Nokogiri::XML::Builder.new do |xml| xml.response do xml.from_celsius output["from_celsius"] xml.to_kelvin output["to_kelvin"] end end content_type "text/xml" builder.to_xml.to_s end end end get "/celsius-to-fahrenheit/:name/?:format?" do unless params[:format] (((params["name"].to_i * 9) / 5) + 32).round(2).to_s else if params[:format] == "json" {"form_celsius" => params[:name].to_f.round(2).to_s , "to_fahrenheit" => (((params["name"].to_i * 9) / 5) + 32).round(2).to_s }.to_json elsif params[:format] == "xml" output = {"from_celsius" => params[:name].to_f.round(2).to_s , "to_fahrenheit" => (((params["name"].to_i * 9) / 5) + 32).round(2).to_s } builder = Nokogiri::XML::Builder.new do |xml| xml.response do xml.from_celsius output["from_celsius"] xml.to_fahrenheit output["to_fahrenheit"] end end content_type "text/xml" builder.to_xml.to_s end end end get "/fahrenheit-to-celsius/:name/?:format?" do unless params[:format] (((params["name"].to_f - 32 ) * 5) / 9).round(2).to_s else if params[:format] == "json" {"from_fahrenheit" => params[:name].to_f.round(2).to_s , "to_celsius" => (((params["name"].to_f - 32 ) * 5) / 9).round(2).to_s }.to_json elsif params[:format] == "xml" output = {"from_fahrenheit" => params[:name].to_f.round(2).to_s , "to_celsius" => (((params["name"].to_f - 32 ) * 5) / 9).round(2).to_s } builder = Nokogiri::XML::Builder.new do |xml| xml.response do xml.from_fahrenheit output["from_fahrenheit"] xml.to_celsius output["to_celsius"] end end content_type "text/xml" builder.to_xml.to_s end end end get "/kelvin-to-fahrenheit/:name/?:format?" do unless params[:format] (((params["name"].to_f * 9) / 5) - 459.67).round(2).to_s else if params[:format] == "json" {"from_kelvin" => params[:name].to_f.round(2).to_s , "to_fahrenheit" => (((params["name"].to_f * 9) / 5) - 459.67).round(2).to_s }.to_json elsif params[:format] == "xml" output = {"from_kelvin" => params[:name].to_f.round(2).to_s , "to_fahrenheit" => (((params["name"].to_f * 9) / 5) - 459.67).round(2).to_s } builder = Nokogiri::XML::Builder.new do |xml| xml.response do xml.from_kelvin output["from_kelvin"] xml.to_fahrenheit output["to_fahrenheit"] end end content_type "text/xml" builder.to_xml.to_s end end end get "/fahrenheit-to-kelvin/:name/?:format?" do unless params[:format] (((params["name"].to_f + 459.67) * 5) / 9).round(2).to_s else if params[:format] == "json" {"from_fahrenheit" => params[:name].to_f.round(2).to_s , "to_kelvin" => (((params["name"].to_f + 459.67) * 5) / 9).round(2).to_s }.to_json elsif params[:format] == "xml" output = {"from_fahrenheit" => params[:name].to_f.round(2).to_s , "to_kelvin" => (((params["name"].to_f + 459.67) * 5) / 9).round(2).to_s } builder = Nokogiri::XML::Builder.new do |xml| xml.response do xml.from_fahrenheit output["from_fahrenheit"] xml.to_kelvin output["to_kelvin"] end end content_type "text/xml" builder.to_xml.to_s end end end
# coding: utf-8 require 'sinatra' require 'json' set server: 'thin', connections: [] set :public_folder, File.dirname(__FILE__) + '/static' messages = [] get '/' do erb :index, :locals => { messages: messages } end post '/message' do settings.connections.each do |sock| sock << "data: #{request.body.read}\n\n" end 201 end get '/stream', provides: 'text/event-stream' do stream :keep_open do |sock| settings.connections << sock sock.callback { settings.connections.delete sock } end end Fixes server bug: req.body.read can only be called once # coding: utf-8 require 'sinatra' require 'json' set server: 'thin', connections: [] set :public_folder, File.dirname(__FILE__) + '/static' messages = [] get '/' do erb :index, :locals => { messages: messages } end post '/message' do text = request.body.read settings.connections.each do |sock| sock << "data: #{text}\n\n" end 201 end get '/stream', provides: 'text/event-stream' do stream :keep_open do |sock| settings.connections << sock sock.callback { settings.connections.delete sock } end end
require "test/test_helper" class Admin::CategoriesControllerTest < ActionController::TestCase setup do @request.session[:typus_user_id] = typus_users(:admin).id @first_category = Factory(:category, :position => 1) @second_category = Factory(:category, :position => 2) end should "verify referer" do @request.env['HTTP_REFERER'] = '/admin/categories' get :position, { :id => @first_category.id, :go => 'move_lower' } assert_response :redirect assert_redirected_to @request.env['HTTP_REFERER'] end should "position item one step down" do get :position, { :id => @first_category.id, :go => 'move_lower' } assert_equal "Record moved lower.", flash[:notice] assert_equal 2, @first_category.reload.position assert_equal 1, @second_category.reload.position end should "position item one step up" do get :position, { :id => @second_category.id, :go => 'move_higher' } assert_equal "Record moved higher.", flash[:notice] assert_equal 2, @first_category.reload.position assert_equal 1, @second_category.reload.position end should "position top item to bottom" do get :position, { :id => @first_category.id, :go => 'move_to_bottom' } assert_equal "Record moved to bottom.", flash[:notice] assert_equal 2, @first_category.reload.position end should "position bottom item to top" do get :position, { :id => @second_category.id, :go => 'move_to_top' } assert_equal "Record moved to top.", flash[:notice] assert_equal 1, @second_category.reload.position end end Gardening require "test/test_helper" class Admin::CategoriesControllerTest < ActionController::TestCase setup do @request.session[:typus_user_id] = typus_users(:admin).id @request.env['HTTP_REFERER'] = '/admin/categories' @first_category = Factory(:category, :position => 1) @second_category = Factory(:category, :position => 2) end should "verify referer" do get :position, { :id => @first_category.id, :go => 'move_lower' } assert_response :redirect assert_redirected_to @request.env['HTTP_REFERER'] end should "position item one step down" do get :position, { :id => @first_category.id, :go => 'move_lower' } assert_equal "Record moved lower.", flash[:notice] assert_equal 2, @first_category.reload.position assert_equal 1, @second_category.reload.position end should "position item one step up" do get :position, { :id => @second_category.id, :go => 'move_higher' } assert_equal "Record moved higher.", flash[:notice] assert_equal 2, @first_category.reload.position assert_equal 1, @second_category.reload.position end should "position top item to bottom" do get :position, { :id => @first_category.id, :go => 'move_to_bottom' } assert_equal "Record moved to bottom.", flash[:notice] assert_equal 2, @first_category.reload.position end should "position bottom item to top" do get :position, { :id => @second_category.id, :go => 'move_to_top' } assert_equal "Record moved to top.", flash[:notice] assert_equal 1, @second_category.reload.position end end
SAFETY_FILE = "config/code_safety.yml" # Temporarily override to only audit external access files SAFETY_REPO = "https://deepthought/svn/extra/era/external-access" require 'yaml' # Force yaml output from hashes to be ordered # e.g. so that file diffs are consistent # TODO: Instead declare ordered version of YAML.dump or use OrderedHash def order_to_yaml_output! if RUBY_VERSION =~ /^1\.8/ eval <<-EOT class Hash # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys) # See http://snippets.dzone.com/posts/show/5811 # # Original function is in /usr/lib/ruby/1.8/yaml/rubytypes.rb def to_yaml( opts = {} ) YAML::quick_emit( object_id, opts ) do |out| out.map( taguri, to_yaml_style ) do |map| sort.each do |k, v| # <-- here's my addition (the 'sort') map.add( k, v ) end end end end end EOT elsif RUBY_VERSION =~ /\A1\.9/ puts "Warning: Hash output will not be sorted." unless YAML::ENGINE.syck? eval <<-EOT class Hash # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys) # See http://snippets.dzone.com/posts/show/5811 # # Original function is in /usr/lib/ruby/1.9.1/syck/rubytypes.rb def to_yaml( opts = {} ) return super unless YAML::ENGINE.syck? YAML::quick_emit( self, opts ) do |out| out.map( taguri, to_yaml_style ) do |map| sort.each do |k, v| # <-- here's my addition (the 'sort') #each do |k, v| map.add( k, v ) end end end end end EOT end end # Run a PL/SQL based password cracker on the main database to identify weak # passwords. # Parameter max_print is number of entries to print before truncating output # (negative value => print all) def audit_code_safety(max_print = 20, ignore_new = false, show_diffs = false, user_name = 'usr') puts <<EOT Running source code safety audit script. This currently takes about 3 minutes to run. We seem to have issues with Apache on deepthought rate limiting svn requests. EOT max_print = 1000000 if max_print < 0 safety_cfg = YAML.load_file(SAFETY_FILE) file_safety = safety_cfg["file safety"] if file_safety.nil? safety_cfg["file safety"] = file_safety = {} end orig_count = file_safety.size if defined? SAFETY_REPO # Temporarily override to only audit a different file list repo = SAFETY_REPO else repo = %x[svn info].split("\n").select{|x| x =~ /^URL: /}.collect{|x| x[5..-1]} end if ignore_new puts "Not checking for new files in #{repo}" else puts "Checking for new files in #{repo}" new_files = %x[svn ls -R "#{repo}"].split("\n") # Ignore subdirectories new_files.delete_if{|f| f =~ /[\/\\]$/} new_files.each{|f| unless file_safety.has_key?(f) file_safety[f] = { "comments" => nil, "reviewed_by" => nil, "safe_revision" => nil } end } File.open(SAFETY_FILE, 'w') do |file| order_to_yaml_output! YAML.dump(safety_cfg, file) # Save changes before checking latest revisions end end puts "Checking latest revisions" update_changed_rev(file_safety) puts "\nSummary:" puts "Number of files originally in #{SAFETY_FILE}: #{orig_count}" puts "Number of new files added: #{file_safety.size - orig_count}" # Now generate statistics: unknown = file_safety.values.select{|x| x["safe_revision"].nil?} unsafe = file_safety.values.select{|x| !x["safe_revision"].nil? && x["safe_revision"] != -1 && x["last_changed_rev"] > x['safe_revision'] } puts "Number of files with no safe version: #{unknown.size}" puts "Number of files which are no longer safe: #{unsafe.size}" puts printed = [] # We also print a third category: ones which are no longer in the repository file_safety.keys.sort.each{|f| if print_file_safety(file_safety, f, false, printed.size >= max_print) printed << f end } puts "... and #{printed.size - max_print} others" if printed.size > max_print if show_diffs puts printed.each{|f| print_file_diffs(file_safety, f, user_name) } end end # Print summary details of a file's known safety # If not verbose, only prints details for unsafe files # Returns true if anything printed (or would have been printed if silent), # or false otherwise. def print_file_safety(file_safety, fname, verbose = false, silent = false) msg = "#{fname}\n " entry = file_safety[fname] if entry.nil? msg += "File not in audit list" elsif entry["safe_revision"].nil? msg += "No safe revision known" else if entry["last_changed_rev"].nil? update_changed_rev(file_safety, [fname]) end svnlatest = entry["last_changed_rev"] # May have been prepopulated en mass if entry["last_changed_rev"] == -1 msg += "Not in svn repository: " elsif svnlatest > entry['safe_revision'] msg += "No longer safe since revision #{svnlatest}: " else return false unless verbose msg += "Safe: " end msg += "revision #{entry['safe_revision']} reviewed by #{entry['reviewed_by']}" end msg += "\n Comments: #{entry['comments']}" if entry['comments'] puts msg unless silent return true end # Print file diffs, for code review def print_file_diffs(file_safety, fname, user_name) entry = file_safety[fname] if entry.nil? # File not in audit list elsif entry["safe_revision"].nil? puts "No safe revision for #{fname}" rev = %x[svn info -r head "#{fname}"].match('Last Changed Rev: ([0-9]*)').to_a[1] if rev mime_type = %x[svn propget svn:mime-type "#{fname}"].chomp if ['application/octet-stream'].include?(mime_type) puts "Cannot display: file marked as a binary type." puts "svn:mime-type = #{mime_type}" else fdata = %x[svn cat -r "#{rev}" "#{fname}"] # TODO: Add header information like svn puts fdata.split("\n").collect{|line| "+ #{line}"} end puts "To flag the changes to this file as safe, run:" else puts "Please code review a recent working copy, note the revision number, and run:" rev = '[revision]' end puts %( rake audit:safe release=#{rev} file=#{fname} reviewed_by=#{user_name} comments="") puts else if entry["last_changed_rev"].nil? update_changed_rev(file_safety, [fname]) end svnlatest = entry["last_changed_rev"] # May have been prepopulated en mass if entry["last_changed_rev"] == -1 # Not in svn repository elsif svnlatest > entry['safe_revision'] cmd = "svn diff -r #{entry['safe_revision']}:#{svnlatest} -x-b #{fname}" puts cmd system(cmd) puts %(To flag the changes to this file as safe, run:) puts %( rake audit:safe release=#{svnlatest} file=#{fname} reviewed_by=#{user_name} comments="") puts else # Safe end end end # Fill in the latest changed revisions in a file safety map. # (Don't write this data to the YAML file, as it is intrinsic to the SVN # repository.) def update_changed_rev(file_safety, fnames = nil) fnames = file_safety.keys if fnames.nil? # TODO: Use svn info --xml instead # TODO: Is it possible to get %x[] syntax to accept variable arguments? #all_info = %x[svn info -r HEAD "#{fnames.join(' ')}"] repo = %x[svn info].split("\n").select{|x| x =~ /^URL: /}.collect{|x| x[5..-1]} # Filename becomes too long, and extra arguments get ignored #all_info = Kernel.send("`", "svn info -r HEAD #{fnames.sort.join(' ')}").split("\n\n") # Note: I'd like to be able to use svn -u status -v instead of svn info, # but it seems to refer only to the local working copy... f2 = fnames.sort # Sorted copy is safe to change all_info = [] while f2 && !f2.empty? blocksize = 10 extra_info = svn_info_entries(f2.first(blocksize)) #if extra_info.size != [blocksize, f2.size].min # puts "Mismatch (got #{extra_info.size}, expected #{[blocksize, f2.size].min})" #end all_info += extra_info f2 = f2[blocksize..-1] end fnames.each{|f| #puts "Checking for URL: #{repo}/#{f}" #puts all_info[0].inspect info = all_info.find{|x| x.include?("URL: #{repo}/#{f}")} if info info = info.split("\n") else #puts "Unknown: #{f}" end #info = %x[svn info -r HEAD "#{f}"].split("\n") if info.nil? || info.empty? # svn writes to stderr: "svn: '#{f}' has no URL", or # "#{f}: (Not a versioned resource)" file_safety[f]["last_changed_rev"] = -1 # Flag as non-existent else file_safety[f]["last_changed_rev"] = info. select{|x| x =~ /^Last Changed Rev: /}.collect{|x| x[18..-1]}[0].to_i end } end # Returns a list of svn info entries, given a list of filenames. # Automatically retries (by default) if multiple filenames are given, and fewer # entries are returned than expected. # debug argument: 0 => silent (even for errors), 1 => only print errors, # 2 => print commands + errors def svn_info_entries(fnames, retries = true, debug = 0) puts "svn info -r HEAD #{fnames.join(' ')}" if debug >= 2 return [] if fnames.empty? # Silence if retries and debug=1, as we'll get repeats when we retry silencer = (debug == 2 || (debug == 1 && !retries)) ? "" : (RUBY_PLATFORM =~ /mswin32|mingw32/ ? " 2>nul " : " 2>/dev/null ") result = Kernel.send("`", "svn info -r HEAD #{fnames.join(' ')}#{silencer}").split("\n\n") if retries && result.size != fnames.size && fnames.size > 1 # At least one invalid (deleted file --> subsequent arguments ignored) # Try each file individually # (It would probably be safe to continue from the extra_info.size argument) puts "Retrying (got #{result.size}, expected #{fnames.size})" if debug >= 2 result = [] fnames.each{ |f| result += svn_info_entries([f], false, debug) } end result end def flag_file_as_safe(release, reviewed_by, comments, f) safety_cfg = YAML.load_file(SAFETY_FILE) file_safety = safety_cfg["file safety"] unless File.exist?(f) abort("Error: Unable to flag non-existent file as safe: #{f}") end unless file_safety.has_key?(f) file_safety[f] = { "comments" => nil, "reviewed_by" => :dummy, # dummy value, will be overwritten "safe_revision" => nil } end entry = file_safety[f] entry_orig = entry.dup if comments.present? && entry["comments"] != comments entry["comments"] = if entry["comments"].blank? comments else "#{entry["comments"]}#{'.' unless entry["comments"].end_with?('.')} Revision #{release}: #{comments}" end end if entry["safe_revision"] unless release abort("Error: File already has safe revision #{entry["safe_revision"]}: #{f}") end if release < entry["safe_revision"] puts("Warning: Rolling back safe revision from #{entry['safe_revision']} to #{release} for #{f}") end end entry["safe_revision"] = release entry["reviewed_by"] = reviewed_by if entry == entry_orig puts "No changes when updating safe_revision to #{release || '[none]'} for #{f}" else File.open(SAFETY_FILE, 'w') do |file| order_to_yaml_output! YAML.dump(safety_cfg, file) # Save changes before checking latest revisions end puts "Updated safe_revision to #{release || '[none]'} for #{f}" end end namespace :audit do desc "Audit safety of source code. Usage: audit:code [max_print=n] [ignore_new=false|true] [show_diffs=false|true] [reviewed_by=usr] File #{SAFETY_FILE} lists the safety and revision information of the era source code. This task updates the list, and [TODO] warns about files which have changed since they were last verified as safe." task(:code) do puts "Usage: audit:code [max_print=n] [ignore_new=false|true] [show_diffs=false|true] [reviewed_by=usr]" ignore_new = (ENV['ignore_new'].to_s =~ /\Afalse\Z/i) show_diffs = (ENV['show_diffs'].to_s =~ /\Atrue\Z/i) if ENV['max_print'] =~ /\A-?[0-9][0-9]*\Z/ audit_code_safety(ENV['max_print'].to_i, ignore_new, show_diffs, ENV['reviewed_by']) else audit_code_safety(20, ignore_new, show_diffs, ENV['reviewed_by']) end unless show_diffs puts "To show file diffs, run: rake audit:code max_print=-1 show_diffs=true" end end desc "Flag a source file as safe. Usage: Flag as safe: rake audit:safe release=revision reviewed_by=usr [comments=...] file=f Needs review: rake audit:safe release=0 [comments=...] file=f" task (:safe) do required_fields = ["release", "file"] required_fields << "reviewed_by" unless ENV['release'] == '0' missing = required_fields.collect{|f| (f if ENV[f].blank? || (f=='reviewed_by' && ENV[f] == 'usr'))}.compact # Avoid accidental missing username if !missing.empty? puts "Usage: rake audit:safe release=revision reviewed_by=usr [comments=...] file=f" puts "or, to flag a file for review: rake audit:safe release=0 [comments=...] file=f" abort("Error: Missing required argument(s): #{missing.join(', ')}") end unless ENV['release'] =~ /\A[0-9][0-9]*\Z/ puts "Usage: rake audit:safe release=revision reviewed_by=usr [comments=...] file=f" puts "or, to flag a file for review: rake audit:safe release=0 [comments=...] file=f" abort("Error: Invalid release: #{ENV['release']}") end release = ENV['release'].to_i release = nil if release == 0 flag_file_as_safe(release, ENV['reviewed_by'], ENV['comments'], ENV['file']) end end # Partial fix of the audit_code rake task to work outside the era project. git-svn-id: 1e0ca63757b8e1a827491254fbf099512871e806@2609 153ec483-9fa4-4787-9925-b21d4235b228 SAFETY_FILE = if defined?(Rails) Rails.root.join('config', 'code_safety.yml') else 'code_safety.yml' end # Temporarily override to only audit external access files SAFETY_REPO = "https://deepthought/svn/extra/era/external-access" require 'yaml' # Force yaml output from hashes to be ordered # e.g. so that file diffs are consistent # TODO: Instead declare ordered version of YAML.dump or use OrderedHash def order_to_yaml_output! if RUBY_VERSION =~ /^1\.8/ eval <<-EOT class Hash # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys) # See http://snippets.dzone.com/posts/show/5811 # # Original function is in /usr/lib/ruby/1.8/yaml/rubytypes.rb def to_yaml( opts = {} ) YAML::quick_emit( object_id, opts ) do |out| out.map( taguri, to_yaml_style ) do |map| sort.each do |k, v| # <-- here's my addition (the 'sort') map.add( k, v ) end end end end end EOT elsif RUBY_VERSION =~ /\A1\.9/ puts "Warning: Hash output will not be sorted." unless YAML::ENGINE.syck? eval <<-EOT class Hash # Replacing the to_yaml function so it'll serialize hashes sorted (by their keys) # See http://snippets.dzone.com/posts/show/5811 # # Original function is in /usr/lib/ruby/1.9.1/syck/rubytypes.rb def to_yaml( opts = {} ) return super unless YAML::ENGINE.syck? YAML::quick_emit( self, opts ) do |out| out.map( taguri, to_yaml_style ) do |map| sort.each do |k, v| # <-- here's my addition (the 'sort') #each do |k, v| map.add( k, v ) end end end end end EOT end end # Run a PL/SQL based password cracker on the main database to identify weak # passwords. # Parameter max_print is number of entries to print before truncating output # (negative value => print all) def audit_code_safety(max_print = 20, ignore_new = false, show_diffs = false, user_name = 'usr') puts <<EOT Running source code safety audit script. This currently takes about 3 minutes to run. We seem to have issues with Apache on deepthought rate limiting svn requests. EOT max_print = 1000000 if max_print < 0 safety_cfg = YAML.load_file(SAFETY_FILE) file_safety = safety_cfg["file safety"] if file_safety.nil? safety_cfg["file safety"] = file_safety = {} end orig_count = file_safety.size if defined? SAFETY_REPO # Temporarily override to only audit a different file list repo = SAFETY_REPO else repo = %x[svn info].split("\n").select{|x| x =~ /^URL: /}.collect{|x| x[5..-1]} end if ignore_new puts "Not checking for new files in #{repo}" else puts "Checking for new files in #{repo}" new_files = %x[svn ls -R "#{repo}"].split("\n") # Ignore subdirectories new_files.delete_if{|f| f =~ /[\/\\]$/} new_files.each{|f| unless file_safety.has_key?(f) file_safety[f] = { "comments" => nil, "reviewed_by" => nil, "safe_revision" => nil } end } File.open(SAFETY_FILE, 'w') do |file| order_to_yaml_output! YAML.dump(safety_cfg, file) # Save changes before checking latest revisions end end puts "Checking latest revisions" update_changed_rev(file_safety) puts "\nSummary:" puts "Number of files originally in #{SAFETY_FILE}: #{orig_count}" puts "Number of new files added: #{file_safety.size - orig_count}" # Now generate statistics: unknown = file_safety.values.select{|x| x["safe_revision"].nil?} unsafe = file_safety.values.select{|x| !x["safe_revision"].nil? && x["safe_revision"] != -1 && x["last_changed_rev"] > x['safe_revision'] } puts "Number of files with no safe version: #{unknown.size}" puts "Number of files which are no longer safe: #{unsafe.size}" puts printed = [] # We also print a third category: ones which are no longer in the repository file_safety.keys.sort.each{|f| if print_file_safety(file_safety, f, false, printed.size >= max_print) printed << f end } puts "... and #{printed.size - max_print} others" if printed.size > max_print if show_diffs puts printed.each{|f| print_file_diffs(file_safety, f, user_name) } end end # Print summary details of a file's known safety # If not verbose, only prints details for unsafe files # Returns true if anything printed (or would have been printed if silent), # or false otherwise. def print_file_safety(file_safety, fname, verbose = false, silent = false) msg = "#{fname}\n " entry = file_safety[fname] if entry.nil? msg += "File not in audit list" elsif entry["safe_revision"].nil? msg += "No safe revision known" else if entry["last_changed_rev"].nil? update_changed_rev(file_safety, [fname]) end svnlatest = entry["last_changed_rev"] # May have been prepopulated en mass if entry["last_changed_rev"] == -1 msg += "Not in svn repository: " elsif svnlatest > entry['safe_revision'] msg += "No longer safe since revision #{svnlatest}: " else return false unless verbose msg += "Safe: " end msg += "revision #{entry['safe_revision']} reviewed by #{entry['reviewed_by']}" end msg += "\n Comments: #{entry['comments']}" if entry['comments'] puts msg unless silent return true end # Print file diffs, for code review def print_file_diffs(file_safety, fname, user_name) entry = file_safety[fname] if entry.nil? # File not in audit list elsif entry["safe_revision"].nil? puts "No safe revision for #{fname}" rev = %x[svn info -r head "#{fname}"].match('Last Changed Rev: ([0-9]*)').to_a[1] if rev mime_type = %x[svn propget svn:mime-type "#{fname}"].chomp if ['application/octet-stream'].include?(mime_type) puts "Cannot display: file marked as a binary type." puts "svn:mime-type = #{mime_type}" else fdata = %x[svn cat -r "#{rev}" "#{fname}"] # TODO: Add header information like svn puts fdata.split("\n").collect{|line| "+ #{line}"} end puts "To flag the changes to this file as safe, run:" else puts "Please code review a recent working copy, note the revision number, and run:" rev = '[revision]' end puts %( rake audit:safe release=#{rev} file=#{fname} reviewed_by=#{user_name} comments="") puts else if entry["last_changed_rev"].nil? update_changed_rev(file_safety, [fname]) end svnlatest = entry["last_changed_rev"] # May have been prepopulated en mass if entry["last_changed_rev"] == -1 # Not in svn repository elsif svnlatest > entry['safe_revision'] cmd = "svn diff -r #{entry['safe_revision']}:#{svnlatest} -x-b #{fname}" puts cmd system(cmd) puts %(To flag the changes to this file as safe, run:) puts %( rake audit:safe release=#{svnlatest} file=#{fname} reviewed_by=#{user_name} comments="") puts else # Safe end end end # Fill in the latest changed revisions in a file safety map. # (Don't write this data to the YAML file, as it is intrinsic to the SVN # repository.) def update_changed_rev(file_safety, fnames = nil) fnames = file_safety.keys if fnames.nil? # TODO: Use svn info --xml instead # TODO: Is it possible to get %x[] syntax to accept variable arguments? #all_info = %x[svn info -r HEAD "#{fnames.join(' ')}"] repo = %x[svn info].split("\n").select{|x| x =~ /^URL: /}.collect{|x| x[5..-1]} # Filename becomes too long, and extra arguments get ignored #all_info = Kernel.send("`", "svn info -r HEAD #{fnames.sort.join(' ')}").split("\n\n") # Note: I'd like to be able to use svn -u status -v instead of svn info, # but it seems to refer only to the local working copy... f2 = fnames.sort # Sorted copy is safe to change all_info = [] while f2 && !f2.empty? blocksize = 10 extra_info = svn_info_entries(f2.first(blocksize)) #if extra_info.size != [blocksize, f2.size].min # puts "Mismatch (got #{extra_info.size}, expected #{[blocksize, f2.size].min})" #end all_info += extra_info f2 = f2[blocksize..-1] end fnames.each{|f| #puts "Checking for URL: #{repo}/#{f}" #puts all_info[0].inspect info = all_info.find{|x| x.include?("URL: #{repo}/#{f}")} if info info = info.split("\n") else #puts "Unknown: #{f}" end #info = %x[svn info -r HEAD "#{f}"].split("\n") if info.nil? || info.empty? # svn writes to stderr: "svn: '#{f}' has no URL", or # "#{f}: (Not a versioned resource)" file_safety[f]["last_changed_rev"] = -1 # Flag as non-existent else file_safety[f]["last_changed_rev"] = info. select{|x| x =~ /^Last Changed Rev: /}.collect{|x| x[18..-1]}[0].to_i end } end # Returns a list of svn info entries, given a list of filenames. # Automatically retries (by default) if multiple filenames are given, and fewer # entries are returned than expected. # debug argument: 0 => silent (even for errors), 1 => only print errors, # 2 => print commands + errors def svn_info_entries(fnames, retries = true, debug = 0) puts "svn info -r HEAD #{fnames.join(' ')}" if debug >= 2 return [] if fnames.empty? # Silence if retries and debug=1, as we'll get repeats when we retry silencer = (debug == 2 || (debug == 1 && !retries)) ? "" : (RUBY_PLATFORM =~ /mswin32|mingw32/ ? " 2>nul " : " 2>/dev/null ") result = Kernel.send("`", "svn info -r HEAD #{fnames.join(' ')}#{silencer}").split("\n\n") if retries && result.size != fnames.size && fnames.size > 1 # At least one invalid (deleted file --> subsequent arguments ignored) # Try each file individually # (It would probably be safe to continue from the extra_info.size argument) puts "Retrying (got #{result.size}, expected #{fnames.size})" if debug >= 2 result = [] fnames.each{ |f| result += svn_info_entries([f], false, debug) } end result end def flag_file_as_safe(release, reviewed_by, comments, f) safety_cfg = YAML.load_file(SAFETY_FILE) file_safety = safety_cfg["file safety"] unless File.exist?(f) abort("Error: Unable to flag non-existent file as safe: #{f}") end unless file_safety.has_key?(f) file_safety[f] = { "comments" => nil, "reviewed_by" => :dummy, # dummy value, will be overwritten "safe_revision" => nil } end entry = file_safety[f] entry_orig = entry.dup if comments.present? && entry["comments"] != comments entry["comments"] = if entry["comments"].blank? comments else "#{entry["comments"]}#{'.' unless entry["comments"].end_with?('.')} Revision #{release}: #{comments}" end end if entry["safe_revision"] unless release abort("Error: File already has safe revision #{entry["safe_revision"]}: #{f}") end if release < entry["safe_revision"] puts("Warning: Rolling back safe revision from #{entry['safe_revision']} to #{release} for #{f}") end end entry["safe_revision"] = release entry["reviewed_by"] = reviewed_by if entry == entry_orig puts "No changes when updating safe_revision to #{release || '[none]'} for #{f}" else File.open(SAFETY_FILE, 'w') do |file| order_to_yaml_output! YAML.dump(safety_cfg, file) # Save changes before checking latest revisions end puts "Updated safe_revision to #{release || '[none]'} for #{f}" end end namespace :audit do desc "Audit safety of source code. Usage: audit:code [max_print=n] [ignore_new=false|true] [show_diffs=false|true] [reviewed_by=usr] File #{SAFETY_FILE} lists the safety and revision information of the era source code. This task updates the list, and [TODO] warns about files which have changed since they were last verified as safe." task(:code) do puts "Usage: audit:code [max_print=n] [ignore_new=false|true] [show_diffs=false|true] [reviewed_by=usr]" ignore_new = (ENV['ignore_new'].to_s =~ /\Afalse\Z/i) show_diffs = (ENV['show_diffs'].to_s =~ /\Atrue\Z/i) if ENV['max_print'] =~ /\A-?[0-9][0-9]*\Z/ audit_code_safety(ENV['max_print'].to_i, ignore_new, show_diffs, ENV['reviewed_by']) else audit_code_safety(20, ignore_new, show_diffs, ENV['reviewed_by']) end unless show_diffs puts "To show file diffs, run: rake audit:code max_print=-1 show_diffs=true" end end desc "Flag a source file as safe. Usage: Flag as safe: rake audit:safe release=revision reviewed_by=usr [comments=...] file=f Needs review: rake audit:safe release=0 [comments=...] file=f" task (:safe) do required_fields = ["release", "file"] required_fields << "reviewed_by" unless ENV['release'] == '0' missing = required_fields.collect{|f| (f if ENV[f].blank? || (f=='reviewed_by' && ENV[f] == 'usr'))}.compact # Avoid accidental missing username if !missing.empty? puts "Usage: rake audit:safe release=revision reviewed_by=usr [comments=...] file=f" puts "or, to flag a file for review: rake audit:safe release=0 [comments=...] file=f" abort("Error: Missing required argument(s): #{missing.join(', ')}") end unless ENV['release'] =~ /\A[0-9][0-9]*\Z/ puts "Usage: rake audit:safe release=revision reviewed_by=usr [comments=...] file=f" puts "or, to flag a file for review: rake audit:safe release=0 [comments=...] file=f" abort("Error: Invalid release: #{ENV['release']}") end release = ENV['release'].to_i release = nil if release == 0 flag_file_as_safe(release, ENV['reviewed_by'], ENV['comments'], ENV['file']) end end
module Heroku::Deploy::Task class PrepareProductionBranch < Base include Heroku::Deploy::Shell def before_deploy @previous_branch = git "rev-parse --abbrev-ref HEAD" # If HEAD is returned, it means we're on a random commit, instead # of a branch. if @previous_branch == "HEAD" @previous_branch = git "rev-parse --verify HEAD" end # Always fetch first. The repo may have already been created. # Also, unshallow the repo with the crazy --depth thing. See # http://permalink.gmane.org/gmane.comp.version-control.git/213186 task "Fetching from #{colorize "origin", :cyan}" git "fetch origin --depth=2147483647 -v", :exec => true task "Switching to #{colorize strategy.branch, :cyan}" do branches = git "branch" if branches.match /#{strategy.branch}$/ git "checkout #{strategy.branch}" else git "checkout -b #{strategy.branch}" end # Always hard reset to whats on origin before merging master # in. When we create the branch - we may not have the latest commits. # This ensures that we do. git "reset origin/#{strategy.branch} --hard" end task "Merging your current branch #{colorize @previous_branch, :cyan} into #{colorize strategy.branch, :cyan}" do git "merge #{strategy.new_commit}" end end def after_deploy switch_back_to_old_branch end def rollback_before_deploy switch_back_to_old_branch end private def switch_back_to_old_branch task "Switching back to #{colorize @previous_branch, :cyan}" do git "checkout #{@previous_branch}" end end end end Remove the shallow file to force an un-shallowing. module Heroku::Deploy::Task class PrepareProductionBranch < Base include Heroku::Deploy::Shell def before_deploy @previous_branch = git "rev-parse --abbrev-ref HEAD" # If HEAD is returned, it means we're on a random commit, instead # of a branch. if @previous_branch == "HEAD" @previous_branch = git "rev-parse --verify HEAD" end # Always fetch first. The repo may have already been created. # Also, unshallow the repo with the crazy --depth thing. See # http://permalink.gmane.org/gmane.comp.version-control.git/213186 task "Fetching from #{colorize "origin", :cyan}" git "(test -e .git/shallow) && rm .git/shallow" git "fetch origin --depth=2147483647 -v", :exec => true task "Switching to #{colorize strategy.branch, :cyan}" do branches = git "branch" if branches.match /#{strategy.branch}$/ git "checkout #{strategy.branch}" else git "checkout -b #{strategy.branch}" end # Always hard reset to whats on origin before merging master # in. When we create the branch - we may not have the latest commits. # This ensures that we do. git "reset origin/#{strategy.branch} --hard" end task "Merging your current branch #{colorize @previous_branch, :cyan} into #{colorize strategy.branch, :cyan}" do git "merge #{strategy.new_commit}" end end def after_deploy switch_back_to_old_branch end def rollback_before_deploy switch_back_to_old_branch end private def switch_back_to_old_branch task "Switching back to #{colorize @previous_branch, :cyan}" do git "checkout #{@previous_branch}" end end end end
module Hydrant::Workflow::WorkflowControllerBehavior def inject_workflow_steps logger.debug "<< Injecting the workflow into the view >>" @workflow_steps = HYDRANT_STEPS end end Added edit and update methods to controller behavior module Hydrant::Workflow::WorkflowControllerBehavior def inject_workflow_steps logger.debug "<< Injecting the workflow into the view >>" @workflow_steps = HYDRANT_STEPS end def edit logger.debug "<< EDIT >>" logger.info "<< Retrieving #{params[:id]} from Fedora >>" model_object = self.instance_variable_set("@#{controller_name.classify.downcase}", ActiveFedora::Base.find(params[:id], cast: true)) @active_step = params[:step] || model_object.workflow.last_completed_step.first @active_step = HYDRANT_STEPS.first.step if @active_step.blank? logger.debug "<< active_step: #{@active_step} >>" prev_step = HYDRANT_STEPS.previous(@active_step) context = params.merge!({controller_name.classify.downcase.to_sym => model_object}) context = HYDRANT_STEPS.get_step(@active_step).before_step context #copy everything out of context and into instance variables context.each {|k,v| self.instance_variable_set("@#{k}", v)} custom_edit #yield to custom_edit in the controller unless prev_step.nil? || model_object.workflow.completed?(prev_step.step) redirect_to edit_polymorphic_path(model_object) return end end def custom_edit end def update logger.debug "<< UPDATE >>" logger.info "<< Updating the media object (including a PBCore datastream) >>" model_object = self.instance_variable_set("@#{controller_name.classify.downcase}", ActiveFedora::Base.find(params[:id], cast: true)) @active_step = params[:step] || model_object.workflow.last_completed_step.first @active_step = HYDRANT_STEPS.first.step if @active_step.blank? logger.debug "<< active_step: #{@active_step} >>" prev_step = HYDRANT_STEPS.previous(@active_step) context = params.merge!({controller_name.classify.downcase.to_sym => model_object, user: user_key}) context = HYDRANT_STEPS.get_step(@active_step).execute context #copy everything out of context and into instance variables context.each {|k,v| self.instance_variable_set("@#{k}", v)} custom_update #yield to custom_update in the controller unless model_object.errors.empty? report_errors model_object else unless params[:donot_advance] == "true" model_object.workflow.update_status(@active_step) model_object.save(validate: false) if HYDRANT_STEPS.has_next?(@active_step) @active_step = HYDRANT_STEPS.next(@active_step).step elsif model_object.workflow.published? @active_step = "published" end end logger.debug "<< ACTIVE STEP => #{@active_step} >>" logger.debug "<< INGEST STATUS => #{model_object.workflow.inspect} >>" respond_to do |format| format.html { (model_object.workflow.published? and model_object.workflow.current?(@active_step)) ? redirect_to(polymorphic_path(model_object)) : redirect_to(get_redirect_path(@active_step, model_object)) } format.json { render :json => nil } end end end def custom_update end protected def get_redirect_path(target, model_object) unless HYDRANT_STEPS.last?(params[:step]) redirect_path = edit_polymorphic_path(model_object, step: target) else flash[:notice] = "This resource is now available for use in the system" redirect_path = polymorphic_path(model_object) end redirect_path end def report_errors(model_object) logger.debug "<< Errors found -> #{model_object.errors} >>" logger.debug "<< #{model_object.errors.size} >>" flash[:error] = "There are errors with your submission. Please correct them before continuing." #XXX is this next line supposed to be HYDRANT_STEPS.first.step or active_step or what?!? step = params[:step] || HYDRANT_STEPS.first.template render :edit and return end end
module Paperclip module Shoulda module Matchers def have_attached_file name HaveAttachedFileMatcher.new(name) end class HaveAttachedFileMatcher def initialize attachment_name @attachment_name = attachment_name end def matches? subject @subject = subject responds? && has_column? && included? end def failure_message "Should have an attachment named #{@attachment_name}" end def negative_failure_message "Should not have an attachment named #{@attachment_name}" end def description "have an attachment named #{@attachment_name}" end protected def responds? methods = @subject.instance_methods methods.include?("#{@attachment_name}") && methods.include?("#{@attachment_name}=") && methods.include?("#{@attachment_name}?") end def has_column? @subject.column_names.include?("#{@attachment_name}_file_name") end def included? @subject.ancestors.include?(Paperclip::InstanceMethods) end end end end end Mapping instance_methods to strings since 1.9 returns symbols module Paperclip module Shoulda module Matchers def have_attached_file name HaveAttachedFileMatcher.new(name) end class HaveAttachedFileMatcher def initialize attachment_name @attachment_name = attachment_name end def matches? subject @subject = subject responds? && has_column? && included? end def failure_message "Should have an attachment named #{@attachment_name}" end def negative_failure_message "Should not have an attachment named #{@attachment_name}" end def description "have an attachment named #{@attachment_name}" end protected def responds? methods = @subject.instance_methods.map(&:to_s) methods.include?("#{@attachment_name}") && methods.include?("#{@attachment_name}=") && methods.include?("#{@attachment_name}?") end def has_column? @subject.column_names.include?("#{@attachment_name}_file_name") end def included? @subject.ancestors.include?(Paperclip::InstanceMethods) end end end end end
require 'typhoeus' require_relative "../interface_topology_provider.rb" require_relative "../../network_entities/topology.rb" require_relative '../../network_entities/abstracts/path.rb' class OpendaylightTopologyProvider < ITopologyProvider attr_accessor :uri_resource def initialize(new_uri_resource) raise ArgumentError, 'No uri recieved as parameter' unless new_uri_resource @uri_resource = new_uri_resource @topology = Topology.new end =begin This is who it looks like the xml received by the opendaylight api <topology> <topology-id>flow:1</topology-id> <node> <node-id>openflow:1</node-id> <inventory-node-ref>/a:nodes/a:node[a:id='openflow:1']</inventory-node-ref> <termination-point> <tp-id>openflow:1:2</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:2']</inventory-node-connector-ref> </termination-point> <termination-point> <tp-id>openflow:1:1</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:1']</inventory-node-connector-ref> </termination-point> <termination-point> <tp-id>openflow:1:LOCAL</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:LOCAL']</inventory-node-connector-ref> </termination-point> </node> <node> <node-id>host:52:57:c6:e4:b3:33</node-id> <id>52:57:c6:e4:b3:33</id> <addresses> <id>1</id> <mac>52:57:c6:e4:b3:33</mac> <ip>10.0.0.2</ip> <first-seen>1480973744947</first-seen> <last-seen>1480973744947</last-seen> </addresses> <attachment-points> <tp-id>openflow:2:2</tp-id> <active>true</active> <corresponding-tp>host:52:57:c6:e4:b3:33</corresponding-tp> </attachment-points> <termination-point> <tp-id>host:52:57:c6:e4:b3:33</tp-id> </termination-point> </node> <link> <link-id>openflow:1:2</link-id> <source> <source-node>openflow:1</source-node> <source-tp>openflow:1:2</source-tp> </source> <destination> <dest-node>openflow:2</dest-node> <dest-tp>openflow:2:1</dest-tp> </destination> </link> <link> <link-id>host:5e:66:e6:c2:d0:02/openflow:3:1</link-id> <source> <source-node>host:5e:66:e6:c2:d0:02</source-node> <source-tp>host:5e:66:e6:c2:d0:02</source-tp> </source> <destination> <dest-node>openflow:3</dest-node> <dest-tp>openflow:3:1</dest-tp> </destination> </link> </topology> =end def get_topology response = Typhoeus.get "http://localhost:8080/restconf/operational/network-topology:network-topology/topology/flow:1/", userpwd:"admin:admin" topology_json_response = (JSON.parse response.body)['topology'].first nodes_info = topology_json_response['node'] links_info = topology_json_response['link'] nodes_info.each do |node| if node['node-id'].include? 'openflow' @topology.add_router node['node-id'] else @topology.add_host node['node-id'], node['ip'], node['mac'] end end links_info.each do |link| source = @topology.get_element_by_id link['source']['source-node'] destiny = @topology.get_element_by_id link['destination']['dest-node'] #TODO: WHICH IS THE FORM OF FIND THE PORT OF THE HOST? source_port = (source.is_a? Host) ? 1 : (link['source']['source-tp'].gsub "#{source.id}:", '').to_i destiny_port = (destiny.is_a? Host) ? 1 : (link['destination']['dest-tp'].gsub "#{destiny.id}:", '').to_i @topology.add_link link['link-id'], source, source_port, destiny, destiny_port end @topology.topology_elements end def get_port_from_to(source, destiny) source_info = nodes_info.select{ |node| node['node-id'] == source.id }.first destiny_info = nodes_info.select{ |node| node['node-id'] == destiny.id }.first byebug if source.is_a? host source_info else source_info['termination-point'].select{ |termination_point| termination_point } end end def get_path_between(source, destination) raise NotImplementedError, "OpenDayLight provider: This method is not implemented!" end end implementing opendaylight support. TODO: Check how to get ports connected in hosts require 'typhoeus' require_relative "../interface_topology_provider.rb" require_relative "../../network_entities/topology.rb" require_relative '../../network_entities/abstracts/path.rb' class OpendaylightTopologyProvider < ITopologyProvider attr_accessor :uri_resource def initialize(new_uri_resource) raise ArgumentError, 'No uri recieved as parameter' unless new_uri_resource @uri_resource = new_uri_resource @topology = Topology.new end =begin This is who it looks like the xml received by the opendaylight api <topology> <topology-id>flow:1</topology-id> <node> <node-id>openflow:1</node-id> <inventory-node-ref>/a:nodes/a:node[a:id='openflow:1']</inventory-node-ref> <termination-point> <tp-id>openflow:1:2</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:2']</inventory-node-connector-ref> </termination-point> <termination-point> <tp-id>openflow:1:1</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:1']</inventory-node-connector-ref> </termination-point> <termination-point> <tp-id>openflow:1:LOCAL</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:LOCAL']</inventory-node-connector-ref> </termination-point> </node> <node> <node-id>host:52:57:c6:e4:b3:33</node-id> <id>52:57:c6:e4:b3:33</id> <addresses> <id>1</id> <mac>52:57:c6:e4:b3:33</mac> <ip>10.0.0.2</ip> <first-seen>1480973744947</first-seen> <last-seen>1480973744947</last-seen> </addresses> <attachment-points> <tp-id>openflow:2:2</tp-id> <active>true</active> <corresponding-tp>host:52:57:c6:e4:b3:33</corresponding-tp> </attachment-points> <termination-point> <tp-id>host:52:57:c6:e4:b3:33</tp-id> </termination-point> </node> <link> <link-id>openflow:1:2</link-id> <source> <source-node>openflow:1</source-node> <source-tp>openflow:1:2</source-tp> </source> <destination> <dest-node>openflow:2</dest-node> <dest-tp>openflow:2:1</dest-tp> </destination> </link> <link> <link-id>host:5e:66:e6:c2:d0:02/openflow:3:1</link-id> <source> <source-node>host:5e:66:e6:c2:d0:02</source-node> <source-tp>host:5e:66:e6:c2:d0:02</source-tp> </source> <destination> <dest-node>openflow:3</dest-node> <dest-tp>openflow:3:1</dest-tp> </destination> </link> </topology> =end def get_topology response = Typhoeus.get "http://localhost:8080/restconf/operational/network-topology:network-topology/topology/flow:1/", userpwd:"admin:admin" topology_json_response = (JSON.parse response.body)['topology'].first nodes_info = topology_json_response['node'] links_info = topology_json_response['link'] nodes_info.each do |node| if node['node-id'].include? 'openflow' @topology.add_router node['node-id'] else @topology.add_host node['node-id'], node['ip'], node['mac'] end end links_info.each do |link| source = @topology.get_element_by_id link['source']['source-node'] destiny = @topology.get_element_by_id link['destination']['dest-node'] #TODO: WHICH IS THE FORM OF FINDING THE PORT OF THE HOST? source_port = (source.is_a? Host) ? 1 : (link['source']['source-tp'].gsub "#{source.id}:", '').to_i destiny_port = (destiny.is_a? Host) ? 1 : (link['destination']['dest-tp'].gsub "#{destiny.id}:", '').to_i @topology.add_link link['link-id'], source, source_port, destiny, destiny_port end @topology.topology_elements end def get_path_between(source, destination) raise NotImplementedError, "OpenDayLight provider: This method is not implemented!" end end
require 'fluent-logger' require "rack/access/capture/collector/abstract_adapter" module Rack module Access module Capture module Collector class FluentdAdapter < AbstractAdapter attr_reader :tag def initialize(options = {}) config = options || {} @tag = config["tag"] || 'development' tag_prefix = config["tag_prefix"] host = config["host"] || 'localhost' port = config["port"] || 24224 handler = proc { |messages| BufferOverflowHandler.new(config["log_file_path"]).flush(messages) } buffer_limit = config["buffer_limit"] || 131072 # Buffer limit of the standard is 128.kilobyte log_reconnect_error_threshold = config["log_reconnect_error_threshold"] || Fluent::Logger::FluentLogger::RECONNECT_WAIT_MAX_COUNT options = { host: host, port: port, buffer_limit: buffer_limit, buffer_overflow_handler: handler, log_reconnect_error_threshold: log_reconnect_error_threshold } @logger = config["logger"] || Fluent::Logger::FluentLogger.new(tag_prefix, options) exclude_request = config["exclude_request"] || [] @collect = [GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, LINK, UNLINK, TRACE] - exclude_request end def collect?(env) @collect.include?(env["REQUEST_METHOD"]) end def collect(log) @logger.post(@tag, log) end end class BufferOverflowHandler def initialize(log_directory_path) @log_directory_path = log_directory_path end def flush(messages) return if @log_directory_path.nil? MessagePack::Unpacker.new.feed_each(messages) do |msg| open("#{@log_directory_path}/#{msg[0]}_#{msg[1]}.json", 'w') do |io| JSON.dump(msg[2], io) end end end end end end end end add exclude user-agent function require 'fluent-logger' require "rack/access/capture/collector/abstract_adapter" module Rack module Access module Capture module Collector class FluentdAdapter < AbstractAdapter attr_reader :tag def initialize(options = {}) config = options || {} @tag = config["tag"] || 'development' tag_prefix = config["tag_prefix"] host = config["host"] || 'localhost' port = config["port"] || 24224 handler = proc { |messages| BufferOverflowHandler.new(config["log_file_path"]).flush(messages) } buffer_limit = config["buffer_limit"] || 131072 # Buffer limit of the standard is 128.kilobyte log_reconnect_error_threshold = config["log_reconnect_error_threshold"] || Fluent::Logger::FluentLogger::RECONNECT_WAIT_MAX_COUNT options = { host: host, port: port, buffer_limit: buffer_limit, buffer_overflow_handler: handler, log_reconnect_error_threshold: log_reconnect_error_threshold } @logger = config["logger"] || Fluent::Logger::FluentLogger.new(tag_prefix, options) exclude_request = config["exclude_request"] || [] @collect = [GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, LINK, UNLINK, TRACE] - exclude_request @exclude_ua_list = config["exclude_user_agents"] || [] end def collect?(env) !@exclude_ua_list.include?(env["HTTP_USER_AGENT"]) && @collect.include?(env["REQUEST_METHOD"]) end def collect(log) @logger.post(@tag, log) end end class BufferOverflowHandler def initialize(log_directory_path) @log_directory_path = log_directory_path end def flush(messages) return if @log_directory_path.nil? MessagePack::Unpacker.new.feed_each(messages) do |msg| open("#{@log_directory_path}/#{msg[0]}_#{msg[1]}.json", 'w') do |io| JSON.dump(msg[2], io) end end end end end end end end
Added script to generate element inventory of folio xml files. =begin Extracts the inventory of element names/types/classes and instance counts for a set of Folio per tape xml files * iterate over all xml files * parse each one * walk the entire dom tree, extract name/type/class attrs for each element, count instances * output as csv Use like so: require 'repositext/folio/folio_per_tape_xml_inventory' i = Repositext::Folio::FolioPerTapeXmlInventory.new i.extract i.to_csv =end require 'nokogiri' class Repositext class Folio class FolioPerTapeXmlInventory attr_accessor :inventory def initialize # path to folder that contains xml files, relative to this file's location @file_pattern = File.expand_path("../../../../../vgr-english/converted_folio/*.xml", __FILE__) @inventory = {} @file_count = 0 end def extract Dir.glob(@file_pattern).find_all { |e| e =~ /\.xml$/}.each do |xml_file_name| puts xml_file_name @file_count += 1 xml = File.read(xml_file_name) doc = Nokogiri::XML.parse(xml) { |cfg| cfg.noblanks } extract_data_from_node(doc.root) end nil end def to_csv puts "Extracted node inventory from #{ @file_count } XML files at #{ @file_pattern }" puts puts %w[name type class level instance_count].map { |e| e.capitalize }.join("\t") @inventory.each do |k,v| r = k r << v[:instance_count] puts r.join("\t") end nil end protected def extract_data_from_node(node) k = [node.name, node['type'], node['class'], node['level']] h = (@inventory[k] ||= { :instance_count => 0 }) h[:instance_count] += 1 node.children.each { |child_node| extract_data_from_node(child_node) } end end end end
module Resque module Plugins module ConcurrentRestriction VERSION = "0.5.9" end end end Bump version to 0.6.0 module Resque module Plugins module ConcurrentRestriction VERSION = "0.6.0" end end end
RSpec::Support.require_rspec_core "formatters/base_text_formatter" RSpec::Support.require_rspec_core "formatters/console_codes" module RSpec module Core module Formatters # @private class DocumentationFormatter < BaseTextFormatter Formatters.register self, :example_started, :example_group_started, :example_group_finished, :example_passed, :example_pending, :example_failed def initialize(output) super @group_level = 0 @example_running = false @messages = [] end def example_started(_notification) @example_running = true end def example_group_started(notification) output.puts if @group_level == 0 output.puts "#{current_indentation}#{notification.group.description.strip}" @group_level += 1 end def example_group_finished(_notification) @group_level -= 1 if @group_level > 0 end def example_passed(passed) output.puts passed_output(passed.example) flush_messages @example_running = false end def example_pending(pending) output.puts pending_output(pending.example, pending.example.execution_result.pending_message) flush_messages @example_running = false end def example_failed(failure) output.puts failure_output(failure.example) flush_messages @example_running = false end def message(notification) if @example_running @messages << notification.message else output.puts "#{current_indentation}#{notification.message}" end end private def flush_messages if @messages.any? @messages.each do |message| output.puts "#{current_indentation(1)}#{message}" end @messages.clear end end def passed_output(example) ConsoleCodes.wrap("#{current_indentation}#{example.description.strip}", :success) end def pending_output(example, message) ConsoleCodes.wrap("#{current_indentation}#{example.description.strip} " \ "(PENDING: #{message})", :pending) end def failure_output(example) ConsoleCodes.wrap("#{current_indentation}#{example.description.strip} " \ "(FAILED - #{next_failure_index})", :failure) end def next_failure_index @next_failure_index ||= 0 @next_failure_index += 1 end def current_indentation(offset=0) ' ' * (@group_level + offset) end end end end end Remove conditional around flushing messages. RSpec::Support.require_rspec_core "formatters/base_text_formatter" RSpec::Support.require_rspec_core "formatters/console_codes" module RSpec module Core module Formatters # @private class DocumentationFormatter < BaseTextFormatter Formatters.register self, :example_started, :example_group_started, :example_group_finished, :example_passed, :example_pending, :example_failed def initialize(output) super @group_level = 0 @example_running = false @messages = [] end def example_started(_notification) @example_running = true end def example_group_started(notification) output.puts if @group_level == 0 output.puts "#{current_indentation}#{notification.group.description.strip}" @group_level += 1 end def example_group_finished(_notification) @group_level -= 1 if @group_level > 0 end def example_passed(passed) output.puts passed_output(passed.example) flush_messages @example_running = false end def example_pending(pending) output.puts pending_output(pending.example, pending.example.execution_result.pending_message) flush_messages @example_running = false end def example_failed(failure) output.puts failure_output(failure.example) flush_messages @example_running = false end def message(notification) if @example_running @messages << notification.message else output.puts "#{current_indentation}#{notification.message}" end end private def flush_messages @messages.each do |message| output.puts "#{current_indentation(1)}#{message}" end @messages.clear end def passed_output(example) ConsoleCodes.wrap("#{current_indentation}#{example.description.strip}", :success) end def pending_output(example, message) ConsoleCodes.wrap("#{current_indentation}#{example.description.strip} " \ "(PENDING: #{message})", :pending) end def failure_output(example) ConsoleCodes.wrap("#{current_indentation}#{example.description.strip} " \ "(FAILED - #{next_failure_index})", :failure) end def next_failure_index @next_failure_index ||= 0 @next_failure_index += 1 end def current_indentation(offset=0) ' ' * (@group_level + offset) end end end end end
module Sorcery module Controller module Submodules # This submodule integrates HTTP Basic authentication into sorcery. # You are provided with a before filter, require_login_from_http_basic, # which requests the browser for authentication. # Then the rest of the submodule takes care of logging the user in # into the session, so that the next requests will keep him logged in. module HttpBasicAuth def self.included(base) base.send(:include, InstanceMethods) Config.module_eval do class << self attr_accessor :controller_to_realm_map # What realm to display for which controller name. def merge_http_basic_auth_defaults! @defaults.merge!(:@controller_to_realm_map => {"application" => "Application"}) end end merge_http_basic_auth_defaults! end Config.login_sources << :login_from_basic_auth end module InstanceMethods protected # to be used as a before_filter. # The method sets a session when requesting the user's credentials. # This is a trick to overcome the way HTTP authentication works (explained below): # # Once the user fills the credentials once, the browser will always send it to the # server when visiting the website, until the browser is closed. # This causes wierd behaviour if the user logs out. The session is reset, yet the # user is re-logged in by the before_filter calling 'login_from_basic_auth'. # To overcome this, we set a session when requesting the password, which logout will # reset, and that's how we know if we need to request for HTTP auth again. def require_login_from_http_basic (request_http_basic_authentication(realm_name_by_controller) and (session[:http_authentication_used] = true) and return) if (request.authorization.nil? || session[:http_authentication_used].nil?) require_login session[:http_authentication_used] = nil unless logged_in? end # given to main controller module as a login source callback def login_from_basic_auth authenticate_with_http_basic do |username, password| @current_user = (user_class.authenticate(username, password) if session[:http_authentication_used]) || false auto_login(@current_user) if @current_user @current_user end end # Sets the realm name by searching the controller name in the hash given at configuration time. def realm_name_by_controller if defined?(ActionController::Base) current_controller = self.class while current_controller != ActionController::Base result = Config.controller_to_realm_map[current_controller.controller_name] return result if result current_controller = self.class.superclass end nil else Config.controller_to_realm_map["application"] end end end end end end end Bugfix: Infinite Loop in http basic auth If the current controller couldn't be found in the Config.controller_to_realm_map and the controller didn't inherit from ActionController::Base,  #realm_name_by_controller would enter an infinite loop. This commit makes the loop actually go through the controller's ancestors, where it will eventually reach ActionController::Base module Sorcery module Controller module Submodules # This submodule integrates HTTP Basic authentication into sorcery. # You are provided with a before filter, require_login_from_http_basic, # which requests the browser for authentication. # Then the rest of the submodule takes care of logging the user in # into the session, so that the next requests will keep him logged in. module HttpBasicAuth def self.included(base) base.send(:include, InstanceMethods) Config.module_eval do class << self attr_accessor :controller_to_realm_map # What realm to display for which controller name. def merge_http_basic_auth_defaults! @defaults.merge!(:@controller_to_realm_map => {"application" => "Application"}) end end merge_http_basic_auth_defaults! end Config.login_sources << :login_from_basic_auth end module InstanceMethods protected # to be used as a before_filter. # The method sets a session when requesting the user's credentials. # This is a trick to overcome the way HTTP authentication works (explained below): # # Once the user fills the credentials once, the browser will always send it to the # server when visiting the website, until the browser is closed. # This causes wierd behaviour if the user logs out. The session is reset, yet the # user is re-logged in by the before_filter calling 'login_from_basic_auth'. # To overcome this, we set a session when requesting the password, which logout will # reset, and that's how we know if we need to request for HTTP auth again. def require_login_from_http_basic (request_http_basic_authentication(realm_name_by_controller) and (session[:http_authentication_used] = true) and return) if (request.authorization.nil? || session[:http_authentication_used].nil?) require_login session[:http_authentication_used] = nil unless logged_in? end # given to main controller module as a login source callback def login_from_basic_auth authenticate_with_http_basic do |username, password| @current_user = (user_class.authenticate(username, password) if session[:http_authentication_used]) || false auto_login(@current_user) if @current_user @current_user end end # Sets the realm name by searching the controller name in the hash given at configuration time. def realm_name_by_controller if defined?(ActionController::Base) current_controller = self.class while current_controller != ActionController::Base result = Config.controller_to_realm_map[current_controller.controller_name] return result if result current_controller = current_controller.superclass end nil else Config.controller_to_realm_map["application"] end end end end end end end
module SvgOptimizer module Plugins class RemoveEditorNamespace < Base NAMESPACES = %w[ http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd http://www.inkscape.org/namespaces/inkscape http://ns.adobe.com/AdobeIllustrator/10.0/ http://ns.adobe.com/Graphs/1.0/ http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/ http://ns.adobe.com/Variables/1.0/ http://ns.adobe.com/SaveForWeb/1.0/ http://ns.adobe.com/Extensibility/1.0/ http://ns.adobe.com/Flows/1.0/ http://ns.adobe.com/ImageReplacement/1.0/ http://ns.adobe.com/GenericCustomNamespace/1.0/ http://ns.adobe.com/XPath/1.0 ] def process namespaces = xml.namespaces xml.remove_namespaces! namespaces.each do |name, value| next if NAMESPACES.include?(value) _, name = name.split(":") xml.root.add_namespace name, value end end end end end Add Sketch namespace. module SvgOptimizer module Plugins class RemoveEditorNamespace < Base NAMESPACES = %w[ http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd http://www.inkscape.org/namespaces/inkscape http://ns.adobe.com/AdobeIllustrator/10.0/ http://ns.adobe.com/Graphs/1.0/ http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/ http://ns.adobe.com/Variables/1.0/ http://ns.adobe.com/SaveForWeb/1.0/ http://ns.adobe.com/Extensibility/1.0/ http://ns.adobe.com/Flows/1.0/ http://ns.adobe.com/ImageReplacement/1.0/ http://ns.adobe.com/GenericCustomNamespace/1.0/ http://ns.adobe.com/XPath/1.0 http://www.bohemiancoding.com/sketch/ns ] def process namespaces = xml.namespaces xml.remove_namespaces! namespaces.each do |name, value| next if NAMESPACES.include?(value) _, name = name.split(":") xml.root.add_namespace name, value end end end end end
desc 'Rename Chinese overseas territories and assign Taiwan to China' task rename_and_assign_chinese_territories: :environment do Country.find_by(name: 'Hong Kong').update(name: 'Hong Kong, SAR China') Country.find_by(name: 'Macau').update(name: 'Macau, SAR China') china = Country.find_by(name: 'China') taiwan = Country.find_by(name: 'Taiwan, Province of China') taiwan.update(parent: china) end fix: newline at end of file desc 'Rename Chinese overseas territories and assign Taiwan to China' task rename_and_assign_chinese_territories: :environment do Country.find_by(name: 'Hong Kong').update(name: 'Hong Kong, SAR China') Country.find_by(name: 'Macau').update(name: 'Macau, SAR China') china = Country.find_by(name: 'China') taiwan = Country.find_by(name: 'Taiwan, Province of China') taiwan.update(parent: china) end
#!/usr/bin/env ruby =begin tooltips.rb - Demonstrates the new tooltip API of Gtk+ 2.12; rg2 translation from gtk/tests/testtooltips.c. Copyright (c) 2007 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. $Id: tooltips.rb,v 1.1 2007/07/10 13:17:34 ggc Exp $ =end require 'gtk2' if str = Gtk.check_version(2, 11, 0) puts "This sample requires GTK+ 2.11.0 or later" puts str exit end def treeview_query_tooltip(treeview, keyboard_tip, x, y, tooltip) if keyboard_tip # Keyboard mode path, = treeview.cursor if not path return false end else bin_x, bin_y = treeview.convert_widget_to_bin_window_coords(x, y) # Mouse mode path, = treeview.get_path_at_pos(bin_x, bin_y) if not path return false end end data = treeview.model.get_value(treeview.model.get_iter(path), 0) tooltip.markup = "<b>Path #{path}:</b> #{data}" return true end def textview_query_tooltip(textview, keyboard_tip, x, y, tooltip, tag) if keyboard_tip iter = textview.buffer.get_iter_at_offset(textview.buffer.cursor_position) else bx, by = textview.window_to_buffer_coords(Gtk::TextView::WINDOW_TEXT, x, y) iter, = textview.get_iter_at_position(bx, by) end if iter.has_tag?(tag) tooltip.text = 'Tooltip on text tag' return true else return false end end def drawingarea_query_tooltip(keyboard_tip, x, y, tooltip, rectangles) if keyboard_tip return false end for r in rectangles if r.x < x && x < r.x + 50 && r.y < y && y < r.y + 50 tooltip.markup = r.tooltip return true end end return false end Gtk.init window = Gtk::Window.new(Gtk::Window::TOPLEVEL) window.title = 'Tooltips test' window.border_width = 10 window.signal_connect('delete-event') { Gtk.main_quit } box = Gtk::VBox.new(false, 3) window.add(box) # A check button using the tooltip-markup property button = Gtk::CheckButton.new('This one uses the tooltip-markup property') button.tooltip_text = 'Hello, I am a static tooltip.' box.pack_start(button, false, false, 0) raise if button.tooltip_text != 'Hello, I am a static tooltip.' raise if button.tooltip_markup != 'Hello, I am a static tooltip.' # A check button using the query-tooltip signal button = Gtk::CheckButton.new('I use the query-tooltip signal') button.has_tooltip = true button.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| tooltip.markup = widget.label tooltip.set_icon_from_stock(Gtk::Stock::DELETE, Gtk::IconSize::MENU) true } box.pack_start(button, false, false, 0) # A label label = Gtk::Label.new('I am just a label') label.selectable = false label.tooltip_text = 'Label & and tooltip' box.pack_start(label, false, false, 0) raise if label.tooltip_text != "Label & and tooltip" raise if label.tooltip_markup != "Label &amp; and tooltip" # A selectable label label = Gtk::Label.new('I am a selectable label') label.selectable = true label.tooltip_markup = '<b>Another</b> Label tooltip' box.pack_start(label, false, false, 0) raise if label.tooltip_text != 'Another Label tooltip' raise if label.tooltip_markup != '<b>Another</b> Label tooltip' # Another one, with a custom tooltip window button = Gtk::CheckButton.new('This one has a custom tooltip window!') box.pack_start(button, false, false, 0) tooltip_window = Gtk::Window.new(Gtk::Window::POPUP) tooltip_button = Gtk::Label.new('blaat!') tooltip_window.add(tooltip_button) tooltip_button.show button.tooltip_window = tooltip_window button.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| widget.tooltip_window.modify_bg(Gtk::StateType::NORMAL, Gdk::Color.new(0, 65535, 0)) true } button.has_tooltip = true # An insensitive button button = Gtk::Button.new('This one is insensitive') button.sensitive = false button.tooltip_text = 'Insensitive!' box.pack_start(button, false, false, 0) # Tree view store = Gtk::TreeStore.new(String) iter = store.insert(nil, 0, ['File Manager']) iter = store.insert(nil, 0, ['Gossip']) iter = store.insert(nil, 0, ['System Settings']) iter = store.insert(nil, 0, ['The GIMP']) iter = store.insert(nil, 0, ['Terminal']) iter = store.insert(nil, 0, ['Word Processor']) treeview = Gtk::TreeView.new(store) treeview.set_size_request(200, 240) treeview.append_column(Gtk::TreeViewColumn.new('Test', Gtk::CellRendererText.new, { :text => 0 })) treeview.has_tooltip = true treeview.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| treeview_query_tooltip(widget, keyboard_tip, x, y, tooltip) } treeview.selection.signal_connect('changed') { treeview.trigger_tooltip_query } # Set a tooltip on the column column = treeview.get_column(0) column.clickable = true #column.button.tooltip_text = 'Header' .button not available box.pack_start(treeview, false, false, 2) # Text view buffer = Gtk::TextBuffer.new buffer.insert(buffer.end_iter, 'Hello, the text ') tag = buffer.create_tag('bold', { 'weight' => Pango::WEIGHT_BOLD }) buffer.insert(buffer.end_iter, 'in bold', tag) buffer.insert(buffer.end_iter, ' has a tooltip!') textview = Gtk::TextView.new(buffer) textview.set_size_request(200, 50) textview.has_tooltip = true textview.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| textview_query_tooltip(widget, keyboard_tip, x, y, tooltip, tag) } box.pack_start(textview, false, false, 2) # Drawing area if Gdk.cairo_available? Rectangle = Struct.new("Rectangle", :x, :y, :r, :g, :b, :tooltip) rectangles = [ Rectangle.new(10, 10, 0.0, 0.0, 0.9, "Blue box!"), Rectangle.new(200, 170, 1.0, 0.0, 0.0, "Red thing"), Rectangle.new(100, 50, 0.8, 0.8, 0.0, "Yellow thing") ] drawingarea = Gtk::DrawingArea.new drawingarea.set_size_request(320, 240) drawingarea.has_tooltip = true drawingarea.signal_connect('expose_event') { cr = drawingarea.window.create_cairo_context cr.rectangle(0, 0, drawingarea.allocation.width, drawingarea.allocation.height) cr.set_source_rgb(1.0, 1.0, 1.0) cr.fill rectangles.each { |r| cr.rectangle(r.x, r.y, 50, 50) cr.set_source_rgb(r.r, r.g, r.b) cr.stroke cr.rectangle(r.x, r.y, 50, 50) cr.set_source_rgba(r.r, r.g, r.b, 0.5) cr.fill } } drawingarea.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| drawingarea_query_tooltip(keyboard_tip, x, y, tooltip, rectangles) } box.pack_start(drawingarea, false, false, 2) else warn "Part of this sample needs Cairo support. Make sure your ruby-gtk2 is compiled with Cairo support, and rcairo is installed." end window.show_all Gtk.main for orthogonality, here too #!/usr/bin/env ruby =begin tooltips.rb - Demonstrates the new tooltip API of Gtk+ 2.12; rg2 translation from gtk/tests/testtooltips.c. Copyright (c) 2007 Ruby-GNOME2 Project Team This program is licenced under the same licence as Ruby-GNOME2. $Id: tooltips.rb,v 1.1 2007/07/10 13:17:34 ggc Exp $ =end require 'gtk2' if str = Gtk.check_version(2, 12, 0) puts "This sample requires GTK+ 2.12.0 or later" puts str exit end def treeview_query_tooltip(treeview, keyboard_tip, x, y, tooltip) if keyboard_tip # Keyboard mode path, = treeview.cursor if not path return false end else bin_x, bin_y = treeview.convert_widget_to_bin_window_coords(x, y) # Mouse mode path, = treeview.get_path_at_pos(bin_x, bin_y) if not path return false end end data = treeview.model.get_value(treeview.model.get_iter(path), 0) tooltip.markup = "<b>Path #{path}:</b> #{data}" return true end def textview_query_tooltip(textview, keyboard_tip, x, y, tooltip, tag) if keyboard_tip iter = textview.buffer.get_iter_at_offset(textview.buffer.cursor_position) else bx, by = textview.window_to_buffer_coords(Gtk::TextView::WINDOW_TEXT, x, y) iter, = textview.get_iter_at_position(bx, by) end if iter.has_tag?(tag) tooltip.text = 'Tooltip on text tag' return true else return false end end def drawingarea_query_tooltip(keyboard_tip, x, y, tooltip, rectangles) if keyboard_tip return false end for r in rectangles if r.x < x && x < r.x + 50 && r.y < y && y < r.y + 50 tooltip.markup = r.tooltip return true end end return false end Gtk.init window = Gtk::Window.new(Gtk::Window::TOPLEVEL) window.title = 'Tooltips test' window.border_width = 10 window.signal_connect('delete-event') { Gtk.main_quit } box = Gtk::VBox.new(false, 3) window.add(box) # A check button using the tooltip-markup property button = Gtk::CheckButton.new('This one uses the tooltip-markup property') button.tooltip_text = 'Hello, I am a static tooltip.' box.pack_start(button, false, false, 0) raise if button.tooltip_text != 'Hello, I am a static tooltip.' raise if button.tooltip_markup != 'Hello, I am a static tooltip.' # A check button using the query-tooltip signal button = Gtk::CheckButton.new('I use the query-tooltip signal') button.has_tooltip = true button.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| tooltip.markup = widget.label tooltip.set_icon_from_stock(Gtk::Stock::DELETE, Gtk::IconSize::MENU) true } box.pack_start(button, false, false, 0) # A label label = Gtk::Label.new('I am just a label') label.selectable = false label.tooltip_text = 'Label & and tooltip' box.pack_start(label, false, false, 0) raise if label.tooltip_text != "Label & and tooltip" raise if label.tooltip_markup != "Label &amp; and tooltip" # A selectable label label = Gtk::Label.new('I am a selectable label') label.selectable = true label.tooltip_markup = '<b>Another</b> Label tooltip' box.pack_start(label, false, false, 0) raise if label.tooltip_text != 'Another Label tooltip' raise if label.tooltip_markup != '<b>Another</b> Label tooltip' # Another one, with a custom tooltip window button = Gtk::CheckButton.new('This one has a custom tooltip window!') box.pack_start(button, false, false, 0) tooltip_window = Gtk::Window.new(Gtk::Window::POPUP) tooltip_button = Gtk::Label.new('blaat!') tooltip_window.add(tooltip_button) tooltip_button.show button.tooltip_window = tooltip_window button.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| widget.tooltip_window.modify_bg(Gtk::StateType::NORMAL, Gdk::Color.new(0, 65535, 0)) true } button.has_tooltip = true # An insensitive button button = Gtk::Button.new('This one is insensitive') button.sensitive = false button.tooltip_text = 'Insensitive!' box.pack_start(button, false, false, 0) # Tree view store = Gtk::TreeStore.new(String) iter = store.insert(nil, 0, ['File Manager']) iter = store.insert(nil, 0, ['Gossip']) iter = store.insert(nil, 0, ['System Settings']) iter = store.insert(nil, 0, ['The GIMP']) iter = store.insert(nil, 0, ['Terminal']) iter = store.insert(nil, 0, ['Word Processor']) treeview = Gtk::TreeView.new(store) treeview.set_size_request(200, 240) treeview.append_column(Gtk::TreeViewColumn.new('Test', Gtk::CellRendererText.new, { :text => 0 })) treeview.has_tooltip = true treeview.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| treeview_query_tooltip(widget, keyboard_tip, x, y, tooltip) } treeview.selection.signal_connect('changed') { treeview.trigger_tooltip_query } # Set a tooltip on the column column = treeview.get_column(0) column.clickable = true #column.button.tooltip_text = 'Header' .button not available box.pack_start(treeview, false, false, 2) # Text view buffer = Gtk::TextBuffer.new buffer.insert(buffer.end_iter, 'Hello, the text ') tag = buffer.create_tag('bold', { 'weight' => Pango::WEIGHT_BOLD }) buffer.insert(buffer.end_iter, 'in bold', tag) buffer.insert(buffer.end_iter, ' has a tooltip!') textview = Gtk::TextView.new(buffer) textview.set_size_request(200, 50) textview.has_tooltip = true textview.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| textview_query_tooltip(widget, keyboard_tip, x, y, tooltip, tag) } box.pack_start(textview, false, false, 2) # Drawing area if Gdk.cairo_available? Rectangle = Struct.new("Rectangle", :x, :y, :r, :g, :b, :tooltip) rectangles = [ Rectangle.new(10, 10, 0.0, 0.0, 0.9, "Blue box!"), Rectangle.new(200, 170, 1.0, 0.0, 0.0, "Red thing"), Rectangle.new(100, 50, 0.8, 0.8, 0.0, "Yellow thing") ] drawingarea = Gtk::DrawingArea.new drawingarea.set_size_request(320, 240) drawingarea.has_tooltip = true drawingarea.signal_connect('expose_event') { cr = drawingarea.window.create_cairo_context cr.rectangle(0, 0, drawingarea.allocation.width, drawingarea.allocation.height) cr.set_source_rgb(1.0, 1.0, 1.0) cr.fill rectangles.each { |r| cr.rectangle(r.x, r.y, 50, 50) cr.set_source_rgb(r.r, r.g, r.b) cr.stroke cr.rectangle(r.x, r.y, 50, 50) cr.set_source_rgba(r.r, r.g, r.b, 0.5) cr.fill } } drawingarea.signal_connect('query-tooltip') { |widget, x, y, keyboard_tip, tooltip| drawingarea_query_tooltip(keyboard_tip, x, y, tooltip, rectangles) } box.pack_start(drawingarea, false, false, 2) else warn "Part of this sample needs Cairo support. Make sure your ruby-gtk2 is compiled with Cairo support, and rcairo is installed." end window.show_all Gtk.main
# -*- encoding: utf-8 -*- require 'rubygems' unless Object.const_defined?(:Gem) require File.dirname(__FILE__) + "/lib/console_update/version" Gem::Specification.new do |s| s.name = "console_update" s.version = ConsoleUpdate::VERSION s.authors = ["Gabriel Horner"] s.email = "gabriel.horner@gmail.com" s.homepage = "http://tagaholic.me/console_update/" s.summary = "Edit your database records via the console and your favorite editor." s.description = "Updates records from the console via your preferred editor. You can update a record's columns as well as <i>any attribute</i> that has accessor methods. Records are edited via a temporary file and once saved, the records are updated. Records go through a filter before and after editing the file. Yaml is the default filter, but you can define your own filter simply with a module and 2 expected methods. See ConsoleUpdate::Filter for more details. Compatible with all major Ruby versions and Rails 2.3.x and up." s.required_rubygems_version = ">= 1.3.6" s.add_development_dependency 'bacon', '>= 1.1.0' s.add_development_dependency 'mocha' s.add_development_dependency 'mocha-on-bacon' s.add_development_dependency 'bacon-bits' s.add_development_dependency 'activerecord', '~> 2.3.0' s.add_development_dependency 'sqlite3', '~> 1.3.0' s.files = Dir.glob(%w[{lib,test}/**/*.rb bin/* [A-Z]*.{txt,rdoc} ext/**/*.{rb,c} **/deps.rip]) + %w{Rakefile .gemspec .travis.yml} s.files += ['init.rb'] s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"] s.license = 'MIT' end update gemspec # -*- encoding: utf-8 -*- require 'rubygems' unless Object.const_defined?(:Gem) require File.dirname(__FILE__) + "/lib/console_update/version" Gem::Specification.new do |s| s.name = "console_update" s.version = ConsoleUpdate::VERSION s.authors = ["Gabriel Horner"] s.email = "gabriel.horner@gmail.com" s.homepage = "http://tagaholic.me/console_update/" s.summary = "Edit your database records via the console and your favorite editor." s.description = "Updates records from the console via your preferred editor. You can update a record's columns as well as <i>any attribute</i> that has accessor methods. Records are edited via a temporary file and once saved, the records are updated. Records go through a filter before and after editing the file. Yaml is the default filter, but you can define your own filter simply with a module and 2 expected methods. See ConsoleUpdate::Filter for more details. Compatible with all major Ruby versions and Rails 2.3.x and up." s.required_rubygems_version = ">= 1.3.6" s.add_development_dependency 'bacon', '>= 1.1.0' s.add_development_dependency 'mocha' s.add_development_dependency 'mocha-on-bacon' s.add_development_dependency 'bacon-bits' s.add_development_dependency 'activerecord', '~> 2.3.0' s.add_development_dependency 'sqlite3', '~> 1.3.0' s.files = Dir.glob(%w[{lib,test}/**/*.rb bin/* [A-Z]*.{txt,rdoc} ext/**/*.{rb,c} **/deps.rip]) + %w{Rakefile .gemspec .travis.yml} s.files += ['init.rb', '.gitignore', 'Gemfile'] s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"] s.license = 'MIT' end
.gemspec: add a stubby gemspec Gem::Specification.new do |s| s.name = "clayoven" s.version = "0.1" s.summary = "Extremely simple website generator" s.description = "Generates html files from a git repository, where files use a special markup. Email posting supported." s.author = "Ramkumar Ramachandra" s.email = "artagnon@gmail.com" s.files = ["clayoven.rb", "httpd.rb", "imapd.rb"] s.homepage = "https://github.com/artagnon/clayoven" s.license = "MIT" s.require_path = "." s.bindir = "." s.post_install_message = "clayoven installed! Run `clayoven -h` for usage" s.executables << "clayoven" s.add_runtime_dependency 'example', '~> 1.1', '>= 1.1.4' end
#!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'rdf' gem.homepage = 'http://rdf.rubyforge.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'A Ruby library for working with Resource Description Framework (RDF) data.' gem.description = 'RDF.rb is a pure-Ruby library for working with Resource Description Framework (RDF) data.' gem.rubyforge_project = 'rdf' gem.authors = ['Arto Bendiken', 'Ben Lavender'] gem.email = 'arto.bendiken@gmail.com' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION) + Dir.glob('bin/rdf*') + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(rdf rdf-count rdf-lengths rdf-objects rdf-predicates rdf-subjects) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_development_dependency 'rspec', '>= 1.2.9' gem.add_development_dependency 'yard' , '>= 0.5.2' gem.add_runtime_dependency 'addressable', '>= 2.1.1' gem.post_install_message = nil end Updated gemspec files and executables. #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'rdf' gem.homepage = 'http://rdf.rubyforge.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'A Ruby library for working with Resource Description Framework (RDF) data.' gem.description = 'RDF.rb is a pure-Ruby library for working with Resource Description Framework (RDF) data.' gem.rubyforge_project = 'rdf' gem.authors = ['Arto Bendiken', 'Ben Lavender'] gem.email = 'arto.bendiken@gmail.com' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION bin/rdf etc/doap.nt) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(rdf) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_development_dependency 'rspec', '>= 1.2.9' gem.add_development_dependency 'yard' , '>= 0.5.2' gem.add_runtime_dependency 'addressable', '>= 2.1.1' gem.post_install_message = nil end
# -*- encoding: utf-8 -*- require 'rubygems' unless Object.const_defined?(:Gem) require File.dirname(__FILE__) + "/lib/ripl/after_rc" Gem::Specification.new do |s| s.name = "ripl-after_rc" s.version = Ripl::AfterRc::VERSION s.authors = ["Gabriel Horner"] s.email = "gabriel.horner@gmail.com" s.homepage = "http://github.com/cldwalker/after_rc" s.summary = "A ripl plugin to define blocks to run after ~/.irbrc" s.description = "DESCRIPTION" s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = 'tagaholic' s.add_dependency 'ripl', '>= 0.2.0' s.files = Dir.glob(%w[{lib,test}/**/*.rb bin/* [A-Z]*.{txt,rdoc} ext/**/*.{rb,c} **/deps.rip]) + %w{Rakefile .gemspec} s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"] s.license = 'MIT' end sync description # -*- encoding: utf-8 -*- require 'rubygems' unless Object.const_defined?(:Gem) require File.dirname(__FILE__) + "/lib/ripl/after_rc" Gem::Specification.new do |s| s.name = "ripl-after_rc" s.version = Ripl::AfterRc::VERSION s.authors = ["Gabriel Horner"] s.email = "gabriel.horner@gmail.com" s.homepage = "http://github.com/cldwalker/after_rc" s.summary = "A ripl plugin to define blocks to run after ~/.irbrc" s.description = "This ripl plugin provides a simple way to define blocks which are run after ~/.irbrc is loaded. A more useful version of IRB.conf[:IRB_RC]." s.required_rubygems_version = ">= 1.3.6" s.rubyforge_project = 'tagaholic' s.add_dependency 'ripl', '>= 0.2.0' s.files = Dir.glob(%w[{lib,test}/**/*.rb bin/* [A-Z]*.{txt,rdoc} ext/**/*.{rb,c} **/deps.rip]) + %w{Rakefile .gemspec} s.extra_rdoc_files = ["README.rdoc", "LICENSE.txt"] s.license = 'MIT' end
#!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'rdf-isomorphic' gem.homepage = 'http://rdf.rubyforge.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'Graph bijections and isomorphic equivalence for rdf.rb' gem.description = <<-EOF rdf-isomorphic provides bijections mapping blank nodes from one RDF::Enumerable to another, and thus equivalence (isomorphism) testing. EOF gem.rubyforge_project = 'rdf-isomorphic' gem.authors = ['Ben Lavender'] gem.email = 'blavender@gmail.com' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION README.md) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w() gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_dependency 'rdf', '>= 0.0.9' gem.add_development_dependency 'rspec', '>= 1.2.9' gem.add_development_dependency 'yard' , '>= 0.5.2' gem.post_install_message = nil end Bump RDF.rb dependency to 0.1.0 #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'rdf-isomorphic' gem.homepage = 'http://rdf.rubyforge.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'Graph bijections and isomorphic equivalence for rdf.rb' gem.description = <<-EOF rdf-isomorphic provides bijections mapping blank nodes from one RDF::Enumerable to another, and thus equivalence (isomorphism) testing. EOF gem.rubyforge_project = 'rdf-isomorphic' gem.authors = ['Ben Lavender'] gem.email = 'blavender@gmail.com' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION README.md) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w() gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_dependency 'rdf', '>= 0.1.0' gem.add_development_dependency 'rspec', '>= 1.2.9' gem.add_development_dependency 'yard' , '>= 0.5.2' gem.post_install_message = nil end
Gem::Specification.new do |s| s.name = "fb_graph" s.version = "#{File.read("VERSION").delete("\n\r")}-kineticsocial" s.authors = ["nov matake", "allen kim"] s.description = %q{A full-stack Facebook Graph API wrapper in Ruby. Modified/Branched by KineticSocial} s.summary = %q{A full-stack Facebook Graph API wrapper in Ruby. Modified/Branched by KineticSocial} s.email = "nov@matake.jp, bighostkim@gmail.com" s.extra_rdoc_files = ["LICENSE", "README.rdoc"] s.rdoc_options = ["--charset=UTF-8"] s.homepage = "http://github.com/kineticsocial/fb_graph" s.require_paths = ["lib"] s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_runtime_dependency "httpclient", ">= 2.2.0.2" s.add_runtime_dependency "rack-oauth2", ">= 0.14.4" s.add_runtime_dependency "tzinfo" s.add_runtime_dependency "json" s.add_development_dependency "rake", ">= 0.8" if RUBY_VERSION >= '1.9' s.add_development_dependency "cover_me", ">= 1.2.0" else s.add_development_dependency "rcov", ">= 0.9" end s.add_development_dependency "rspec", ">= 2" s.add_development_dependency "webmock", ">= 1.6.2" s.add_development_dependency "actionpack", ">= 3.0.6" end changed version number Gem::Specification.new do |s| s.name = "fb_graph" s.version = "#{File.read("VERSION").delete("\n\r")}.1" s.authors = ["nov matake", "allen kim"] s.description = %q{A full-stack Facebook Graph API wrapper in Ruby. Modified/Branched by KineticSocial} s.summary = %q{A full-stack Facebook Graph API wrapper in Ruby. Modified/Branched by KineticSocial} s.email = "nov@matake.jp, bighostkim@gmail.com" s.extra_rdoc_files = ["LICENSE", "README.rdoc"] s.rdoc_options = ["--charset=UTF-8"] s.homepage = "http://github.com/kineticsocial/fb_graph" s.require_paths = ["lib"] s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.add_runtime_dependency "httpclient", ">= 2.2.0.2" s.add_runtime_dependency "rack-oauth2", ">= 0.14.4" s.add_runtime_dependency "tzinfo" s.add_runtime_dependency "json" s.add_development_dependency "rake", ">= 0.8" if RUBY_VERSION >= '1.9' s.add_development_dependency "cover_me", ">= 1.2.0" else s.add_development_dependency "rcov", ">= 0.9" end s.add_development_dependency "rspec", ">= 2" s.add_development_dependency "webmock", ">= 1.6.2" s.add_development_dependency "actionpack", ">= 3.0.6" end
#!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'datagraph' gem.homepage = 'http://datagraph.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'Datagraph.org API client.' gem.description = gem.summary gem.rubyforge_project = 'datagraph' gem.authors = ['Datagraph'] gem.email = 'datagraph@googlegroups.com' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION bin/datagraph) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(datagraph) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.2' gem.requirements = [] gem.add_development_dependency 'rdf-spec', '>= 0.1.10' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'yard' , '>= 0.5.5' gem.add_runtime_dependency 'rdf', '>= 0.1.10' gem.add_runtime_dependency 'rdfbus', '>= 0.0.1' gem.post_install_message = nil end Bumped the gem dependencies. #!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- GEMSPEC = Gem::Specification.new do |gem| gem.version = File.read('VERSION').chomp gem.date = File.mtime('VERSION').strftime('%Y-%m-%d') gem.name = 'datagraph' gem.homepage = 'http://datagraph.org/' gem.license = 'Public Domain' if gem.respond_to?(:license=) gem.summary = 'Datagraph.org API client.' gem.description = gem.summary gem.rubyforge_project = 'datagraph' gem.author = 'Datagraph' gem.email = 'datagraph@googlegroups.com' gem.platform = Gem::Platform::RUBY gem.files = %w(AUTHORS README UNLICENSE VERSION bin/datagraph) + Dir.glob('lib/**/*.rb') gem.bindir = %q(bin) gem.executables = %w(datagraph) gem.default_executable = gem.executables.first gem.require_paths = %w(lib) gem.extensions = %w() gem.test_files = %w() gem.has_rdoc = false gem.required_ruby_version = '>= 1.8.1' gem.requirements = [] gem.add_runtime_dependency 'rdf', '~> 0.2.3' #gem.add_runtime_dependency 'rdfbus', '>= 0.0.1' gem.add_development_dependency 'yard' , '>= 0.6.0' gem.add_development_dependency 'rspec', '>= 1.3.0' gem.add_development_dependency 'rdf-spec', '~> 0.2.3' gem.post_install_message = nil end
Gem::Specification.new do |s| s.name = 'airborne' s.version = '0.1.14' s.date = '2015-03-02' s.summary = "RSpec driven API testing framework" s.authors = ["Alex Friedman", "Seth Pollack"] s.email = ['a.friedman07@gmail.com', 'teampollack@gmail.com'] s.require_paths = ['lib'] s.files = `git ls-files`.split("\n") s.license = 'MIT' s.add_runtime_dependency 'rspec', '~> 3.1', '>= 3.1.0' s.add_runtime_dependency 'rest-client', '~> 1.7', '>= 1.7.3' #version 1.7.3 fixes security vulnerability https://github.com/brooklynDev/airborne/issues/41 s.add_runtime_dependency 'rack-test', '~> 0.6', '>= 0.6.2' s.add_runtime_dependency 'activesupport', '>= 3.0.0', '>= 3.0.0' s.add_development_dependency 'webmock', '~> 0' end Bump gem version Gem::Specification.new do |s| s.name = 'airborne' s.version = '0.1.15' s.date = '2015-03-03' s.summary = "RSpec driven API testing framework" s.authors = ["Alex Friedman", "Seth Pollack"] s.email = ['a.friedman07@gmail.com', 'teampollack@gmail.com'] s.require_paths = ['lib'] s.files = `git ls-files`.split("\n") s.license = 'MIT' s.add_runtime_dependency 'rspec', '~> 3.1', '>= 3.1.0' s.add_runtime_dependency 'rest-client', '~> 1.7', '>= 1.7.3' #version 1.7.3 fixes security vulnerability https://github.com/brooklynDev/airborne/issues/41 s.add_runtime_dependency 'rack-test', '~> 0.6', '>= 0.6.2' s.add_runtime_dependency 'activesupport', '>= 3.0.0', '>= 3.0.0' s.add_development_dependency 'webmock', '~> 0' end
# -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "airbrake/version" Gem::Specification.new do |s| s.name = %q{airbrake} s.version = Airbrake::VERSION.dup s.summary = %q{Send your application errors to our hosted service and reclaim your inbox.} s.require_paths = ["lib"] s.executables << "airbrake" s.files = Dir["{generators/**/*,lib/**/*,rails/**/*,resources/*,script/*}"] + %w(airbrake.gemspec CHANGELOG Gemfile Guardfile INSTALL MIT-LICENSE Rakefile README_FOR_HEROKU_ADDON.md README.md TESTING.md SUPPORTED_RAILS_VERSIONS install.rb) s.test_files = Dir.glob("{test,spec,features}/**/*") s.add_runtime_dependency("builder") s.add_runtime_dependency("girl_friday") s.add_development_dependency("bourne", ">= 1.0") s.add_development_dependency("cucumber-rails","~> 1.1.1") s.add_development_dependency("fakeweb", "~> 1.3.0") s.add_development_dependency("nokogiri", "~> 1.5.0") s.add_development_dependency("rspec", "~> 2.6.0") s.add_development_dependency("sham_rack", "~> 1.3.0") s.add_development_dependency("shoulda", "~> 2.11.3") s.add_development_dependency("capistrano") s.add_development_dependency("aruba") s.add_development_dependency("appraisal") s.add_development_dependency("rspec-rails") s.add_development_dependency("sinatra") s.authors = ["Airbrake"] s.email = %q{support@airbrake.io} s.homepage = "http://www.airbrake.io" s.platform = Gem::Platform::RUBY end use specific version of builder # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) require "airbrake/version" Gem::Specification.new do |s| s.name = %q{airbrake} s.version = Airbrake::VERSION.dup s.summary = %q{Send your application errors to our hosted service and reclaim your inbox.} s.require_paths = ["lib"] s.executables << "airbrake" s.files = Dir["{generators/**/*,lib/**/*,rails/**/*,resources/*,script/*}"] + %w(airbrake.gemspec CHANGELOG Gemfile Guardfile INSTALL MIT-LICENSE Rakefile README_FOR_HEROKU_ADDON.md README.md TESTING.md SUPPORTED_RAILS_VERSIONS install.rb) s.test_files = Dir.glob("{test,spec,features}/**/*") s.add_runtime_dependency("builder", "~> 3.0.4") s.add_runtime_dependency("girl_friday") s.add_development_dependency("bourne", ">= 1.0") s.add_development_dependency("cucumber-rails","~> 1.1.1") s.add_development_dependency("fakeweb", "~> 1.3.0") s.add_development_dependency("nokogiri", "~> 1.5.0") s.add_development_dependency("rspec", "~> 2.6.0") s.add_development_dependency("sham_rack", "~> 1.3.0") s.add_development_dependency("shoulda", "~> 2.11.3") s.add_development_dependency("capistrano") s.add_development_dependency("aruba") s.add_development_dependency("appraisal") s.add_development_dependency("rspec-rails") s.add_development_dependency("sinatra") s.authors = ["Airbrake"] s.email = %q{support@airbrake.io} s.homepage = "http://www.airbrake.io" s.platform = Gem::Platform::RUBY end
Gem::Specification.new do |s| s.name = 'hive-runner-android' s.version = '1.1.2' s.date = '2015-02-26' s.summary = 'Hive Runner Android' s.description = 'The Android controller module for Hive Runner' s.authors = ['Jon Wilson'] s.email = 'jon.wilson01@bbc.co.uk' s.files = Dir['README.md', 'lib/**/*.rb'] s.homepage = 'https://github.com/bbc/hive-runner-android' s.license = 'MIT' s.add_runtime_dependency 'device_api-android', '~> 1.0' s.add_runtime_dependency 'hive-runner', '~> 2.0' s.add_runtime_dependency 'terminal-table', '>= 1.4' end Use hive-runner 2.0.5 or greater Gem::Specification.new do |s| s.name = 'hive-runner-android' s.version = '1.1.3' s.date = '2015-02-26' s.summary = 'Hive Runner Android' s.description = 'The Android controller module for Hive Runner' s.authors = ['Jon Wilson'] s.email = 'jon.wilson01@bbc.co.uk' s.files = Dir['README.md', 'lib/**/*.rb'] s.homepage = 'https://github.com/bbc/hive-runner-android' s.license = 'MIT' s.add_runtime_dependency 'device_api-android', '~> 1.0' s.add_runtime_dependency 'hive-runner', '~> 2.0.5' s.add_runtime_dependency 'terminal-table', '>= 1.4' end
working on starting the sinatra frontend #!/usr/bin/env ruby require 'sinatra' get '/adsb.kml' do end
module Tritium module Parser class Instruction attr :name, true attr :args, true attr :children, true attr :parent, true attr :root, true def initialize(name = nil, args = []) @name = name @args = args @parent = nil @children = [] @root = self end def add(child) child.parent = self child.root = root children << child end def root? root == self end end end end Instructions now track source line number and script name and pre-processed script value module Tritium module Parser class Instruction attr :name, true attr :args, true attr :children, true attr :parent, true attr :root, true attr :line_number attr :line attr :processed_line def initialize(name = nil, options = {}) # Primary Attributes @name = name @args = options[:args] || options["args"] || [] # Default Setup @parent = nil @children = [] @root = self # Debug information @line_number = options[:line_number] || options["line_number"] || 0 @line = options[:line] || options["line"] || '' @processed_line = options[:processed_line] || options["processed_line"] || '' end def add(child) child.parent = self child.root = root children << child end def root? root == self 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{phat_pgsearch} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Marco Scholl"] s.date = %q{2011-02-22} s.description = %q{a plugin for tssearch support from postgresql} s.email = %q{develop@marco-scholl.de} s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "lib/phat_pgsearch.rb", "lib/phat_pgsearch/active_record.rb", "lib/phat_pgsearch/index_builder.rb", "lib/phat_pgsearch/index_definition.rb", "lib/phat_pgsearch/postgresql.rb", "phat_pgsearch.gemspec", "spec/active_record_spec.rb", "spec/phat_pgsearch_spec.rb", "spec/spec_helper.rb", "spec/support/active_record.rb" ] s.homepage = %q{http://github.com/traxanos/phat_pgsearch} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.5.2} s.summary = %q{a postgresql based search plugin} s.test_files = [ "spec/active_record_spec.rb", "spec/phat_pgsearch_spec.rb", "spec/spec_helper.rb", "spec/support/active_record.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 s.add_runtime_dependency(%q<rails>, ["~> 3.0.0"]) s.add_development_dependency(%q<autotest>, [">= 0"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<yard>, [">= 0"]) s.add_development_dependency(%q<pg>, [">= 0"]) else s.add_dependency(%q<rails>, ["~> 3.0.0"]) s.add_dependency(%q<autotest>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) s.add_dependency(%q<pg>, [">= 0"]) end else s.add_dependency(%q<rails>, ["~> 3.0.0"]) s.add_dependency(%q<autotest>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) s.add_dependency(%q<pg>, [">= 0"]) end end fix url # 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{phat_pgsearch} s.version = "0.1.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Marco Scholl"] s.date = %q{2011-02-22} s.description = %q{a plugin for tssearch support from postgresql} s.email = %q{develop@marco-scholl.de} s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", ".rspec", "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "lib/phat_pgsearch.rb", "lib/phat_pgsearch/active_record.rb", "lib/phat_pgsearch/index_builder.rb", "lib/phat_pgsearch/index_definition.rb", "lib/phat_pgsearch/postgresql.rb", "phat_pgsearch.gemspec", "spec/active_record_spec.rb", "spec/phat_pgsearch_spec.rb", "spec/spec_helper.rb", "spec/support/active_record.rb" ] s.homepage = %q{http://github.com/phatserver/phat_pgsearch} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.5.2} s.summary = %q{a postgresql based search plugin} s.test_files = [ "spec/active_record_spec.rb", "spec/phat_pgsearch_spec.rb", "spec/spec_helper.rb", "spec/support/active_record.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 s.add_runtime_dependency(%q<rails>, ["~> 3.0.0"]) s.add_development_dependency(%q<autotest>, [">= 0"]) s.add_development_dependency(%q<bundler>, [">= 0"]) s.add_development_dependency(%q<jeweler>, [">= 0"]) s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<yard>, [">= 0"]) s.add_development_dependency(%q<pg>, [">= 0"]) else s.add_dependency(%q<rails>, ["~> 3.0.0"]) s.add_dependency(%q<autotest>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) s.add_dependency(%q<pg>, [">= 0"]) end else s.add_dependency(%q<rails>, ["~> 3.0.0"]) s.add_dependency(%q<autotest>, [">= 0"]) s.add_dependency(%q<bundler>, [">= 0"]) s.add_dependency(%q<jeweler>, [">= 0"]) s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) s.add_dependency(%q<pg>, [">= 0"]) end end
# This file is part of Metasm, the Ruby assembly manipulation suite # Copyright (C) 2006-2009 Yoann GUILLOT # # Licence is LGPL, see LICENCE in the top-level directory require 'metasm/arm/opcodes' require 'metasm/decode' module Metasm class ARM # create the bin_mask for a given opcode def build_opcode_bin_mask(op) # bit = 0 if can be mutated by an field value, 1 if fixed by opcode op.bin_mask = 0 op.fields.each { |k, (m, s)| op.bin_mask |= m << s } op.bin_mask = 0xffffffff ^ op.bin_mask end # create the lookaside hash from the first byte of the opcode def build_bin_lookaside lookaside = Array.new(256) { [] } opcode_list.each { |op| build_opcode_bin_mask op b = (op.bin >> 20) & 0xff msk = (op.bin_mask >> 20) & 0xff b &= msk for i in b..(b | (255^msk)) lookaside[i] << op if i & msk == b end } lookaside end def decode_findopcode(edata) return if edata.ptr >= edata.data.length di = DecodedInstruction.new(self) val = edata.decode_imm(:u32, @endianness) di.instance_variable_set('@raw', val) di if di.opcode = @bin_lookaside[(val >> 20) & 0xff].find { |op| (not op.props[:cond] or ((op.bin >> @fields_shift[:cond]) & @fields_mask[:cond]) != 0xf) and (op.bin & op.bin_mask) == (val & op.bin_mask) } end def disassembler_default_func df = DecodedFunction.new df end def decode_instr_op(edata, di) op = di.opcode di.instruction.opname = op.name val = di.instance_variable_get('@raw') field_val = lambda { |f| r = (val >> @fields_shift[f]) & @fields_mask[f] case f when :i16; Expression.make_signed(r, 16) when :i24; Expression.make_signed(r, 24) when :i8_12; ((r >> 4) & 0xf0) | (r & 0xf) when :stype; [:lsl, :lsr, :asr, :ror][r] when :u; [:-, :+][r] else r end } if op.props[:cond] cd = %w[eq ne cs cc mi pl vs vc hi ls ge lt gt le al][field_val[:cond]] if cd != 'al' di.opcode = di.opcode.dup di.instruction.opname = di.opcode.name.dup di.instruction.opname[(op.props[:cond_name_off] || di.opcode.name.length), 0] = cd if di.opcode.props[:stopexec] di.opcode.props = di.opcode.props.dup di.opcode.props.delete :stopexec end end end op.args.each { |a| di.instruction.args << case a when :rd, :rn, :rm; Reg.new field_val[a] when :rm_rs; Reg.new field_val[:rm], field_val[:stype], Reg.new(field_val[:rs]) when :rm_is; Reg.new field_val[:rm], field_val[:stype], field_val[:shifti]*2 when :i24; Expression[field_val[a] << 2] when :i8_r i = field_val[:i8] r = field_val[:rotate]*2 Expression[((i >> r) | (i << (32-r))) & 0xffff_ffff] when :mem_rn_rm, :mem_rn_i8_12, :mem_rn_rms, :mem_rn_i12 b = Reg.new(field_val[:rn]) o = case a when :mem_rn_rm; Reg.new(field_val[:rm]) when :mem_rn_i8_12; field_val[:i8_12] when :mem_rn_rms; Reg.new(field_val[:rm], field_val[:stype], field_val[:shifti]*2) when :mem_rn_i12; field_val[:i12] end Memref.new(b, o, field_val[:u], op.props[:baseincr]) when :reglist di.instruction.args.last.updated = true if op.props[:baseincr] msk = field_val[a] l = RegList.new((0..15).map { |i| Reg.new(i) if (msk & (1 << i)) > 0 }.compact) l.usermoderegs = true if op.props[:usermoderegs] l else raise SyntaxError, "Internal error: invalid argument #{a} in #{op.name}" end } p di.instruction.args di.bin_length = 4 di end def decode_instr_interpret(di, addr) if di.opcode.args.include? :i24 di.instruction.args[-1] = Expression[di.instruction.args[-1] + addr + 8] end di end def backtrace_binding @backtrace_binding ||= init_backtrace_binding end def init_backtrace_binding @backtrace_binding ||= {} end def get_backtrace_binding(di) a = di.instruction.args.map { |arg| case arg when Reg; arg.symbolic when Memref; arg.symbolic(di.address) else arg end } if binding = backtrace_binding[di.opcode.name] bd = binding[di, *a] else puts "unhandled instruction to backtrace: #{di}" if $VERBOSE # assume nothing except the 1st arg is modified case a[0] when Indirection, Symbol; { a[0] => Expression::Unknown } when Expression; (x = a[0].externals.first) ? { x => Expression::Unknown } : {} else {} end.update(:incomplete_binding => Expression[1]) end end def get_xrefs_x(dasm, di) if di.opcode.props[:setip] [di.instruction.args.last] else # TODO ldr pc, .. [] end end end end arm: rm debug statement # This file is part of Metasm, the Ruby assembly manipulation suite # Copyright (C) 2006-2009 Yoann GUILLOT # # Licence is LGPL, see LICENCE in the top-level directory require 'metasm/arm/opcodes' require 'metasm/decode' module Metasm class ARM # create the bin_mask for a given opcode def build_opcode_bin_mask(op) # bit = 0 if can be mutated by an field value, 1 if fixed by opcode op.bin_mask = 0 op.fields.each { |k, (m, s)| op.bin_mask |= m << s } op.bin_mask = 0xffffffff ^ op.bin_mask end # create the lookaside hash from the first byte of the opcode def build_bin_lookaside lookaside = Array.new(256) { [] } opcode_list.each { |op| build_opcode_bin_mask op b = (op.bin >> 20) & 0xff msk = (op.bin_mask >> 20) & 0xff b &= msk for i in b..(b | (255^msk)) lookaside[i] << op if i & msk == b end } lookaside end def decode_findopcode(edata) return if edata.ptr >= edata.data.length di = DecodedInstruction.new(self) val = edata.decode_imm(:u32, @endianness) di.instance_variable_set('@raw', val) di if di.opcode = @bin_lookaside[(val >> 20) & 0xff].find { |op| (not op.props[:cond] or ((op.bin >> @fields_shift[:cond]) & @fields_mask[:cond]) != 0xf) and (op.bin & op.bin_mask) == (val & op.bin_mask) } end def disassembler_default_func df = DecodedFunction.new df end def decode_instr_op(edata, di) op = di.opcode di.instruction.opname = op.name val = di.instance_variable_get('@raw') field_val = lambda { |f| r = (val >> @fields_shift[f]) & @fields_mask[f] case f when :i16; Expression.make_signed(r, 16) when :i24; Expression.make_signed(r, 24) when :i8_12; ((r >> 4) & 0xf0) | (r & 0xf) when :stype; [:lsl, :lsr, :asr, :ror][r] when :u; [:-, :+][r] else r end } if op.props[:cond] cd = %w[eq ne cs cc mi pl vs vc hi ls ge lt gt le al][field_val[:cond]] if cd != 'al' di.opcode = di.opcode.dup di.instruction.opname = di.opcode.name.dup di.instruction.opname[(op.props[:cond_name_off] || di.opcode.name.length), 0] = cd if di.opcode.props[:stopexec] di.opcode.props = di.opcode.props.dup di.opcode.props.delete :stopexec end end end op.args.each { |a| di.instruction.args << case a when :rd, :rn, :rm; Reg.new field_val[a] when :rm_rs; Reg.new field_val[:rm], field_val[:stype], Reg.new(field_val[:rs]) when :rm_is; Reg.new field_val[:rm], field_val[:stype], field_val[:shifti]*2 when :i24; Expression[field_val[a] << 2] when :i8_r i = field_val[:i8] r = field_val[:rotate]*2 Expression[((i >> r) | (i << (32-r))) & 0xffff_ffff] when :mem_rn_rm, :mem_rn_i8_12, :mem_rn_rms, :mem_rn_i12 b = Reg.new(field_val[:rn]) o = case a when :mem_rn_rm; Reg.new(field_val[:rm]) when :mem_rn_i8_12; field_val[:i8_12] when :mem_rn_rms; Reg.new(field_val[:rm], field_val[:stype], field_val[:shifti]*2) when :mem_rn_i12; field_val[:i12] end Memref.new(b, o, field_val[:u], op.props[:baseincr]) when :reglist di.instruction.args.last.updated = true if op.props[:baseincr] msk = field_val[a] l = RegList.new((0..15).map { |i| Reg.new(i) if (msk & (1 << i)) > 0 }.compact) l.usermoderegs = true if op.props[:usermoderegs] l else raise SyntaxError, "Internal error: invalid argument #{a} in #{op.name}" end } di.bin_length = 4 di end def decode_instr_interpret(di, addr) if di.opcode.args.include? :i24 di.instruction.args[-1] = Expression[di.instruction.args[-1] + addr + 8] end di end def backtrace_binding @backtrace_binding ||= init_backtrace_binding end def init_backtrace_binding @backtrace_binding ||= {} end def get_backtrace_binding(di) a = di.instruction.args.map { |arg| case arg when Reg; arg.symbolic when Memref; arg.symbolic(di.address) else arg end } if binding = backtrace_binding[di.opcode.name] bd = binding[di, *a] else puts "unhandled instruction to backtrace: #{di}" if $VERBOSE # assume nothing except the 1st arg is modified case a[0] when Indirection, Symbol; { a[0] => Expression::Unknown } when Expression; (x = a[0].externals.first) ? { x => Expression::Unknown } : {} else {} end.update(:incomplete_binding => Expression[1]) end end def get_xrefs_x(dasm, di) if di.opcode.props[:setip] [di.instruction.args.last] else # TODO ldr pc, .. [] end end end end
require 'formula' class PingboardWorkflow < Formula homepage 'https://github.com/pingboard/git-pivotal-workflow' url 'https://github.com/pingboard/git-pivotal-workflow.git', :using => :git depends_on 'git-flow-avh' depends_on 'pivotal-tracker' => :ruby def install bin.install 'git-pivotal' end def caveats s = <<-EOS.undent Add your personal pivotal token and the Pingboard project id to the git config git config --add pivotal.token PIVOTAL_TOKEN git config --add pivotal.token PIVOTAL_TOKEN git config --add pivotal.project-id PIVOTAL_PROJECT_ID Next system link the .git/hooks directory in your Pingboard code base. ln -s #{opt_prefix}/hooks CODBASE_PATH/pingboard/.git/hooks EOS end end Adding in share require 'formula' class PingboardWorkflow < Formula homepage 'https://github.com/pingboard/git-pivotal-workflow' url 'https://github.com/pingboard/git-pivotal-workflow.git', :using => :git depends_on 'git-flow-avh' depends_on 'pivotal-tracker' => :ruby def install bin.install 'git-pivotal' share.install 'hooks' end def caveats s = <<-EOS.undent Add your personal pivotal token and the Pingboard project id to the git config git config --add pivotal.token PIVOTAL_TOKEN git config --add pivotal.project-id PIVOTAL_PROJECT_ID Next system link the .git/hooks directory in your Pingboard code base. ln -s #{opt_prefix}/hooks CODBASE_PATH/pingboard/.git/hooks EOS end end
$:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = 'infoconnect_wrapper' s.version = '0.0.0' s.date = '2015-06-02' s.summary = %q{Ruby wrapper around InfoConnect API} s.description = "A Ruby wrapper for Infoconnect API. Currently supporting http://developer.infoconnect.com/company-object" s.authors = ["Brian Schwartz"] s.email = 'bschwartz@creativereason.com' s.files = ["lib/infoconnect_wrapper.rb", "lib/infoconnect_wrapper/", "lib/infoconnect_wrapper/response.rb", "lib/infoconnect_wrapper/company.rb", "lib/infoconnect_wrapper/find_company.rb"] s.homepage = 'https://github.com/creativereason/infoconnect_wrapper' s.license = 'MIT' end RestClient is used $:.push File.expand_path("../lib", __FILE__) Gem::Specification.new do |s| s.name = 'infoconnect_wrapper' s.version = '0.0.0' s.date = '2015-06-02' s.summary = %q{Ruby wrapper around InfoConnect API} s.description = "A Ruby wrapper for Infoconnect API. Currently supporting http://developer.infoconnect.com/company-object" s.authors = ["Brian Schwartz"] s.add_runtime_dependency 'rest-client' s.email = 'bschwartz@creativereason.com' s.files = ["lib/infoconnect_wrapper.rb", "lib/infoconnect_wrapper/", "lib/infoconnect_wrapper/response.rb", "lib/infoconnect_wrapper/company.rb", "lib/infoconnect_wrapper/find_company.rb"] s.homepage = 'https://github.com/creativereason/infoconnect_wrapper' s.license = 'MIT' end
require 'pegrb' module LetGrammar # Environment class. Basically just chained hash maps modeling the usual # lexical scope structure we all know and love. Not optimized at all for any # kind of special access patterns. class Env def initialize(inner, outer); @inner, @outer = inner, outer; end def [](val); @inner[val] || @outer[val]; end def []=(key, val); @inner[key] = val; end def increment; Env.new({}, self); end end # AST classes. class ConstExp < Struct.new(:value) def eval(_); self.value; end end # Common evaluation strategy so we abstract it. class ArithmeticOp < Struct.new(:expressions) # We again use lazy enumerators to not evaluate all the expressions. There might be # a type error along the way so evaluating all the expressions and then hitting a type # error is wasted effort. Evaluate only when necessary and die as soon as we have a type error. def eval(env, op) accumulator = self.expressions[0].eval(env) self.expressions.lazy.drop(1).each {|x| accumulator = accumulator.send(op, x.eval(env))} accumulator end end # Just need the right symbol to evaluate. class DiffExp < ArithmeticOp def eval(env); super(env, :-); end end class AddExp < ArithmeticOp def eval(env); super(env, :+); end end class MultExp < ArithmeticOp def eval(env); super(env, :*); end end class DivExp < ArithmeticOp def eval(env); super(env, :/); end end class ModExp < ArithmeticOp def eval(env); super(env, :%); end end # Similar kind of abstraction as for +ArithmeticOp+. class OrderOp < Struct.new(:expressions) # We use lazy enumerators for short circuiting the operations because we don't # need to evaluate all the expressions. We can bail as soon as we see a false result. # We are assuming a finite collection of expressions and in the absence of macros this # assumption holds. def eval(env, op) lazy_exprs = self.expressions.lazy pairs = lazy_exprs.zip(lazy_exprs.drop(1)).take(self.expression.length - 1) pairs.each {|x, y| return false unless x.eval(env).send(op, y.eval(env))} true end end # Just need the right symbol to evaluate. class LessExp < OrderOp def eval(env); super(env, :<); end end class LessEqExp < OrderOp def eval(env); super(env, :<=); end end class EqExp < OrderOp def eval(env); super(env, :==); end end class GreaterExp < OrderOp def eval(env); super(env, :>); end end class GreaterEqExp < OrderOp def eval(env); super(env, :>=); end end class ZeroCheck < Struct.new(:expressions) def eval(env); self.expressions.all? {|x| x.eval(env) == 0}; end end class IfExp < Struct.new(:test, :true_branch, :false_branch) def eval(env) self.test.eval(env) ? self.true_branch.eval(env) : self.false_branch.eval(env) end end class Identifier < Struct.new(:value) def eval(env); env[self.value]; end end class Assignment < Struct.new(:variable, :value) # This is a little tricky but I'm going to go with an eager evaluation strategy. # Might come back and re-think this in terms of lazy evaluation. def eval(env); env[self.variable.value] = self.value.eval(env); end end class LetExp < Struct.new(:assignments, :body) def eval(env) new_env = env.increment assignments.each {|assignment| assignment.eval(new_env)} self.body.eval(new_env) end end class ListExp < Struct.new(:list) def eval(env); self.list.map {|x| x.eval(env)}; end end class CarExp < Struct.new(:list) def eval(env); self.list.eval(env).first; end end class CdrExp < Struct.new(:list) def eval(env); self.list.eval(env)[1..-1]; end end class NullExp < Struct.new(:list) def eval(env); self.list.eval(env).empty?; end end class ConsExp < Struct.new(:head, :tail) def eval(env); [self.head.eval(env)] + self.tail.eval(env); end end class Condition < Struct.new(:left, :right) def eval(env); self.left.eval(env) ? self.right.eval(env) : false; end end class CondExp < Struct.new(:conditions) def eval(env); self.conditions.each {|x| if (val = x.eval(env)) then return val end}; end end class Procedure < Struct.new(:arguments, :body) end class ProcedureCall < Struct.new(:operator, :operands) end @grammar = Grammar.rules do operator_class_mapping = {'-' => DiffExp, '+' => AddExp, '*' => MultExp, '/' => DivExp, '%' => ModExp, '<' => LessExp, '<=' => LessEqExp, '=' => EqExp, '>' => GreaterExp, '>=' => GreaterEqExp, 'car' => CarExp, 'cdr' => CdrExp, 'null?' => NullExp, 'cons' => ConsExp } whitespace = one_of(/\s/).many.any.ignore sep = one_of(/\s/).many.ignore # any sequence of digits, e.g. 123 number = (one_of(/\d/).many[:digits] > cut!) >> ->(s) { [ConstExp.new(s[:digits].map(&:text).join.to_i)] } # All order operators have a similar structure as well order_op = ((m('<=') | m('>=') | one_of('<', '=', '>'))[:operator] > cut!) >> ->(s) { [operator_class_mapping[s[:operator].map(&:text).join]] } # All the operator expressions have a common structure so abstract it arithmetic_op = (one_of('-', '+', '*', '/')[:operator] > cut!) >> ->(s) { [operator_class_mapping[s[:operator].first.text]] } # Combine the operators into one general_arithmetic_op = order_op | arithmetic_op # {-, +, *, /, <, <=, =, >, >=}(expression {, expression}+) arithmetic_expression = (general_arithmetic_op[:operator] > one_of('(') > whitespace > cut! > r(:expression)[:first] > (whitespace > one_of(',').ignore > whitespace > cut! > r(:expression)).many[:rest] > whitespace > one_of(')') > cut!) >> ->(s) { [s[:operator][0].new(s[:first] + s[:rest])] } # list expressions: list(), list(expression {, expression}*) empty_list = (m('list()') > cut!)>> ->(s) { [ListExp.new([])] } non_empty_list = (m('list(') > whitespace > cut! > r(:expression)[:head] > (whitespace > one_of(',').ignore > whitespace > cut! > r(:expression)).many.any[:tail] > whitespace > one_of(')') > cut!) >> ->(s) { [ListExp.new(s[:head] + s[:tail])] } list_expression = empty_list | non_empty_list # unary list operators unary_list_op = ((m('car') | m('cdr') | m('null?')) > cut!)[:list_operator] >> ->(s) { [operator_class_mapping[s[:list_operator].map(&:text).join]] } unary_list_op_expression = (unary_list_op[:op] > one_of('(') > whitespace > cut! > r(:expression)[:list_expression] > whitespace > one_of(')') > cut!) >> ->(s) { [s[:op][0].new(s[:list_expression][0])] } # binary list operators binary_list_op = (m('cons') > cut!)[:list_operator] >> ->(s) { [operator_class_mapping[s[:list_operator].map(&:text).join]] } binary_list_op_expression = (binary_list_op[:op] > one_of('(') > whitespace > cut! > r(:expression)[:first] > whitespace > one_of(',') > whitespace > cut! > r(:expression)[:second] > whitespace > one_of(')') > cut!) >> ->(s) { [s[:op][0].new(s[:first][0], s[:second][0])] } # unary or binary list expressions list_op_expression = unary_list_op_expression | binary_list_op_expression # cond expression cond_expression = (m('cond') > cut! > (sep > r(:expression) > sep > m('==>').ignore > cut! > sep > r(:expression)).many.any[:conditions] > whitespace > m('end') > cut!) >> ->(s) { [CondExp.new(s[:conditions].each_slice(2).map {|l, r| Condition.new(l, r)})] } # zero?(expression {, expression}+) zero_check = (m('zero?(') > whitespace > cut! > r(:expression)[:first] > (whitespace > one_of(',').ignore > whitespace > cut! > r(:expression)).many.any[:rest] > whitespace > one_of(')') > cut!) >> ->(s) { [ZeroCheck.new(s[:first] + s[:rest])] } # if expression then expression else expression if_expression = (m('if') > sep > cut! > whitespace > r(:expression)[:test] > sep > m('then') > sep > cut! > r(:expression)[:true] > sep > m('else') > sep > cut! > r(:expression)[:false] > cut!) >> ->(s) { [IfExp.new(s[:test][0], s[:true][0], s[:false][0])] } # non-space, non-paren, non-comma characters all become identifiers identifier = one_of(/[^\s\(\),]/).many[:chars] >> ->(s) { [Identifier.new(s[:chars].map(&:text).join)] } # variable = expression assignment = (identifier[:variable] > sep > one_of('=') > sep > cut! > r(:expression)[:value]) >> ->(s) { [Assignment.new(s[:variable][0], s[:value][0])] } # let identifier = expression {, identifier = expression }* in expression let_expression = (m('let') > sep > cut! > assignment[:first] > (whitespace > one_of(',').ignore > cut! > whitespace > assignment).many.any[:rest] > sep > cut! > m('in') > sep > cut! > r(:expression)[:body] > cut!) >> ->(s) { [LetExp.new(s[:first] + s[:rest], s[:body][0])] } # procedures, proc (var1 {, var}*) expression proc_expression = (m('proc') > cut! > whitespace > one_of('(') > identifier[:first] > cut! > (whitespace > one_of(',') > whitespace > identifier).many.any[:rest] > one_of(')') > cut! > sep > r(:expression)[:body]) >> ->(s) { [Procedure.new(s[:first] + s[:rest], s[:body][0])] } # procedure call, lisp style, (expression expression) proc_call_expression = (one_of('(') > cut! > whitespace > r(:expression)[:operator] > (sep > r(:expression)).many[:operands] > whitespace > one_of(')') > cut!) >> ->(s) { [ProcedureCall.new(s[:operator][0], s[:operands])] } # all the expressions together rule :expression, number | arithmetic_expression | zero_check | if_expression | let_expression | list_expression | list_op_expression | cond_expression | proc_expression | proc_call_expression | identifier rule :start, r(:expression) end def self.parse(indexable); @grammar.parse(indexable); end end procedure evaluation implemented and we also got recursion to work for free because of how we implemented environments require 'pegrb' module LetGrammar # Environment class. Basically just chained hash maps modeling the usual # lexical scope structure we all know and love. Not optimized at all for any # kind of special access patterns. class Env def initialize(inner, outer); @inner, @outer = inner, outer; end def [](val); @inner[val] || @outer[val]; end def []=(key, val); @inner[key] = val; end def increment; Env.new({}, self); end end # AST classes. class ConstExp < Struct.new(:value) def eval(_); self.value; end end # Common evaluation strategy so we abstract it. class ArithmeticOp < Struct.new(:expressions) # We again use lazy enumerators to not evaluate all the expressions. There might be # a type error along the way so evaluating all the expressions and then hitting a type # error is wasted effort. Evaluate only when necessary and die as soon as we have a type error. def eval(env, op) accumulator = self.expressions[0].eval(env) self.expressions.lazy.drop(1).each {|x| accumulator = accumulator.send(op, x.eval(env))} accumulator end end # Just need the right symbol to evaluate. class DiffExp < ArithmeticOp def eval(env); super(env, :-); end end class AddExp < ArithmeticOp def eval(env); super(env, :+); end end class MultExp < ArithmeticOp def eval(env); super(env, :*); end end class DivExp < ArithmeticOp def eval(env); super(env, :/); end end class ModExp < ArithmeticOp def eval(env); super(env, :%); end end # Similar kind of abstraction as for +ArithmeticOp+. class OrderOp < Struct.new(:expressions) # We use lazy enumerators for short circuiting the operations because we don't # need to evaluate all the expressions. We can bail as soon as we see a false result. # We are assuming a finite collection of expressions and in the absence of macros this # assumption holds. def eval(env, op) lazy_exprs = self.expressions.lazy pairs = lazy_exprs.zip(lazy_exprs.drop(1)).take(self.expressions.length - 1) pairs.each {|x, y| return false unless x.eval(env).send(op, y.eval(env))} true end end # Just need the right symbol to evaluate. class LessExp < OrderOp def eval(env); super(env, :<); end end class LessEqExp < OrderOp def eval(env); super(env, :<=); end end class EqExp < OrderOp def eval(env); super(env, :==); end end class GreaterExp < OrderOp def eval(env); super(env, :>); end end class GreaterEqExp < OrderOp def eval(env); super(env, :>=); end end class ZeroCheck < Struct.new(:expressions) def eval(env); self.expressions.all? {|x| x.eval(env) == 0}; end end class IfExp < Struct.new(:test, :true_branch, :false_branch) def eval(env) self.test.eval(env) ? self.true_branch.eval(env) : self.false_branch.eval(env) end end class Identifier < Struct.new(:value) def eval(env); env[self.value]; end end class Assignment < Struct.new(:variable, :value) # This is a little tricky but I'm going to go with an eager evaluation strategy. # Might come back and re-think this in terms of lazy evaluation. def eval(env); env[self.variable.value] = self.value.eval(env); end end class LetExp < Struct.new(:assignments, :body) def eval(env) new_env = env.increment assignments.each {|assignment| assignment.eval(new_env)} self.body.eval(new_env) end end class ListExp < Struct.new(:list) def eval(env); self.list.map {|x| x.eval(env)}; end end class CarExp < Struct.new(:list) def eval(env); self.list.eval(env).first; end end class CdrExp < Struct.new(:list) def eval(env); self.list.eval(env)[1..-1]; end end class NullExp < Struct.new(:list) def eval(env); self.list.eval(env).empty?; end end class ConsExp < Struct.new(:head, :tail) def eval(env); [self.head.eval(env)] + self.tail.eval(env); end end class Condition < Struct.new(:left, :right) def eval(env); self.left.eval(env) ? self.right.eval(env) : false; end end class CondExp < Struct.new(:conditions) def eval(env); self.conditions.each {|x| if (val = x.eval(env)) then return val end}; end end class Procedure < Struct.new(:arguments, :body) def eval(env) lambda do |*args| procedure_env = env.increment self.arguments.zip(args).each {|arg, value| procedure_env[arg.value] = value} self.body.eval(procedure_env) end end end class ProcedureCall < Struct.new(:operator, :operands) def eval(env) self.operator.eval(env).call(*self.operands.map {|x| x.eval(env)}) end end @grammar = Grammar.rules do operator_class_mapping = {'-' => DiffExp, '+' => AddExp, '*' => MultExp, '/' => DivExp, '%' => ModExp, '<' => LessExp, '<=' => LessEqExp, '=' => EqExp, '>' => GreaterExp, '>=' => GreaterEqExp, 'car' => CarExp, 'cdr' => CdrExp, 'null?' => NullExp, 'cons' => ConsExp } whitespace = one_of(/\s/).many.any.ignore sep = one_of(/\s/).many.ignore # any sequence of digits, e.g. 123 number = (one_of(/\d/).many[:digits] > cut!) >> ->(s) { [ConstExp.new(s[:digits].map(&:text).join.to_i)] } # All order operators have a similar structure as well order_op = ((m('<=') | m('>=') | one_of('<', '=', '>'))[:operator] > cut!) >> ->(s) { [operator_class_mapping[s[:operator].map(&:text).join]] } # All the operator expressions have a common structure so abstract it arithmetic_op = (one_of('-', '+', '*', '/')[:operator] > cut!) >> ->(s) { [operator_class_mapping[s[:operator].first.text]] } # Combine the operators into one general_arithmetic_op = order_op | arithmetic_op # {-, +, *, /, <, <=, =, >, >=}(expression {, expression}+) arithmetic_expression = (general_arithmetic_op[:operator] > one_of('(') > whitespace > cut! > r(:expression)[:first] > (whitespace > one_of(',').ignore > whitespace > cut! > r(:expression)).many[:rest] > whitespace > one_of(')') > cut!) >> ->(s) { [s[:operator][0].new(s[:first] + s[:rest])] } # list expressions: list(), list(expression {, expression}*) empty_list = (m('list()') > cut!)>> ->(s) { [ListExp.new([])] } non_empty_list = (m('list(') > whitespace > cut! > r(:expression)[:head] > (whitespace > one_of(',').ignore > whitespace > cut! > r(:expression)).many.any[:tail] > whitespace > one_of(')') > cut!) >> ->(s) { [ListExp.new(s[:head] + s[:tail])] } list_expression = empty_list | non_empty_list # unary list operators unary_list_op = ((m('car') | m('cdr') | m('null?')) > cut!)[:list_operator] >> ->(s) { [operator_class_mapping[s[:list_operator].map(&:text).join]] } unary_list_op_expression = (unary_list_op[:op] > one_of('(') > whitespace > cut! > r(:expression)[:list_expression] > whitespace > one_of(')') > cut!) >> ->(s) { [s[:op][0].new(s[:list_expression][0])] } # binary list operators binary_list_op = (m('cons') > cut!)[:list_operator] >> ->(s) { [operator_class_mapping[s[:list_operator].map(&:text).join]] } binary_list_op_expression = (binary_list_op[:op] > one_of('(') > whitespace > cut! > r(:expression)[:first] > whitespace > one_of(',') > whitespace > cut! > r(:expression)[:second] > whitespace > one_of(')') > cut!) >> ->(s) { [s[:op][0].new(s[:first][0], s[:second][0])] } # unary or binary list expressions list_op_expression = unary_list_op_expression | binary_list_op_expression # cond expression cond_expression = (m('cond') > cut! > (sep > r(:expression) > sep > m('==>').ignore > cut! > sep > r(:expression)).many.any[:conditions] > whitespace > m('end') > cut!) >> ->(s) { [CondExp.new(s[:conditions].each_slice(2).map {|l, r| Condition.new(l, r)})] } # zero?(expression {, expression}+) zero_check = (m('zero?(') > whitespace > cut! > r(:expression)[:first] > (whitespace > one_of(',').ignore > whitespace > cut! > r(:expression)).many.any[:rest] > whitespace > one_of(')') > cut!) >> ->(s) { [ZeroCheck.new(s[:first] + s[:rest])] } # if expression then expression else expression if_expression = (m('if') > sep > cut! > whitespace > r(:expression)[:test] > sep > m('then') > sep > cut! > r(:expression)[:true] > sep > m('else') > sep > cut! > r(:expression)[:false] > cut!) >> ->(s) { [IfExp.new(s[:test][0], s[:true][0], s[:false][0])] } # non-space, non-paren, non-comma characters all become identifiers identifier = one_of(/[^\s\(\),]/).many[:chars] >> ->(s) { [Identifier.new(s[:chars].map(&:text).join)] } # variable = expression assignment = (identifier[:variable] > sep > one_of('=') > sep > cut! > r(:expression)[:value]) >> ->(s) { [Assignment.new(s[:variable][0], s[:value][0])] } # let identifier = expression {, identifier = expression }* in expression let_expression = (m('let') > sep > cut! > assignment[:first] > (whitespace > one_of(',').ignore > cut! > whitespace > assignment).many.any[:rest] > sep > cut! > m('in') > sep > cut! > r(:expression)[:body] > cut!) >> ->(s) { [LetExp.new(s[:first] + s[:rest], s[:body][0])] } # procedures, proc (var1 {, var}*) expression proc_expression = (m('proc') > cut! > whitespace > one_of('(') > identifier[:first] > cut! > (whitespace > one_of(',').ignore > whitespace > identifier).many.any[:rest] > one_of(')') > cut! > sep > r(:expression)[:body]) >> ->(s) { [Procedure.new(s[:first] + s[:rest], s[:body][0])] } # procedure call, lisp style, (expression expression) proc_call_expression = (one_of('(') > cut! > whitespace > r(:expression)[:operator] > (sep > r(:expression)).many[:operands] > whitespace > one_of(')') > cut!) >> ->(s) { [ProcedureCall.new(s[:operator][0], s[:operands])] } # all the expressions together rule :expression, number | arithmetic_expression | zero_check | if_expression | let_expression | list_expression | list_op_expression | cond_expression | proc_expression | proc_call_expression | identifier rule :start, r(:expression) end def self.parse(indexable); @grammar.parse(indexable); end def self.eval(indexable); @grammar.parse(indexable)[0].eval(Env.new({}, {})); end end
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "introspective_admin/version" require "introspective_admin/base" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "introspective_admin" s.version = IntrospectiveAdmin::VERSION s.authors = ["Josh Buermann"] s.email = ["buermann@gmail.com"] s.homepage = "https://github.com/buermann/introspective_admin" s.summary = "Set up basic ActiveAdmin screens for an ActiveRecord model." s.description = "Set up basic ActiveAdmin screens for an ActiveRecord model." s.license = "MIT" s.files = `git ls-files`.split("\n").sort s.test_files = `git ls-files -- spec/*`.split("\n") s.required_ruby_version = '>= 1.9.3' s.add_dependency 'sass-rails' if RUBY_PLATFORM == 'java' s.add_development_dependency "jdbc-sqlite3" else s.add_development_dependency "sqlite3" end s.add_development_dependency "rspec-rails", '>= 3.0' s.add_development_dependency 'devise' s.add_development_dependency 'devise-async' s.add_development_dependency 'machinist' s.add_development_dependency 'simplecov' s.add_development_dependency 'rufus-mnemo' if RUBY_VERSION >= '2.0.0' s.add_development_dependency 'byebug' else s.add_development_dependency 'debugger' end end only keep the debugger around for the dev env $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "introspective_admin/version" require "introspective_admin/base" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "introspective_admin" s.version = IntrospectiveAdmin::VERSION s.authors = ["Josh Buermann"] s.email = ["buermann@gmail.com"] s.homepage = "https://github.com/buermann/introspective_admin" s.summary = "Set up basic ActiveAdmin screens for an ActiveRecord model." s.description = "Set up basic ActiveAdmin screens for an ActiveRecord model." s.license = "MIT" s.files = `git ls-files`.split("\n").sort s.test_files = `git ls-files -- spec/*`.split("\n") s.required_ruby_version = '>= 1.9.3' s.add_dependency 'sass-rails' if RUBY_PLATFORM == 'java' s.add_development_dependency "jdbc-sqlite3" else s.add_development_dependency "sqlite3" if RUBY_VERSION < '2.0.0' s.add_development_dependency 'byebug' end end s.add_development_dependency "rspec-rails", '>= 3.0' s.add_development_dependency 'devise' s.add_development_dependency 'devise-async' s.add_development_dependency 'machinist' s.add_development_dependency 'simplecov' s.add_development_dependency 'rufus-mnemo' end
add jekyll-theme-cayman.gemspec # encoding: utf-8 Gem::Specification.new do |s| s.name = "jekyll-theme-cayman" s.version = "0.0.4" s.license = "CC0-1.0" s.authors = ["Jason Long", "GitHub, Inc."] s.email = ["opensource+jekyll-theme-cayman@github.com"] s.homepage = "https://github.com/pages-themes/cayman" s.summary = "Cayman is a Jekyll theme for GitHub Pages" s.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^((_includes|_layouts|_sass|assets)/|(LICENSE|README)((\.(txt|md|markdown)|$)))}i) end s.platform = Gem::Platform::RUBY s.add_runtime_dependency "jekyll", "~> 3.3" end
# encoding: utf-8 Gem::Specification.new do |s| s.name = "jekyll-theme-hacker" s.version = "0.0.4" s.license = "CC0-1.0" s.authors = ["Jason Costello", "GitHub, Inc."] s.email = ["opensource+jekyll-theme-hacker@github.com"] s.homepage = "https://github.com/pages-themes/hacker" s.summary = "Hacker is a Jekyll theme for GitHub Pages" s.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^((_includes|_layouts|_sass|assets)/|(LICENSE|README)((\.(txt|md|markdown)|$)))}i) end s.platform = Gem::Platform::RUBY s.add_runtime_dependency "jekyll", "~> 3.5" s.add_runtime_dependency "jekyll-seo-tag", "~> 2.0" end :gem: bump # encoding: utf-8 Gem::Specification.new do |s| s.name = "jekyll-theme-hacker" s.version = "0.1.0" s.license = "CC0-1.0" s.authors = ["Jason Costello", "GitHub, Inc."] s.email = ["opensource+jekyll-theme-hacker@github.com"] s.homepage = "https://github.com/pages-themes/hacker" s.summary = "Hacker is a Jekyll theme for GitHub Pages" s.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r{^((_includes|_layouts|_sass|assets)/|(LICENSE|README)((\.(txt|md|markdown)|$)))}i) end s.platform = Gem::Platform::RUBY s.add_runtime_dependency "jekyll", "~> 3.5" s.add_runtime_dependency "jekyll-seo-tag", "~> 2.0" end
# list statuses here to define a person's status in OneBody # any status not listed will cause a person to be 'inactive' in OneBody STATUSES = { pending: [ 'Visitor' ], active: [ 'Member - Active', 'Non-Member - Active' ] }.freeze # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # require 'bundler' Bundler.require require 'csv' COLUMNS = %w[ legacy_id first_name middle_name last_name suffix email alternate_email gender child birthday date2 date3 date4 date5 date6 date7 date8 date9 date10 date11 date12 status sequence mobile_phone work_phone fax note1 note2 note3 note4 note5 family_legacy_id family_name family_last_name family_address1 family_address2 family_city family_state family_zip family_country ].freeze (DATA_PATH, OUT_PATH) = ARGV unless DATA_PATH && OUT_PATH puts 'ERROR: You must pass path to database and path for output csv file' exit 1 end me = DBF::Table.new(File.join(DATA_PATH, 'me.dbf')) ma = DBF::Table.new(File.join(DATA_PATH, 'ma.dbf')) me_codes = DBF::Table.new(File.join(DATA_PATH, 'macodes.dbf')) CODES = me_codes.each_with_object({}) do |code, hash| hash[code['FIELD']] ||= {} hash[code['FIELD']][code['CODE']] = code['DESCRIPT'] end families = ma.each_with_object({}) { |f, h| h[f['MAIL_NO']] = f } def format_date(date) date && date.strftime('%Y-%m-%d') end def status(code) description = CODES.fetch('CATEGORY', {})[code] if (found = STATUSES.detect { |_, matching| matching.include?(description) }) found.first.to_s else 'inactive' end end CSV.open(OUT_PATH, 'w') do |csv| csv << COLUMNS me.each do |person| print '.' family = families[person['MAIL_NO']] csv << [ person['PERS_NO'], person['FIRSTNAME'].strip, person['MIDDLENAME'].strip, person['LASTNAME'].strip, person['SUFFIX'].strip, person['E_MAIL'].strip, person['E_MAIL2'].strip, person['M_F'].strip, { 'Y' => 'false', 'N' => 'true' }[person['ADULT'].strip], format_date(person['BORN']), format_date(person['DATE2']), format_date(person['DATE3']), format_date(person['DATE4']), format_date(person['DATE5']), format_date(person['DATE6']), format_date(person['DATE7']), format_date(person['DATE8']), format_date(person['DATE9']), format_date(person['DATE10']), format_date(person['DATE11']), format_date(person['DATE12']), status(person['STATUS']), person['PERS_NO'], person['MEPHN3'], person['MEPHN1'], person['MEPHN2'], person['NOTE1'], person['NOTE2'], person['NOTE3'], person['NOTE4'], person['NOTE5'], person['MAIL_NO'], family['NAMELINE'].strip, family['LASTNAME'].strip, family['ADDRESS'].strip, family['ADDRESS2'].strip, family['CITY'].strip, family['STATE'].strip, family['ZIP'].strip, family['COUNTRY'].strip ] end end puts puts 'done' Just some notes and code to help find stuff # list statuses here to define a person's status in OneBody # any status not listed will cause a person to be 'inactive' in OneBody STATUSES = { pending: [ 'Visitor' ], active: [ 'Member - Active', 'Non-Member - Active' ] }.freeze # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # require 'bundler' Bundler.require require 'csv' COLUMNS = %w[ legacy_id first_name middle_name last_name suffix email alternate_email gender child birthday date2 date3 date4 date5 date6 date7 date8 date9 date10 date11 date12 status sequence mobile_phone work_phone fax note1 note2 note3 note4 note5 family_legacy_id family_name family_last_name family_address1 family_address2 family_city family_state family_zip family_country ].freeze (DATA_PATH, OUT_PATH) = ARGV unless DATA_PATH && OUT_PATH puts 'ERROR: You must pass path to database and path for output csv file' exit 1 end me = DBF::Table.new(File.join(DATA_PATH, 'me.dbf')) ma = DBF::Table.new(File.join(DATA_PATH, 'ma.dbf')) me_codes = DBF::Table.new(File.join(DATA_PATH, 'macodes.dbf')) CODES = me_codes.each_with_object({}) do |code, hash| hash[code['FIELD']] ||= {} hash[code['FIELD']][code['CODE']] = code['DESCRIPT'] end # SKREF.DBF => descriptions of activities and skills # SK.DBF => relation from person to activity/skill record # for exploration #Dir[File.join(DATA_PATH, '*.DBF')].each do |path| #puts #puts '-' * 10 #p path #DBF::Table.new(path).each do |rec| #p rec.attributes #end #end #exit families = ma.each_with_object({}) { |f, h| h[f['MAIL_NO']] = f } def format_date(date) date && date.strftime('%Y-%m-%d') end def status(code) description = CODES.fetch('CATEGORY', {})[code] if (found = STATUSES.detect { |_, matching| matching.include?(description) }) found.first.to_s else 'inactive' end end CSV.open(OUT_PATH, 'w') do |csv| csv << COLUMNS me.each do |person| print '.' family = families[person['MAIL_NO']] csv << [ person['PERS_NO'], person['FIRSTNAME'].strip, person['MIDDLENAME'].strip, person['LASTNAME'].strip, person['SUFFIX'].strip, person['E_MAIL'].strip, person['E_MAIL2'].strip, person['M_F'].strip, { 'Y' => 'false', 'N' => 'true' }[person['ADULT'].strip], format_date(person['BORN']), format_date(person['DATE2']), format_date(person['DATE3']), format_date(person['DATE4']), format_date(person['DATE5']), format_date(person['DATE6']), format_date(person['DATE7']), format_date(person['DATE8']), format_date(person['DATE9']), format_date(person['DATE10']), format_date(person['DATE11']), format_date(person['DATE12']), status(person['STATUS']), person['PERS_NO'], person['MEPHN3'], person['MEPHN1'], person['MEPHN2'], person['NOTE1'], person['NOTE2'], person['NOTE3'], person['NOTE4'], person['NOTE5'], person['MAIL_NO'], family['NAMELINE'].strip, family['LASTNAME'].strip, family['ADDRESS'].strip, family['ADDRESS2'].strip, family['CITY'].strip, family['STATE'].strip, family['ZIP'].strip, family['COUNTRY'].strip ] end end puts puts 'done'
$:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "notify_user/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "notify_user" s.version = NotifyUser::VERSION s.authors = ["Tom Spacek"] s.email = ["ts@papercloud.com.au"] s.homepage = "http://www.papercloud.com.au" s.summary = "A Rails engine for user notifications." s.description = "Drop-in solution for user notifications. Handles notifying by email, SMS and APNS, plus per-user notification frequency settings and views for checking new notifications." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", ">= 3.2" s.add_dependency "aasm" s.add_dependency "sidekiq" s.add_dependency "kaminari" s.add_dependency "active_model_serializers" s.add_dependency "urbanairship" s.add_dependency "pubnub" s.add_dependency "houston" s.add_dependency "connection_pool" s.add_development_dependency "pg" s.add_development_dependency "rspec-rails" s.add_development_dependency "rspec-sidekiq" s.add_development_dependency "factory_girl_rails" s.add_development_dependency "capybara" s.add_development_dependency "awesome_print" s.add_development_dependency "test_after_commit" s.add_development_dependency "pry" s.test_files = Dir["spec/**/*"] end Removes `urbanairship` from the gemspec. $:.push File.expand_path("../lib", __FILE__) # Maintain your gem's version: require "notify_user/version" # Describe your gem and declare its dependencies: Gem::Specification.new do |s| s.name = "notify_user" s.version = NotifyUser::VERSION s.authors = ["Tom Spacek"] s.email = ["ts@papercloud.com.au"] s.homepage = "http://www.papercloud.com.au" s.summary = "A Rails engine for user notifications." s.description = "Drop-in solution for user notifications. Handles notifying by email, SMS and APNS, plus per-user notification frequency settings and views for checking new notifications." s.files = Dir["{app,config,db,lib}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.md"] s.add_dependency "rails", ">= 3.2" s.add_dependency "aasm" s.add_dependency "sidekiq" s.add_dependency "kaminari" s.add_dependency "active_model_serializers" s.add_dependency "pubnub" s.add_dependency "houston" s.add_dependency "connection_pool" s.add_development_dependency "pg" s.add_development_dependency "rspec-rails" s.add_development_dependency "rspec-sidekiq" s.add_development_dependency "factory_girl_rails" s.add_development_dependency "capybara" s.add_development_dependency "awesome_print" s.add_development_dependency "test_after_commit" s.add_development_dependency "pry" s.test_files = Dir["spec/**/*"] end
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{ss-attachment_fu} s.authors = ["Rick Olson", "Steven Pothoven"] s.summary = %q{attachment_fu as a gem} s.description = %q{This is a fork of Steven Pothoven's attachment_fu including custom some enhancements for Zoo Property} s.email = %q{m.yunan.helmy@gmail.com} s.homepage = %q{https://github.com/yunanhelmy/attachment_fu} s.version = "3.4.0" s.date = %q{2015-09-16} s.files = Dir.glob("{lib,vendor}/**/*") + %w( CHANGELOG LICENSE README.rdoc amazon_s3.yml.tpl rackspace_cloudfiles.yml.tpl ) s.extra_rdoc_files = ["README.rdoc"] s.rdoc_options = ["--inline-source", "--charset=UTF-8"] s.require_paths = ["lib"] s.rubyforge_project = "nowarning" s.rubygems_version = %q{1.8.29} if s.respond_to? :specification_version then s.specification_version = 2 end end bump to 3.4.1 # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{ss-attachment_fu} s.authors = ["Rick Olson", "Steven Pothoven"] s.summary = %q{attachment_fu as a gem} s.description = %q{This is a fork of Steven Pothoven's attachment_fu including custom some enhancements for Zoo Property} s.email = %q{m.yunan.helmy@gmail.com} s.homepage = %q{https://github.com/yunanhelmy/attachment_fu} s.version = "3.4.1" s.date = %q{2015-09-16} s.files = Dir.glob("{lib,vendor}/**/*") + %w( CHANGELOG LICENSE README.rdoc amazon_s3.yml.tpl rackspace_cloudfiles.yml.tpl ) s.extra_rdoc_files = ["README.rdoc"] s.rdoc_options = ["--inline-source", "--charset=UTF-8"] s.require_paths = ["lib"] s.rubyforge_project = "nowarning" s.rubygems_version = %q{1.8.29} if s.respond_to? :specification_version then s.specification_version = 2 end end
# # Cookbook Name:: nfs # Attributes:: default # # Copyright 2011, Eric G. Wolfe # # 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. # include_attribute 'sysctl' # Allowing Version 2, 3 and 4 of NFS to be enabled or disabled. # Default behavior, defer to protocol level(s) supported by kernel. default['nfs']['v2'] = nil default['nfs']['v3'] = nil default['nfs']['v4'] = nil # rquotad needed? default['nfs']['rquotad'] = 'no' # Default options are taken from the Debian guide on static NFS ports default['nfs']['port']['statd'] = 32_765 default['nfs']['port']['statd_out'] = 32_766 default['nfs']['port']['mountd'] = 32_767 default['nfs']['port']['lockd'] = 32_768 default['nfs']['port']['rquotad'] = 32_769 # Number of rpc.nfsd threads to start (default 8) default['nfs']['threads'] = 8 # Default options are based on RHEL6 default['nfs']['packages'] = %w(nfs-utils rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfslock' default['nfs']['service']['server'] = 'nfs' default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) default['nfs']['config']['server_template'] = '/etc/sysconfig/nfs' # idmap recipe attributes default['nfs']['config']['idmap_template'] = '/etc/idmapd.conf' default['nfs']['service']['idmap'] = 'rpcidmapd' default['nfs']['idmap']['domain'] = node['domain'] default['nfs']['idmap']['pipefs_directory'] = '/var/lib/nfs/rpc_pipefs' default['nfs']['idmap']['user'] = 'nobody' default['nfs']['idmap']['group'] = 'nobody' default['nfs']['client-services'] = %w(portmap lock) case node['platform_family'] when 'rhel' case node['platform'] when 'amazon' # For future amazon versions else # RHEL5 edge case package set and portmap name if node['platform_version'].to_i <= 5 default['nfs']['packages'] = %w(nfs-utils portmap) default['nfs']['service']['portmap'] = 'portmap' elsif node['platform_version'].to_i >= 7 default['nfs']['service']['lock'] = 'nfs-lock' default['nfs']['service']['server'] = 'nfs-server' default['nfs']['service']['idmap'] = 'nfs-idmap' if node['platform_version'] == '7.0.1406' default['nfs']['client-services'] = %w(nfs-lock.service) else default['nfs']['client-services'] = %w(nfs-client.target) end end end when 'freebsd' # Packages are installed by default default['nfs']['packages'] = [] default['nfs']['config']['server_template'] = '/etc/rc.conf.d/nfsd' default['nfs']['config']['client_templates'] = %w(/etc/rc.conf.d/mountd) default['nfs']['service']['lock'] = 'lockd' default['nfs']['service']['server'] = 'nfsd' default['nfs']['threads'] = 24 default['nfs']['mountd_flags'] = '-r' if node['nfs']['threads'] >= 0 default['nfs']['server_flags'] = "-u -t -n #{node['nfs']['threads']}" else default['nfs']['server_flags'] = '-u -t' end when 'suse' default['nfs']['packages'] = %w(nfs-client nfs-kernel-server rpcbind) default['nfs']['service']['lock'] = 'nfsserver' default['nfs']['service']['server'] = 'nfsserver' default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) when 'debian' # Use Debian 7 as default case default['nfs']['packages'] = %w(nfs-common rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfs-common' default['nfs']['service']['idmap'] = 'nfs-common' default['nfs']['service']['server'] = 'nfs-kernel-server' default['nfs']['config']['client_templates'] = %w(/etc/default/nfs-common /etc/modprobe.d/lockd.conf) default['nfs']['config']['server_template'] = '/etc/default/nfs-kernel-server' default['nfs']['idmap']['group'] = 'nogroup' # Debian 6.0 if node['platform_version'].to_i <= 6 default['nfs']['packages'] = %w(nfs-common portmap) default['nfs']['service']['portmap'] = 'portmap' end case node['platform'] when 'ubuntu' default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'statd' # There is no lock service on Ubuntu default['nfs']['service']['idmap'] = 'idmapd' default['nfs']['idmap']['pipefs_directory'] = '/run/rpc_pipefs' default['nfs']['service_provider']['idmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['portmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['lock'] = Chef::Provider::Service::Upstart # Ubuntu 13.04 and earlier service name = 'portmap' if node['platform_version'].to_f <= 13.04 default['nfs']['service']['portmap'] = 'portmap' end end end use package portmap instead of rpcbind on Ubuntu <=13.04 # # Cookbook Name:: nfs # Attributes:: default # # Copyright 2011, Eric G. Wolfe # # 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. # include_attribute 'sysctl' # Allowing Version 2, 3 and 4 of NFS to be enabled or disabled. # Default behavior, defer to protocol level(s) supported by kernel. default['nfs']['v2'] = nil default['nfs']['v3'] = nil default['nfs']['v4'] = nil # rquotad needed? default['nfs']['rquotad'] = 'no' # Default options are taken from the Debian guide on static NFS ports default['nfs']['port']['statd'] = 32_765 default['nfs']['port']['statd_out'] = 32_766 default['nfs']['port']['mountd'] = 32_767 default['nfs']['port']['lockd'] = 32_768 default['nfs']['port']['rquotad'] = 32_769 # Number of rpc.nfsd threads to start (default 8) default['nfs']['threads'] = 8 # Default options are based on RHEL6 default['nfs']['packages'] = %w(nfs-utils rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfslock' default['nfs']['service']['server'] = 'nfs' default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) default['nfs']['config']['server_template'] = '/etc/sysconfig/nfs' # idmap recipe attributes default['nfs']['config']['idmap_template'] = '/etc/idmapd.conf' default['nfs']['service']['idmap'] = 'rpcidmapd' default['nfs']['idmap']['domain'] = node['domain'] default['nfs']['idmap']['pipefs_directory'] = '/var/lib/nfs/rpc_pipefs' default['nfs']['idmap']['user'] = 'nobody' default['nfs']['idmap']['group'] = 'nobody' default['nfs']['client-services'] = %w(portmap lock) case node['platform_family'] when 'rhel' case node['platform'] when 'amazon' # For future amazon versions else # RHEL5 edge case package set and portmap name if node['platform_version'].to_i <= 5 default['nfs']['packages'] = %w(nfs-utils portmap) default['nfs']['service']['portmap'] = 'portmap' elsif node['platform_version'].to_i >= 7 default['nfs']['service']['lock'] = 'nfs-lock' default['nfs']['service']['server'] = 'nfs-server' default['nfs']['service']['idmap'] = 'nfs-idmap' if node['platform_version'] == '7.0.1406' default['nfs']['client-services'] = %w(nfs-lock.service) else default['nfs']['client-services'] = %w(nfs-client.target) end end end when 'freebsd' # Packages are installed by default default['nfs']['packages'] = [] default['nfs']['config']['server_template'] = '/etc/rc.conf.d/nfsd' default['nfs']['config']['client_templates'] = %w(/etc/rc.conf.d/mountd) default['nfs']['service']['lock'] = 'lockd' default['nfs']['service']['server'] = 'nfsd' default['nfs']['threads'] = 24 default['nfs']['mountd_flags'] = '-r' if node['nfs']['threads'] >= 0 default['nfs']['server_flags'] = "-u -t -n #{node['nfs']['threads']}" else default['nfs']['server_flags'] = '-u -t' end when 'suse' default['nfs']['packages'] = %w(nfs-client nfs-kernel-server rpcbind) default['nfs']['service']['lock'] = 'nfsserver' default['nfs']['service']['server'] = 'nfsserver' default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) when 'debian' # Use Debian 7 as default case default['nfs']['packages'] = %w(nfs-common rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfs-common' default['nfs']['service']['idmap'] = 'nfs-common' default['nfs']['service']['server'] = 'nfs-kernel-server' default['nfs']['config']['client_templates'] = %w(/etc/default/nfs-common /etc/modprobe.d/lockd.conf) default['nfs']['config']['server_template'] = '/etc/default/nfs-kernel-server' default['nfs']['idmap']['group'] = 'nogroup' # Debian 6.0 if node['platform_version'].to_i <= 6 default['nfs']['packages'] = %w(nfs-common portmap) default['nfs']['service']['portmap'] = 'portmap' end case node['platform'] when 'ubuntu' default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'statd' # There is no lock service on Ubuntu default['nfs']['service']['idmap'] = 'idmapd' default['nfs']['idmap']['pipefs_directory'] = '/run/rpc_pipefs' default['nfs']['service_provider']['idmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['portmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['lock'] = Chef::Provider::Service::Upstart # Ubuntu 13.04 and earlier service name = 'portmap' if node['platform_version'].to_f <= 13.04 default['nfs']['packages'] = %w(nfs-common portmap) default['nfs']['service']['portmap'] = 'portmap' end end end
# # Author:: Joshua Timberman <joshua@chef.io> # Copyright:: Copyright (c) 2012, Chef Software, Inc. <legal@chef.io> # # 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. # default['erlang']['gui_tools'] = false default['erlang']['install_method'] = 'package' default['erlang']['source']['version'] = 'R16B03' default['erlang']['source']['checksum'] = '6133b3410681a5c934e54c76eee1825f96dead8d6a12c31a64f6e160daf0bb06' default['erlang']['source']['build_flags'] = '' default['erlang']['source']['cflags'] = '' default['erlang']['esl']['version'] = nil default['erlang']['esl']['lsb_codename'] = node['lsb'] ? node['lsb']['codename'] : 'no_lsb' Install 18.3 for source installs by default # # Author:: Joshua Timberman <joshua@chef.io> # Copyright:: Copyright (c) 2012-2016, Chef Software, Inc. <legal@chef.io> # # 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. # default['erlang']['gui_tools'] = false default['erlang']['install_method'] = 'package' default['erlang']['source']['version'] = '18.3' default['erlang']['source']['checksum'] = '0e24e32ca4912b7b08d6b8e33c25c107486da410f6c8d56ef81b17f018b0c614' default['erlang']['source']['build_flags'] = '' default['erlang']['source']['cflags'] = '' default['erlang']['esl']['version'] = nil default['erlang']['esl']['lsb_codename'] = node['lsb'] ? node['lsb']['codename'] : 'no_lsb'
include_attribute "kagent" include_attribute "ndb" include_attribute "kzookeeper" default['hops']['versions'] = "2.8.2.2" default['hops']['version'] = "2.8.2.3" default['hops']['hdfs']['user'] = node['install']['user'].empty? ? "hdfs" : node['install']['user'] default['hops']['group'] = node['install']['user'].empty? ? "hadoop" : node['install']['user'] default['hops']['secure_group'] = node['install']['user'].empty? ? "metaserver" : node['install']['user'] default['hops']['yarn']['user'] = node['install']['user'].empty? ? "yarn" : node['install']['user'] default['hops']['yarnapp']['user'] = node['install']['user'].empty? ? "yarnapp" : node['install']['user'] default['hops']['rm']['user'] = node['install']['user'].empty? ? "rmyarn" : node['install']['user'] default['hops']['mr']['user'] = node['install']['user'].empty? ? "mapred" : node['install']['user'] default['hopsworks']['user'] = node['install']['user'].empty? ? "glassfish" : node['install']['user'] default['hops']['jmx']['username'] = "monitorRole" default['hops']['jmx']['password'] = "hadoop" default['hops']['jmx']['adminUsername'] = "adminRole" default['hops']['jmx']['adminPassword'] = "hadoopAdmin" default['hops']['dir'] = node['install']['dir'].empty? ? "/srv" : node['install']['dir'] default['hops']['base_dir'] = node['hops']['dir'] + "/hadoop" default['hops']['home'] = node['hops']['dir'] + "/hadoop-" + node['hops']['version'] default['hops']['logs_dir'] = node['hops']['base_dir'] + "/logs" default['hops']['tmp_dir'] = node['hops']['base_dir'] + "/tmp" default['hops']['conf_dir_parent'] = node['hops']['base_dir'] + "/etc" default['hops']['conf_dir'] = node['hops']['conf_dir_parent'] + "/hadoop" default['hops']['sbin_dir'] = node['hops']['base_dir'] + "/sbin" default['hops']['bin_dir'] = node['hops']['base_dir'] + "/bin" default['hops']['data_dir'] = node['hops']['dir'] + "/hopsdata" default['hops']['dn']['data_dir'] = "file://" + node['hops']['data_dir'] + "/hdfs/dn" default['hops']['dn']['data_dir_permissions'] = '700' default['hops']['nn']['name_dir'] = "file://" + node['hops']['data_dir'] + "/hdfs/nn" default['hops']['nm']['log_dir'] = node['hops']['logs_dir'] + "/userlogs" default['hops']['hdfs']['user_home'] = "/user" default['hops']['hdfs']['blocksize'] = "134217728" default['hops']['hdfs']['umask'] = "0022" default['hops']['url']['primary'] = node['download_url'] + "/hops-" + node['hops']['version'] + ".tgz" default['hops']['url']['secondary'] = "https://www.hops.site/hops-" + node['hops']['version'] + ".tgz" default['hops']['install_protobuf'] = "false" default['hops']['protobuf_url'] = "https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz" default['hops']['hadoop_src_url'] = "https://archive.apache.org/dist/hadoop/core/hadoop-" + node['hops']['version'] + "/hadoop-" + node['hops']['version'] + "-src.tar.gz" default['hops']['nn']['http_port'] = 50070 default['hops']['dn']['http_port'] = 50075 default['hops']['nn']['port'] = 8020 default['hops']['nn']['format_options'] = "-format -nonInteractive" default['hops']['leader_check_interval_ms'] = 1000 default['hops']['missed_hb'] = 1 default['hops']['num_replicas'] = 3 default['hops']['db'] = "hops" default['hops']['nn']['scripts'] = %w{ start-nn.sh stop-nn.sh restart-nn.sh root-start-nn.sh hdfs.sh yarn.sh hadoop.sh } default['hops']['dn']['scripts'] = %w{ start-dn.sh stop-dn.sh restart-dn.sh root-start-dn.sh hdfs.sh yarn.sh hadoop.sh } default['hops']['max_retries'] = 0 default['hops']['reformat'] = "false" default['hops']['format'] = "true" default['hops']['io_buffer_sz'] = 131072 default['hops']['container_cleanup_delay_sec'] = 0 default['hops']['yarn']['scripts'] = %w{ start stop restart root-start } default['hops']['yarn']['ps_port'] = 20888 case node['platform_family'] when "debian" default['hops']['yarn']['vpmem_ratio'] = "50.1" default['hops']['yarn']['vmem_check'] = true when "rhel" default['hops']['yarn']['vpmem_ratio'] = "50.1" default['hops']['yarn']['vmem_check'] = false end default['hops']['yarn']['pmem_check'] = true default['hops']['yarn']['vcores'] = 8 default['hops']['yarn']['min_vcores'] = 1 default['hops']['yarn']['max_vcores'] = 8 default['hops']['yarn']['log_aggregation'] = "true" default['hops']['yarn']['nodemanager']['remote_app_log_dir'] = node['hops']['hdfs']['user_home'] + "/" + node['hops']['yarn']['user'] + "/logs" default['hops']['yarn']['log_retain_secs'] = 86400 default['hops']['yarn']['log_retain_check'] = 100 default['hops']['yarn']['log_roll_interval'] = 3600 default['hops']['yarn']['container_cleanup_delay_sec'] = 0 default['hops']['yarn']['nodemanager_hb_ms'] = "1000" default['hops']['am']['max_retries'] = 2 default['hops']['yarn']['aux_services'] = "spark_shuffle,mapreduce_shuffle" default['hops']['mr']['shuffle_class'] = "org.apache.hadoop.mapred.ShuffleHandler" default['hops']['yarn']['app_classpath'] = "#{node['hops']['home']}, #{node['hops']['home']}/lib/*, #{node['hops']['home']}/etc/hadoop/, #{node['hops']['home']}/share/hadoop/common/*, #{node['hops']['home']}/share/hadoop/common/lib/*, #{node['hops']['home']}/share/hadoop/hdfs/*, #{node['hops']['home']}/share/hadoop/hdfs/lib/*, #{node['hops']['home']}/share/hadoop/yarn/*, #{node['hops']['home']}/share/hadoop/yarn/lib/*, #{node['hops']['home']}/share/hadoop/tools/lib/*, #{node['hops']['home']}/share/hadoop/mapreduce/*, #{node['hops']['home']}/share/hadoop/mapreduce/lib/*" # #{node['hops']['home']}/share/hadoop/yarn/test/*, # #{node['hops']['home']}/share/hadoop/mapreduce/test/*" default['hops']['rm']['addr'] = [] default['hops']['rm']['http_port'] = 8088 default['hops']['nm']['http_port'] = 8042 default['hops']['jhs']['http_port'] = 19888 #default['hops']['rm']['scheduler_class'] = "org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler" default['hops']['rm']['scheduler_class'] = "org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler" default['hops']['rm']['scheduler_capacity']['calculator_class'] = "org.apache.hadoop.yarn.util.resource.DominantResourceCalculator" default['hops']['mr']['tmp_dir'] = "/mapreduce" default['hops']['mr']['staging_dir'] = "#{default['hops']['mr']['tmp_dir']}/#{default['hops']['mr']['user']}/staging" default['hops']['jhs']['inter_dir'] = "/mr-history/done_intermediate" default['hops']['jhs']['done_dir'] = "/mr-history/done" # YARN CONFIG VARIABLES # http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-common/yarn-default.xml # If you need mapreduce, mapreduce.shuffle should be included here. # You can have a comma-separated list of services # http://hadoop.apache.org/docs/r2.1.0-beta/hadoop-mapreduce-client/hadoop-mapreduce-client-core/PluggableShuffleAndPluggableSort.html default['hops']['nn']['jmxport'] = "8077" default['hops']['rm']['jmxport'] = "8082" default['hops']['nm']['jmxport'] = "8083" default['hops']['nn']['public_ips'] = ['10.0.2.15'] default['hops']['nn']['private_ips'] = ['10.0.2.15'] default['hops']['dn']['public_ips'] = ['10.0.2.15'] default['hops']['dn']['private_ips'] = ['10.0.2.15'] default['hops']['rm']['public_ips'] = ['10.0.2.15'] default['hops']['rm']['private_ips'] = ['10.0.2.15'] default['hops']['nm']['public_ips'] = ['10.0.2.15'] default['hops']['nm']['private_ips'] = ['10.0.2.15'] default['hops']['jhs']['public_ips'] = ['10.0.2.15'] default['hops']['jhs']['private_ips'] = ['10.0.2.15'] default['hops']['ps']['public_ips'] = ['10.0.2.15'] default['hops']['ps']['private_ips'] = ['10.0.2.15'] # comma-separated list of namenode addrs default['hops']['nn']['addrs'] = [] # build the native libraries. Is much slower, but removes warning when using services. default['hops']['native_libraries'] = "false" default['hops']['cgroups'] = "false" default['maven']['version'] = "3.2.5" default['maven']['checksum'] = "" # If yarn.nm.memory_mbs is not set, then memory_percent is used instead default['hops']['yarn']['memory_mbs'] = 12000 default['hops']['yarn']['memory_percent'] = "75" default['hops']['limits']['nofile'] = '32768' default['hops']['limits']['nproc'] = '65536' default['hops']['limits']['memory_limit'] = '100000' default['hops']['os_defaults'] = "true" default['hops']['user_envs'] = "true" default['hops']['logging_level'] = "WARN" default['hops']['nn']['direct_memory_size'] = 100 default['hops']['ha_enabled'] = "false" default['hops']['systemd'] = "true" default['hops']['log']['maxfilesize'] = "256MB" default['hops']['log']['maxbackupindex'] = 10 ################################################################### ################################################################### ################################################################### ################################################################### # set the location of libndbclient.so. set-env.sh sets LD_LIBRARY_PATH to find this library. default['ndb']['libndb'] = "#{node['mysql']['version_dir']}/lib" default['mysql']['port'] = default['ndb']['mysql_port'] default['hadoop']['mysql_url'] = "jdbc:mysql://#{node['ndb']['mysql_ip']}:#{default['ndb']['mysql_port']}/" default['hops']['log_level'] = "DEBUG" default['hops']['hdfs']['blocksize'] = "134217728" default['dal']['download_url'] = "#{node['download_url']}/ndb-dal-#{node['hops']['version']}-#{node['ndb']['version']}.jar" default['dal']['lib_url'] = "#{node['download_url']}/libhopsyarn-#{node['hops']['version']}-#{node['ndb']['version']}.so" default['nvidia']['download_url'] = "#{node['download_url']}/nvidia-management-#{node['hops']['version']}-#{node['ndb']['version']}.jar" default['hops']['libnvml_url'] = "#{node['download_url']}/libhopsnvml-#{node['hops']['version']}.so" default['dal']['schema_url'] = "#{node['download_url']}/hops-#{node['hops']['version']}-#{node['ndb']['version']}.sql" default['hops']['recipes'] = %w{ nn dn rm nm jhs ps } # limits.d settings default['hops']['limits']['nofile'] = '32768' default['hops']['limits']['nproc'] = '65536' default['hops']['jhs']['https']['port'] = "19443" default['hops']['rm']['https']['port'] = "8090" default['hops']['nm']['https']['port'] = "45443" default['hops']['yarn']['resource_tracker'] = "false" default['hops']['nn']['direct_memory_size'] = 50 default['hops']['nn']['heap_size'] = 500 default['hops']['nn']['public_ips'] = ['10.0.2.15'] default['hops']['nn']['private_ips'] = ['10.0.2.15'] default['hops']['dn']['public_ips'] = ['10.0.2.15'] default['hops']['dn']['private_ips'] = ['10.0.2.15'] default['hops']['rm']['public_ips'] = ['10.0.2.15'] default['hops']['rm']['private_ips'] = ['10.0.2.15'] default['hops']['nm']['public_ips'] = ['10.0.2.15'] default['hops']['nm']['private_ips'] = ['10.0.2.15'] default['hops']['jhs']['public_ips'] = ['10.0.2.15'] default['hops']['jhs']['private_ips'] = ['10.0.2.15'] default['hops']['ps']['public_ips'] = ['10.0.2.15'] default['hops']['ps']['private_ips'] = ['10.0.2.15'] default['hops']['yarn']['resource_tracker'] = "false" default['hops']['erasure_coding'] = "false" default['hops']['nn']['cache'] = "true" default['hops']['nn']['partition_key'] = "true" default['vagrant'] = "false" default['hops']['reverse_dns_lookup_supported'] = "false" default['hops']['use_systemd'] = "false" default['hops']['yarn']['log_aggregation'] = "true" default['hops']['nn']['format_options'] = "-formatAll" default['hops']['trash']['interval'] = 360 default['hops']['trash']['checkpoint']['interval']= 60 default['hops']['yarn']['nodemanager_ha_enabled'] = "false" default['hops']['yarn']['nodemanager_auto_failover_enabled'] = "false" default['hops']['yarn']['nodemanager_recovery_enabled'] = "true" # NM heartbeats need to be at least twice as long as NDB transaction timeouts default['hops']['yarn']['rm_heartbeat'] = 1000 default['hops']['yarn']['nodemanager_rpc_batch_max_size'] = 60 default['hops']['yarn']['nodemanager_rpc_batch_max_duration']= 60 default['hops']['yarn']['rm_distributed'] = "false" default['hops']['yarn']['nodemanager_rm_streaming_enabled'] = "true" default['hops']['yarn']['client_failover_sleep_base_ms'] = 100 default['hops']['yarn']['client_failover_sleep_max_ms'] = 1000 default['hops']['yarn']['quota_enabled'] = "true" default['hops']['yarn']['quota_monitor_interval'] = 1000 default['hops']['yarn']['quota_ticks_per_credit'] = 60 default['hops']['yarn']['quota_min_ticks_charge'] = 600 default['hops']['yarn']['quota_checkpoint_nbticks'] = 600 default['hops']['yarn']['nm_heapsize_mbs'] = 1000 default['hops']['yarn']['rm_heapsize_mbs'] = 1000 ## SSL Config Attributes## #hdfs-site.xml default['hops']['dfs']['https']['enable'] = "true" default['hops']['dfs']['http']['policy'] = "HTTPS_ONLY" default['hops']['dfs']['datanode']['https']['address'] = "0.0.0.0:50475" default['hops']['dfs']['https']['port'] = "50470" default['hops']['dfs']['namenode']["https-address"] = "0.0.0.0:50470" #mapred-site.xml default['hops']['mapreduce']['jobhistory']['http']['policy'] = "HTTPS_ONLY" default['hops']['mapreduce']['jobhistory']['webapp']['https']['address'] = "#{node['hops']['jhs']['public_ips']}:#{node['hops']['jhs']['https']['port']}" #yarn-site.xml default['hops']['yarn']['http']['policy'] = "HTTPS_ONLY" default['hops']['yarn']['log']['server']['url'] = "https://#{node['hops']['jhs']['private_ips']}:#{node['hops']['jhs']['https']['port']}/jobhistory/logs" default['hops']['yarn']['resourcemanager']['webapp']['https']['address'] = "#{node['hops']['rm']['private_ips']}:#{node['hops']['rm']['https']['port']}" default['hops']['yarn']['nodemanager']['webapp']['https']['address'] = "0.0.0.0:#{node['hops']['nm']['https']['port']}" #ssl-server.xml default['hops']['ssl']['server']['keystore']['password'] = node['hopsworks']['master']['password'] default['hops']['ssl']['server']['keystore']['keypassword'] = node['hopsworks']['master']['password'] ## Keystore and truststore locations are substitued in recipes/default.rb ## They should be removed from here. They are not used anywhere default['hops']['ssl']['server']['keystore']['location'] = "#{node['kagent']['keystore_dir']}/node_server_keystore.jks" default['hops']['ssl']['server']['truststore']['location'] = "#{node['kagent']['keystore_dir']}/node_server_truststore.jks" ## default['hops']['ssl']['server']['truststore']['password'] = node['hopsworks']['master']['password'] #ssl-client.xml default['hops']['ssl']['client']['truststore']['password'] = node['hopsworks']['master']['password'] default['hops']['ssl']['client']['truststore']['location'] = "#{node['kagent']['keystore_dir']}/node_client_truststore.jks" # Number of reader threads of the IPC/RPC server # Default is 1, when TLS is enabled it is advisable to increase it default['hops']['server']['threadpool'] = 3 # RPC TLS default['hops']['rpc']['ssl'] = "false" # Do not verify the hostname default['hops']['hadoop']['ssl']['hostname']['verifier'] = "ALLOW_ALL" # Socket factory for the client default['hops']['hadoop']['rpc']['socket']['factory'] = "org.apache.hadoop.net.HopsSSLSocketFactory" default['hops']['hadoop']['ssl']['enabled']['protocols'] = "TLSv1.2,TLSv1.1,TLSv1,SSLv3" #capacity scheduler queue configuration default['hops']['capacity']['max_app'] = 10000 default['hops']['capacity']['max_am_percent'] = 0.3 #default['hops']['capacity']['resource_calculator_class'] = "org.apache.hadoop.yarn.util.resource.DominantResourceCalculatorGPU" default['hops']['capacity']['resource_calculator_class'] = "org.apache.hadoop.yarn.util.resource.DominantResourceCalculator" default['hops']['capacity']['root_queues'] = "default" default['hops']['capacity']['default_capacity'] = 100 default['hops']['capacity']['user_limit_factor'] = 1 default['hops']['capacity']['default_max_capacity'] = 100 default['hops']['capacity']['default_state'] = "RUNNING" default['hops']['capacity']['default_acl_submit_applications'] = "*" default['hops']['capacity']['default_acl_administer_queue'] = "*" default['hops']['capacity']['queue_mapping'] = "" default['hops']['capacity']['queue_mapping_override']['enable'] = "false" # # Flyway - Database upgrades # default['hops']['flyway']['version'] = "5.0.3" default['hops']['flyway_url'] = node['download_url'] + "/flyway-commandline-#{node['hops']['flyway']['version']}-linux-x64.tar.gz" default['hops']['hopsutil_version'] = "0.4.0" default['hops']['hopsexamples_version'] = "0.4.0" default['hops']['hopsutil']['url'] = "#{node['download_url']}/hops-util-#{node['hops']['hopsutil_version']}.jar" default['hops']['hops_examples_spark']['url'] = "#{node['download_url']}/hops-examples-spark-#{node['hops']['hopsexamples_version']}.jar" #GPU default['hops']['yarn']['min_gpus'] = 0 default['hops']['yarn']['max_gpus'] = 10 default['hops']['gpu'] = "false" default['hops']['yarn']['gpus'] = "*" default['hops']['yarn']['linux_container_local_user'] = node['install']['user'].empty? ? "yarnapp" : node['install']['user'] default['hops']['yarn']['linux_container_limit_users'] = "true" #Store Small files in NDB default['hops']['small_files']['store_in_db'] = "true" default['hops']['small_files']['max_size'] = 65536 default['hops']['small_files']['on_disk']['max_size']['small'] = 2000 default['hops']['small_files']['on_disk']['max_size']['medium'] = 4000 default['hops']['small_files']['on_disk']['max_size']['large'] = 65536 default['hops']['small_files']['in_memory']['max_size'] = 1024 default['hopsmonitor']['default']['private_ips'] = ['10.0.2.15'] default['hopsworks']['default']['private_ips'] = ['10.0.2.15'] Need to include all previous hops version in the hops.versions attribute (#82) include_attribute "kagent" include_attribute "ndb" include_attribute "kzookeeper" default['hops']['versions'] = "2.8.2.1, 2.8.2.2" default['hops']['version'] = "2.8.2.3" default['hops']['hdfs']['user'] = node['install']['user'].empty? ? "hdfs" : node['install']['user'] default['hops']['group'] = node['install']['user'].empty? ? "hadoop" : node['install']['user'] default['hops']['secure_group'] = node['install']['user'].empty? ? "metaserver" : node['install']['user'] default['hops']['yarn']['user'] = node['install']['user'].empty? ? "yarn" : node['install']['user'] default['hops']['yarnapp']['user'] = node['install']['user'].empty? ? "yarnapp" : node['install']['user'] default['hops']['rm']['user'] = node['install']['user'].empty? ? "rmyarn" : node['install']['user'] default['hops']['mr']['user'] = node['install']['user'].empty? ? "mapred" : node['install']['user'] default['hopsworks']['user'] = node['install']['user'].empty? ? "glassfish" : node['install']['user'] default['hops']['jmx']['username'] = "monitorRole" default['hops']['jmx']['password'] = "hadoop" default['hops']['jmx']['adminUsername'] = "adminRole" default['hops']['jmx']['adminPassword'] = "hadoopAdmin" default['hops']['dir'] = node['install']['dir'].empty? ? "/srv" : node['install']['dir'] default['hops']['base_dir'] = node['hops']['dir'] + "/hadoop" default['hops']['home'] = node['hops']['dir'] + "/hadoop-" + node['hops']['version'] default['hops']['logs_dir'] = node['hops']['base_dir'] + "/logs" default['hops']['tmp_dir'] = node['hops']['base_dir'] + "/tmp" default['hops']['conf_dir_parent'] = node['hops']['base_dir'] + "/etc" default['hops']['conf_dir'] = node['hops']['conf_dir_parent'] + "/hadoop" default['hops']['sbin_dir'] = node['hops']['base_dir'] + "/sbin" default['hops']['bin_dir'] = node['hops']['base_dir'] + "/bin" default['hops']['data_dir'] = node['hops']['dir'] + "/hopsdata" default['hops']['dn']['data_dir'] = "file://" + node['hops']['data_dir'] + "/hdfs/dn" default['hops']['dn']['data_dir_permissions'] = '700' default['hops']['nn']['name_dir'] = "file://" + node['hops']['data_dir'] + "/hdfs/nn" default['hops']['nm']['log_dir'] = node['hops']['logs_dir'] + "/userlogs" default['hops']['hdfs']['user_home'] = "/user" default['hops']['hdfs']['blocksize'] = "134217728" default['hops']['hdfs']['umask'] = "0022" default['hops']['url']['primary'] = node['download_url'] + "/hops-" + node['hops']['version'] + ".tgz" default['hops']['url']['secondary'] = "https://www.hops.site/hops-" + node['hops']['version'] + ".tgz" default['hops']['install_protobuf'] = "false" default['hops']['protobuf_url'] = "https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.gz" default['hops']['hadoop_src_url'] = "https://archive.apache.org/dist/hadoop/core/hadoop-" + node['hops']['version'] + "/hadoop-" + node['hops']['version'] + "-src.tar.gz" default['hops']['nn']['http_port'] = 50070 default['hops']['dn']['http_port'] = 50075 default['hops']['nn']['port'] = 8020 default['hops']['nn']['format_options'] = "-format -nonInteractive" default['hops']['leader_check_interval_ms'] = 1000 default['hops']['missed_hb'] = 1 default['hops']['num_replicas'] = 3 default['hops']['db'] = "hops" default['hops']['nn']['scripts'] = %w{ start-nn.sh stop-nn.sh restart-nn.sh root-start-nn.sh hdfs.sh yarn.sh hadoop.sh } default['hops']['dn']['scripts'] = %w{ start-dn.sh stop-dn.sh restart-dn.sh root-start-dn.sh hdfs.sh yarn.sh hadoop.sh } default['hops']['max_retries'] = 0 default['hops']['reformat'] = "false" default['hops']['format'] = "true" default['hops']['io_buffer_sz'] = 131072 default['hops']['container_cleanup_delay_sec'] = 0 default['hops']['yarn']['scripts'] = %w{ start stop restart root-start } default['hops']['yarn']['ps_port'] = 20888 case node['platform_family'] when "debian" default['hops']['yarn']['vpmem_ratio'] = "50.1" default['hops']['yarn']['vmem_check'] = true when "rhel" default['hops']['yarn']['vpmem_ratio'] = "50.1" default['hops']['yarn']['vmem_check'] = false end default['hops']['yarn']['pmem_check'] = true default['hops']['yarn']['vcores'] = 8 default['hops']['yarn']['min_vcores'] = 1 default['hops']['yarn']['max_vcores'] = 8 default['hops']['yarn']['log_aggregation'] = "true" default['hops']['yarn']['nodemanager']['remote_app_log_dir'] = node['hops']['hdfs']['user_home'] + "/" + node['hops']['yarn']['user'] + "/logs" default['hops']['yarn']['log_retain_secs'] = 86400 default['hops']['yarn']['log_retain_check'] = 100 default['hops']['yarn']['log_roll_interval'] = 3600 default['hops']['yarn']['container_cleanup_delay_sec'] = 0 default['hops']['yarn']['nodemanager_hb_ms'] = "1000" default['hops']['am']['max_retries'] = 2 default['hops']['yarn']['aux_services'] = "spark_shuffle,mapreduce_shuffle" default['hops']['mr']['shuffle_class'] = "org.apache.hadoop.mapred.ShuffleHandler" default['hops']['yarn']['app_classpath'] = "#{node['hops']['home']}, #{node['hops']['home']}/lib/*, #{node['hops']['home']}/etc/hadoop/, #{node['hops']['home']}/share/hadoop/common/*, #{node['hops']['home']}/share/hadoop/common/lib/*, #{node['hops']['home']}/share/hadoop/hdfs/*, #{node['hops']['home']}/share/hadoop/hdfs/lib/*, #{node['hops']['home']}/share/hadoop/yarn/*, #{node['hops']['home']}/share/hadoop/yarn/lib/*, #{node['hops']['home']}/share/hadoop/tools/lib/*, #{node['hops']['home']}/share/hadoop/mapreduce/*, #{node['hops']['home']}/share/hadoop/mapreduce/lib/*" # #{node['hops']['home']}/share/hadoop/yarn/test/*, # #{node['hops']['home']}/share/hadoop/mapreduce/test/*" default['hops']['rm']['addr'] = [] default['hops']['rm']['http_port'] = 8088 default['hops']['nm']['http_port'] = 8042 default['hops']['jhs']['http_port'] = 19888 #default['hops']['rm']['scheduler_class'] = "org.apache.hadoop.yarn.server.resourcemanager.scheduler.fifo.FifoScheduler" default['hops']['rm']['scheduler_class'] = "org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler" default['hops']['rm']['scheduler_capacity']['calculator_class'] = "org.apache.hadoop.yarn.util.resource.DominantResourceCalculator" default['hops']['mr']['tmp_dir'] = "/mapreduce" default['hops']['mr']['staging_dir'] = "#{default['hops']['mr']['tmp_dir']}/#{default['hops']['mr']['user']}/staging" default['hops']['jhs']['inter_dir'] = "/mr-history/done_intermediate" default['hops']['jhs']['done_dir'] = "/mr-history/done" # YARN CONFIG VARIABLES # http://hadoop.apache.org/docs/current/hadoop-yarn/hadoop-yarn-common/yarn-default.xml # If you need mapreduce, mapreduce.shuffle should be included here. # You can have a comma-separated list of services # http://hadoop.apache.org/docs/r2.1.0-beta/hadoop-mapreduce-client/hadoop-mapreduce-client-core/PluggableShuffleAndPluggableSort.html default['hops']['nn']['jmxport'] = "8077" default['hops']['rm']['jmxport'] = "8082" default['hops']['nm']['jmxport'] = "8083" default['hops']['nn']['public_ips'] = ['10.0.2.15'] default['hops']['nn']['private_ips'] = ['10.0.2.15'] default['hops']['dn']['public_ips'] = ['10.0.2.15'] default['hops']['dn']['private_ips'] = ['10.0.2.15'] default['hops']['rm']['public_ips'] = ['10.0.2.15'] default['hops']['rm']['private_ips'] = ['10.0.2.15'] default['hops']['nm']['public_ips'] = ['10.0.2.15'] default['hops']['nm']['private_ips'] = ['10.0.2.15'] default['hops']['jhs']['public_ips'] = ['10.0.2.15'] default['hops']['jhs']['private_ips'] = ['10.0.2.15'] default['hops']['ps']['public_ips'] = ['10.0.2.15'] default['hops']['ps']['private_ips'] = ['10.0.2.15'] # comma-separated list of namenode addrs default['hops']['nn']['addrs'] = [] # build the native libraries. Is much slower, but removes warning when using services. default['hops']['native_libraries'] = "false" default['hops']['cgroups'] = "false" default['maven']['version'] = "3.2.5" default['maven']['checksum'] = "" # If yarn.nm.memory_mbs is not set, then memory_percent is used instead default['hops']['yarn']['memory_mbs'] = 12000 default['hops']['yarn']['memory_percent'] = "75" default['hops']['limits']['nofile'] = '32768' default['hops']['limits']['nproc'] = '65536' default['hops']['limits']['memory_limit'] = '100000' default['hops']['os_defaults'] = "true" default['hops']['user_envs'] = "true" default['hops']['logging_level'] = "WARN" default['hops']['nn']['direct_memory_size'] = 100 default['hops']['ha_enabled'] = "false" default['hops']['systemd'] = "true" default['hops']['log']['maxfilesize'] = "256MB" default['hops']['log']['maxbackupindex'] = 10 ################################################################### ################################################################### ################################################################### ################################################################### # set the location of libndbclient.so. set-env.sh sets LD_LIBRARY_PATH to find this library. default['ndb']['libndb'] = "#{node['mysql']['version_dir']}/lib" default['mysql']['port'] = default['ndb']['mysql_port'] default['hadoop']['mysql_url'] = "jdbc:mysql://#{node['ndb']['mysql_ip']}:#{default['ndb']['mysql_port']}/" default['hops']['log_level'] = "DEBUG" default['hops']['hdfs']['blocksize'] = "134217728" default['dal']['download_url'] = "#{node['download_url']}/ndb-dal-#{node['hops']['version']}-#{node['ndb']['version']}.jar" default['dal']['lib_url'] = "#{node['download_url']}/libhopsyarn-#{node['hops']['version']}-#{node['ndb']['version']}.so" default['nvidia']['download_url'] = "#{node['download_url']}/nvidia-management-#{node['hops']['version']}-#{node['ndb']['version']}.jar" default['hops']['libnvml_url'] = "#{node['download_url']}/libhopsnvml-#{node['hops']['version']}.so" default['dal']['schema_url'] = "#{node['download_url']}/hops-#{node['hops']['version']}-#{node['ndb']['version']}.sql" default['hops']['recipes'] = %w{ nn dn rm nm jhs ps } # limits.d settings default['hops']['limits']['nofile'] = '32768' default['hops']['limits']['nproc'] = '65536' default['hops']['jhs']['https']['port'] = "19443" default['hops']['rm']['https']['port'] = "8090" default['hops']['nm']['https']['port'] = "45443" default['hops']['yarn']['resource_tracker'] = "false" default['hops']['nn']['direct_memory_size'] = 50 default['hops']['nn']['heap_size'] = 500 default['hops']['nn']['public_ips'] = ['10.0.2.15'] default['hops']['nn']['private_ips'] = ['10.0.2.15'] default['hops']['dn']['public_ips'] = ['10.0.2.15'] default['hops']['dn']['private_ips'] = ['10.0.2.15'] default['hops']['rm']['public_ips'] = ['10.0.2.15'] default['hops']['rm']['private_ips'] = ['10.0.2.15'] default['hops']['nm']['public_ips'] = ['10.0.2.15'] default['hops']['nm']['private_ips'] = ['10.0.2.15'] default['hops']['jhs']['public_ips'] = ['10.0.2.15'] default['hops']['jhs']['private_ips'] = ['10.0.2.15'] default['hops']['ps']['public_ips'] = ['10.0.2.15'] default['hops']['ps']['private_ips'] = ['10.0.2.15'] default['hops']['yarn']['resource_tracker'] = "false" default['hops']['erasure_coding'] = "false" default['hops']['nn']['cache'] = "true" default['hops']['nn']['partition_key'] = "true" default['vagrant'] = "false" default['hops']['reverse_dns_lookup_supported'] = "false" default['hops']['use_systemd'] = "false" default['hops']['yarn']['log_aggregation'] = "true" default['hops']['nn']['format_options'] = "-formatAll" default['hops']['trash']['interval'] = 360 default['hops']['trash']['checkpoint']['interval']= 60 default['hops']['yarn']['nodemanager_ha_enabled'] = "false" default['hops']['yarn']['nodemanager_auto_failover_enabled'] = "false" default['hops']['yarn']['nodemanager_recovery_enabled'] = "true" # NM heartbeats need to be at least twice as long as NDB transaction timeouts default['hops']['yarn']['rm_heartbeat'] = 1000 default['hops']['yarn']['nodemanager_rpc_batch_max_size'] = 60 default['hops']['yarn']['nodemanager_rpc_batch_max_duration']= 60 default['hops']['yarn']['rm_distributed'] = "false" default['hops']['yarn']['nodemanager_rm_streaming_enabled'] = "true" default['hops']['yarn']['client_failover_sleep_base_ms'] = 100 default['hops']['yarn']['client_failover_sleep_max_ms'] = 1000 default['hops']['yarn']['quota_enabled'] = "true" default['hops']['yarn']['quota_monitor_interval'] = 1000 default['hops']['yarn']['quota_ticks_per_credit'] = 60 default['hops']['yarn']['quota_min_ticks_charge'] = 600 default['hops']['yarn']['quota_checkpoint_nbticks'] = 600 default['hops']['yarn']['nm_heapsize_mbs'] = 1000 default['hops']['yarn']['rm_heapsize_mbs'] = 1000 ## SSL Config Attributes## #hdfs-site.xml default['hops']['dfs']['https']['enable'] = "true" default['hops']['dfs']['http']['policy'] = "HTTPS_ONLY" default['hops']['dfs']['datanode']['https']['address'] = "0.0.0.0:50475" default['hops']['dfs']['https']['port'] = "50470" default['hops']['dfs']['namenode']["https-address"] = "0.0.0.0:50470" #mapred-site.xml default['hops']['mapreduce']['jobhistory']['http']['policy'] = "HTTPS_ONLY" default['hops']['mapreduce']['jobhistory']['webapp']['https']['address'] = "#{node['hops']['jhs']['public_ips']}:#{node['hops']['jhs']['https']['port']}" #yarn-site.xml default['hops']['yarn']['http']['policy'] = "HTTPS_ONLY" default['hops']['yarn']['log']['server']['url'] = "https://#{node['hops']['jhs']['private_ips']}:#{node['hops']['jhs']['https']['port']}/jobhistory/logs" default['hops']['yarn']['resourcemanager']['webapp']['https']['address'] = "#{node['hops']['rm']['private_ips']}:#{node['hops']['rm']['https']['port']}" default['hops']['yarn']['nodemanager']['webapp']['https']['address'] = "0.0.0.0:#{node['hops']['nm']['https']['port']}" #ssl-server.xml default['hops']['ssl']['server']['keystore']['password'] = node['hopsworks']['master']['password'] default['hops']['ssl']['server']['keystore']['keypassword'] = node['hopsworks']['master']['password'] ## Keystore and truststore locations are substitued in recipes/default.rb ## They should be removed from here. They are not used anywhere default['hops']['ssl']['server']['keystore']['location'] = "#{node['kagent']['keystore_dir']}/node_server_keystore.jks" default['hops']['ssl']['server']['truststore']['location'] = "#{node['kagent']['keystore_dir']}/node_server_truststore.jks" ## default['hops']['ssl']['server']['truststore']['password'] = node['hopsworks']['master']['password'] #ssl-client.xml default['hops']['ssl']['client']['truststore']['password'] = node['hopsworks']['master']['password'] default['hops']['ssl']['client']['truststore']['location'] = "#{node['kagent']['keystore_dir']}/node_client_truststore.jks" # Number of reader threads of the IPC/RPC server # Default is 1, when TLS is enabled it is advisable to increase it default['hops']['server']['threadpool'] = 3 # RPC TLS default['hops']['rpc']['ssl'] = "false" # Do not verify the hostname default['hops']['hadoop']['ssl']['hostname']['verifier'] = "ALLOW_ALL" # Socket factory for the client default['hops']['hadoop']['rpc']['socket']['factory'] = "org.apache.hadoop.net.HopsSSLSocketFactory" default['hops']['hadoop']['ssl']['enabled']['protocols'] = "TLSv1.2,TLSv1.1,TLSv1,SSLv3" #capacity scheduler queue configuration default['hops']['capacity']['max_app'] = 10000 default['hops']['capacity']['max_am_percent'] = 0.3 #default['hops']['capacity']['resource_calculator_class'] = "org.apache.hadoop.yarn.util.resource.DominantResourceCalculatorGPU" default['hops']['capacity']['resource_calculator_class'] = "org.apache.hadoop.yarn.util.resource.DominantResourceCalculator" default['hops']['capacity']['root_queues'] = "default" default['hops']['capacity']['default_capacity'] = 100 default['hops']['capacity']['user_limit_factor'] = 1 default['hops']['capacity']['default_max_capacity'] = 100 default['hops']['capacity']['default_state'] = "RUNNING" default['hops']['capacity']['default_acl_submit_applications'] = "*" default['hops']['capacity']['default_acl_administer_queue'] = "*" default['hops']['capacity']['queue_mapping'] = "" default['hops']['capacity']['queue_mapping_override']['enable'] = "false" # # Flyway - Database upgrades # default['hops']['flyway']['version'] = "5.0.3" default['hops']['flyway_url'] = node['download_url'] + "/flyway-commandline-#{node['hops']['flyway']['version']}-linux-x64.tar.gz" default['hops']['hopsutil_version'] = "0.4.0" default['hops']['hopsexamples_version'] = "0.4.0" default['hops']['hopsutil']['url'] = "#{node['download_url']}/hops-util-#{node['hops']['hopsutil_version']}.jar" default['hops']['hops_examples_spark']['url'] = "#{node['download_url']}/hops-examples-spark-#{node['hops']['hopsexamples_version']}.jar" #GPU default['hops']['yarn']['min_gpus'] = 0 default['hops']['yarn']['max_gpus'] = 10 default['hops']['gpu'] = "false" default['hops']['yarn']['gpus'] = "*" default['hops']['yarn']['linux_container_local_user'] = node['install']['user'].empty? ? "yarnapp" : node['install']['user'] default['hops']['yarn']['linux_container_limit_users'] = "true" #Store Small files in NDB default['hops']['small_files']['store_in_db'] = "true" default['hops']['small_files']['max_size'] = 65536 default['hops']['small_files']['on_disk']['max_size']['small'] = 2000 default['hops']['small_files']['on_disk']['max_size']['medium'] = 4000 default['hops']['small_files']['on_disk']['max_size']['large'] = 65536 default['hops']['small_files']['in_memory']['max_size'] = 1024 default['hopsmonitor']['default']['private_ips'] = ['10.0.2.15'] default['hopsworks']['default']['private_ips'] = ['10.0.2.15']
# # Cookbook Name:: practicingruby # Attributes:: default # # Ruby version to install default["practicingruby"]["ruby"]["version"] = "2.0.0-p247" # Defaults for gem_package resource default["practicingruby"]["ruby"]["gem"]["binary"] = "/opt/rubies/#{node["practicingruby"]["ruby"]["version"]}/bin/gem" default["practicingruby"]["ruby"]["gem"]["options"] = "--no-ri --no-rdoc" # Databases to create default["practicingruby"]["databases"] = { "practicing-ruby-development" => true, "practicing-ruby-test" => true, "practicing-ruby-production" => true, } default["practicingruby"]["database"]["practicing-ruby-development"] = { "environment" => "development", "adapter" => "postgresql", "host" => "localhost", "username" => "postgres", "password" => "practicingruby", } default["practicingruby"]["database"]["practicing-ruby-test"] = { "environment" => "test", "adapter" => "postgresql", "host" => "localhost", "username" => "postgres", "password" => "practicingruby", } default["practicingruby"]["database"]["practicing-ruby-production"] = { "environment" => "production", "adapter" => "postgresql", "host" => "localhost", "username" => "postgres", "password" => "practicingruby", } # Deployment user for Capistrano default["practicingruby"]["deploy"]["username"] = "deploy" default["practicingruby"]["deploy"]["ssh_keys"] = [] default["practicingruby"]["deploy"]["sudo_commands"] = ["/usr/local/bin/god"] default["practicingruby"]["deploy"]["home_dir"] = "/home/#{node["practicingruby"]["deploy"]["username"]}" # Rails app settings default["practicingruby"]["rails"]["secret_token"] = "3f8e352c942d04b489795f5a9fe464c0" default["practicingruby"]["rails"]["host"] = "practicingruby.local" default["practicingruby"]["rails"]["cachecooker"]["base_uri"] = "http://practicingruby.local" default["practicingruby"]["rails"]["cachecooker"]["password"] = "supersecret" default["practicingruby"]["rails"]["cachecooker"]["realm"] = "Practicing Ruby" default["practicingruby"]["rails"]["cachecooker"]["username"] = "cachecooker" default["practicingruby"]["rails"]["mailchimp"]["api_key"] = "YOUR-API-KEY" default["practicingruby"]["rails"]["mailchimp"]["list_id"] = "YOUR-LIST-ID" default["practicingruby"]["rails"]["mailchimp"]["sender_email"] = "Your Sender Email" default["practicingruby"]["rails"]["mailchimp"]["sender_name"] = "Your Sender Name" default["practicingruby"]["rails"]["mailchimp"]["testers"] = ["your@email.com"] default["practicingruby"]["rails"]["mailchimp"]["webhook_key"] = "Your/webhook/key" default["practicingruby"]["rails"]["mixpanel"]["api_token"] = "..." default["practicingruby"]["rails"]["stripe"]["publishable_key"] = "PUBLISHABLE" default["practicingruby"]["rails"]["stripe"]["secret_key"] = "SECRET" default["practicingruby"]["rails"]["stripe"]["webhook_path"] = "/oh/yeah/stripe/webhooks" Remove Chef attributes for gem_package # # Cookbook Name:: practicingruby # Attributes:: default # # Ruby version to install default["practicingruby"]["ruby"]["version"] = "2.0.0-p247" # Databases to create default["practicingruby"]["databases"] = { "practicing-ruby-development" => true, "practicing-ruby-test" => true, "practicing-ruby-production" => true, } default["practicingruby"]["database"]["practicing-ruby-development"] = { "environment" => "development", "adapter" => "postgresql", "host" => "localhost", "username" => "postgres", "password" => "practicingruby", } default["practicingruby"]["database"]["practicing-ruby-test"] = { "environment" => "test", "adapter" => "postgresql", "host" => "localhost", "username" => "postgres", "password" => "practicingruby", } default["practicingruby"]["database"]["practicing-ruby-production"] = { "environment" => "production", "adapter" => "postgresql", "host" => "localhost", "username" => "postgres", "password" => "practicingruby", } # Deployment user for Capistrano default["practicingruby"]["deploy"]["username"] = "deploy" default["practicingruby"]["deploy"]["ssh_keys"] = [] default["practicingruby"]["deploy"]["sudo_commands"] = ["/usr/local/bin/god"] default["practicingruby"]["deploy"]["home_dir"] = "/home/#{node["practicingruby"]["deploy"]["username"]}" # Rails app settings default["practicingruby"]["rails"]["secret_token"] = "3f8e352c942d04b489795f5a9fe464c0" default["practicingruby"]["rails"]["host"] = "practicingruby.local" default["practicingruby"]["rails"]["cachecooker"]["base_uri"] = "http://practicingruby.local" default["practicingruby"]["rails"]["cachecooker"]["password"] = "supersecret" default["practicingruby"]["rails"]["cachecooker"]["realm"] = "Practicing Ruby" default["practicingruby"]["rails"]["cachecooker"]["username"] = "cachecooker" default["practicingruby"]["rails"]["mailchimp"]["api_key"] = "YOUR-API-KEY" default["practicingruby"]["rails"]["mailchimp"]["list_id"] = "YOUR-LIST-ID" default["practicingruby"]["rails"]["mailchimp"]["sender_email"] = "Your Sender Email" default["practicingruby"]["rails"]["mailchimp"]["sender_name"] = "Your Sender Name" default["practicingruby"]["rails"]["mailchimp"]["testers"] = ["your@email.com"] default["practicingruby"]["rails"]["mailchimp"]["webhook_key"] = "Your/webhook/key" default["practicingruby"]["rails"]["mixpanel"]["api_token"] = "..." default["practicingruby"]["rails"]["stripe"]["publishable_key"] = "PUBLISHABLE" default["practicingruby"]["rails"]["stripe"]["secret_key"] = "SECRET" default["practicingruby"]["rails"]["stripe"]["webhook_path"] = "/oh/yeah/stripe/webhooks"
# General Attributes for ManageIQ cookbook # DB user definition default['manageiq']['db_username'] = "evm" default['manageiq']['db_password'] = "password" default['manageiq']['ruby'] = "ruby-1.9.3-p551" # URL for manageiq code repo default['manageiq']['code_repo'] = "https://github.com/booz-allen-hamilton/manageiq" # RVM setup for miqbuilder default['rvm']['user_installs'] = [{'user' => 'miqbuilder'}] # Name of the BAH miq automate code file located in the cookbook files directory default['manageiq']['automate_import'] = '' default['manageiq']['domain'] = '' # PostgreSQL Attributes default['postgresql']['password']['postgres'] = node['manageiq']['db_password'] default['postgresql']['pg_hba'] = [{type: 'local', db: 'all', user: 'all', addr: '', method: 'trust'}, {type: 'host', db: 'all', user: 'all', addr: '127.0.0.1/32 ', method: 'trust'}] default['postgresql']['config']['port'] = 5432 default['postgresql']['host'] = "127.0.0.1" default['postgresql']['config']['listen_addresses'] = "*" update ruby version # General Attributes for ManageIQ cookbook # DB user definition default['manageiq']['db_username'] = "evm" default['manageiq']['db_password'] = "password" default['manageiq']['ruby'] = "2.0.0" # URL for manageiq code repo default['manageiq']['code_repo'] = "https://github.com/booz-allen-hamilton/manageiq" # RVM setup for miqbuilder default['rvm']['user_installs'] = [{'user' => 'miqbuilder'}] # Name of the BAH miq automate code file located in the cookbook files directory default['manageiq']['automate_import'] = '' default['manageiq']['domain'] = '' # PostgreSQL Attributes default['postgresql']['password']['postgres'] = node['manageiq']['db_password'] default['postgresql']['pg_hba'] = [{type: 'local', db: 'all', user: 'all', addr: '', method: 'trust'}, {type: 'host', db: 'all', user: 'all', addr: '127.0.0.1/32 ', method: 'trust'}] default['postgresql']['config']['port'] = 5432 default['postgresql']['host'] = "127.0.0.1" default['postgresql']['config']['listen_addresses'] = "*"
# # Cookbook Name:: nfs # Attributes:: default # # Copyright 2011, Eric G. Wolfe # # 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. # # Allowing Version 2, 3 and 4 of NFS to be enabled or disabled. # Default behavior, defer to protocol level(s) supported by kernel. default['nfs']['v2'] = nil default['nfs']['v3'] = nil default['nfs']['v4'] = nil # rquotad needed? default['nfs']['rquotad'] = 'no' # Default options are taken from the Debian guide on static NFS ports default['nfs']['port']['statd'] = 32_765 default['nfs']['port']['statd_out'] = 32_766 default['nfs']['port']['mountd'] = 32_767 default['nfs']['port']['lockd'] = 32_768 default['nfs']['port']['rquotad'] = 32_769 # Number of rpc.nfsd threads to start (default 8) default['nfs']['threads'] = 8 # Default options are based on RHEL6 default['nfs']['packages'] = %w(nfs-utils rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfslock' default['nfs']['service']['server'] = 'nfs' default['nfs']['service_provider']['lock'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['service_provider']['portmap'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['service_provider']['server'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) default['nfs']['config']['server_template'] = '/etc/sysconfig/nfs' # idmap recipe attributes default['nfs']['config']['idmap_template'] = '/etc/idmapd.conf' default['nfs']['service']['idmap'] = 'rpcidmapd' default['nfs']['service_provider']['idmap'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['idmap']['domain'] = node['domain'] default['nfs']['idmap']['pipefs_directory'] = '/var/lib/nfs/rpc_pipefs' default['nfs']['idmap']['user'] = 'nobody' default['nfs']['idmap']['group'] = 'nobody' case node['platform_family'] when 'rhel' # RHEL5 edge case package set and portmap name if node['platform_version'].to_i <= 5 default['nfs']['packages'] = %w(nfs-utils portmap) default['nfs']['service']['portmap'] = 'portmap' elsif node['platform_version'].to_i >= 7 default['nfs']['service']['lock'] = 'nfs-lock' default['nfs']['service']['server'] = 'nfs-server' default['nfs']['service']['idmap'] = 'nfs-idmap' end when 'freebsd' # Packages are installed by default default['nfs']['packages'] = [] default['nfs']['config']['server_template'] = '/etc/rc.conf.d/nfsd' default['nfs']['config']['client_templates'] = %w(/etc/rc.conf.d/mountd) default['nfs']['service']['lock'] = 'lockd' default['nfs']['service']['server'] = 'nfsd' default['nfs']['threads'] = 24 default['nfs']['mountd_flags'] = '-r' if node['nfs']['threads'] >= 0 default['nfs']['server_flags'] = "-u -t -n #{node['nfs']['threads']}" else default['nfs']['server_flags'] = '-u -t' end when 'suse' default['nfs']['packages'] = %w(nfs-client nfs-kernel-server rpcbind) default['nfs']['service']['lock'] = 'nfsserver' default['nfs']['service']['server'] = 'nfsserver' default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) when 'debian' # Use Debian 7 as default case default['nfs']['packages'] = %w(nfs-common rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfs-common' default['nfs']['service']['idmap'] = 'nfs-common' default['nfs']['service']['server'] = 'nfs-kernel-server' default['nfs']['config']['client_templates'] = %w(/etc/default/nfs-common /etc/modprobe.d/lockd.conf) default['nfs']['config']['server_template'] = '/etc/default/nfs-kernel-server' default['nfs']['idmap']['group'] = 'nogroup' # Debian 6.0 if node['platform_version'].to_i <= 6 default['nfs']['packages'] = %w(nfs-common portmap) default['nfs']['service']['portmap'] = 'portmap' end case node['platform'] when 'ubuntu' # Start with latest release, and work backwards default['nfs']['service']['portmap'] = 'rpcbind-boot' default['nfs']['service']['lock'] = 'statd' default['nfs']['service']['idmap'] = 'idmapd' default['nfs']['idmap']['pipefs_directory'] = '/run/rpc_pipefs' default['nfs']['service_provider']['idmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['portmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['lock'] = Chef::Provider::Service::Upstart # Ubuntu < 11.04 edge case package set and portmap name if node['platform_version'].to_f <= 11.04 default['nfs']['service']['portmap'] = 'rpcbind' end end end avoid recipe compile error on Windows # # Cookbook Name:: nfs # Attributes:: default # # Copyright 2011, Eric G. Wolfe # # 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. # # Allowing Version 2, 3 and 4 of NFS to be enabled or disabled. # Default behavior, defer to protocol level(s) supported by kernel. default['nfs']['v2'] = nil default['nfs']['v3'] = nil default['nfs']['v4'] = nil # rquotad needed? default['nfs']['rquotad'] = 'no' # Default options are taken from the Debian guide on static NFS ports default['nfs']['port']['statd'] = 32_765 default['nfs']['port']['statd_out'] = 32_766 default['nfs']['port']['mountd'] = 32_767 default['nfs']['port']['lockd'] = 32_768 default['nfs']['port']['rquotad'] = 32_769 # Number of rpc.nfsd threads to start (default 8) default['nfs']['threads'] = 8 unless node['platform_family'] == 'windows' # Default options are based on RHEL6 default['nfs']['packages'] = %w(nfs-utils rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfslock' default['nfs']['service']['server'] = 'nfs' default['nfs']['service_provider']['lock'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['service_provider']['portmap'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['service_provider']['server'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) default['nfs']['config']['server_template'] = '/etc/sysconfig/nfs' # idmap recipe attributes default['nfs']['config']['idmap_template'] = '/etc/idmapd.conf' default['nfs']['service']['idmap'] = 'rpcidmapd' default['nfs']['service_provider']['idmap'] = Chef::Platform.find_provider_for_node node, :service default['nfs']['idmap']['domain'] = node['domain'] default['nfs']['idmap']['pipefs_directory'] = '/var/lib/nfs/rpc_pipefs' default['nfs']['idmap']['user'] = 'nobody' default['nfs']['idmap']['group'] = 'nobody' end case node['platform_family'] when 'rhel' # RHEL5 edge case package set and portmap name if node['platform_version'].to_i <= 5 default['nfs']['packages'] = %w(nfs-utils portmap) default['nfs']['service']['portmap'] = 'portmap' elsif node['platform_version'].to_i >= 7 default['nfs']['service']['lock'] = 'nfs-lock' default['nfs']['service']['server'] = 'nfs-server' default['nfs']['service']['idmap'] = 'nfs-idmap' end when 'freebsd' # Packages are installed by default default['nfs']['packages'] = [] default['nfs']['config']['server_template'] = '/etc/rc.conf.d/nfsd' default['nfs']['config']['client_templates'] = %w(/etc/rc.conf.d/mountd) default['nfs']['service']['lock'] = 'lockd' default['nfs']['service']['server'] = 'nfsd' default['nfs']['threads'] = 24 default['nfs']['mountd_flags'] = '-r' if node['nfs']['threads'] >= 0 default['nfs']['server_flags'] = "-u -t -n #{node['nfs']['threads']}" else default['nfs']['server_flags'] = '-u -t' end when 'suse' default['nfs']['packages'] = %w(nfs-client nfs-kernel-server rpcbind) default['nfs']['service']['lock'] = 'nfsserver' default['nfs']['service']['server'] = 'nfsserver' default['nfs']['config']['client_templates'] = %w(/etc/sysconfig/nfs) when 'debian' # Use Debian 7 as default case default['nfs']['packages'] = %w(nfs-common rpcbind) default['nfs']['service']['portmap'] = 'rpcbind' default['nfs']['service']['lock'] = 'nfs-common' default['nfs']['service']['idmap'] = 'nfs-common' default['nfs']['service']['server'] = 'nfs-kernel-server' default['nfs']['config']['client_templates'] = %w(/etc/default/nfs-common /etc/modprobe.d/lockd.conf) default['nfs']['config']['server_template'] = '/etc/default/nfs-kernel-server' default['nfs']['idmap']['group'] = 'nogroup' # Debian 6.0 if node['platform_version'].to_i <= 6 default['nfs']['packages'] = %w(nfs-common portmap) default['nfs']['service']['portmap'] = 'portmap' end case node['platform'] when 'ubuntu' # Start with latest release, and work backwards default['nfs']['service']['portmap'] = 'rpcbind-boot' default['nfs']['service']['lock'] = 'statd' default['nfs']['service']['idmap'] = 'idmapd' default['nfs']['idmap']['pipefs_directory'] = '/run/rpc_pipefs' default['nfs']['service_provider']['idmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['portmap'] = Chef::Provider::Service::Upstart default['nfs']['service_provider']['lock'] = Chef::Provider::Service::Upstart # Ubuntu < 11.04 edge case package set and portmap name if node['platform_version'].to_f <= 11.04 default['nfs']['service']['portmap'] = 'rpcbind' end end end
default['android-sdk']['name'] = 'android-sdk' default['android-sdk']['owner'] = 'root' default['android-sdk']['group'] = 'root' default['android-sdk']['setup_root'] = nil # ark defaults (/usr/local) is used if this attribute is not defined default['android-sdk']['with_symlink'] = true # use ark's :install action when true; use ark's :put action when false default['android-sdk']['set_environment_variables'] = true default['android-sdk']['version'] = '24.4' default['android-sdk']['checksum'] = 'f2bb546534d16e2004665257ee530060338c684adad14a49cd4bbde08098d8a4' default['android-sdk']['download_url'] = "http://dl.google.com/android/android-sdk_r#{node['android-sdk']['version']}-linux.tgz" # # List of Android SDK components to preinstall: # Selection based on # - Platform usage statistics (see http://developer.android.com/about/dashboards/index.html) # - Build Tools releases: http://developer.android.com/tools/revisions/build-tools.html # # Hint: # Add 'tools' to the list below if you wish to get the latest version, # without having to adapt 'version' and 'checksum' attributes of this cookbook. # Note that it will require (waste) some extra download effort. # default['android-sdk']['components'] = %w( platform-tools build-tools-23.0.1 android-22 sys-img-armeabi-v7a-android-22 android-21 sys-img-armeabi-v7a-android-21 android-20 sys-img-armeabi-v7a-android-wear-20 android-19 sys-img-armeabi-v7a-android-19 android-18 sys-img-armeabi-v7a-android-18 android-17 sys-img-armeabi-v7a-android-17 android-16 sys-img-armeabi-v7a-android-16 android-15 sys-img-armeabi-v7a-android-15 android-10 extra-android-support extra-google-google_play_services extra-google-m2repository extra-android-m2repository ) default['android-sdk']['license']['white_list'] = %w(.+) default['android-sdk']['license']['black_list'] = [] # e.g. ['intel-.+', 'mips-.+', 'android-wear-sdk-license-.+'] default['android-sdk']['license']['default_answer'] = 'n' # 'y' or 'n' ('yes' or 'no') default['android-sdk']['scripts']['path'] = '/usr/local/bin' default['android-sdk']['scripts']['owner'] = node['android-sdk']['owner'] default['android-sdk']['scripts']['group'] = node['android-sdk']['group'] default['android-sdk']['java_from_system'] = false default['android-sdk']['maven-rescue'] = false Install some Android 6.0 (API level 23) components default['android-sdk']['name'] = 'android-sdk' default['android-sdk']['owner'] = 'root' default['android-sdk']['group'] = 'root' default['android-sdk']['setup_root'] = nil # ark defaults (/usr/local) is used if this attribute is not defined default['android-sdk']['with_symlink'] = true # use ark's :install action when true; use ark's :put action when false default['android-sdk']['set_environment_variables'] = true default['android-sdk']['version'] = '24.4' default['android-sdk']['checksum'] = 'f2bb546534d16e2004665257ee530060338c684adad14a49cd4bbde08098d8a4' default['android-sdk']['download_url'] = "http://dl.google.com/android/android-sdk_r#{node['android-sdk']['version']}-linux.tgz" # # List of Android SDK components to preinstall: # Selection based on # - Platform usage statistics (see http://developer.android.com/about/dashboards/index.html) # - Build Tools releases: http://developer.android.com/tools/revisions/build-tools.html # # Hint: # Add 'tools' to the list below if you wish to get the latest version, # without having to adapt 'version' and 'checksum' attributes of this cookbook. # Note that it will require (waste) some extra download effort. # default['android-sdk']['components'] = %w( platform-tools build-tools-23.0.1 android-23 sys-img-armeabi-v7a-android-23 sys-img-armeabi-v7a-android-tv-23 android-22 sys-img-armeabi-v7a-android-22 android-21 sys-img-armeabi-v7a-android-21 android-20 sys-img-armeabi-v7a-android-wear-20 android-19 sys-img-armeabi-v7a-android-19 android-18 sys-img-armeabi-v7a-android-18 android-17 sys-img-armeabi-v7a-android-17 android-16 sys-img-armeabi-v7a-android-16 android-15 sys-img-armeabi-v7a-android-15 android-10 extra-android-support extra-google-google_play_services extra-google-m2repository extra-android-m2repository ) default['android-sdk']['license']['white_list'] = %w(.+) default['android-sdk']['license']['black_list'] = [] # e.g. ['intel-.+', 'mips-.+', 'android-wear-sdk-license-.+'] default['android-sdk']['license']['default_answer'] = 'n' # 'y' or 'n' ('yes' or 'no') default['android-sdk']['scripts']['path'] = '/usr/local/bin' default['android-sdk']['scripts']['owner'] = node['android-sdk']['owner'] default['android-sdk']['scripts']['group'] = node['android-sdk']['group'] default['android-sdk']['java_from_system'] = false default['android-sdk']['maven-rescue'] = false
# # Author:: Mike Moate (<chef@mikemoate.co.uk>) # Cookbook Name:: mac_bootstrap # Attributes:: default # default['homebrew']['formulas'] = ["git"] default['homebrew']['casks'] = ["google-chrome"] Initial list of software to install Mike's initial list of software to install. Eventually need to break this into common layers (core, developer etc) and user specific installs (an attributes file named after the user most likely). # # Author:: Mike Moate (<chef@mikemoate.co.uk>) # Cookbook Name:: mac_bootstrap # Attributes:: default # default['homebrew']['formulas'] = [ "git" ] default['homebrew']['casks'] = [ "beyond-compare", "sublime-text3", "royal-tsx", "joinme", "java", "flash-player", "the-unarchiver", "hipchat", "wireshark", "chefdk", "vagrant", "virtualbox", "packer", "google-drive", "skype", "inssider", "dropbox", "sourcetree" ]
default[:neo4j][:docker_image]="tpires/neo4j" default[:neo4j][:docker_image_tag]="latest" default[:neo4j][:docker_container]="neo4j" default[:neo4j][:data_path]="/var/data/neo4j" default[:neo4j][:config_path]="/etc/neo4j" default[:neo4j][:container_data_path]="/var/lib/neo4j/data" default[:neo4j][:container_config_path]="/var/lib/neo4j/config" default[:neo4j][:config]={} default[:neo4j][:java][:initmemory]="1g" default[:neo4j][:java][:maxmemory]="4g" Changed memory defaults to megabytes default[:neo4j][:docker_image]="tpires/neo4j" default[:neo4j][:docker_image_tag]="latest" default[:neo4j][:docker_container]="neo4j" default[:neo4j][:data_path]="/var/data/neo4j" default[:neo4j][:config_path]="/etc/neo4j" default[:neo4j][:container_data_path]="/var/lib/neo4j/data" default[:neo4j][:container_config_path]="/var/lib/neo4j/config" default[:neo4j][:config]={} default[:neo4j][:java][:initmemory]=1024 default[:neo4j][:java][:maxmemory]=4096
# Cookbook Name:: collectd-abiquo # Attributes:: collectd-abiquo # # Copyright 2014, Abiquo # # 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. # Package to install case node['platform'] when 'ubuntu' default['collectd_abiquo']['packages'] = ['collectd-core', 'libpython2.7'] when 'centos' override['collectd']['conf_dir'] = '/etc' override['collectd']['plugin_dir'] = '/usr/lib64/collectd' default['collectd_abiquo']['packages'] = ['collectd'] else default['collectd_abiquo']['packages'] = ['collectd'] end # Default plugin configuration default['collectd_abiquo']['version'] = 'master' default['collectd_abiquo']['url'] = "https://cdn.rawgit.com/abiquo/collectd-abiquo-cookbook/#{node['collectd_abiquo']['version']}/files/default/abiquo.py" default['collectd_abiquo']['plugins'] = ['cpu', 'disk', 'interface'] default['collectd_abiquo']['log_traces'] = true # Fix typo in the collectd-lib cookbook override['collectd']['extra_conf_dir'] = '/etc/collectd/collectd.conf.d' Configure paths dynamically based on the node arch # Cookbook Name:: collectd-abiquo # Attributes:: collectd-abiquo # # Copyright 2014, Abiquo # # 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. # Package to install case node['platform'] when 'ubuntu' default['collectd_abiquo']['packages'] = ['collectd-core', 'libpython2.7'] when 'centos' default['collectd_abiquo']['packages'] = ['collectd'] override['collectd']['conf_dir'] = '/etc' if node['kernel']['machine'] == 'x86_64' override['collectd']['plugin_dir'] = '/usr/lib64/collectd' end else default['collectd_abiquo']['packages'] = ['collectd'] end # Default plugin configuration default['collectd_abiquo']['version'] = 'master' default['collectd_abiquo']['url'] = "https://rawgit.com/abiquo/collectd-abiquo-cookbook/#{node['collectd_abiquo']['version']}/files/default/abiquo.py" default['collectd_abiquo']['plugins'] = ['cpu', 'disk', 'interface'] default['collectd_abiquo']['log_traces'] = true # Fix typo in the collectd-lib cookbook override['collectd']['extra_conf_dir'] = '/etc/collectd/collectd.conf.d'
default[:ucscGenomeBrowser][:jksrc][:url]="http://hgdownload.cse.ucsc.edu/admin/jksrc.zip" # 2016-04-04 default[:ucscGenomeBrowser][:jksrc][:checksum]="61c59dfc1671a8d0038d380f7fa833c9afb545668884f9b2d2e6037c3212d02b" Update jksrc.zip sha256sum default[:ucscGenomeBrowser][:jksrc][:url]="http://hgdownload.cse.ucsc.edu/admin/jksrc.zip" # 2016-04-22 default[:ucscGenomeBrowser][:jksrc][:checksum]="c24d16af0112f2240cb1b9efc70ac8f84ef089b443099551fe395de8d454d5bb"
default['nrpe']['manage'] = true default['nrpe']['user'] = 'nagios' default['nrpe']['group'] = 'nagios' default['nrpe']['port'] = '5666' default['nrpe']['packages'] = value_for_platform( %w(centos redhat fedora amazon) => { 'default' => %w(perl perl-Switch nrpe nagios-plugins-all nagios-plugins-nrpe) }, %w(ubuntu) => { 'default' => %w(nagios-nrpe-server nagios-plugins nagios-plugins-basic nagios-plugins-standard nagios-snmp-plugins nagios-plugins-extra nagios-nrpe-plugin), '14.04' => %w(nagios-nrpe-server nagios-plugins nagios-plugins-basic nagios-plugins-standard nagios-snmp-plugins nagios-plugins-extra nagios-nrpe-plugin nagios-plugins-common nagios-plugins-contrib) } ) default['nrpe']['service_name'] = value_for_platform_family( 'debian' => 'nagios-nrpe-server', 'rhel' => 'nrpe' ) default['nrpe']['pid_dir'] = value_for_platform_family( 'debian' => '/var/run/nagios', 'rhel' => '/var/run' ) default['nrpe']['conf_dir'] = '/etc/nagios' default['nrpe']['include_dir'] = ::File.join(node['nrpe']['conf_dir'], 'nrpe.d') default['nrpe']['conf_file'] = ::File.join(node['nrpe']['conf_dir'], 'nrpe.cfg') default['nrpe']['options']['allow_arguments'] = 0 default['nrpe']['options']['allowed_hosts'] = %w(localhost 127.0.0.1) default['nrpe']['options']['debug'] = 0 default['nrpe']['options']['command_timeout'] = 60 default['nrpe']['options']['connection_timeout'] = 300 case node['platform_family'] when 'rhel' case node['kernel']['machine'] when 'x86_64' default['nrpe']['plugins_dir'] = '/usr/lib64/nagios/plugins' else default['nrpe']['plugins_dir'] = '/usr/lib/nagios/plugins' end when 'debian' default['nrpe']['plugins_dir'] = '/usr/lib/nagios/plugins' end default['nrpe']['checks'] = {} issue #3, fix default['nrpe']['manage'] = true default['nrpe']['user'] = 'nagios' default['nrpe']['group'] = 'nagios' default['nrpe']['port'] = '5666' default['nrpe']['packages'] = value_for_platform( %w(centos redhat fedora amazon) => { 'default' => %w(perl perl-Switch nrpe nagios-plugins-all nagios-plugins-nrpe) }, %w(ubuntu) => { 'default' => %w(nagios-nrpe-server nagios-plugins nagios-plugins-basic nagios-plugins-standard nagios-snmp-plugins nagios-plugins-extra), '14.04' => %w(nagios-nrpe-server nagios-plugins nagios-plugins-basic nagios-plugins-standard nagios-snmp-plugins nagios-plugins-extra nagios-plugins-common nagios-plugins-contrib) } ) default['nrpe']['service_name'] = value_for_platform_family( 'debian' => 'nagios-nrpe-server', 'rhel' => 'nrpe' ) default['nrpe']['pid_dir'] = value_for_platform_family( 'debian' => '/var/run/nagios', 'rhel' => '/var/run' ) default['nrpe']['conf_dir'] = '/etc/nagios' default['nrpe']['include_dir'] = ::File.join(node['nrpe']['conf_dir'], 'nrpe.d') default['nrpe']['conf_file'] = ::File.join(node['nrpe']['conf_dir'], 'nrpe.cfg') default['nrpe']['options']['allow_arguments'] = 0 default['nrpe']['options']['allowed_hosts'] = %w(localhost 127.0.0.1) default['nrpe']['options']['debug'] = 0 default['nrpe']['options']['command_timeout'] = 60 default['nrpe']['options']['connection_timeout'] = 300 case node['platform_family'] when 'rhel' case node['kernel']['machine'] when 'x86_64' default['nrpe']['plugins_dir'] = '/usr/lib64/nagios/plugins' else default['nrpe']['plugins_dir'] = '/usr/lib/nagios/plugins' end when 'debian' default['nrpe']['plugins_dir'] = '/usr/lib/nagios/plugins' end default['nrpe']['checks'] = {}
# # Copyright:: Copyright (c) 2012 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['omnibus'].tap do |omnibus| omnibus['build_user'] = 'omnibus' omnibus['build_user_home'] = nil if platform_family == 'windows' omnibus['build_user_group'] = 'Administrators' omnibus['install_dir'] = windows_safe_path_join(ENV['SYSTEMDRIVE'], 'omnibus') omnibus['cache_dir'] = windows_safe_path_join(ENV['SYSTEMDRIVE'], 'cache', 'omnibus') omnibus['ruby_version'] = '2.0.0-p481' # 2.1.1 does not exist for Windows yet! :( # Passsword must be clear-text on Windows. You should store this password in # an encrypted data bag item and override in your wrapper. omnibus['build_user_password'] = 'getonthebus' else omnibus['build_user_group'] = 'omnibus' omnibus['install_dir'] = '/opt/omnibus' omnibus['cache_dir'] = '/var/cache/omnibus' omnibus['ruby_version'] = '2.1.1' # You should store this password in an encrypted data bag item and override # in your wrapper. Per Chef's requirements on Unix systems, the password below is # hashed using the MD5-based BSD password algorithm 1. The plain text version # is 'getonthebus'. omnibus['build_user_password'] = '$1$4/uIC5oO$Q/Ggd/DztxWAew8/MKr9j0' end end bump ruby version to 2.1.2, fixes build failure related to readline # # Copyright:: Copyright (c) 2012 Chef Software, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['omnibus'].tap do |omnibus| omnibus['build_user'] = 'omnibus' omnibus['build_user_home'] = nil omnibus['ruby_version'] = '2.1.2' if platform_family == 'windows' omnibus['build_user_group'] = 'Administrators' omnibus['install_dir'] = windows_safe_path_join(ENV['SYSTEMDRIVE'], 'omnibus') omnibus['cache_dir'] = windows_safe_path_join(ENV['SYSTEMDRIVE'], 'cache', 'omnibus') omnibus['ruby_version'] = '2.0.0-p481' # 2.1.1 does not exist for Windows yet! :( # Passsword must be clear-text on Windows. You should store this password in # an encrypted data bag item and override in your wrapper. omnibus['build_user_password'] = 'getonthebus' else omnibus['build_user_group'] = 'omnibus' omnibus['install_dir'] = '/opt/omnibus' omnibus['cache_dir'] = '/var/cache/omnibus' omnibus['ruby_version'] = '2.1.1' # You should store this password in an encrypted data bag item and override # in your wrapper. Per Chef's requirements on Unix systems, the password below is # hashed using the MD5-based BSD password algorithm 1. The plain text version # is 'getonthebus'. omnibus['build_user_password'] = '$1$4/uIC5oO$Q/Ggd/DztxWAew8/MKr9j0' end end
node.default['graylog2'] ||= {} node.default['mongodb'] ||= {} # General default['graylog2']['major_version'] = '2.2' default['graylog2']['server']['version'] = '2.2.1-1' ## By default the cookbook installs a meta package containing the key and URL for the current Graylog repository. To disable ## this behavior set your own repository informations here. default['graylog2']['server']['repos'] = { # 'rhel' => { # 'url' => "https://packages.graylog2.org/repo/el/stable/#{node['graylog2']['major_version']}/x86_64/", # 'key' => 'https://raw.githubusercontent.com/Graylog2/fpm-recipes/master/recipes/graylog-repository/files/rpm/RPM-GPG-KEY-graylog' # }, # 'debian' => { # 'url' => "https://packages.graylog2.org/repo/debian/", # 'distribution' => '', # 'components' => ['stable', node['graylog2']['major_version']], # 'key' => 'https://raw.githubusercontent.com/Graylog2/fpm-recipes/master/recipes/graylog-repository/files/deb/graylog-keyring.gpg' # } } default['graylog2']['root_username'] = 'admin' default['graylog2']['root_email'] = nil default['graylog2']['root_timezone'] = nil default['graylog2']['restart'] = 'delayed' default['graylog2']['no_retention'] = nil default['graylog2']['disable_sigar'] = nil default['graylog2']['dashboard_widget_default_cache_time'] = '10s' default['graylog2']['secrets_data_bag'] = 'secrets' # Users default['graylog2']['server']['user'] = 'graylog' default['graylog2']['server']['group'] = 'graylog' # SHAs default['graylog2']['password_secret'] = nil # pwgen -s 96 1 default['graylog2']['password_secret_enclose_char'] = '"' default['graylog2']['root_password_sha2'] = nil # echo -n yourpassword | shasum -a 256 # Paths default['graylog2']['node_id_file'] = '/etc/graylog/server/node-id' default['graylog2']['plugin_dir'] = '/usr/share/graylog-server/plugin' # Network default['graylog2']['trusted_proxies'] = nil default['graylog2']['http_proxy_uri'] = nil default['graylog2']['authorized_ports'] = 514 # Rest default['graylog2']['rest']['listen_uri'] = 'http://0.0.0.0:9000/api/' default['graylog2']['rest']['transport_uri'] = nil default['graylog2']['rest']['enable_cors'] = nil default['graylog2']['rest']['enable_gzip'] = nil default['graylog2']['rest']['admin_access_token'] = nil # pwgen -s 96 1 default['graylog2']['rest']['enable_tls'] = nil default['graylog2']['rest']['tls_cert_file'] = nil default['graylog2']['rest']['tls_key_file'] = nil default['graylog2']['rest']['tls_key_password'] = nil default['graylog2']['rest']['max_chunk_size'] = nil default['graylog2']['rest']['max_header_size'] = nil default['graylog2']['rest']['max_initial_line_length'] = nil default['graylog2']['rest']['thread_pool_size'] = nil default['graylog2']['rest']['worker_threads_max_pool_size'] = nil # Elasticsearch default['graylog2']['elasticsearch']['config_file'] = '/etc/graylog/server/graylog-elasticsearch.yml' default['graylog2']['elasticsearch']['shards'] = 4 default['graylog2']['elasticsearch']['replicas'] = 0 default['graylog2']['elasticsearch']['index_prefix'] = 'graylog' default['graylog2']['elasticsearch']['cluster_name'] = 'graylog' default['graylog2']['elasticsearch']['http_enabled'] = false default['graylog2']['elasticsearch']['discovery_zen_ping_unicast_hosts'] = '127.0.0.1:9300' default['graylog2']['elasticsearch']['unicast_search_query'] = nil default['graylog2']['elasticsearch']['search_node_attribute'] = nil default['graylog2']['elasticsearch']['network_host'] = nil default['graylog2']['elasticsearch']['network_bind_host'] = nil default['graylog2']['elasticsearch']['network_publish_host'] = nil default['graylog2']['elasticsearch']['analyzer'] = 'standard' default['graylog2']['elasticsearch']['output_batch_size'] = 500 default['graylog2']['elasticsearch']['output_flush_interval'] = 1 default['graylog2']['elasticsearch']['output_fault_count_threshold'] = 5 default['graylog2']['elasticsearch']['output_fault_penalty_seconds'] = 30 default['graylog2']['elasticsearch']['transport_tcp_port'] = 9350 default['graylog2']['elasticsearch']['disable_version_check'] = nil default['graylog2']['elasticsearch']['disable_index_optimization'] = nil default['graylog2']['elasticsearch']['index_optimization_max_num_segments'] = nil default['graylog2']['elasticsearch']['index_ranges_cleanup_interval'] = nil default['graylog2']['elasticsearch']['template_name'] = nil default['graylog2']['elasticsearch']['node_name_prefix'] = nil default['graylog2']['elasticsearch']['template_name'] = nil # MongoDb default['graylog2']['mongodb']['uri'] = 'mongodb://127.0.0.1:27017/graylog' default['graylog2']['mongodb']['max_connections'] = 100 default['graylog2']['mongodb']['threads_allowed_to_block_multiplier'] = 5 # Search default['graylog2']['allow_leading_wildcard_searches'] = false default['graylog2']['allow_highlighting'] = false # Streams default['graylog2']['stream_processing_max_faults'] = 3 # Buffer default['graylog2']['processbuffer_processors'] = 5 default['graylog2']['outputbuffer_processors'] = 3 default['graylog2']['async_eventbus_processors'] = 2 default['graylog2']['outputbuffer_processor_keep_alive_time'] = 5000 default['graylog2']['outputbuffer_processor_threads_core_pool_size'] = 3 default['graylog2']['outputbuffer_processor_threads_max_pool_size'] = 30 default['graylog2']['processor_wait_strategy'] = 'blocking' default['graylog2']['ring_size'] = 65536 default['graylog2']['udp_recvbuffer_sizes'] = 1048576 default['graylog2']['inputbuffer_ring_size'] = 65536 default['graylog2']['inputbuffer_processors'] = 2 default['graylog2']['inputbuffer_wait_strategy'] = 'blocking' # Message journal default['graylog2']['message_journal_enabled'] = true default['graylog2']['message_journal_dir'] = '/var/lib/graylog-server/journal' default['graylog2']['message_journal_max_age'] = '12h' default['graylog2']['message_journal_max_size'] = '5gb' default['graylog2']['message_journal_flush_age'] = '1m' default['graylog2']['message_journal_flush_interval'] = 1000000 default['graylog2']['message_journal_segment_age'] = '1h' default['graylog2']['message_journal_segment_size'] = '100mb' # Timeouts default['graylog2']['output_module_timeout'] = 10000 default['graylog2']['stale_master_timeout'] = 2000 default['graylog2']['shutdown_timeout'] = 30000 default['graylog2']['stream_processing_timeout'] = 2000 default['graylog2']['ldap_connection_timeout'] = 2000 default['graylog2']['api_client_timeout'] = 300 default['graylog2']['http_connect_timeout'] = '5s' default['graylog2']['http_read_timeout'] = '10s' default['graylog2']['http_write_timeout'] = '10s' default['graylog2']['elasticsearch']['cluster_discovery_timeout'] = 5000 default['graylog2']['elasticsearch']['discovery_initial_state_timeout'] = '3s' default['graylog2']['elasticsearch']['request_timeout'] = '1m' # Intervals default['graylog2']['server']['alert_check_interval'] = nil # Cluster default['graylog2']['ip_of_master'] = node['ipaddress'] default['graylog2']['lb_recognition_period_seconds'] = 3 # Email transport default['graylog2']['transport_email_enabled'] = false default['graylog2']['transport_email_hostname'] = 'mail.example.com' default['graylog2']['transport_email_port'] = 587 default['graylog2']['transport_email_use_auth'] = true default['graylog2']['transport_email_use_tls'] = true default['graylog2']['transport_email_use_ssl'] = true default['graylog2']['transport_email_auth_username'] = 'you@example.com' default['graylog2']['transport_email_auth_password'] = 'secret' default['graylog2']['transport_email_subject_prefix'] = '[graylog]' default['graylog2']['transport_email_from_email'] = 'graylog@example.com' default['graylog2']['transport_email_web_interface_url'] = nil # Logging default['graylog2']['server']['log_file'] = '/var/log/graylog-server/server.log' default['graylog2']['server']['log_max_size'] = '50MB' default['graylog2']['server']['log_max_index'] = 10 default['graylog2']['server']['log_pattern'] = "%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5p [%c{1}] %m%n" default['graylog2']['server']['log_level_application'] = 'info' default['graylog2']['server']['log_level_root'] = 'warn' # JVM default['graylog2']['server']['java_bin'] = '/usr/bin/java' default['graylog2']['server']['java_home'] = '' default['graylog2']['server']['java_opts'] = '-Djava.net.preferIPv4Stack=true -Xms1g -Xmx1g -XX:NewRatio=1 -server -XX:+ResizeTLAB -XX:+UseConcMarkSweepGC -XX:+CMSConcurrentMTEnabled -XX:+CMSClassUnloadingEnabled -XX:+UseParNewGC -XX:-OmitStackTraceInFastThrow' default['graylog2']['server']['args'] = '' default['graylog2']['server']['wrapper'] = '' default['graylog2']['server']['gc_warning_threshold'] = nil # Server default['graylog2']['server']['override_restart_command'] = false default['graylog2']['server']['additional_options'] = nil default['graylog2']['server']['additional_env_vars'] = nil default['graylog2']['server']['install_tzdata_java'] = true # Web default['graylog2']['web']['enable'] = true default['graylog2']['web']['listen_uri'] = 'http://0.0.0.0:9000' default['graylog2']['web']['endpoint_uri'] = nil default['graylog2']['web']['enable_cors'] = nil default['graylog2']['web']['enable_gzip'] = nil default['graylog2']['web']['enable_tls'] = nil default['graylog2']['web']['tls_cert_file'] = nil default['graylog2']['web']['tls_key_file'] = nil default['graylog2']['web']['tls_key_password'] = nil default['graylog2']['web']['max_header_size'] = nil default['graylog2']['web']['max_initial_line_length'] = nil default['graylog2']['web']['thread_pool_size'] = nil # Collector Sidecar default['graylog2']['sidecar']['release'] = '0.0.9' default['graylog2']['sidecar']['version'] = '0.0.9' default['graylog2']['sidecar']['build'] = 1 default['graylog2']['sidecar']['arch'] = 'amd64' default['graylog2']['sidecar']['package_base_url'] = "https://github.com/Graylog2/collector-sidecar/releases/download/#{node['graylog2']['sidecar'][:release]}" default['graylog2']['sidecar']['server_url'] = 'http://localhost:9000/api' default['graylog2']['sidecar']['update_interval'] = 10 default['graylog2']['sidecar']['tls_skip_verify'] = false default['graylog2']['sidecar']['send_status'] = false default['graylog2']['sidecar']['list_log_files'] = nil # single directory or '[dir1, dir2, dir3]' default['graylog2']['sidecar']['name'] = 'graylog-collector-sidecar' default['graylog2']['sidecar']['id'] = 'file:/etc/graylog/collector-sidecar/collector-id' default['graylog2']['sidecar']['log_path'] = '/var/log/graylog/collector-sidecar' default['graylog2']['sidecar']['log_rotation_time'] = 86400 default['graylog2']['sidecar']['log_max_age'] = 604800 default['graylog2']['sidecar']['tags'] = 'linux' # multiple tags '[tag1, tag2, tag3]' default['graylog2']['sidecar']['backends']['nxlog']['enabled'] = false default['graylog2']['sidecar']['backends']['nxlog']['binary_path'] = '/usr/bin/nxlog' default['graylog2']['sidecar']['backends']['nxlog']['configuration_path'] = '/etc/graylog/collector-sidecar/generated/nxlog.conf' default['graylog2']['sidecar']['backends']['filebeat']['enabled'] = true default['graylog2']['sidecar']['backends']['filebeat']['binary_path'] = '/usr/bin/filebeat' default['graylog2']['sidecar']['backends']['filebeat']['configuration_path'] = '/etc/graylog/collector-sidecar/generated/filebeat.yml' default['graylog2']['server']['collector_inactive_threshold'] = '1m' default['graylog2']['server']['collector_expiration_threshold'] = '14d' # Content packs default['graylog2']['server']['content_packs_loader_enabled'] = false default['graylog2']['server']['content_packs_dir'] = '/usr/share/graylog-server/contentpacks' default['graylog2']['server']['content_packs_auto_load'] = 'grok-patterns.json' Bump to GL 2.2.2 node.default['graylog2'] ||= {} node.default['mongodb'] ||= {} # General default['graylog2']['major_version'] = '2.2' default['graylog2']['server']['version'] = '2.2.2-1' ## By default the cookbook installs a meta package containing the key and URL for the current Graylog repository. To disable ## this behavior set your own repository informations here. default['graylog2']['server']['repos'] = { # 'rhel' => { # 'url' => "https://packages.graylog2.org/repo/el/stable/#{node['graylog2']['major_version']}/x86_64/", # 'key' => 'https://raw.githubusercontent.com/Graylog2/fpm-recipes/master/recipes/graylog-repository/files/rpm/RPM-GPG-KEY-graylog' # }, # 'debian' => { # 'url' => "https://packages.graylog2.org/repo/debian/", # 'distribution' => '', # 'components' => ['stable', node['graylog2']['major_version']], # 'key' => 'https://raw.githubusercontent.com/Graylog2/fpm-recipes/master/recipes/graylog-repository/files/deb/graylog-keyring.gpg' # } } default['graylog2']['root_username'] = 'admin' default['graylog2']['root_email'] = nil default['graylog2']['root_timezone'] = nil default['graylog2']['restart'] = 'delayed' default['graylog2']['no_retention'] = nil default['graylog2']['disable_sigar'] = nil default['graylog2']['dashboard_widget_default_cache_time'] = '10s' default['graylog2']['secrets_data_bag'] = 'secrets' # Users default['graylog2']['server']['user'] = 'graylog' default['graylog2']['server']['group'] = 'graylog' # SHAs default['graylog2']['password_secret'] = nil # pwgen -s 96 1 default['graylog2']['password_secret_enclose_char'] = '"' default['graylog2']['root_password_sha2'] = nil # echo -n yourpassword | shasum -a 256 # Paths default['graylog2']['node_id_file'] = '/etc/graylog/server/node-id' default['graylog2']['plugin_dir'] = '/usr/share/graylog-server/plugin' # Network default['graylog2']['trusted_proxies'] = nil default['graylog2']['http_proxy_uri'] = nil default['graylog2']['authorized_ports'] = 514 # Rest default['graylog2']['rest']['listen_uri'] = 'http://0.0.0.0:9000/api/' default['graylog2']['rest']['transport_uri'] = nil default['graylog2']['rest']['enable_cors'] = nil default['graylog2']['rest']['enable_gzip'] = nil default['graylog2']['rest']['admin_access_token'] = nil # pwgen -s 96 1 default['graylog2']['rest']['enable_tls'] = nil default['graylog2']['rest']['tls_cert_file'] = nil default['graylog2']['rest']['tls_key_file'] = nil default['graylog2']['rest']['tls_key_password'] = nil default['graylog2']['rest']['max_chunk_size'] = nil default['graylog2']['rest']['max_header_size'] = nil default['graylog2']['rest']['max_initial_line_length'] = nil default['graylog2']['rest']['thread_pool_size'] = nil default['graylog2']['rest']['worker_threads_max_pool_size'] = nil # Elasticsearch default['graylog2']['elasticsearch']['config_file'] = '/etc/graylog/server/graylog-elasticsearch.yml' default['graylog2']['elasticsearch']['shards'] = 4 default['graylog2']['elasticsearch']['replicas'] = 0 default['graylog2']['elasticsearch']['index_prefix'] = 'graylog' default['graylog2']['elasticsearch']['cluster_name'] = 'graylog' default['graylog2']['elasticsearch']['http_enabled'] = false default['graylog2']['elasticsearch']['discovery_zen_ping_unicast_hosts'] = '127.0.0.1:9300' default['graylog2']['elasticsearch']['unicast_search_query'] = nil default['graylog2']['elasticsearch']['search_node_attribute'] = nil default['graylog2']['elasticsearch']['network_host'] = nil default['graylog2']['elasticsearch']['network_bind_host'] = nil default['graylog2']['elasticsearch']['network_publish_host'] = nil default['graylog2']['elasticsearch']['analyzer'] = 'standard' default['graylog2']['elasticsearch']['output_batch_size'] = 500 default['graylog2']['elasticsearch']['output_flush_interval'] = 1 default['graylog2']['elasticsearch']['output_fault_count_threshold'] = 5 default['graylog2']['elasticsearch']['output_fault_penalty_seconds'] = 30 default['graylog2']['elasticsearch']['transport_tcp_port'] = 9350 default['graylog2']['elasticsearch']['disable_version_check'] = nil default['graylog2']['elasticsearch']['disable_index_optimization'] = nil default['graylog2']['elasticsearch']['index_optimization_max_num_segments'] = nil default['graylog2']['elasticsearch']['index_ranges_cleanup_interval'] = nil default['graylog2']['elasticsearch']['template_name'] = nil default['graylog2']['elasticsearch']['node_name_prefix'] = nil default['graylog2']['elasticsearch']['template_name'] = nil # MongoDb default['graylog2']['mongodb']['uri'] = 'mongodb://127.0.0.1:27017/graylog' default['graylog2']['mongodb']['max_connections'] = 100 default['graylog2']['mongodb']['threads_allowed_to_block_multiplier'] = 5 # Search default['graylog2']['allow_leading_wildcard_searches'] = false default['graylog2']['allow_highlighting'] = false # Streams default['graylog2']['stream_processing_max_faults'] = 3 # Buffer default['graylog2']['processbuffer_processors'] = 5 default['graylog2']['outputbuffer_processors'] = 3 default['graylog2']['async_eventbus_processors'] = 2 default['graylog2']['outputbuffer_processor_keep_alive_time'] = 5000 default['graylog2']['outputbuffer_processor_threads_core_pool_size'] = 3 default['graylog2']['outputbuffer_processor_threads_max_pool_size'] = 30 default['graylog2']['processor_wait_strategy'] = 'blocking' default['graylog2']['ring_size'] = 65536 default['graylog2']['udp_recvbuffer_sizes'] = 1048576 default['graylog2']['inputbuffer_ring_size'] = 65536 default['graylog2']['inputbuffer_processors'] = 2 default['graylog2']['inputbuffer_wait_strategy'] = 'blocking' # Message journal default['graylog2']['message_journal_enabled'] = true default['graylog2']['message_journal_dir'] = '/var/lib/graylog-server/journal' default['graylog2']['message_journal_max_age'] = '12h' default['graylog2']['message_journal_max_size'] = '5gb' default['graylog2']['message_journal_flush_age'] = '1m' default['graylog2']['message_journal_flush_interval'] = 1000000 default['graylog2']['message_journal_segment_age'] = '1h' default['graylog2']['message_journal_segment_size'] = '100mb' # Timeouts default['graylog2']['output_module_timeout'] = 10000 default['graylog2']['stale_master_timeout'] = 2000 default['graylog2']['shutdown_timeout'] = 30000 default['graylog2']['stream_processing_timeout'] = 2000 default['graylog2']['ldap_connection_timeout'] = 2000 default['graylog2']['api_client_timeout'] = 300 default['graylog2']['http_connect_timeout'] = '5s' default['graylog2']['http_read_timeout'] = '10s' default['graylog2']['http_write_timeout'] = '10s' default['graylog2']['elasticsearch']['cluster_discovery_timeout'] = 5000 default['graylog2']['elasticsearch']['discovery_initial_state_timeout'] = '3s' default['graylog2']['elasticsearch']['request_timeout'] = '1m' # Intervals default['graylog2']['server']['alert_check_interval'] = nil # Cluster default['graylog2']['ip_of_master'] = node['ipaddress'] default['graylog2']['lb_recognition_period_seconds'] = 3 # Email transport default['graylog2']['transport_email_enabled'] = false default['graylog2']['transport_email_hostname'] = 'mail.example.com' default['graylog2']['transport_email_port'] = 587 default['graylog2']['transport_email_use_auth'] = true default['graylog2']['transport_email_use_tls'] = true default['graylog2']['transport_email_use_ssl'] = true default['graylog2']['transport_email_auth_username'] = 'you@example.com' default['graylog2']['transport_email_auth_password'] = 'secret' default['graylog2']['transport_email_subject_prefix'] = '[graylog]' default['graylog2']['transport_email_from_email'] = 'graylog@example.com' default['graylog2']['transport_email_web_interface_url'] = nil # Logging default['graylog2']['server']['log_file'] = '/var/log/graylog-server/server.log' default['graylog2']['server']['log_max_size'] = '50MB' default['graylog2']['server']['log_max_index'] = 10 default['graylog2']['server']['log_pattern'] = "%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5p [%c{1}] %m%n" default['graylog2']['server']['log_level_application'] = 'info' default['graylog2']['server']['log_level_root'] = 'warn' # JVM default['graylog2']['server']['java_bin'] = '/usr/bin/java' default['graylog2']['server']['java_home'] = '' default['graylog2']['server']['java_opts'] = '-Djava.net.preferIPv4Stack=true -Xms1g -Xmx1g -XX:NewRatio=1 -server -XX:+ResizeTLAB -XX:+UseConcMarkSweepGC -XX:+CMSConcurrentMTEnabled -XX:+CMSClassUnloadingEnabled -XX:+UseParNewGC -XX:-OmitStackTraceInFastThrow' default['graylog2']['server']['args'] = '' default['graylog2']['server']['wrapper'] = '' default['graylog2']['server']['gc_warning_threshold'] = nil # Server default['graylog2']['server']['override_restart_command'] = false default['graylog2']['server']['additional_options'] = nil default['graylog2']['server']['additional_env_vars'] = nil default['graylog2']['server']['install_tzdata_java'] = true # Web default['graylog2']['web']['enable'] = true default['graylog2']['web']['listen_uri'] = 'http://0.0.0.0:9000' default['graylog2']['web']['endpoint_uri'] = nil default['graylog2']['web']['enable_cors'] = nil default['graylog2']['web']['enable_gzip'] = nil default['graylog2']['web']['enable_tls'] = nil default['graylog2']['web']['tls_cert_file'] = nil default['graylog2']['web']['tls_key_file'] = nil default['graylog2']['web']['tls_key_password'] = nil default['graylog2']['web']['max_header_size'] = nil default['graylog2']['web']['max_initial_line_length'] = nil default['graylog2']['web']['thread_pool_size'] = nil # Collector Sidecar default['graylog2']['sidecar']['release'] = '0.0.9' default['graylog2']['sidecar']['version'] = '0.0.9' default['graylog2']['sidecar']['build'] = 1 default['graylog2']['sidecar']['arch'] = 'amd64' default['graylog2']['sidecar']['package_base_url'] = "https://github.com/Graylog2/collector-sidecar/releases/download/#{node['graylog2']['sidecar'][:release]}" default['graylog2']['sidecar']['server_url'] = 'http://localhost:9000/api' default['graylog2']['sidecar']['update_interval'] = 10 default['graylog2']['sidecar']['tls_skip_verify'] = false default['graylog2']['sidecar']['send_status'] = false default['graylog2']['sidecar']['list_log_files'] = nil # single directory or '[dir1, dir2, dir3]' default['graylog2']['sidecar']['name'] = 'graylog-collector-sidecar' default['graylog2']['sidecar']['id'] = 'file:/etc/graylog/collector-sidecar/collector-id' default['graylog2']['sidecar']['log_path'] = '/var/log/graylog/collector-sidecar' default['graylog2']['sidecar']['log_rotation_time'] = 86400 default['graylog2']['sidecar']['log_max_age'] = 604800 default['graylog2']['sidecar']['tags'] = 'linux' # multiple tags '[tag1, tag2, tag3]' default['graylog2']['sidecar']['backends']['nxlog']['enabled'] = false default['graylog2']['sidecar']['backends']['nxlog']['binary_path'] = '/usr/bin/nxlog' default['graylog2']['sidecar']['backends']['nxlog']['configuration_path'] = '/etc/graylog/collector-sidecar/generated/nxlog.conf' default['graylog2']['sidecar']['backends']['filebeat']['enabled'] = true default['graylog2']['sidecar']['backends']['filebeat']['binary_path'] = '/usr/bin/filebeat' default['graylog2']['sidecar']['backends']['filebeat']['configuration_path'] = '/etc/graylog/collector-sidecar/generated/filebeat.yml' default['graylog2']['server']['collector_inactive_threshold'] = '1m' default['graylog2']['server']['collector_expiration_threshold'] = '14d' # Content packs default['graylog2']['server']['content_packs_loader_enabled'] = false default['graylog2']['server']['content_packs_dir'] = '/usr/share/graylog-server/contentpacks' default['graylog2']['server']['content_packs_auto_load'] = 'grok-patterns.json'
default[:cassandra] = { :cluster_name => "Test Cluster", :initial_token => "", :version => '2.0.4', :user => "cassandra", :jvm => { :xms => 32, :xmx => 512 }, :limits => { :memlock => 'unlimited', :nofile => 48000 }, :templates_cookbook => "cassandra", :installation_dir => "/usr/local/cassandra", :bin_dir => "/usr/local/cassandra/bin", :lib_dir => "/usr/local/cassandra/lib", :conf_dir => "/etc/cassandra/", # commit log, data directory, saved caches and so on are all stored under the data root. MK. :data_root_dir => "/var/lib/cassandra/", :commitlog_dir => "/var/lib/cassandra/", :log_dir => "/var/log/cassandra/", :max_hint_window_in_ms=> 10800000, # 3 hours :listen_address => node[:ipaddress], :partitioner => "org.apache.cassandra.dht.Murmur3Partitioner", :key_cache_size_in_mb => "", :broadcast_address => node[:ipaddress], :start_rpc => "true", :rpc_address => node[:ipaddress], :rpc_port => "9160", :range_request_timeout_in_ms => 10000, :streaming_socket_timeout_in_ms => 0, #never timeout streams :start_native_transport => "true", :native_transport_port => "9042", :max_heap_size => nil, :heap_new_size => nil, :xss => "256k", :vnodes => false, :seeds => [], :concurrent_reads => 32, :concurrent_writes => 32, :index_interval => 128, :snitch => 'SimpleSnitch', :package_name => 'dsc12', :snitch_conf => false, :enable_assertions => true, :jmx_server_hostname => false, :auto_bootstrap => true, } default[:cassandra][:jna] = { :base_url => "https://github.com/twall/jna/raw/4.0/dist", :jar_name => "jna.jar", :sha256sum => "dac270b6441ce24d93a96ddb6e8f93d8df099192738799a6f6fcfc2b2416ca19" } default[:cassandra][:tarball] = { :url => "auto", :md5 => "4c7c7620056ed436cd4d3c0756d02761" } default[:cassandra][:opscenter][:server] = { :package_name => "opscenter-free", :port => "8888", :interface => "0.0.0.0" } default[:cassandra][:opscenter][:agent] = { :download_url => nil, :checksum => nil, :install_dir => "/opt", :install_folder_name => "opscenter_agent", :binary_name => "opscenter-agent", :server_host => nil, # if nil, will use search to get IP by server role :server_role => "opscenter_server", :use_ssl => true } Cassandra 2.0.5 default[:cassandra] = { :cluster_name => "Test Cluster", :initial_token => "", :version => '2.0.5', :user => "cassandra", :jvm => { :xms => 32, :xmx => 512 }, :limits => { :memlock => 'unlimited', :nofile => 48000 }, :templates_cookbook => "cassandra", :installation_dir => "/usr/local/cassandra", :bin_dir => "/usr/local/cassandra/bin", :lib_dir => "/usr/local/cassandra/lib", :conf_dir => "/etc/cassandra/", # commit log, data directory, saved caches and so on are all stored under the data root. MK. :data_root_dir => "/var/lib/cassandra/", :commitlog_dir => "/var/lib/cassandra/", :log_dir => "/var/log/cassandra/", :max_hint_window_in_ms=> 10800000, # 3 hours :listen_address => node[:ipaddress], :partitioner => "org.apache.cassandra.dht.Murmur3Partitioner", :key_cache_size_in_mb => "", :broadcast_address => node[:ipaddress], :start_rpc => "true", :rpc_address => node[:ipaddress], :rpc_port => "9160", :range_request_timeout_in_ms => 10000, :streaming_socket_timeout_in_ms => 0, #never timeout streams :start_native_transport => "true", :native_transport_port => "9042", :max_heap_size => nil, :heap_new_size => nil, :xss => "256k", :vnodes => false, :seeds => [], :concurrent_reads => 32, :concurrent_writes => 32, :index_interval => 128, :snitch => 'SimpleSnitch', :package_name => 'dsc12', :snitch_conf => false, :enable_assertions => true, :jmx_server_hostname => false, :auto_bootstrap => true, } default[:cassandra][:jna] = { :base_url => "https://github.com/twall/jna/raw/4.0/dist", :jar_name => "jna.jar", :sha256sum => "dac270b6441ce24d93a96ddb6e8f93d8df099192738799a6f6fcfc2b2416ca19" } default[:cassandra][:tarball] = { :url => "auto", :md5 => "d046e3e5754d89007bbe4d940ae68758" } default[:cassandra][:opscenter][:server] = { :package_name => "opscenter-free", :port => "8888", :interface => "0.0.0.0" } default[:cassandra][:opscenter][:agent] = { :download_url => nil, :checksum => nil, :install_dir => "/opt", :install_folder_name => "opscenter_agent", :binary_name => "opscenter-agent", :server_host => nil, # if nil, will use search to get IP by server role :server_role => "opscenter_server", :use_ssl => true }
default[:mesos] = { :type => "mesosphere", :mesosphere => { :with_zookeeper => false }, :version => "0.25.0", :prefix => "/usr/local", :home => "/opt", :build => { :skip_test => true }, :master_ips => [], :slave_ips => [], :master => { :log_dir => "/var/log/mesos", :work_dir => "/tmp/mesos", :port => "5050" }, :slave => { :log_dir => "/var/log/mesos", :work_dir => "/tmp/mesos", :isolation=> "cgroups/cpu,cgroups/mem" :attributes=> "role:dev" }, :ssh_opts => "-o StrictHostKeyChecking=no -o ConnectTimeout=2", :deploy_with_sudo => "1" } default[:mesos][:mesosphere][:build_version] = value_for_platform( "ubuntu" => { "default" => "-0.2.70.ubuntu1404" }, "default" => nil ) default[:mesos][:slave][:cgroups_hierarchy] = value_for_platform( "centos" => { "default" => "/cgroup" }, "default" => nil ) update default[:mesos] = { :type => "mesosphere", :mesosphere => { :with_zookeeper => false }, :version => "0.25.0", :prefix => "/usr/local", :home => "/opt", :build => { :skip_test => true }, :master_ips => [], :slave_ips => [], :master => { :log_dir => "/var/log/mesos", :work_dir => "/tmp/mesos", :port => "5050" }, :slave => { :log_dir => "/var/log/mesos", :work_dir => "/tmp/mesos", :isolation=> "cgroups/cpu,cgroups/mem", :attributes=> "role:dev" }, :ssh_opts => "-o StrictHostKeyChecking=no -o ConnectTimeout=2", :deploy_with_sudo => "1" } default[:mesos][:mesosphere][:build_version] = value_for_platform( "ubuntu" => { "default" => "-0.2.70.ubuntu1404" }, "default" => nil ) default[:mesos][:slave][:cgroups_hierarchy] = value_for_platform( "centos" => { "default" => "/cgroup" }, "default" => nil )
# # Cookbook Name:: cookbook-openshift3 # Recipe:: default # # Copyright (c) 2015 The Authors, All Rights Reserved. default['cookbook-openshift3']['use_params_roles'] = false default['cookbook-openshift3']['use_wildcard_nodes'] = false default['cookbook-openshift3']['wildcard_domain'] = '' default['cookbook-openshift3']['openshift_cluster_name'] = nil default['cookbook-openshift3']['openshift_master_cluster_vip'] = nil default['cookbook-openshift3']['openshift_HA'] = false default['cookbook-openshift3']['openshift_HA_method'] = 'native' default['cookbook-openshift3']['master_servers'] = [] default['cookbook-openshift3']['master_peers'] = [] default['cookbook-openshift3']['etcd_servers'] = [] default['cookbook-openshift3']['node_servers'] = [] if node['cookbook-openshift3']['openshift_HA'] default['cookbook-openshift3']['openshift_common_public_hostname'] = node['cookbook-openshift3']['openshift_cluster_name'] default['cookbook-openshift3']['openshift_master_embedded_etcd'] = false default['cookbook-openshift3']['openshift_master_etcd_port'] = '2379' default['cookbook-openshift3']['master_etcd_cert_prefix'] = 'master.etcd-' else default['cookbook-openshift3']['openshift_common_public_hostname'] = node['fqdn'] default['cookbook-openshift3']['openshift_master_embedded_etcd'] = true default['cookbook-openshift3']['openshift_master_etcd_port'] = '4001' default['cookbook-openshift3']['master_etcd_cert_prefix'] = '' end default['cookbook-openshift3']['deploy_containerized'] = false default['cookbook-openshift3']['deploy_example'] = false default['cookbook-openshift3']['deploy_dnsmasq'] = false default['cookbook-openshift3']['docker_version'] = nil default['cookbook-openshift3']['docker_log_options'] = nil default['cookbook-openshift3']['install_method'] = 'yum' default['cookbook-openshift3']['httpd_xfer_port'] = '9999' default['cookbook-openshift3']['set_nameserver'] = false default['cookbook-openshift3']['register_dns'] = false default['cookbook-openshift3']['core_packages'] = %w(libselinux-python wget vim-enhanced net-tools bind-utils git bash-completion bash-completion dnsmasq) default['cookbook-openshift3']['osn_cluster_dns_domain'] = 'cluster.local' default['cookbook-openshift3']['enabled_firewall_rules_master'] = %w(firewall_master) default['cookbook-openshift3']['enabled_firewall_rules_master_cluster'] = %w(firewall_master_cluster) default['cookbook-openshift3']['enabled_firewall_rules_node'] = %w(firewall_node) default['cookbook-openshift3']['enabled_firewall_additional_rules_node'] = [] default['cookbook-openshift3']['enabled_firewall_rules_etcd'] = %w(firewall_etcd) default['cookbook-openshift3']['openshift_deployment_type'] = 'enterprise' default['cookbook-openshift3']['openshift_service_type'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'atomic-openshift' : 'origin' default['cookbook-openshift3']['yum_repositories'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? %w() : [{ 'name' => 'centos-openshift-origin', 'baseurl' => 'http://mirror.centos.org/centos/7/paas/x86_64/openshift-origin/', 'gpgcheck' => false }] default['cookbook-openshift3']['openshift_data_dir'] = '/var/lib/origin' default['cookbook-openshift3']['openshift_master_cluster_password'] = 'openshift_cluster' default['cookbook-openshift3']['openshift_common_base_dir'] = '/etc/origin' default['cookbook-openshift3']['openshift_common_master_dir'] = '/etc/origin' default['cookbook-openshift3']['openshift_common_node_dir'] = '/etc/origin' default['cookbook-openshift3']['openshift_common_portal_net'] = '172.30.0.0/16' default['cookbook-openshift3']['openshift_common_first_svc_ip'] = node['cookbook-openshift3']['openshift_common_portal_net'].split('/')[0].gsub(/\.0$/, '.1') default['cookbook-openshift3']['openshift_common_reverse_svc_ip'] = node['cookbook-openshift3']['openshift_common_portal_net'].split('/')[0].split('.')[0..1].reverse!.join('.') default['cookbook-openshift3']['openshift_common_default_nodeSelector'] = 'region=user' default['cookbook-openshift3']['openshift_common_infra_label'] = 'region=infra' default['cookbook-openshift3']['openshift_common_examples_base'] = '/usr/share/openshift/examples' default['cookbook-openshift3']['openshift_common_hostname'] = node['fqdn'] default['cookbook-openshift3']['openshift_common_ip'] = node['ipaddress'] default['cookbook-openshift3']['openshift_common_infra_project'] = %w(default openshift-infra) default['cookbook-openshift3']['openshift_common_public_ip'] = node['cookbook-openshift3']['openshift_HA'] == true ? node['cookbook-openshift3']['openshift_master_cluster_vip'] : node['ipaddress'] default['cookbook-openshift3']['openshift_common_admin_binary'] = node['cookbook-openshift3']['deploy_containerized'] == true ? '/usr/local/bin/oadm' : '/usr/bin/oadm' default['cookbook-openshift3']['openshift_common_client_binary'] = node['cookbook-openshift3']['deploy_containerized'] == true ? '/usr/local/bin/oc' : '/usr/bin/oc' default['cookbook-openshift3']['openshift_common_service_accounts'] = [{ 'name' => 'router', 'namespace' => 'default', 'scc' => true }, { 'name' => 'registry', 'namespace' => 'default', 'scc' => true }] default['cookbook-openshift3']['openshift_common_service_accounts_additional'] = [] default['cookbook-openshift3']['openshift_common_use_openshift_sdn'] = true default['cookbook-openshift3']['openshift_common_sdn_network_plugin_name'] = 'redhat/openshift-ovs-subnet' default['cookbook-openshift3']['openshift_common_svc_names'] = ['openshift', 'openshift.default', 'openshift.default.svc', "openshift.default.svc.#{node['cookbook-openshift3']['osn_cluster_dns_domain']}", 'kubernetes', 'kubernetes.default', 'kubernetes.default.svc', "kubernetes.default.svc.#{node['cookbook-openshift3']['osn_cluster_dns_domain']}", node['cookbook-openshift3']['openshift_common_first_svc_ip']] default['cookbook-openshift3']['openshift_common_registry_url'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/ose-${component}:${version}' : 'openshift/origin-${component}:${version}' default['cookbook-openshift3']['openshift_docker_insecure_registry_arg'] = [] default['cookbook-openshift3']['openshift_docker_add_registry_arg'] = [] default['cookbook-openshift3']['openshift_docker_block_registry_arg'] = [] default['cookbook-openshift3']['openshift_docker_insecure_registries'] = node['cookbook-openshift3']['openshift_docker_add_registry_arg'].empty? ? [node['cookbook-openshift3']['openshift_common_portal_net']] : [node['cookbook-openshift3']['openshift_common_portal_net']] + node['cookbook-openshift3']['openshift_docker_insecure_registry_arg'] default['cookbook-openshift3']['openshift_docker_image_version'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'v3.2.0.44' : 'v1.2.0' default['cookbook-openshift3']['openshift_docker_cli_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/ose' : 'openshift/origin' default['cookbook-openshift3']['openshift_docker_master_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/ose' : 'openshift/origin' default['cookbook-openshift3']['openshift_docker_node_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/node' : 'openshift/node' default['cookbook-openshift3']['openshift_docker_ovs_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/openvswitch' : 'openshift/openvswitch' default['cookbook-openshift3']['openshift_master_config_dir'] = "#{node['cookbook-openshift3']['openshift_common_master_dir']}/master" default['cookbook-openshift3']['openshift_master_bind_addr'] = '0.0.0.0' default['cookbook-openshift3']['openshift_master_api_port'] = '8443' default['cookbook-openshift3']['openshift_master_console_port'] = '8443' default['cookbook-openshift3']['openshift_master_controllers_port'] = '8444' default['cookbook-openshift3']['openshift_master_controller_lease_ttl'] = '30' default['cookbook-openshift3']['openshift_master_dynamic_provisioning_enabled'] = true default['cookbook-openshift3']['openshift_master_embedded_dns'] = true default['cookbook-openshift3']['openshift_master_embedded_kube'] = true default['cookbook-openshift3']['openshift_master_debug_level'] = '2' default['cookbook-openshift3']['openshift_master_dns_port'] = node['cookbook-openshift3']['deploy_dnsmasq'] == true ? '8053' : '53' default['cookbook-openshift3']['openshift_master_label'] = 'region=infra' default['cookbook-openshift3']['openshift_master_metrics_public_url'] = nil default['cookbook-openshift3']['openshift_master_logging_public_url'] = nil default['cookbook-openshift3']['openshift_master_generated_configs_dir'] = '/var/www/html/generated-configs' default['cookbook-openshift3']['openshift_master_router_subdomain'] = 'cloudapps.domain.local' default['cookbook-openshift3']['openshift_master_sdn_cluster_network_cidr'] = '10.1.0.0/16' default['cookbook-openshift3']['openshift_master_sdn_host_subnet_length'] = '8' default['cookbook-openshift3']['openshift_master_oauth_grant_method'] = 'auto' default['cookbook-openshift3']['openshift_master_session_max_seconds'] = '3600' default['cookbook-openshift3']['openshift_master_session_name'] = 'ssn' default['cookbook-openshift3']['openshift_master_session_secrets_file'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/session-secrets.yaml" default['cookbook-openshift3']['openshift_master_access_token_max_seconds'] = '86400' default['cookbook-openshift3']['openshift_master_auth_token_max_seconds'] = '500' default['cookbook-openshift3']['openshift_master_public_api_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_api_port']}" default['cookbook-openshift3']['openshift_master_api_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_api_port']}" default['cookbook-openshift3']['openshift_master_loopback_api_url'] = "https://#{node['fqdn']}:#{node['cookbook-openshift3']['openshift_master_api_port']}" default['cookbook-openshift3']['openshift_master_console_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_console_port']}/console" default['cookbook-openshift3']['openshift_master_etcd_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_etcd_port']}" default['cookbook-openshift3']['openshift_master_policy'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/policy.json" default['cookbook-openshift3']['openshift_master_config_file'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/master-config.yaml" default['cookbook-openshift3']['openshift_master_api_sysconfig'] = '/etc/sysconfig/atomic-openshift-master-api' default['cookbook-openshift3']['openshift_master_api_systemd'] = '/usr/lib/systemd/system/atomic-openshift-master-api.service' default['cookbook-openshift3']['openshift_master_controllers_sysconfig'] = '/etc/sysconfig/atomic-openshift-master-controllers' default['cookbook-openshift3']['openshift_master_controllers_systemd'] = '/usr/lib/systemd/system/atomic-openshift-master-controllers.service' default['cookbook-openshift3']['openshift_master_named_certificates'] = %w() default['cookbook-openshift3']['openshift_master_scheduler_conf'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/scheduler.json" default['cookbook-openshift3']['openshift_master_certs_no_etcd'] = %w(admin.crt master.kubelet-client.crt master.server.crt openshift-master.crt openshift-registry.crt openshift-router.crt etcd.server.crt) default['cookbook-openshift3']['openshift_node_config_dir'] = "#{node['cookbook-openshift3']['openshift_common_node_dir']}/node" default['cookbook-openshift3']['openshift_node_config_file'] = "#{node['cookbook-openshift3']['openshift_node_config_dir']}/node-config.yaml" default['cookbook-openshift3']['openshift_node_debug_level'] = '2' default['cookbook-openshift3']['openshift_node_docker-storage'] = {} default['cookbook-openshift3']['openshift_node_label'] = node['cookbook-openshift3']['openshift_common_default_nodeSelector'] default['cookbook-openshift3']['openshift_node_iptables_sync_period'] = '5s' default['cookbook-openshift3']['openshift_node_max_pod'] = '40' default['cookbook-openshift3']['openshift_node_sdn_mtu_sdn'] = '1450' default['cookbook-openshift3']['openshift_node_minimum_container_ttl_duration'] = '10s' default['cookbook-openshift3']['openshift_node_maximum_dead_containers_per_container'] = '2' default['cookbook-openshift3']['openshift_node_maximum_dead_containers'] = '100' default['cookbook-openshift3']['openshift_node_image_gc_high_threshold'] = '90' default['cookbook-openshift3']['openshift_node_image_gc_low_threshold'] = '80' default['cookbook-openshift3']['erb_corsAllowedOrigins'] = ['127.0.0.1', 'localhost', node['cookbook-openshift3']['openshift_common_hostname'], node['cookbook-openshift3']['openshift_common_ip'], node['cookbook-openshift3']['openshift_common_public_hostname'], node['cookbook-openshift3']['openshift_common_public_ip']] + node['cookbook-openshift3']['openshift_common_svc_names'] default['cookbook-openshift3']['erb_etcdClientInfo_urls'] = [node['cookbook-openshift3']['openshift_master_etcd_url'], "https://#{node['cookbook-openshift3']['openshift_common_hostname']}:#{node['cookbook-openshift3']['openshift_master_etcd_port']}"] default['cookbook-openshift3']['master_generated_certs_dir'] = '/var/www/html/master/generated_certs' default['cookbook-openshift3']['etcd_conf_dir'] = '/etc/etcd' default['cookbook-openshift3']['etcd_ca_dir'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/ca" default['cookbook-openshift3']['etcd_generated_certs_dir'] = '/var/www/html/etcd/generated_certs' default['cookbook-openshift3']['etcd_ca_cert'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/ca.crt" default['cookbook-openshift3']['etcd_ca_peer'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/ca.crt" default['cookbook-openshift3']['etcd_cert_file'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/server.crt" default['cookbook-openshift3']['etcd_cert_key'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/server.key" default['cookbook-openshift3']['etcd_peer_file'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/peer.crt" default['cookbook-openshift3']['etcd_peer_key'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/peer.key" default['cookbook-openshift3']['etcd_openssl_conf'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/openssl.cnf" default['cookbook-openshift3']['etcd_ca_name'] = 'etcd_ca' default['cookbook-openshift3']['etcd_req_ext'] = 'etcd_v3_req' default['cookbook-openshift3']['etcd_ca_exts_peer'] = 'etcd_v3_ca_peer' default['cookbook-openshift3']['etcd_ca_exts_server'] = 'etcd_v3_ca_server' default['cookbook-openshift3']['etcd_initial_cluster_state'] = 'new' default['cookbook-openshift3']['etcd_initial_cluster_token'] = 'etcd-cluster-1' default['cookbook-openshift3']['etcd_data_dir'] = '/var/lib/etcd/' default['cookbook-openshift3']['etcd_default_days'] = '365' default['cookbook-openshift3']['etcd_client_port'] = '2379' default['cookbook-openshift3']['etcd_peer_port'] = '2380' default['cookbook-openshift3']['etcd_initial_advertise_peer_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_peer_port']}" default['cookbook-openshift3']['etcd_listen_peer_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_peer_port']}" default['cookbook-openshift3']['etcd_listen_client_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_client_port']}" default['cookbook-openshift3']['etcd_advertise_client_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_client_port']}" default['cookbook-openshift3']['etcd_listen_client_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_client_port']}" Update default.rb # # Cookbook Name:: cookbook-openshift3 # Recipe:: default # # Copyright (c) 2015 The Authors, All Rights Reserved. default['cookbook-openshift3']['use_params_roles'] = false default['cookbook-openshift3']['use_wildcard_nodes'] = false default['cookbook-openshift3']['wildcard_domain'] = '' default['cookbook-openshift3']['openshift_cluster_name'] = nil default['cookbook-openshift3']['openshift_master_cluster_vip'] = nil default['cookbook-openshift3']['openshift_HA'] = false default['cookbook-openshift3']['openshift_HA_method'] = 'native' default['cookbook-openshift3']['master_servers'] = [] default['cookbook-openshift3']['master_peers'] = [] default['cookbook-openshift3']['etcd_servers'] = [] default['cookbook-openshift3']['node_servers'] = [] if node['cookbook-openshift3']['openshift_HA'] default['cookbook-openshift3']['openshift_common_public_hostname'] = node['cookbook-openshift3']['openshift_cluster_name'] default['cookbook-openshift3']['openshift_master_embedded_etcd'] = false default['cookbook-openshift3']['openshift_master_etcd_port'] = '2379' default['cookbook-openshift3']['master_etcd_cert_prefix'] = 'master.etcd-' else default['cookbook-openshift3']['openshift_common_public_hostname'] = node['fqdn'] default['cookbook-openshift3']['openshift_master_embedded_etcd'] = true default['cookbook-openshift3']['openshift_master_etcd_port'] = '4001' default['cookbook-openshift3']['master_etcd_cert_prefix'] = '' end default['cookbook-openshift3']['ose_version'] = nil default['cookbook-openshift3']['deploy_containerized'] = false default['cookbook-openshift3']['deploy_example'] = false default['cookbook-openshift3']['deploy_dnsmasq'] = false default['cookbook-openshift3']['docker_version'] = nil default['cookbook-openshift3']['docker_log_options'] = nil default['cookbook-openshift3']['install_method'] = 'yum' default['cookbook-openshift3']['httpd_xfer_port'] = '9999' default['cookbook-openshift3']['set_nameserver'] = false default['cookbook-openshift3']['register_dns'] = false default['cookbook-openshift3']['core_packages'] = %w(libselinux-python wget vim-enhanced net-tools bind-utils git bash-completion bash-completion dnsmasq) default['cookbook-openshift3']['osn_cluster_dns_domain'] = 'cluster.local' default['cookbook-openshift3']['enabled_firewall_rules_master'] = %w(firewall_master) default['cookbook-openshift3']['enabled_firewall_rules_master_cluster'] = %w(firewall_master_cluster) default['cookbook-openshift3']['enabled_firewall_rules_node'] = %w(firewall_node) default['cookbook-openshift3']['enabled_firewall_additional_rules_node'] = [] default['cookbook-openshift3']['enabled_firewall_rules_etcd'] = %w(firewall_etcd) default['cookbook-openshift3']['openshift_deployment_type'] = 'enterprise' default['cookbook-openshift3']['openshift_service_type'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'atomic-openshift' : 'origin' default['cookbook-openshift3']['yum_repositories'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? %w() : [{ 'name' => 'centos-openshift-origin', 'baseurl' => 'http://mirror.centos.org/centos/7/paas/x86_64/openshift-origin/', 'gpgcheck' => false }] default['cookbook-openshift3']['openshift_data_dir'] = '/var/lib/origin' default['cookbook-openshift3']['openshift_master_cluster_password'] = 'openshift_cluster' default['cookbook-openshift3']['openshift_common_base_dir'] = '/etc/origin' default['cookbook-openshift3']['openshift_common_master_dir'] = '/etc/origin' default['cookbook-openshift3']['openshift_common_node_dir'] = '/etc/origin' default['cookbook-openshift3']['openshift_common_portal_net'] = '172.30.0.0/16' default['cookbook-openshift3']['openshift_common_first_svc_ip'] = node['cookbook-openshift3']['openshift_common_portal_net'].split('/')[0].gsub(/\.0$/, '.1') default['cookbook-openshift3']['openshift_common_reverse_svc_ip'] = node['cookbook-openshift3']['openshift_common_portal_net'].split('/')[0].split('.')[0..1].reverse!.join('.') default['cookbook-openshift3']['openshift_common_default_nodeSelector'] = 'region=user' default['cookbook-openshift3']['openshift_common_infra_label'] = 'region=infra' default['cookbook-openshift3']['openshift_common_examples_base'] = '/usr/share/openshift/examples' default['cookbook-openshift3']['openshift_common_hostname'] = node['fqdn'] default['cookbook-openshift3']['openshift_common_ip'] = node['ipaddress'] default['cookbook-openshift3']['openshift_common_infra_project'] = %w(default openshift-infra) default['cookbook-openshift3']['openshift_common_public_ip'] = node['cookbook-openshift3']['openshift_HA'] == true ? node['cookbook-openshift3']['openshift_master_cluster_vip'] : node['ipaddress'] default['cookbook-openshift3']['openshift_common_admin_binary'] = node['cookbook-openshift3']['deploy_containerized'] == true ? '/usr/local/bin/oadm' : '/usr/bin/oadm' default['cookbook-openshift3']['openshift_common_client_binary'] = node['cookbook-openshift3']['deploy_containerized'] == true ? '/usr/local/bin/oc' : '/usr/bin/oc' default['cookbook-openshift3']['openshift_common_service_accounts'] = [{ 'name' => 'router', 'namespace' => 'default', 'scc' => true }, { 'name' => 'registry', 'namespace' => 'default', 'scc' => true }] default['cookbook-openshift3']['openshift_common_service_accounts_additional'] = [] default['cookbook-openshift3']['openshift_common_use_openshift_sdn'] = true default['cookbook-openshift3']['openshift_common_sdn_network_plugin_name'] = 'redhat/openshift-ovs-subnet' default['cookbook-openshift3']['openshift_common_svc_names'] = ['openshift', 'openshift.default', 'openshift.default.svc', "openshift.default.svc.#{node['cookbook-openshift3']['osn_cluster_dns_domain']}", 'kubernetes', 'kubernetes.default', 'kubernetes.default.svc', "kubernetes.default.svc.#{node['cookbook-openshift3']['osn_cluster_dns_domain']}", node['cookbook-openshift3']['openshift_common_first_svc_ip']] default['cookbook-openshift3']['openshift_common_registry_url'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/ose-${component}:${version}' : 'openshift/origin-${component}:${version}' default['cookbook-openshift3']['openshift_docker_insecure_registry_arg'] = [] default['cookbook-openshift3']['openshift_docker_add_registry_arg'] = [] default['cookbook-openshift3']['openshift_docker_block_registry_arg'] = [] default['cookbook-openshift3']['openshift_docker_insecure_registries'] = node['cookbook-openshift3']['openshift_docker_add_registry_arg'].empty? ? [node['cookbook-openshift3']['openshift_common_portal_net']] : [node['cookbook-openshift3']['openshift_common_portal_net']] + node['cookbook-openshift3']['openshift_docker_insecure_registry_arg'] default['cookbook-openshift3']['openshift_docker_image_version'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'v3.2.0.44' : 'v1.2.0' default['cookbook-openshift3']['openshift_docker_cli_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/ose' : 'openshift/origin' default['cookbook-openshift3']['openshift_docker_master_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/ose' : 'openshift/origin' default['cookbook-openshift3']['openshift_docker_node_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/node' : 'openshift/node' default['cookbook-openshift3']['openshift_docker_ovs_image'] = node['cookbook-openshift3']['openshift_deployment_type'] =~ /enterprise/ ? 'openshift3/openvswitch' : 'openshift/openvswitch' default['cookbook-openshift3']['openshift_master_config_dir'] = "#{node['cookbook-openshift3']['openshift_common_master_dir']}/master" default['cookbook-openshift3']['openshift_master_bind_addr'] = '0.0.0.0' default['cookbook-openshift3']['openshift_master_api_port'] = '8443' default['cookbook-openshift3']['openshift_master_console_port'] = '8443' default['cookbook-openshift3']['openshift_master_controllers_port'] = '8444' default['cookbook-openshift3']['openshift_master_controller_lease_ttl'] = '30' default['cookbook-openshift3']['openshift_master_dynamic_provisioning_enabled'] = true default['cookbook-openshift3']['openshift_master_embedded_dns'] = true default['cookbook-openshift3']['openshift_master_embedded_kube'] = true default['cookbook-openshift3']['openshift_master_debug_level'] = '2' default['cookbook-openshift3']['openshift_master_dns_port'] = node['cookbook-openshift3']['deploy_dnsmasq'] == true ? '8053' : '53' default['cookbook-openshift3']['openshift_master_label'] = 'region=infra' default['cookbook-openshift3']['openshift_master_metrics_public_url'] = nil default['cookbook-openshift3']['openshift_master_logging_public_url'] = nil default['cookbook-openshift3']['openshift_master_generated_configs_dir'] = '/var/www/html/generated-configs' default['cookbook-openshift3']['openshift_master_router_subdomain'] = 'cloudapps.domain.local' default['cookbook-openshift3']['openshift_master_sdn_cluster_network_cidr'] = '10.1.0.0/16' default['cookbook-openshift3']['openshift_master_sdn_host_subnet_length'] = '8' default['cookbook-openshift3']['openshift_master_oauth_grant_method'] = 'auto' default['cookbook-openshift3']['openshift_master_session_max_seconds'] = '3600' default['cookbook-openshift3']['openshift_master_session_name'] = 'ssn' default['cookbook-openshift3']['openshift_master_session_secrets_file'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/session-secrets.yaml" default['cookbook-openshift3']['openshift_master_access_token_max_seconds'] = '86400' default['cookbook-openshift3']['openshift_master_auth_token_max_seconds'] = '500' default['cookbook-openshift3']['openshift_master_public_api_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_api_port']}" default['cookbook-openshift3']['openshift_master_api_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_api_port']}" default['cookbook-openshift3']['openshift_master_loopback_api_url'] = "https://#{node['fqdn']}:#{node['cookbook-openshift3']['openshift_master_api_port']}" default['cookbook-openshift3']['openshift_master_console_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_console_port']}/console" default['cookbook-openshift3']['openshift_master_etcd_url'] = "https://#{node['cookbook-openshift3']['openshift_common_public_hostname']}:#{node['cookbook-openshift3']['openshift_master_etcd_port']}" default['cookbook-openshift3']['openshift_master_policy'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/policy.json" default['cookbook-openshift3']['openshift_master_config_file'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/master-config.yaml" default['cookbook-openshift3']['openshift_master_api_sysconfig'] = '/etc/sysconfig/atomic-openshift-master-api' default['cookbook-openshift3']['openshift_master_api_systemd'] = '/usr/lib/systemd/system/atomic-openshift-master-api.service' default['cookbook-openshift3']['openshift_master_controllers_sysconfig'] = '/etc/sysconfig/atomic-openshift-master-controllers' default['cookbook-openshift3']['openshift_master_controllers_systemd'] = '/usr/lib/systemd/system/atomic-openshift-master-controllers.service' default['cookbook-openshift3']['openshift_master_named_certificates'] = %w() default['cookbook-openshift3']['openshift_master_scheduler_conf'] = "#{node['cookbook-openshift3']['openshift_master_config_dir']}/scheduler.json" default['cookbook-openshift3']['openshift_master_certs_no_etcd'] = %w(admin.crt master.kubelet-client.crt master.server.crt openshift-master.crt openshift-registry.crt openshift-router.crt etcd.server.crt) default['cookbook-openshift3']['openshift_node_config_dir'] = "#{node['cookbook-openshift3']['openshift_common_node_dir']}/node" default['cookbook-openshift3']['openshift_node_config_file'] = "#{node['cookbook-openshift3']['openshift_node_config_dir']}/node-config.yaml" default['cookbook-openshift3']['openshift_node_debug_level'] = '2' default['cookbook-openshift3']['openshift_node_docker-storage'] = {} default['cookbook-openshift3']['openshift_node_label'] = node['cookbook-openshift3']['openshift_common_default_nodeSelector'] default['cookbook-openshift3']['openshift_node_iptables_sync_period'] = '5s' default['cookbook-openshift3']['openshift_node_max_pod'] = '40' default['cookbook-openshift3']['openshift_node_sdn_mtu_sdn'] = '1450' default['cookbook-openshift3']['openshift_node_minimum_container_ttl_duration'] = '10s' default['cookbook-openshift3']['openshift_node_maximum_dead_containers_per_container'] = '2' default['cookbook-openshift3']['openshift_node_maximum_dead_containers'] = '100' default['cookbook-openshift3']['openshift_node_image_gc_high_threshold'] = '90' default['cookbook-openshift3']['openshift_node_image_gc_low_threshold'] = '80' default['cookbook-openshift3']['erb_corsAllowedOrigins'] = ['127.0.0.1', 'localhost', node['cookbook-openshift3']['openshift_common_hostname'], node['cookbook-openshift3']['openshift_common_ip'], node['cookbook-openshift3']['openshift_common_public_hostname'], node['cookbook-openshift3']['openshift_common_public_ip']] + node['cookbook-openshift3']['openshift_common_svc_names'] default['cookbook-openshift3']['erb_etcdClientInfo_urls'] = [node['cookbook-openshift3']['openshift_master_etcd_url'], "https://#{node['cookbook-openshift3']['openshift_common_hostname']}:#{node['cookbook-openshift3']['openshift_master_etcd_port']}"] default['cookbook-openshift3']['master_generated_certs_dir'] = '/var/www/html/master/generated_certs' default['cookbook-openshift3']['etcd_conf_dir'] = '/etc/etcd' default['cookbook-openshift3']['etcd_ca_dir'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/ca" default['cookbook-openshift3']['etcd_generated_certs_dir'] = '/var/www/html/etcd/generated_certs' default['cookbook-openshift3']['etcd_ca_cert'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/ca.crt" default['cookbook-openshift3']['etcd_ca_peer'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/ca.crt" default['cookbook-openshift3']['etcd_cert_file'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/server.crt" default['cookbook-openshift3']['etcd_cert_key'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/server.key" default['cookbook-openshift3']['etcd_peer_file'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/peer.crt" default['cookbook-openshift3']['etcd_peer_key'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/peer.key" default['cookbook-openshift3']['etcd_openssl_conf'] = "#{node['cookbook-openshift3']['etcd_conf_dir']}/openssl.cnf" default['cookbook-openshift3']['etcd_ca_name'] = 'etcd_ca' default['cookbook-openshift3']['etcd_req_ext'] = 'etcd_v3_req' default['cookbook-openshift3']['etcd_ca_exts_peer'] = 'etcd_v3_ca_peer' default['cookbook-openshift3']['etcd_ca_exts_server'] = 'etcd_v3_ca_server' default['cookbook-openshift3']['etcd_initial_cluster_state'] = 'new' default['cookbook-openshift3']['etcd_initial_cluster_token'] = 'etcd-cluster-1' default['cookbook-openshift3']['etcd_data_dir'] = '/var/lib/etcd/' default['cookbook-openshift3']['etcd_default_days'] = '365' default['cookbook-openshift3']['etcd_client_port'] = '2379' default['cookbook-openshift3']['etcd_peer_port'] = '2380' default['cookbook-openshift3']['etcd_initial_advertise_peer_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_peer_port']}" default['cookbook-openshift3']['etcd_listen_peer_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_peer_port']}" default['cookbook-openshift3']['etcd_listen_client_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_client_port']}" default['cookbook-openshift3']['etcd_advertise_client_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_client_port']}" default['cookbook-openshift3']['etcd_listen_client_urls'] = "https://#{node['ipaddress']}:#{node['cookbook-openshift3']['etcd_client_port']}"
##### thumbor cookbook core attributes default['thumbor_ng']['version'] = '4.12.2' default['thumbor_ng']['workers'] = node['cpu']['total'] default['thumbor_ng']['base_port'] = 9000 default['thumbor_ng']['key'] = 'secretkey' default['thumbor_ng']['init_style'] = 'upstart' # options: upstart, initd default['thumbor_ng']['service_name'] = 'thumbor' default['thumbor_ng']['install_method'] = 'pip' default['thumbor_ng']['pip_dependencies'] = ['remotecv', 'graphicsmagick-engine', 'opencv-engine'] default['thumbor_ng']['listen_address'] = '127.0.0.1' default['thumbor_ng']['binary'] = '/usr/local/bin/thumbor' default['thumbor_ng']['upstart_respawn'] = true default['thumbor_ng']['conf_file'] = '/etc/thumbor.conf' default['thumbor_ng']['key_file'] = '/etc/thumbor.key' default['thumbor_ng']['service_config_file'] = case node['platform_family'] when 'debian' '/etc/default/thumbor' when 'rhel' '/etc/sysconfig/thumbor' end default['thumbor_ng']['proxy'] = 'nginx' # options: nginx # notify restart to service default['thumbor_ng']['notify_restart'] = true # thumbor workers log location default['thumbor_ng']['log_dir'] = '/var/log/thumbor' # thumbor log level default['thumbor_ng']['log_level'] = 'warning' # thumbor logrotate default['thumbor_ng']['logrotate']['rotate'] = 7 # thumbor service user default['thumbor_ng']['setup_user'] = true default['thumbor_ng']['group'] = 'thumbor' default['thumbor_ng']['user'] = 'thumbor' default['thumbor_ng']['user_home'] = nil # thumbor process limits default['thumbor_ng']['limits']['memlock'] = 'unlimited' default['thumbor_ng']['limits']['nofile'] = 48_000 default['thumbor_ng']['limits']['nproc'] = 'unlimited' ##### thumbor configuration options # https://github.com/thumbor/thumbor/wiki/Configuration # For default parameters value, check out thumbor-config command # thumbor storage location default['thumbor_ng']['options']['FILE_STORAGE_ROOT_PATH'] = '/var/lib/thumbor/storage' default['thumbor_ng']['options']['RESULT_STORAGE_FILE_STORAGE_ROOT_PATH'] = '/var/lib/thumbor/result-storage' ##### monit default['thumbor_ng']['monit']['enable'] = false ##### nginx # keeping nginx configuration minimal. # modify attributes for cookbook nginx as per requirement # disable nginx default vhost node.default['nginx']['default_site_enabled'] = false node.default['nginx']['worker_connections'] = '4096' # nginx thumbor vhost configuration default['thumbor_ng']['nginx']['port'] = 80 default['thumbor_ng']['nginx']['enable_status'] = false default['thumbor_ng']['nginx']['server_name'] = node['fqdn'] default['thumbor_ng']['nginx']['client_max_body_size'] = '10M' default['thumbor_ng']['nginx']['proxy_read_timeout'] = '300' default['thumbor_ng']['nginx']['proxy_cache']['enabled'] = false default['thumbor_ng']['nginx']['proxy_cache']['path'] = '/var/www/thumbor_cache' default['thumbor_ng']['nginx']['proxy_cache']['key_zone'] = 'thumbor_cache' default['thumbor_ng']['nginx']['proxy_cache_valid'] = '900s' default['thumbor_ng']['nginx']['vhost']['cookbook'] = 'thumbor_ng' default['thumbor_ng']['nginx']['vhost']['template'] = 'nginx.vhost.erb' default['thumbor_ng']['nginx']['vhost']['variables'] = {} ##### redisio # keeping redis configuration minimal. # modify attributes for cookbook redisio as per requirement # setup local redis server default['thumbor_ng']['setup_redis'] = false node.default['redisio']['version'] = '2.8.17' bump thumbor version to 5.0.3 ##### thumbor cookbook core attributes default['thumbor_ng']['version'] = '5.0.3' default['thumbor_ng']['workers'] = node['cpu']['total'] default['thumbor_ng']['base_port'] = 9000 default['thumbor_ng']['key'] = 'secretkey' default['thumbor_ng']['init_style'] = 'upstart' # options: upstart, initd default['thumbor_ng']['service_name'] = 'thumbor' default['thumbor_ng']['install_method'] = 'pip' default['thumbor_ng']['pip_dependencies'] = ['remotecv', 'graphicsmagick-engine', 'opencv-engine'] default['thumbor_ng']['listen_address'] = '127.0.0.1' default['thumbor_ng']['binary'] = '/usr/local/bin/thumbor' default['thumbor_ng']['upstart_respawn'] = true default['thumbor_ng']['conf_file'] = '/etc/thumbor.conf' default['thumbor_ng']['key_file'] = '/etc/thumbor.key' default['thumbor_ng']['service_config_file'] = case node['platform_family'] when 'debian' '/etc/default/thumbor' when 'rhel' '/etc/sysconfig/thumbor' end default['thumbor_ng']['proxy'] = 'nginx' # options: nginx # notify restart to service default['thumbor_ng']['notify_restart'] = true # thumbor workers log location default['thumbor_ng']['log_dir'] = '/var/log/thumbor' # thumbor log level default['thumbor_ng']['log_level'] = 'warning' # thumbor logrotate default['thumbor_ng']['logrotate']['rotate'] = 7 # thumbor service user default['thumbor_ng']['setup_user'] = true default['thumbor_ng']['group'] = 'thumbor' default['thumbor_ng']['user'] = 'thumbor' default['thumbor_ng']['user_home'] = nil # thumbor process limits default['thumbor_ng']['limits']['memlock'] = 'unlimited' default['thumbor_ng']['limits']['nofile'] = 48_000 default['thumbor_ng']['limits']['nproc'] = 'unlimited' ##### thumbor configuration options # https://github.com/thumbor/thumbor/wiki/Configuration # For default parameters value, check out thumbor-config command # thumbor storage location default['thumbor_ng']['options']['FILE_STORAGE_ROOT_PATH'] = '/var/lib/thumbor/storage' default['thumbor_ng']['options']['RESULT_STORAGE_FILE_STORAGE_ROOT_PATH'] = '/var/lib/thumbor/result-storage' ##### monit default['thumbor_ng']['monit']['enable'] = false ##### nginx # keeping nginx configuration minimal. # modify attributes for cookbook nginx as per requirement # disable nginx default vhost node.default['nginx']['default_site_enabled'] = false node.default['nginx']['worker_connections'] = '4096' # nginx thumbor vhost configuration default['thumbor_ng']['nginx']['port'] = 80 default['thumbor_ng']['nginx']['enable_status'] = false default['thumbor_ng']['nginx']['server_name'] = node['fqdn'] default['thumbor_ng']['nginx']['client_max_body_size'] = '10M' default['thumbor_ng']['nginx']['proxy_read_timeout'] = '300' default['thumbor_ng']['nginx']['proxy_cache']['enabled'] = false default['thumbor_ng']['nginx']['proxy_cache']['path'] = '/var/www/thumbor_cache' default['thumbor_ng']['nginx']['proxy_cache']['key_zone'] = 'thumbor_cache' default['thumbor_ng']['nginx']['proxy_cache_valid'] = '900s' default['thumbor_ng']['nginx']['vhost']['cookbook'] = 'thumbor_ng' default['thumbor_ng']['nginx']['vhost']['template'] = 'nginx.vhost.erb' default['thumbor_ng']['nginx']['vhost']['variables'] = {} ##### redisio # keeping redis configuration minimal. # modify attributes for cookbook redisio as per requirement # setup local redis server default['thumbor_ng']['setup_redis'] = false node.default['redisio']['version'] = '2.8.17'
# Encoding: UTF-8 default[:etcd][:install_method] = 'binary' # address to announce to peers specified as ip:port or ip (will default to :7001) default[:etcd][:peer_addr] = '' # the adress that etcd uses publically. if not set we compute it to node.ipaddress:4001 default[:etcd][:addr] = '' # set if you want to override the node name. It uses fqdn by default default[:etcd][:name] = nil # cluster options default[:etcd][:seed_node] = nil # if you wrap this cookbook you should use your wrappers cook name here default[:etcd][:search_cook] = 'etcd\:\:cluster' # set to false if you don't want environment scoped searching default[:etcd][:env_scope] = true # service start args to pass default[:etcd][:args] = '' # v0.3.0 API cluster discovery default[:etcd][:discovery] = '' # nodes in cluster default[:etcd][:nodes] = [] # Activate snapshoting default[:etcd][:snapshot] = true # restart etcd when the config file is updated default[:etcd][:trigger_restart] = true # Upstart parameters for starting/stopping etcd service default[:etcd][:upstart][:start_on] = 'started networking' default[:etcd][:upstart][:stop_on] = 'shutdown' # Release to install default[:etcd][:version] = '0.4.2' # Auto respawn default[:etcd][:respawn] = false # Sha for github tarball Linux by default default[:etcd][:sha256] = '18be476ba59db42c573ee23fbe00f4a205830ac54f752c0d46280707603c9192' # Use this to supply your own url to a tarball default[:etcd][:url] = nil # Etcd's backend storage default[:etcd][:state_dir] = '/var/cache/etcd/state' # Used for source_install method default[:etcd][:source][:repo] = 'https://github.com/coreos/etcd' default[:etcd][:source][:revision] = 'HEAD' default[:etcd][:source][:go_ver] = '1.1.2' default[:etcd][:source][:go_url] = nil default[:etcdctl][:source][:repo] = 'https://github.com/coreos/etcdctl' default[:etcdctl][:source][:revision] = 'HEAD' Etcd 0.4.3 # Encoding: UTF-8 default[:etcd][:install_method] = 'binary' # address to announce to peers specified as ip:port or ip (will default to :7001) default[:etcd][:peer_addr] = '' # the adress that etcd uses publically. if not set we compute it to node.ipaddress:4001 default[:etcd][:addr] = '' # set if you want to override the node name. It uses fqdn by default default[:etcd][:name] = nil # cluster options default[:etcd][:seed_node] = nil # if you wrap this cookbook you should use your wrappers cook name here default[:etcd][:search_cook] = 'etcd\:\:cluster' # set to false if you don't want environment scoped searching default[:etcd][:env_scope] = true # service start args to pass default[:etcd][:args] = '' # v0.3.0 API cluster discovery default[:etcd][:discovery] = '' # nodes in cluster default[:etcd][:nodes] = [] # Activate snapshoting default[:etcd][:snapshot] = true # restart etcd when the config file is updated default[:etcd][:trigger_restart] = true # Upstart parameters for starting/stopping etcd service default[:etcd][:upstart][:start_on] = 'started networking' default[:etcd][:upstart][:stop_on] = 'shutdown' # Release to install default[:etcd][:version] = '0.4.3' # Auto respawn default[:etcd][:respawn] = false # Sha for github tarball Linux by default default[:etcd][:sha256] = '18be476ba59db42c573ee23fbe00f4a205830ac54f752c0d46280707603c9192' # Use this to supply your own url to a tarball default[:etcd][:url] = nil # Etcd's backend storage default[:etcd][:state_dir] = '/var/cache/etcd/state' # Used for source_install method default[:etcd][:source][:repo] = 'https://github.com/coreos/etcd' default[:etcd][:source][:revision] = 'HEAD' default[:etcd][:source][:go_ver] = '1.1.2' default[:etcd][:source][:go_url] = nil default[:etcdctl][:source][:repo] = 'https://github.com/coreos/etcdctl' default[:etcdctl][:source][:revision] = 'HEAD'
default['supermarket_omnibus']['chef_server_url'] = nil default['supermarket_omnibus']['chef_oauth2_app_id'] = nil default['supermarket_omnibus']['chef_oauth2_secret'] = nil default['supermarket_omnibus']['chef_oauth2_verify_ssl'] = false default['supermarket_omnibus']['config'] = {} default['supermarket_omnibus']['package_url'] = nil default['supermarket_omnibus']['package_version'] = :latest default['supermarket_omnibus']['package_repo'] = 'stable' # Specify a recipe to install supermarket from a custom repo. default['supermarket_omnibus']['custom_repo_recipe'] = nil # Enable collaborator groups default['supermarket_omnibus']['config']['features'] = 'tools, gravatar, collaborator_groups' # use the following to consume integration builds: # default['supermarket_omnibus']['package_repo'] = 'current' Cookstyle fixes Signed-off-by: Tim Smith <764ef62106582a09ed09dfa0b6bff7c05fd7d1e4@chef.io> default['supermarket_omnibus']['chef_server_url'] = nil default['supermarket_omnibus']['chef_oauth2_app_id'] = nil default['supermarket_omnibus']['chef_oauth2_secret'] = nil default['supermarket_omnibus']['chef_oauth2_verify_ssl'] = false default['supermarket_omnibus']['config'] = {} default['supermarket_omnibus']['package_url'] = nil default['supermarket_omnibus']['package_version'] = :latest default['supermarket_omnibus']['package_repo'] = 'stable' # Specify a recipe to install supermarket from a custom repo. default['supermarket_omnibus']['custom_repo_recipe'] = nil # Enable collaborator groups default['supermarket_omnibus']['config']['features'] = 'tools, gravatar, collaborator_groups' # use the following to consume integration builds: # default['supermarket_omnibus']['package_repo'] = 'current'
default[:node][:version] = '7.9.0-1' default[:node][:major_version] = '7.x' default[:node][:schema] = 'https' case node[:platform_family] when 'debian' default[:node][:host] = 'deb.nodesource.com' when 'rhel' default[:node][:host] = 'rpm.nodesource.com' end # CENTOS # EPEL 6: https://rpm.nodesource.com/pub_5.x/el/6/x86_64/nodejs-5.7.1-1nodesource.el6.x86_64.rpm # EPEL 7: https://rpm.nodesource.com/pub_5.x/el/7/x86_64/nodejs-5.7.1-1nodesource.el7.centos.x86_64.rpm # 0.10 Release https://rpm.nodesource.com/pub_0.10/el/6/x86_64/nodejs-0.10.43-1nodesource.el6.x86_64.rpm # Debian # https://deb.nodesource.com/node_6.x/pool/main/n/nodejs/ feat: install Node 8 by default default[:node][:version] = '8.1.4-1' default[:node][:major_version] = '8.x' default[:node][:schema] = 'https' case node[:platform_family] when 'debian' default[:node][:host] = 'deb.nodesource.com' when 'rhel' default[:node][:host] = 'rpm.nodesource.com' end # CENTOS # EPEL 6: https://rpm.nodesource.com/pub_5.x/el/6/x86_64/nodejs-5.7.1-1nodesource.el6.x86_64.rpm # EPEL 7: https://rpm.nodesource.com/pub_5.x/el/7/x86_64/nodejs-5.7.1-1nodesource.el7.centos.x86_64.rpm # 0.10 Release https://rpm.nodesource.com/pub_0.10/el/6/x86_64/nodejs-0.10.43-1nodesource.el6.x86_64.rpm # Debian # https://deb.nodesource.com/node_6.x/pool/main/n/nodejs/
default[:tabula_rasa][:chef_version] = '11.10' default[:tabula_rasa][:recipes] = {} default[:tabula_rasa][:home_dir] = '/home/tabula-rasa' default[:tabula_rasa][:scm][:type] = "none" default[:tabula_rasa][:scm][:repository] = null default[:tabula_rasa][:scm][:user] = null default[:tabula_rasa][:scm][:password] = null default[:tabula_rasa][:scm][:revision] = null default[:tabula_rasa][:scm][:ssh_key] = null default[:tabula_rasa][:scm][:enable_submodules] = true Update default.rb default[:tabula_rasa][:chef_version] = '11.10' default[:tabula_rasa][:recipes] = {} default[:tabula_rasa][:home_dir] = '/home/tabula-rasa' default[:tabula_rasa][:scm] = {} default[:tabula_rasa][:scm][:type] = "none" default[:tabula_rasa][:scm][:repository] = null default[:tabula_rasa][:scm][:user] = null default[:tabula_rasa][:scm][:password] = null default[:tabula_rasa][:scm][:revision] = null default[:tabula_rasa][:scm][:ssh_key] = null default[:tabula_rasa][:scm][:enable_submodules] = true
# # Cookbook:: apache2 # Attributes:: mod_ssl # # Copyright:: 2012-2013, Chef Software, Inc. # Copyright:: 2014, Viverae, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['apache']['mod_ssl']['port'] = 443 default['apache']['mod_ssl']['protocol'] = 'All -SSLv2 -SSLv3' default['apache']['mod_ssl']['cipher_suite'] = 'EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA256:EECDH:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA128-SHA:AES128-SHA' default['apache']['mod_ssl']['honor_cipher_order'] = 'On' default['apache']['mod_ssl']['insecure_renegotiation'] = 'Off' default['apache']['mod_ssl']['strict_sni_vhost_check'] = 'Off' default['apache']['mod_ssl']['session_cache'] = 'shmcb:/var/run/apache2/ssl_scache' default['apache']['mod_ssl']['session_cache_timeout'] = 300 default['apache']['mod_ssl']['compression'] = 'Off' default['apache']['mod_ssl']['use_stapling'] = 'Off' default['apache']['mod_ssl']['stapling_responder_timeout'] = 5 default['apache']['mod_ssl']['stapling_return_responder_errors'] = 'Off' default['apache']['mod_ssl']['stapling_cache'] = 'shmcb:/var/run/ocsp(128000)' default['apache']['mod_ssl']['pass_phrase_dialog'] = 'builtin' default['apache']['mod_ssl']['mutex'] = 'file:/var/run/apache2/ssl_mutex' default['apache']['mod_ssl']['directives'] = {} default['apache']['mod_ssl']['pkg_name'] = 'mod_ssl' case node['platform_family'] when 'debian' case node['platform'] when 'ubuntu' if node['apache']['version'] == '2.4' default['apache']['mod_ssl']['pass_phrase_dialog'] = 'exec:/usr/share/apache2/ask-for-passphrase' end end when 'freebsd' default['apache']['mod_ssl']['session_cache'] = 'shmcb:/var/run/ssl_scache(512000)' default['apache']['mod_ssl']['mutex'] = 'file:/var/run/ssl_mutex' when 'amazon' if node['apache']['version'] == '2.4' default['apache']['mod_ssl']['pkg_name'] = 'mod24_ssl' end when 'rhel', 'fedora', 'suse' case node['platform'] when 'amazon' if node['apache']['version'] == '2.4' default['apache']['mod_ssl']['pkg_name'] = 'mod24_ssl' end end default['apache']['mod_ssl']['session_cache'] = 'shmcb:/var/cache/mod_ssl/scache(512000)' default['apache']['mod_ssl']['mutex'] = 'default' end Fix a Chef 13 amazon incompatibility Signed-off-by: Tim Smith <764ef62106582a09ed09dfa0b6bff7c05fd7d1e4@chef.io> # # Cookbook:: apache2 # Attributes:: mod_ssl # # Copyright:: 2012-2013, Chef Software, Inc. # Copyright:: 2014, Viverae, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['apache']['mod_ssl']['port'] = 443 default['apache']['mod_ssl']['protocol'] = 'All -SSLv2 -SSLv3' default['apache']['mod_ssl']['cipher_suite'] = 'EDH+CAMELLIA:EDH+aRSA:EECDH+aRSA+AESGCM:EECDH+aRSA+SHA256:EECDH:+CAMELLIA128:+AES128:+SSLv3:!aNULL:!eNULL:!LOW:!3DES:!MD5:!EXP:!PSK:!DSS:!RC4:!SEED:!IDEA:!ECDSA:kEDH:CAMELLIA128-SHA:AES128-SHA' default['apache']['mod_ssl']['honor_cipher_order'] = 'On' default['apache']['mod_ssl']['insecure_renegotiation'] = 'Off' default['apache']['mod_ssl']['strict_sni_vhost_check'] = 'Off' default['apache']['mod_ssl']['session_cache'] = 'shmcb:/var/run/apache2/ssl_scache' default['apache']['mod_ssl']['session_cache_timeout'] = 300 default['apache']['mod_ssl']['compression'] = 'Off' default['apache']['mod_ssl']['use_stapling'] = 'Off' default['apache']['mod_ssl']['stapling_responder_timeout'] = 5 default['apache']['mod_ssl']['stapling_return_responder_errors'] = 'Off' default['apache']['mod_ssl']['stapling_cache'] = 'shmcb:/var/run/ocsp(128000)' default['apache']['mod_ssl']['pass_phrase_dialog'] = 'builtin' default['apache']['mod_ssl']['mutex'] = 'file:/var/run/apache2/ssl_mutex' default['apache']['mod_ssl']['directives'] = {} default['apache']['mod_ssl']['pkg_name'] = 'mod_ssl' case node['platform_family'] when 'debian' case node['platform'] when 'ubuntu' if node['apache']['version'] == '2.4' default['apache']['mod_ssl']['pass_phrase_dialog'] = 'exec:/usr/share/apache2/ask-for-passphrase' end end when 'freebsd' default['apache']['mod_ssl']['session_cache'] = 'shmcb:/var/run/ssl_scache(512000)' default['apache']['mod_ssl']['mutex'] = 'file:/var/run/ssl_mutex' when 'amazon' if node['apache']['version'] == '2.4' default['apache']['mod_ssl']['pkg_name'] = 'mod24_ssl' end when 'rhel', 'fedora', 'suse', 'amazon' case node['platform'] when 'amazon' # This is for chef 12 compatibility if node['apache']['version'] == '2.4' default['apache']['mod_ssl']['pkg_name'] = 'mod24_ssl' end end default['apache']['mod_ssl']['session_cache'] = 'shmcb:/var/cache/mod_ssl/scache(512000)' default['apache']['mod_ssl']['mutex'] = 'default' 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 = "authpwn_rails" s.version = "0.14.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Victor Costan"] s.date = "2013-12-11" s.description = "Works with Facebook." s.email = "victor@costan.us" s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".project", ".travis.yml", "Gemfile", "Gemfile.lock", "Gemfile.rails3", "Gemfile.rails4", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "app/helpers/session_helper.rb", "app/models/credentials/email.rb", "app/models/credentials/facebook.rb", "app/models/credentials/password.rb", "app/models/tokens/base.rb", "app/models/tokens/email_verification.rb", "app/models/tokens/one_time.rb", "app/models/tokens/password_reset.rb", "app/models/tokens/session_uid.rb", "authpwn_rails.gemspec", "legacy/migrate_011_to_012.rb", "legacy/migrate_09_to_010.rb", "lib/authpwn_rails.rb", "lib/authpwn_rails/credential_model.rb", "lib/authpwn_rails/current_user.rb", "lib/authpwn_rails/engine.rb", "lib/authpwn_rails/expires.rb", "lib/authpwn_rails/facebook_session.rb", "lib/authpwn_rails/generators/all_generator.rb", "lib/authpwn_rails/generators/templates/001_create_users.rb", "lib/authpwn_rails/generators/templates/003_create_credentials.rb", "lib/authpwn_rails/generators/templates/credential.rb", "lib/authpwn_rails/generators/templates/credentials.yml", "lib/authpwn_rails/generators/templates/initializer.rb", "lib/authpwn_rails/generators/templates/session/forbidden.html.erb", "lib/authpwn_rails/generators/templates/session/home.html.erb", "lib/authpwn_rails/generators/templates/session/new.html.erb", "lib/authpwn_rails/generators/templates/session/password_change.html.erb", "lib/authpwn_rails/generators/templates/session/welcome.html.erb", "lib/authpwn_rails/generators/templates/session_controller.rb", "lib/authpwn_rails/generators/templates/session_controller_test.rb", "lib/authpwn_rails/generators/templates/session_mailer.rb", "lib/authpwn_rails/generators/templates/session_mailer/email_verification_email.html.erb", "lib/authpwn_rails/generators/templates/session_mailer/email_verification_email.text.erb", "lib/authpwn_rails/generators/templates/session_mailer/reset_password_email.html.erb", "lib/authpwn_rails/generators/templates/session_mailer/reset_password_email.text.erb", "lib/authpwn_rails/generators/templates/session_mailer_test.rb", "lib/authpwn_rails/generators/templates/user.rb", "lib/authpwn_rails/generators/templates/users.yml", "lib/authpwn_rails/http_basic.rb", "lib/authpwn_rails/routes.rb", "lib/authpwn_rails/session.rb", "lib/authpwn_rails/session_controller.rb", "lib/authpwn_rails/session_mailer.rb", "lib/authpwn_rails/test_extensions.rb", "lib/authpwn_rails/user_extensions/email_field.rb", "lib/authpwn_rails/user_extensions/facebook_fields.rb", "lib/authpwn_rails/user_extensions/password_field.rb", "lib/authpwn_rails/user_model.rb", "test/cookie_controller_test.rb", "test/credentials/email_credential_test.rb", "test/credentials/email_verification_token_test.rb", "test/credentials/facebook_credential_test.rb", "test/credentials/one_time_token_credential_test.rb", "test/credentials/password_credential_test.rb", "test/credentials/password_reset_token_test.rb", "test/credentials/session_uid_token_test.rb", "test/credentials/token_crendential_test.rb", "test/facebook_controller_test.rb", "test/fixtures/bare_session/forbidden.html.erb", "test/fixtures/bare_session/home.html.erb", "test/fixtures/bare_session/new.html.erb", "test/fixtures/bare_session/password_change.html.erb", "test/fixtures/bare_session/welcome.html.erb", "test/helpers/action_controller.rb", "test/helpers/action_mailer.rb", "test/helpers/application_controller.rb", "test/helpers/autoload_path.rb", "test/helpers/db_setup.rb", "test/helpers/fbgraph.rb", "test/helpers/rails.rb", "test/helpers/rails_undo.rb", "test/helpers/routes.rb", "test/helpers/view_helpers.rb", "test/http_basic_controller_test.rb", "test/initializer_test.rb", "test/routes_test.rb", "test/session_controller_api_test.rb", "test/session_mailer_api_test.rb", "test/test_extensions_test.rb", "test/test_helper.rb", "test/user_extensions/email_field_test.rb", "test/user_extensions/facebook_fields_test.rb", "test/user_extensions/password_field_test.rb", "test/user_test.rb" ] s.homepage = "http://github.com/pwnall/authpwn_rails" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "2.0.14" s.summary = "User authentication for Rails 3 applications." if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<fbgraph_rails>, [">= 0.2.2"]) s.add_runtime_dependency(%q<rails>, [">= 3.2.16"]) s.add_development_dependency(%q<bundler>, [">= 1.3.5"]) s.add_development_dependency(%q<mocha>, [">= 0.14.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.8"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<mysql2>, [">= 0.3.14"]) s.add_development_dependency(%q<pg>, [">= 0.17.0"]) s.add_development_dependency(%q<sqlite3>, [">= 1.3.8"]) else s.add_dependency(%q<fbgraph_rails>, [">= 0.2.2"]) s.add_dependency(%q<rails>, [">= 3.2.16"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<mocha>, [">= 0.14.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.8"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<mysql2>, [">= 0.3.14"]) s.add_dependency(%q<pg>, [">= 0.17.0"]) s.add_dependency(%q<sqlite3>, [">= 1.3.8"]) end else s.add_dependency(%q<fbgraph_rails>, [">= 0.2.2"]) s.add_dependency(%q<rails>, [">= 3.2.16"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<mocha>, [">= 0.14.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.8"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<mysql2>, [">= 0.3.14"]) s.add_dependency(%q<pg>, [">= 0.17.0"]) s.add_dependency(%q<sqlite3>, [">= 1.3.8"]) end end Regenerate gemspec for version 0.15.0 # 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 = "authpwn_rails" s.version = "0.15.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Victor Costan"] s.date = "2013-12-11" s.description = "Works with Facebook." s.email = "victor@costan.us" s.extra_rdoc_files = [ "LICENSE", "README.rdoc" ] s.files = [ ".document", ".project", ".travis.yml", "Gemfile", "Gemfile.lock", "Gemfile.rails3", "Gemfile.rails4", "LICENSE", "README.rdoc", "Rakefile", "VERSION", "app/helpers/session_helper.rb", "app/models/credentials/email.rb", "app/models/credentials/facebook.rb", "app/models/credentials/password.rb", "app/models/tokens/base.rb", "app/models/tokens/email_verification.rb", "app/models/tokens/one_time.rb", "app/models/tokens/password_reset.rb", "app/models/tokens/session_uid.rb", "authpwn_rails.gemspec", "legacy/migrate_011_to_012.rb", "legacy/migrate_09_to_010.rb", "lib/authpwn_rails.rb", "lib/authpwn_rails/credential_model.rb", "lib/authpwn_rails/current_user.rb", "lib/authpwn_rails/engine.rb", "lib/authpwn_rails/expires.rb", "lib/authpwn_rails/facebook_session.rb", "lib/authpwn_rails/generators/all_generator.rb", "lib/authpwn_rails/generators/templates/001_create_users.rb", "lib/authpwn_rails/generators/templates/003_create_credentials.rb", "lib/authpwn_rails/generators/templates/credential.rb", "lib/authpwn_rails/generators/templates/credentials.yml", "lib/authpwn_rails/generators/templates/initializer.rb", "lib/authpwn_rails/generators/templates/session.rb", "lib/authpwn_rails/generators/templates/session/forbidden.html.erb", "lib/authpwn_rails/generators/templates/session/home.html.erb", "lib/authpwn_rails/generators/templates/session/new.html.erb", "lib/authpwn_rails/generators/templates/session/password_change.html.erb", "lib/authpwn_rails/generators/templates/session/welcome.html.erb", "lib/authpwn_rails/generators/templates/session_controller.rb", "lib/authpwn_rails/generators/templates/session_controller_test.rb", "lib/authpwn_rails/generators/templates/session_mailer.rb", "lib/authpwn_rails/generators/templates/session_mailer/email_verification_email.html.erb", "lib/authpwn_rails/generators/templates/session_mailer/email_verification_email.text.erb", "lib/authpwn_rails/generators/templates/session_mailer/reset_password_email.html.erb", "lib/authpwn_rails/generators/templates/session_mailer/reset_password_email.text.erb", "lib/authpwn_rails/generators/templates/session_mailer_test.rb", "lib/authpwn_rails/generators/templates/user.rb", "lib/authpwn_rails/generators/templates/users.yml", "lib/authpwn_rails/http_basic.rb", "lib/authpwn_rails/routes.rb", "lib/authpwn_rails/session.rb", "lib/authpwn_rails/session_controller.rb", "lib/authpwn_rails/session_mailer.rb", "lib/authpwn_rails/session_model.rb", "lib/authpwn_rails/test_extensions.rb", "lib/authpwn_rails/user_extensions/email_field.rb", "lib/authpwn_rails/user_extensions/facebook_fields.rb", "lib/authpwn_rails/user_extensions/password_field.rb", "lib/authpwn_rails/user_model.rb", "test/cookie_controller_test.rb", "test/credentials/email_credential_test.rb", "test/credentials/email_verification_token_test.rb", "test/credentials/facebook_credential_test.rb", "test/credentials/one_time_token_credential_test.rb", "test/credentials/password_credential_test.rb", "test/credentials/password_reset_token_test.rb", "test/credentials/session_uid_token_test.rb", "test/credentials/token_crendential_test.rb", "test/facebook_controller_test.rb", "test/fixtures/bare_session/forbidden.html.erb", "test/fixtures/bare_session/home.html.erb", "test/fixtures/bare_session/new.html.erb", "test/fixtures/bare_session/password_change.html.erb", "test/fixtures/bare_session/welcome.html.erb", "test/helpers/action_controller.rb", "test/helpers/action_mailer.rb", "test/helpers/application_controller.rb", "test/helpers/autoload_path.rb", "test/helpers/db_setup.rb", "test/helpers/fbgraph.rb", "test/helpers/rails.rb", "test/helpers/rails_undo.rb", "test/helpers/routes.rb", "test/helpers/view_helpers.rb", "test/http_basic_controller_test.rb", "test/initializer_test.rb", "test/routes_test.rb", "test/session_controller_api_test.rb", "test/session_mailer_api_test.rb", "test/session_test.rb", "test/test_extensions_test.rb", "test/test_helper.rb", "test/user_extensions/email_field_test.rb", "test/user_extensions/facebook_fields_test.rb", "test/user_extensions/password_field_test.rb", "test/user_test.rb" ] s.homepage = "http://github.com/pwnall/authpwn_rails" s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = "2.0.14" s.summary = "User authentication for Rails 3 applications." if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<fbgraph_rails>, [">= 0.2.2"]) s.add_runtime_dependency(%q<rails>, [">= 3.2.16"]) s.add_development_dependency(%q<bundler>, [">= 1.3.5"]) s.add_development_dependency(%q<mocha>, [">= 0.14.0"]) s.add_development_dependency(%q<jeweler>, [">= 1.8.8"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<mysql2>, [">= 0.3.14"]) s.add_development_dependency(%q<pg>, [">= 0.17.0"]) s.add_development_dependency(%q<sqlite3>, [">= 1.3.8"]) else s.add_dependency(%q<fbgraph_rails>, [">= 0.2.2"]) s.add_dependency(%q<rails>, [">= 3.2.16"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<mocha>, [">= 0.14.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.8"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<mysql2>, [">= 0.3.14"]) s.add_dependency(%q<pg>, [">= 0.17.0"]) s.add_dependency(%q<sqlite3>, [">= 1.3.8"]) end else s.add_dependency(%q<fbgraph_rails>, [">= 0.2.2"]) s.add_dependency(%q<rails>, [">= 3.2.16"]) s.add_dependency(%q<bundler>, [">= 1.3.5"]) s.add_dependency(%q<mocha>, [">= 0.14.0"]) s.add_dependency(%q<jeweler>, [">= 1.8.8"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<mysql2>, [">= 0.3.14"]) s.add_dependency(%q<pg>, [">= 0.17.0"]) s.add_dependency(%q<sqlite3>, [">= 1.3.8"]) end end
# Lower-level foosey functions # database wrapper function that makes it so we don't have to copy code later # also makes sure the block is performed in a transaction for thread safety # note that you must use the return keyword at the end of these blocks because # the transaction block returns its own values def database db = SQLite3::Database.new 'foosey.db' yield db rescue SQLite3::Exception => e puts e puts e.backtrace ensure db.close if db end # dank helper function that returns an array of hashes from execute2 output def create_query_hash(array) names = array.shift rval = [] array.each do |r| row = {} names.each_with_index { |column, idx| row[column] = r[idx] } rval << row end rval end # takes a game_id and returns a string of the game results useful for slack # if date = true, it will be prepended with a nicely formatted date def game_to_s(game_id, date, league_id) database do |db| game = create_query_hash(db.execute2('SELECT p.DisplayName, g.Score, g.Timestamp FROM Game g JOIN Player p USING (PlayerID) WHERE g.GameID = :game_id AND g.LeagueID = :league_id AND p.LeagueID = :league_id ORDER BY g.Score DESC', game_id, league_id)) s = if date Time.at(game.first['Timestamp']).strftime '%b %d, %Y - ' else '' end game.each do |player| s << "#{player['DisplayName']} #{player['Score']} " end return s.strip end end def message_slack(text, attach, url) data = { username: 'Foosey', channel: '#foosey', text: text, attachments: attach, icon_url: 'http://foosey.futbol/icon.png' } uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_version = :TLSv1 http.verify_mode = OpenSSL::SSL::VERIFY_PEER req = Net::HTTP::Post.new(uri.request_uri) req.body = data.to_json req['Content-Type'] = 'application/json' http.request(req) end # true if a game with the given id exists, false otherwise def valid_game?(game_id, league_id) database do |db| game = db.get_first_value 'SELECT GameID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id return !game.nil? end end # true if a player with the given id exists, false otherwise def valid_player?(player_id, league_id) database do |db| player = db.get_first_value 'SELECT PlayerID FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id return !player.nil? end end # true if league exists def league_exists?(league_name) database do |db| league = db.get_first_value 'SELECT * FROM League WHERE LeagueName = :league_name', league_name return !league.nil? end end # pull and load # hot hot hot deploys def update app_dir = app_dir # there's probably a git gem we could use here system "cd #{app_dir} && git pull" unless app_dir.nil? system "cd #{File.dirname(__FILE__)} && git pull" end def admin?(slack_name, league_id = 1) database do |db| admin = db.get_first_value 'SELECT Admin from Player WHERE SlackName = :slack_name AND LeagueID = :league_id COLLATE NOCASE', slack_name, league_id return admin == 1 end end def app_dir database do |db| # return dir return db.get_first_value 'SELECT Value FROM Config WHERE Setting = "AppDirectory"' end end # returns array of players and their badges in a given league def badges(league_id, player_id) # get players players = player_ids league_id badges = Hash.new { |h, k| h[k] = [] } all_games = game_ids(league_id) # plays a lot players.each do |p| badges[p] << badge('⚠️', 'Very Active') if games_this_week(p, league_id) > 50 end # fire badge # best daily change best_change = players.group_by { |p| daily_elo_change(p, league_id) }.max best_change.last.each { |b| badges[b] << badge('🔥', 'On Fire') } if !best_change.nil? && best_change.first >= 10 # poop badge # worst daily change worst_change = players.group_by { |p| daily_elo_change(p, league_id) }.min worst_change.last.each { |b| badges[b] << badge('💩', 'Rough Day') } if !worst_change.nil? && worst_change.first <= -10 # baby badge # 10-15 games played babies = players.select do |p| games_with_player(p, league_id).length.between?(10, 15) end babies.each { |b| badges[b] << badge('👶🏼', 'Newly Ranked') } unless all_games.length < 100 || babies.nil? # monkey badge # won last game but elo went down # flexing badge # won last game and gained 10+ elo players.select do |p| games = games_with_player(p, league_id) next if games.empty? last_game = api_game(games.first, league_id) winner = last_game[:teams][0][:players].any? { |a| a[:playerID] == p } badges[p] << badge('🙈', 'Monkey\'d') if last_game[:teams][0][:delta] < 0 && winner badges[p] << badge('🍌', 'Graceful Loss') if last_game[:teams][0][:delta] < 0 && !winner badges[p] << badge('💪🏼', 'Hefty Win') if last_game[:teams][0][:delta] >= 10 && winner badges[p] << badge('🤕', 'Hospital Bound') if last_game[:teams][0][:delta] >= 10 && !winner end # toilet badge # last skunk (lost w/ 0 points) toilet_game = all_games.find do |g| (api_game(g, league_id)[:teams][1][:score]).zero? end toilets = api_game(toilet_game, league_id)[:teams][1][:players] if toilet_game toilets.each { |b| badges[b[:playerID]] << badge('🚽', 'Get Rekt') } unless toilets.nil? # win streak badges # 5 and 10 current win streak win_streaks = {} players.each do |p| games = games_with_player(p, league_id) last_wins = games.take_while do |g| game = api_game(g, league_id) game[:teams][0][:players].any? { |a| a[:playerID] == p } end win_streaks[p] = last_wins.length end win_streaks.each do |p, s| badges[p] << badge("#{s}⃣", "#{s}-Win Streak") if s.between?(3, 9) badges[p] << badge('🔟', "#{s}-Win Streak") if s == 10 badges[p] << badge('💰', "#{s}-Win Streak") if s > 10 end # zzz badge # hasn't played a game in 2 weeks if league_id == 1 sleepers = players.select do |p| player_snoozin(p, league_id) end sleepers.each { |b| badges[b] << badge('💤', 'Snoozin\'') } end # nemesis and ally badges if player_id > 0 nemeses = [] allies = [] you = api_player(player_id, true, league_id) players.each do |p| this_player = api_player(p, false, league_id) nemeses << p if this_player[:displayName] == you[:nemesis] allies << p if this_player[:displayName] == you[:ally] end nemeses.each { |b| badges[b] << badge('😈', 'Your Nemesis') } allies.each { |b| badges[b] << badge('😇', 'Your Ally') } end # build hash badges.collect do |k, v| { playerID: k, badges: v } end end def badge(emoji, definition) { emoji: emoji, definition: definition } end def player_snoozin(player_id, league_id) games = games_with_player(player_id, league_id) return false if games.length < 10 last_game = api_game(games.first, league_id) Time.now.to_i - last_game[:timestamp] > 1_209_600 # 2 weeks end # returns the respective elo deltas given two ratings and two scores def elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # elo math please never quiz me on this expected_a = 1 / (1 + 10**((rating_b - rating_a) / 800.to_f)) expected_b = 1 / (1 + 10**((rating_a - rating_b) / 800.to_f)) outcome_a = score_a / (score_a + score_b).to_f if outcome_a < 0.5 # a won outcome_a **= win_weight outcome_b = 1 - outcome_a else # b won outcome_b = (1 - outcome_a)**win_weight outcome_a = 1 - outcome_b end # divide elo change to be smaller if it wasn't a full game to 10 ratio = [score_a, score_b].max / max_score.to_f # calculate elo change delta_a = (k_factor * (outcome_a - expected_a) * ratio).round delta_b = (k_factor * (outcome_b - expected_b) * ratio).round [delta_a, delta_b] end # returns an array of all game ids def game_ids(league_id) database do |db| # return id return db.execute('SELECT DISTINCT GameID FROM Game WHERE LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', league_id).flatten end end def history(league_id, ids) database do |db| games = db.execute 'SELECT GameID, GROUP_CONCAT(g.PlayerID), GROUP_CONCAT(p.DisplayName), GROUP_CONCAT(g.Score), timestamp FROM Game g JOIN Player p using (PlayerID) WHERE g.LeagueID = :league_id GROUP BY g.GameID ORDER BY timestamp DESC', league_id the_games = [] games.each do |game| game_id = game[0] player_ids = game[1].split(',') names = game[2].split(',') scores = game[3].split(',') timestamp = game[4] looking_for = ids.split(',') # skip to next game if doesn't contain the same players # skip if a doubles game and teams don't match next if looking_for.sort != player_ids.sort || (looking_for.length == 4 && scores[player_ids.index(looking_for[0])] != scores[player_ids.index(looking_for[1])]) response = { gameID: game_id, timestamp: timestamp, teams: [] } player_ids.each_with_index do |player_id, idx| i = response[:teams].index { |t| t[:score] == scores[idx].to_i } if i # team exists in hash response[:teams][i][:players] << { playerID: player_id.to_i, displayName: names[idx] } else response[:teams] << { players: [{ playerID: player_id.to_i, displayName: names[idx] }], score: scores[idx].to_i, delta: elo_change(player_id, game_id, league_id).to_i } end end response[:teams] = response[:teams].sort! { |a, b| b[:score] <=> a[:score] } the_games << response end return the_games end end # returns an array of game ids involving player with id player_id def games_with_player(player_id, league_id) database do |db| return db.execute('SELECT GameID From Game WHERE PlayerID = :player_id AND LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', player_id, league_id).flatten end end # returns an array of game ids involving only both player1 and player2 def games(player1_id, player2_id, league_id) database do |db| return db.execute('SELECT GameID FROM ( SELECT GameID FROM Game WHERE PlayerID IN (:player1_id, :player2_id) AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T1 JOIN ( SELECT GameID FROM Game AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T2 USING (GameID)', player1_id, player2_id, league_id).flatten end end # returns the id of a player, given their display name def id(name, league_id) database do |db| # return id return db.get_first_value 'SELECT PlayerID FROM Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end # returns the elo change over the last 24 hours for the specified player def daily_elo_change(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return today - 1200 unless prev return today - prev end end def daily_ladder_move(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return 0 unless prev return today - prev end end def games_this_week(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i week_ago = midnight - 604_800 return db.get_first_value('SELECT COUNT(GameID) FROM Game g WHERE g.PlayerID = :player_id AND g.LeagueID = :league_id AND g.Timestamp >= :week_ago', player_id, league_id, week_ago) end end def extended_stats(player_id, league_id) database do |db| allies = Hash.new(0) # key -> player_id, value -> wins nemeses = Hash.new(0) # key -> player_id, value -> losses singles_games = 0 singles_wins = 0 doubles_games = 0 doubles_wins = 0 db.execute('SELECT DISTINCT GameID FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) case game.length when 2 singles_games += 1 if game[1]['PlayerID'] == player_id # this player won singles_wins += 1 else # this player lost nemeses[game[1]['PlayerID']] += 1 end when 4 doubles_games += 1 idx = game.index { |g| g['PlayerID'] == player_id } if idx >= 2 # this player won doubles_wins += 1 allies[game[idx == 2 ? 3 : 2]['PlayerID']] += 1 end end end ally = allies.max_by { |_k, v| v } || ['Nobody', 0] nemesis = nemeses.max_by { |_k, v| v } || ['Nobody', 0] doubles_win_rate = doubles_wins / doubles_games.to_f singles_win_rate = singles_wins / singles_games.to_f return { ally: name(ally[0], league_id), allyCount: ally[1], doublesWinRate: doubles_win_rate.nan? ? nil : doubles_win_rate, doublesTotal: doubles_games, nemesis: name(nemesis[0], league_id), nemesisCount: nemesis[1], singlesWinRate: singles_win_rate.nan? ? nil : singles_win_rate, singlesTotal: singles_games, pastWeek: games_this_week(player_id, league_id) } end end def elo(player_id, game_id, league_id) database do |db| game_id ||= game_ids(league_id).last elo = db.get_first_value 'SELECT Elo FROM EloHistory WHERE PlayerID = :player_id AND LeagueID = :league_id AND GameID = :game_id', player_id, league_id, game_id # 1200 in case they have no games return elo || 1200 end end # returns the elo change for player with id player_id from game with id game_id # if the player was not involved in the game, the delta of their last game # before game with id game_id will be returned # if the player doesn't exist or has no games, 0 will be returned def elo_change(player_id, game_id, league_id) database do |db| # get game timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id elos = db.execute('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp <= :timestamp ORDER BY g.Timestamp DESC, g.GameID DESC LIMIT 2', player_id, league_id, timestamp).flatten # safety if player doesn't have any games return 0 if elos.empty? # safety if there is only one game, so we should delta from 1200 return elos.first - 1200 if elos.length == 1 return elos.first - elos.last end end # returns a player's display name, given id def name(player_id, league_id) database do |db| return db.get_first_value 'SELECT DisplayName FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id end end # returns an array of active players # sorted by PlayerID # NOTE: index != PlayerID def names(league_id) database do |db| return db.execute('SELECT DisplayName FROM Player WHERE ACTIVE = 1 AND LeagueID = :league_id', league_id).flatten end end # returns an array of elo/names def player_elos(league_id) database do |db| return db.execute('SELECT DisplayName, Elo from Player WHERE ACTIVE = 1 AND LeagueID = :league_id AND GamesPlayed >= 10 ORDER BY Elo DESC', league_id) end end # returns true if a player with DisplayName name is in the database # false otherwise def player_exists?(name, league_id, player_id = 0) database do |db| player = db.get_first_value 'SELECT * from Player WHERE DisplayName = :name AND LeagueID = :league_id AND PlayerID != :player_id COLLATE NOCASE', name, league_id, player_id return !player.nil? end end # returns an array of all player ids def player_ids(league_id) database do |db| # return id return db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id ORDER BY PlayerID', league_id).flatten end end # returns the id of the winning player (or players) in game with id id def winner(game_id, league_id) database do |db| # get max score winner = db.execute('SELECT PlayerID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id AND Score = ( SELECT MAX(Score) FROM Game WHERE GameID = :game_id AND LeagueID = :league_id GROUP BY GameID )', game_id, league_id).flatten winner = winner.first if winner.length == 1 # return the winner(s) return winner end end # add a game to the database and update the history tables # outcome is hash containing key/value pairs where # key = player id # value = score # it's a little wonky but we need to support games of any number of # players/score combinations, so i think it's best def add_game(outcome, league_id, timestamp) database do |db| # get unix time timestamp ||= Time.now.to_i # get next game id game_id = 1 + db.get_first_value('SELECT GameID FROM Game ORDER BY GameID DESC LIMIT 1') # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end # calling recalc with timestamp means we update elo properly for the # new game, regardless of the time it was played recalc(league_id, timestamp) players = outcome.keys.collect do |player_id| { name: name(player_id, league_id), elo: elo(player_id, game_id, league_id), delta: elo_change(player_id, game_id, league_id) } end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' unless league_id != 1 || slack_url.empty? text = "Game added: #{game_to_s(game_id, false, league_id)}" attachments = [{ fields: players.collect do |p| delta = p[:delta] >= 0 ? "+#{p[:delta]}" : p[:delta] { title: p[:name], value: "#{p[:elo]} (#{delta})", short: true } end }] message_slack(text, attachments, slack_url) end return { gameID: game_id, players: players } end end # adds a player to the database def add_player(league_id, name, slack_name = '', admin = false, active = true) database do |db| db.execute 'INSERT INTO Player (LeagueID, DisplayName, SlackName, Admin, Active) VALUES (:league_id, :name, :slack_name, :admin, :active)', league_id, name, slack_name, admin ? 1 : 0, active ? 1 : 0 recalc_elo(Time.now.to_i, league_id) return db.get_first_value 'SELECT PlayerID from Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end def add_league(league_name, display_name) database do |db| return db.execute 'INSERT INTO League (LeagueName, DisplayName) VALUES (:league_name, :display_name)', league_name, display_name end end # changes properties of game with id game_id def edit_game(league_id, game_id, outcome, timestamp = nil, rec = true) database do |db| # get timestamp if we need to keep it unchanged timestamp ||= db.get_first_value 'SELECT Timestamp FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # delete game with id game_id db.execute 'DELETE FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game edited: #{game_to_s(game_id, false, league_id)}", [], slack_url) if league_id == 1 end recalc(league_id) if rec end def edit_player(league_id, player_id, display_name = nil, slack_name = nil, admin = nil, active = nil) database do |db| # update the defined fields unless player_exists?(display_name, league_id, player_id) || display_name.nil? db.execute 'UPDATE Player SET DisplayName = :display_name WHERE PlayerID = :player_id AND LeagueID = :league_id', display_name, player_id, league_id end unless slack_name.nil? db.execute 'UPDATE Player SET SlackName = :slack_name WHERE PlayerID = :player_id AND LeagueID = :league_id', slack_name, player_id, league_id end unless admin.nil? db.execute 'UPDATE Player SET Admin = :admin WHERE PlayerID = :player_id AND LeagueID = :league_id', admin ? 1 : 0, player_id, league_id end unless active.nil? db.execute 'UPDATE Player SET Active = :active WHERE PlayerID = :player_id AND LeagueID = :league_id', active ? 1 : 0, player_id, league_id recalc_elo(0, league_id) end end end # recalculate all the stats and populate the history stat tables # if timestamp is specified, recalcs all games after timestamp def recalc(league_id, timestamp = 0, silent = true) unless silent start = Time.now.to_f puts 'Calculating Elo' end recalc_elo(timestamp, league_id) unless silent printf("Took %.3f seconds\n", Time.now.to_f - start) start = Time.now.to_f puts 'Calculating win rate' end recalc_win_rate(league_id) printf("Took %.3f seconds\n", Time.now.to_f - start) unless silent end def recalc_elo(timestamp, league_id) database do |db| # init transaction for zoom db.transaction db.execute 'DELETE FROM EloHistory WHERE GameID IN ( SELECT GameID FROM Game WHERE Timestamp >= :timestamp ) AND LeagueID = :league_id', timestamp, league_id win_weight = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "WinWeight"' max_score = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "MaxScore"' k_factor = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "KFactor"' # temporary array of hashes to keep track of player rankings elos = {} ladder = {} active = {} # find the last rung on the ladder so we can set any future players to be on the bottom of the ladder last_rung = db.get_first_value('SELECT Ladder FROM EloHistory WHERE Ladder is not null AND LeagueID = :league_id ORDER by Ladder desc limit 1', league_id) last_rung ||= 0 player_ids(league_id).each do |player_id| elos[player_id] = db.get_first_value('SELECT Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) ladder[player_id] = db.get_first_value('SELECT Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) active[player_id] = db.get_first_value('SELECT Active FROM Player WHERE PlayerID = :player_id', player_id) # in case they had no games before timestamp elos[player_id] ||= 1200 if ladder[player_id].nil? ladder[player_id] = last_rung + 1 last_rung += 1 end end # for each game db.execute('SELECT DISTINCT GameID FROM Game WHERE Timestamp >= :timestamp AND LeagueID = :league_id ORDER BY Timestamp, GameID', timestamp, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) # calculate the leaderboard rankings case game.length when 2 score_a = game[0]['Score'] score_b = game[1]['Score'] # elo rating_a = elos[game[0]['PlayerID']] rating_b = elos[game[1]['PlayerID']] # ladder - only applies to active players if active[game[0]['PlayerID']] == 1 && active[game[1]['PlayerID']] == 1 old_a = ladder[game[0]['PlayerID']] old_b = ladder[game[1]['PlayerID']] ladder_jump = ((old_a - old_b).abs / 2.0).ceil # player a is lower on the ladder and they won if old_a > old_b && score_a > score_b new_a = ladder[game[0]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_a && ladder_value >= new_a ladder[player_id] += 1 end end ladder[game[0]['PlayerID']] = new_a end # player b is lower on the ladder and they won if old_b > old_a && score_b > score_a new_b = ladder[game[1]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_b && ladder_value >= new_b ladder[player_id] += 1 end end ladder[game[1]['PlayerID']] = new_b end end when 4 rating_a = ((elos[game[0]['PlayerID']] + elos[game[1]['PlayerID']]) / 2).round rating_b = ((elos[game[2]['PlayerID']] + elos[game[3]['PlayerID']]) / 2).round score_a = game[0]['Score'] score_b = game[2]['Score'] else # fuck trips next end delta_a, delta_b = elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # insert into history table game.each_with_index do |player, idx| case game.length when 2 elos[player['PlayerID']] += idx < 1 ? delta_a : delta_b when 4 elos[player['PlayerID']] += idx < 2 ? delta_a : delta_b end db.execute 'INSERT INTO EloHistory VALUES (:game_id, :player_id, :league_id, :elo, :ladder)', game_id, player['PlayerID'], league_id, elos[player['PlayerID']], ladder[player['PlayerID']] end end # update the player table player_ids(league_id).each do |player_id| db.execute 'UPDATE Player SET Elo = :elo, Ladder = :ladder WHERE PlayerID = :player_id', elos[player_id], ladder[player_id], player_id end # end transaction db.commit end end def recalc_win_rate(league_id) database do |db| db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id', league_id) do |player_id| db.execute('UPDATE Player SET GamesPlayed = ( SELECT COUNT(*) FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) db.execute('UPDATE Player SET GamesWon = ( SELECT COUNT(*) FROM Game JOIN ( SELECT GameID, MAX(Score) AS Score FROM Game WHERE LeagueID = :league_id GROUP BY GameID ) USING (GameID, Score) WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', league_id, player_id) end end end # remove a game by game_id def remove_game(game_id, league_id) database do |db| # get timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id removed = game_to_s(game_id, false, league_id) # remove the game db.execute 'DELETE FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id db.execute 'DELETE FROM EloHistory WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game removed: #{removed}", [], slack_url) if league_id == 1 recalc(league_id, timestamp) end end def slack_url(url) database do |db| db.execute 'UPDATE Config SET Value = :url WHERE Setting = "SlackUrl"', url end end Set snoozers to 4 weeks # Lower-level foosey functions # database wrapper function that makes it so we don't have to copy code later # also makes sure the block is performed in a transaction for thread safety # note that you must use the return keyword at the end of these blocks because # the transaction block returns its own values def database db = SQLite3::Database.new 'foosey.db' yield db rescue SQLite3::Exception => e puts e puts e.backtrace ensure db.close if db end # dank helper function that returns an array of hashes from execute2 output def create_query_hash(array) names = array.shift rval = [] array.each do |r| row = {} names.each_with_index { |column, idx| row[column] = r[idx] } rval << row end rval end # takes a game_id and returns a string of the game results useful for slack # if date = true, it will be prepended with a nicely formatted date def game_to_s(game_id, date, league_id) database do |db| game = create_query_hash(db.execute2('SELECT p.DisplayName, g.Score, g.Timestamp FROM Game g JOIN Player p USING (PlayerID) WHERE g.GameID = :game_id AND g.LeagueID = :league_id AND p.LeagueID = :league_id ORDER BY g.Score DESC', game_id, league_id)) s = if date Time.at(game.first['Timestamp']).strftime '%b %d, %Y - ' else '' end game.each do |player| s << "#{player['DisplayName']} #{player['Score']} " end return s.strip end end def message_slack(text, attach, url) data = { username: 'Foosey', channel: '#foosey', text: text, attachments: attach, icon_url: 'http://foosey.futbol/icon.png' } uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_version = :TLSv1 http.verify_mode = OpenSSL::SSL::VERIFY_PEER req = Net::HTTP::Post.new(uri.request_uri) req.body = data.to_json req['Content-Type'] = 'application/json' http.request(req) end # true if a game with the given id exists, false otherwise def valid_game?(game_id, league_id) database do |db| game = db.get_first_value 'SELECT GameID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id return !game.nil? end end # true if a player with the given id exists, false otherwise def valid_player?(player_id, league_id) database do |db| player = db.get_first_value 'SELECT PlayerID FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id return !player.nil? end end # true if league exists def league_exists?(league_name) database do |db| league = db.get_first_value 'SELECT * FROM League WHERE LeagueName = :league_name', league_name return !league.nil? end end # pull and load # hot hot hot deploys def update app_dir = app_dir # there's probably a git gem we could use here system "cd #{app_dir} && git pull" unless app_dir.nil? system "cd #{File.dirname(__FILE__)} && git pull" end def admin?(slack_name, league_id = 1) database do |db| admin = db.get_first_value 'SELECT Admin from Player WHERE SlackName = :slack_name AND LeagueID = :league_id COLLATE NOCASE', slack_name, league_id return admin == 1 end end def app_dir database do |db| # return dir return db.get_first_value 'SELECT Value FROM Config WHERE Setting = "AppDirectory"' end end # returns array of players and their badges in a given league def badges(league_id, player_id) # get players players = player_ids league_id badges = Hash.new { |h, k| h[k] = [] } all_games = game_ids(league_id) # plays a lot players.each do |p| badges[p] << badge('⚠️', 'Very Active') if games_this_week(p, league_id) > 50 end # fire badge # best daily change best_change = players.group_by { |p| daily_elo_change(p, league_id) }.max best_change.last.each { |b| badges[b] << badge('🔥', 'On Fire') } if !best_change.nil? && best_change.first >= 10 # poop badge # worst daily change worst_change = players.group_by { |p| daily_elo_change(p, league_id) }.min worst_change.last.each { |b| badges[b] << badge('💩', 'Rough Day') } if !worst_change.nil? && worst_change.first <= -10 # baby badge # 10-15 games played babies = players.select do |p| games_with_player(p, league_id).length.between?(10, 15) end babies.each { |b| badges[b] << badge('👶🏼', 'Newly Ranked') } unless all_games.length < 100 || babies.nil? # monkey badge # won last game but elo went down # flexing badge # won last game and gained 10+ elo players.select do |p| games = games_with_player(p, league_id) next if games.empty? last_game = api_game(games.first, league_id) winner = last_game[:teams][0][:players].any? { |a| a[:playerID] == p } badges[p] << badge('🙈', 'Monkey\'d') if last_game[:teams][0][:delta] < 0 && winner badges[p] << badge('🍌', 'Graceful Loss') if last_game[:teams][0][:delta] < 0 && !winner badges[p] << badge('💪🏼', 'Hefty Win') if last_game[:teams][0][:delta] >= 10 && winner badges[p] << badge('🤕', 'Hospital Bound') if last_game[:teams][0][:delta] >= 10 && !winner end # toilet badge # last skunk (lost w/ 0 points) toilet_game = all_games.find do |g| (api_game(g, league_id)[:teams][1][:score]).zero? end toilets = api_game(toilet_game, league_id)[:teams][1][:players] if toilet_game toilets.each { |b| badges[b[:playerID]] << badge('🚽', 'Get Rekt') } unless toilets.nil? # win streak badges # 5 and 10 current win streak win_streaks = {} players.each do |p| games = games_with_player(p, league_id) last_wins = games.take_while do |g| game = api_game(g, league_id) game[:teams][0][:players].any? { |a| a[:playerID] == p } end win_streaks[p] = last_wins.length end win_streaks.each do |p, s| badges[p] << badge("#{s}⃣", "#{s}-Win Streak") if s.between?(3, 9) badges[p] << badge('🔟', "#{s}-Win Streak") if s == 10 badges[p] << badge('💰', "#{s}-Win Streak") if s > 10 end # zzz badge # hasn't played a game in 2 weeks if league_id == 1 sleepers = players.select do |p| player_snoozin(p, league_id) end sleepers.each { |b| badges[b] << badge('💤', 'Snoozin\'') } end # nemesis and ally badges if player_id > 0 nemeses = [] allies = [] you = api_player(player_id, true, league_id) players.each do |p| this_player = api_player(p, false, league_id) nemeses << p if this_player[:displayName] == you[:nemesis] allies << p if this_player[:displayName] == you[:ally] end nemeses.each { |b| badges[b] << badge('😈', 'Your Nemesis') } allies.each { |b| badges[b] << badge('😇', 'Your Ally') } end # build hash badges.collect do |k, v| { playerID: k, badges: v } end end def badge(emoji, definition) { emoji: emoji, definition: definition } end def player_snoozin(player_id, league_id) games = games_with_player(player_id, league_id) return false if games.length < 10 last_game = api_game(games.first, league_id) Time.now.to_i - last_game[:timestamp] > 2_419_200 # 4 weeks end # returns the respective elo deltas given two ratings and two scores def elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # elo math please never quiz me on this expected_a = 1 / (1 + 10**((rating_b - rating_a) / 800.to_f)) expected_b = 1 / (1 + 10**((rating_a - rating_b) / 800.to_f)) outcome_a = score_a / (score_a + score_b).to_f if outcome_a < 0.5 # a won outcome_a **= win_weight outcome_b = 1 - outcome_a else # b won outcome_b = (1 - outcome_a)**win_weight outcome_a = 1 - outcome_b end # divide elo change to be smaller if it wasn't a full game to 10 ratio = [score_a, score_b].max / max_score.to_f # calculate elo change delta_a = (k_factor * (outcome_a - expected_a) * ratio).round delta_b = (k_factor * (outcome_b - expected_b) * ratio).round [delta_a, delta_b] end # returns an array of all game ids def game_ids(league_id) database do |db| # return id return db.execute('SELECT DISTINCT GameID FROM Game WHERE LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', league_id).flatten end end def history(league_id, ids) database do |db| games = db.execute 'SELECT GameID, GROUP_CONCAT(g.PlayerID), GROUP_CONCAT(p.DisplayName), GROUP_CONCAT(g.Score), timestamp FROM Game g JOIN Player p using (PlayerID) WHERE g.LeagueID = :league_id GROUP BY g.GameID ORDER BY timestamp DESC', league_id the_games = [] games.each do |game| game_id = game[0] player_ids = game[1].split(',') names = game[2].split(',') scores = game[3].split(',') timestamp = game[4] looking_for = ids.split(',') # skip to next game if doesn't contain the same players # skip if a doubles game and teams don't match next if looking_for.sort != player_ids.sort || (looking_for.length == 4 && scores[player_ids.index(looking_for[0])] != scores[player_ids.index(looking_for[1])]) response = { gameID: game_id, timestamp: timestamp, teams: [] } player_ids.each_with_index do |player_id, idx| i = response[:teams].index { |t| t[:score] == scores[idx].to_i } if i # team exists in hash response[:teams][i][:players] << { playerID: player_id.to_i, displayName: names[idx] } else response[:teams] << { players: [{ playerID: player_id.to_i, displayName: names[idx] }], score: scores[idx].to_i, delta: elo_change(player_id, game_id, league_id).to_i } end end response[:teams] = response[:teams].sort! { |a, b| b[:score] <=> a[:score] } the_games << response end return the_games end end # returns an array of game ids involving player with id player_id def games_with_player(player_id, league_id) database do |db| return db.execute('SELECT GameID From Game WHERE PlayerID = :player_id AND LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', player_id, league_id).flatten end end # returns an array of game ids involving only both player1 and player2 def games(player1_id, player2_id, league_id) database do |db| return db.execute('SELECT GameID FROM ( SELECT GameID FROM Game WHERE PlayerID IN (:player1_id, :player2_id) AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T1 JOIN ( SELECT GameID FROM Game AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T2 USING (GameID)', player1_id, player2_id, league_id).flatten end end # returns the id of a player, given their display name def id(name, league_id) database do |db| # return id return db.get_first_value 'SELECT PlayerID FROM Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end # returns the elo change over the last 24 hours for the specified player def daily_elo_change(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return today - 1200 unless prev return today - prev end end def daily_ladder_move(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return 0 unless prev return today - prev end end def games_this_week(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i week_ago = midnight - 604_800 return db.get_first_value('SELECT COUNT(GameID) FROM Game g WHERE g.PlayerID = :player_id AND g.LeagueID = :league_id AND g.Timestamp >= :week_ago', player_id, league_id, week_ago) end end def extended_stats(player_id, league_id) database do |db| allies = Hash.new(0) # key -> player_id, value -> wins nemeses = Hash.new(0) # key -> player_id, value -> losses singles_games = 0 singles_wins = 0 doubles_games = 0 doubles_wins = 0 db.execute('SELECT DISTINCT GameID FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) case game.length when 2 singles_games += 1 if game[1]['PlayerID'] == player_id # this player won singles_wins += 1 else # this player lost nemeses[game[1]['PlayerID']] += 1 end when 4 doubles_games += 1 idx = game.index { |g| g['PlayerID'] == player_id } if idx >= 2 # this player won doubles_wins += 1 allies[game[idx == 2 ? 3 : 2]['PlayerID']] += 1 end end end ally = allies.max_by { |_k, v| v } || ['Nobody', 0] nemesis = nemeses.max_by { |_k, v| v } || ['Nobody', 0] doubles_win_rate = doubles_wins / doubles_games.to_f singles_win_rate = singles_wins / singles_games.to_f return { ally: name(ally[0], league_id), allyCount: ally[1], doublesWinRate: doubles_win_rate.nan? ? nil : doubles_win_rate, doublesTotal: doubles_games, nemesis: name(nemesis[0], league_id), nemesisCount: nemesis[1], singlesWinRate: singles_win_rate.nan? ? nil : singles_win_rate, singlesTotal: singles_games, pastWeek: games_this_week(player_id, league_id) } end end def elo(player_id, game_id, league_id) database do |db| game_id ||= game_ids(league_id).last elo = db.get_first_value 'SELECT Elo FROM EloHistory WHERE PlayerID = :player_id AND LeagueID = :league_id AND GameID = :game_id', player_id, league_id, game_id # 1200 in case they have no games return elo || 1200 end end # returns the elo change for player with id player_id from game with id game_id # if the player was not involved in the game, the delta of their last game # before game with id game_id will be returned # if the player doesn't exist or has no games, 0 will be returned def elo_change(player_id, game_id, league_id) database do |db| # get game timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id elos = db.execute('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp <= :timestamp ORDER BY g.Timestamp DESC, g.GameID DESC LIMIT 2', player_id, league_id, timestamp).flatten # safety if player doesn't have any games return 0 if elos.empty? # safety if there is only one game, so we should delta from 1200 return elos.first - 1200 if elos.length == 1 return elos.first - elos.last end end # returns a player's display name, given id def name(player_id, league_id) database do |db| return db.get_first_value 'SELECT DisplayName FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id end end # returns an array of active players # sorted by PlayerID # NOTE: index != PlayerID def names(league_id) database do |db| return db.execute('SELECT DisplayName FROM Player WHERE ACTIVE = 1 AND LeagueID = :league_id', league_id).flatten end end # returns an array of elo/names def player_elos(league_id) database do |db| return db.execute('SELECT DisplayName, Elo from Player WHERE ACTIVE = 1 AND LeagueID = :league_id AND GamesPlayed >= 10 ORDER BY Elo DESC', league_id) end end # returns true if a player with DisplayName name is in the database # false otherwise def player_exists?(name, league_id, player_id = 0) database do |db| player = db.get_first_value 'SELECT * from Player WHERE DisplayName = :name AND LeagueID = :league_id AND PlayerID != :player_id COLLATE NOCASE', name, league_id, player_id return !player.nil? end end # returns an array of all player ids def player_ids(league_id) database do |db| # return id return db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id ORDER BY PlayerID', league_id).flatten end end # returns the id of the winning player (or players) in game with id id def winner(game_id, league_id) database do |db| # get max score winner = db.execute('SELECT PlayerID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id AND Score = ( SELECT MAX(Score) FROM Game WHERE GameID = :game_id AND LeagueID = :league_id GROUP BY GameID )', game_id, league_id).flatten winner = winner.first if winner.length == 1 # return the winner(s) return winner end end # add a game to the database and update the history tables # outcome is hash containing key/value pairs where # key = player id # value = score # it's a little wonky but we need to support games of any number of # players/score combinations, so i think it's best def add_game(outcome, league_id, timestamp) database do |db| # get unix time timestamp ||= Time.now.to_i # get next game id game_id = 1 + db.get_first_value('SELECT GameID FROM Game ORDER BY GameID DESC LIMIT 1') # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end # calling recalc with timestamp means we update elo properly for the # new game, regardless of the time it was played recalc(league_id, timestamp) players = outcome.keys.collect do |player_id| { name: name(player_id, league_id), elo: elo(player_id, game_id, league_id), delta: elo_change(player_id, game_id, league_id) } end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' unless league_id != 1 || slack_url.empty? text = "Game added: #{game_to_s(game_id, false, league_id)}" attachments = [{ fields: players.collect do |p| delta = p[:delta] >= 0 ? "+#{p[:delta]}" : p[:delta] { title: p[:name], value: "#{p[:elo]} (#{delta})", short: true } end }] message_slack(text, attachments, slack_url) end return { gameID: game_id, players: players } end end # adds a player to the database def add_player(league_id, name, slack_name = '', admin = false, active = true) database do |db| db.execute 'INSERT INTO Player (LeagueID, DisplayName, SlackName, Admin, Active) VALUES (:league_id, :name, :slack_name, :admin, :active)', league_id, name, slack_name, admin ? 1 : 0, active ? 1 : 0 recalc_elo(Time.now.to_i, league_id) return db.get_first_value 'SELECT PlayerID from Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end def add_league(league_name, display_name) database do |db| return db.execute 'INSERT INTO League (LeagueName, DisplayName) VALUES (:league_name, :display_name)', league_name, display_name end end # changes properties of game with id game_id def edit_game(league_id, game_id, outcome, timestamp = nil, rec = true) database do |db| # get timestamp if we need to keep it unchanged timestamp ||= db.get_first_value 'SELECT Timestamp FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # delete game with id game_id db.execute 'DELETE FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game edited: #{game_to_s(game_id, false, league_id)}", [], slack_url) if league_id == 1 end recalc(league_id) if rec end def edit_player(league_id, player_id, display_name = nil, slack_name = nil, admin = nil, active = nil) database do |db| # update the defined fields unless player_exists?(display_name, league_id, player_id) || display_name.nil? db.execute 'UPDATE Player SET DisplayName = :display_name WHERE PlayerID = :player_id AND LeagueID = :league_id', display_name, player_id, league_id end unless slack_name.nil? db.execute 'UPDATE Player SET SlackName = :slack_name WHERE PlayerID = :player_id AND LeagueID = :league_id', slack_name, player_id, league_id end unless admin.nil? db.execute 'UPDATE Player SET Admin = :admin WHERE PlayerID = :player_id AND LeagueID = :league_id', admin ? 1 : 0, player_id, league_id end unless active.nil? db.execute 'UPDATE Player SET Active = :active WHERE PlayerID = :player_id AND LeagueID = :league_id', active ? 1 : 0, player_id, league_id recalc_elo(0, league_id) end end end # recalculate all the stats and populate the history stat tables # if timestamp is specified, recalcs all games after timestamp def recalc(league_id, timestamp = 0, silent = true) unless silent start = Time.now.to_f puts 'Calculating Elo' end recalc_elo(timestamp, league_id) unless silent printf("Took %.3f seconds\n", Time.now.to_f - start) start = Time.now.to_f puts 'Calculating win rate' end recalc_win_rate(league_id) printf("Took %.3f seconds\n", Time.now.to_f - start) unless silent end def recalc_elo(timestamp, league_id) database do |db| # init transaction for zoom db.transaction db.execute 'DELETE FROM EloHistory WHERE GameID IN ( SELECT GameID FROM Game WHERE Timestamp >= :timestamp ) AND LeagueID = :league_id', timestamp, league_id win_weight = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "WinWeight"' max_score = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "MaxScore"' k_factor = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "KFactor"' # temporary array of hashes to keep track of player rankings elos = {} ladder = {} active = {} # find the last rung on the ladder so we can set any future players to be on the bottom of the ladder last_rung = db.get_first_value('SELECT Ladder FROM EloHistory WHERE Ladder is not null AND LeagueID = :league_id ORDER by Ladder desc limit 1', league_id) last_rung ||= 0 player_ids(league_id).each do |player_id| elos[player_id] = db.get_first_value('SELECT Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) ladder[player_id] = db.get_first_value('SELECT Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) active[player_id] = db.get_first_value('SELECT Active FROM Player WHERE PlayerID = :player_id', player_id) # in case they had no games before timestamp elos[player_id] ||= 1200 if ladder[player_id].nil? ladder[player_id] = last_rung + 1 last_rung += 1 end end # for each game db.execute('SELECT DISTINCT GameID FROM Game WHERE Timestamp >= :timestamp AND LeagueID = :league_id ORDER BY Timestamp, GameID', timestamp, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) # calculate the leaderboard rankings case game.length when 2 score_a = game[0]['Score'] score_b = game[1]['Score'] # elo rating_a = elos[game[0]['PlayerID']] rating_b = elos[game[1]['PlayerID']] # ladder - only applies to active players if active[game[0]['PlayerID']] == 1 && active[game[1]['PlayerID']] == 1 old_a = ladder[game[0]['PlayerID']] old_b = ladder[game[1]['PlayerID']] ladder_jump = ((old_a - old_b).abs / 2.0).ceil # player a is lower on the ladder and they won if old_a > old_b && score_a > score_b new_a = ladder[game[0]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_a && ladder_value >= new_a ladder[player_id] += 1 end end ladder[game[0]['PlayerID']] = new_a end # player b is lower on the ladder and they won if old_b > old_a && score_b > score_a new_b = ladder[game[1]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_b && ladder_value >= new_b ladder[player_id] += 1 end end ladder[game[1]['PlayerID']] = new_b end end when 4 rating_a = ((elos[game[0]['PlayerID']] + elos[game[1]['PlayerID']]) / 2).round rating_b = ((elos[game[2]['PlayerID']] + elos[game[3]['PlayerID']]) / 2).round score_a = game[0]['Score'] score_b = game[2]['Score'] else # fuck trips next end delta_a, delta_b = elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # insert into history table game.each_with_index do |player, idx| case game.length when 2 elos[player['PlayerID']] += idx < 1 ? delta_a : delta_b when 4 elos[player['PlayerID']] += idx < 2 ? delta_a : delta_b end db.execute 'INSERT INTO EloHistory VALUES (:game_id, :player_id, :league_id, :elo, :ladder)', game_id, player['PlayerID'], league_id, elos[player['PlayerID']], ladder[player['PlayerID']] end end # update the player table player_ids(league_id).each do |player_id| db.execute 'UPDATE Player SET Elo = :elo, Ladder = :ladder WHERE PlayerID = :player_id', elos[player_id], ladder[player_id], player_id end # end transaction db.commit end end def recalc_win_rate(league_id) database do |db| db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id', league_id) do |player_id| db.execute('UPDATE Player SET GamesPlayed = ( SELECT COUNT(*) FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) db.execute('UPDATE Player SET GamesWon = ( SELECT COUNT(*) FROM Game JOIN ( SELECT GameID, MAX(Score) AS Score FROM Game WHERE LeagueID = :league_id GROUP BY GameID ) USING (GameID, Score) WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', league_id, player_id) end end end # remove a game by game_id def remove_game(game_id, league_id) database do |db| # get timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id removed = game_to_s(game_id, false, league_id) # remove the game db.execute 'DELETE FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id db.execute 'DELETE FROM EloHistory WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game removed: #{removed}", [], slack_url) if league_id == 1 recalc(league_id, timestamp) end end def slack_url(url) database do |db| db.execute 'UPDATE Config SET Value = :url WHERE Setting = "SlackUrl"', url end end
# Lower-level foosey functions # database wrapper function that makes it so we don't have to copy code later # also makes sure the block is performed in a transaction for thread safety # note that you must use the return keyword at the end of these blocks because # the transaction block returns its own values def database db = SQLite3::Database.new 'foosey.db' yield db rescue SQLite3::Exception => e puts e puts e.backtrace ensure db.close if db end # dank helper function that returns an array of hashes from execute2 output def create_query_hash(array) names = array.shift rval = [] array.each do |r| row = {} names.each_with_index { |column, idx| row[column] = r[idx] } rval << row end rval end # takes a game_id and returns a string of the game results useful for slack # if date = true, it will be prepended with a nicely formatted date def game_to_s(game_id, date, league_id) database do |db| game = create_query_hash(db.execute2('SELECT p.DisplayName, g.Score, g.Timestamp FROM Game g JOIN Player p USING (PlayerID) WHERE g.GameID = :game_id AND g.LeagueID = :league_id AND p.LeagueID = :league_id ORDER BY g.Score DESC', game_id, league_id)) s = if date Time.at(game.first['Timestamp']).strftime '%b %d, %Y - ' else '' end game.each do |player| s << "#{player['DisplayName']} #{player['Score']} " end return s.strip end end def message_slack(text, attach, url, league_id) data = { username: league_id == 1 ? 'Foosey' : 'Foosey for Cornhole', channel: '#foosey', text: text, attachments: attach, icon_url: league_id == 1 ? 'http://foosey.futbol/icon.png' : 'https://i2.wp.com/tailorspot.com/wp-content/uploads/2015/09/TailorSpot_Cornhole_Bag_Turquoise1.jpg' } uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_version = :TLSv1 http.verify_mode = OpenSSL::SSL::VERIFY_PEER req = Net::HTTP::Post.new(uri.request_uri) req.body = data.to_json req['Content-Type'] = 'application/json' http.request(req) end # true if a game with the given id exists, false otherwise def valid_game?(game_id, league_id) database do |db| game = db.get_first_value 'SELECT GameID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id return !game.nil? end end # true if a player with the given id exists, false otherwise def valid_player?(player_id, league_id) database do |db| player = db.get_first_value 'SELECT PlayerID FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id return !player.nil? end end # true if league exists def league_exists?(league_name) database do |db| league = db.get_first_value 'SELECT * FROM League WHERE LeagueName = :league_name', league_name return !league.nil? end end # pull and load # hot hot hot deploys def update app_dir = app_dir # there's probably a git gem we could use here system "cd #{app_dir} && git pull" unless app_dir.nil? system "cd #{File.dirname(__FILE__)} && git pull" end def admin?(slack_name, league_id = 1) database do |db| admin = db.get_first_value 'SELECT Admin from Player WHERE SlackName = :slack_name AND LeagueID = :league_id COLLATE NOCASE', slack_name, league_id return admin == 1 end end def app_dir database do |db| # return dir return db.get_first_value 'SELECT Value FROM Config WHERE Setting = "AppDirectory"' end end # returns array of players and their badges in a given league def badges(league_id, player_id) # get players players = player_ids league_id badges = Hash.new { |h, k| h[k] = [] } all_games = game_ids(league_id) # tournament hack # badges[12] << badge('🏆', 'Dec 6th Champs') #adam # badges[36] << badge('🏆', 'Dec 6th Champs') #colin # badges[9] << badge('🥈', 'Dec 6th - 2nd Place') #peter # badges[453] << badge('🥈', 'Dec 6th - 2nd Place') #james # badges[13] << badge('🥉', 'Dec 6th - 3rd Place') #erich # badges[8] << badge('🥉', 'Dec 6th - 3rd Place') #greg # taco badges[1] << badge('🌮', 'Eating everything') #matt # plays a lot players.each do |p| badges[p] << badge('⚠️', 'Very Active') if games_this_week(p, league_id) > 50 end # fire badge # best daily change best_change = players.group_by { |p| daily_elo_change(p, league_id) }.max best_change.last.each { |b| badges[b] << badge('🔥', 'On Fire') } if !best_change.nil? && best_change.first >= 10 # poop badge # worst daily change worst_change = players.group_by { |p| daily_elo_change(p, league_id) }.min worst_change.last.each { |b| badges[b] << badge('💩', 'Rough Day') } if !worst_change.nil? && worst_change.first <= -10 # baby badge # 10-15 games played babies = players.select do |p| games_with_player(p, league_id).length.between?(10, 15) end babies.each { |b| badges[b] << badge('👶🏼', 'Newly Ranked') } unless all_games.length < 100 || babies.nil? # monkey badge # won last game but elo went down # flexing badge # won last game and gained 10+ elo players.select do |p| games = games_with_player(p, league_id) next if games.empty? last_game = api_game(games.first, league_id) winner = last_game[:teams][0][:players].any? { |a| a[:playerID] == p } badges[p] << badge('🙈', 'Monkey\'d') if last_game[:teams][0][:delta] < 0 && winner badges[p] << badge('🍌', 'Graceful Loss') if last_game[:teams][0][:delta] < 0 && !winner badges[p] << badge('💪🏼', 'Hefty Win') if last_game[:teams][0][:delta] >= 10 && winner badges[p] << badge('🤕', 'Hospital Bound') if last_game[:teams][0][:delta] >= 10 && !winner end # toilet badge # last skunk (lost w/ 0 points) toilet_game = all_games.find do |g| (api_game(g, league_id)[:teams][1][:score]).zero? end toilets = api_game(toilet_game, league_id)[:teams][1][:players] if toilet_game toilets.each { |b| badges[b[:playerID]] << badge('🚽', 'Get Rekt') } unless toilets.nil? # win streak badges # 5 and 10 current win streak win_streaks = {} players.each do |p| games = games_with_player(p, league_id) last_wins = games.take_while do |g| game = api_game(g, league_id) game[:teams][0][:players].any? { |a| a[:playerID] == p } end win_streaks[p] = last_wins.length end win_streaks.each do |p, s| badges[p] << badge("#{s}⃣", "#{s}-Win Streak") if s.between?(3, 9) badges[p] << badge('🔟', "#{s}-Win Streak") if s == 10 badges[p] << badge('💰', "#{s}-Win Streak") if s > 10 end # zzz badge # hasn't played a game in 2 weeks if league_id == 1 sleepers = players.select do |p| player_snoozin(p, league_id) end sleepers.each { |b| badges[b] << badge('💤', 'Snoozin\'') } end # nemesis and ally badges if player_id > 0 nemeses = [] allies = [] you = api_player(player_id, true, league_id) players.each do |p| this_player = api_player(p, false, league_id) nemeses << p if this_player[:displayName] == you[:nemesis] allies << p if this_player[:displayName] == you[:ally] end nemeses.each { |b| badges[b] << badge('😈', 'Your Nemesis') } allies.each { |b| badges[b] << badge('😇', 'Your Ally') } end # build hash badges.collect do |k, v| { playerID: k, badges: v } end end def badge(emoji, definition) { emoji: emoji, definition: definition } end def player_snoozin(player_id, league_id) games = games_with_player(player_id, league_id) return false if games.length < 10 last_game = api_game(games.first, league_id) Time.now.to_i - last_game[:timestamp] > 2_419_200 # 4 weeks end # returns the respective elo deltas given two ratings and two scores def elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # elo math please never quiz me on this expected_a = 1 / (1 + 10**((rating_b - rating_a) / 800.to_f)) expected_b = 1 / (1 + 10**((rating_a - rating_b) / 800.to_f)) outcome_a = score_a / (score_a + score_b).to_f if outcome_a < 0.5 # a won outcome_a **= win_weight outcome_b = 1 - outcome_a else # b won outcome_b = (1 - outcome_a)**win_weight outcome_a = 1 - outcome_b end # divide elo change to be smaller if it wasn't a full game to 10 ratio = [score_a, score_b].max / max_score.to_f # calculate elo change delta_a = (k_factor * (outcome_a - expected_a) * ratio).round delta_b = (k_factor * (outcome_b - expected_b) * ratio).round [delta_a, delta_b] end # returns an array of all game ids def game_ids(league_id) database do |db| # return id return db.execute('SELECT DISTINCT GameID FROM Game WHERE LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', league_id).flatten end end def history(league_id, ids) database do |db| games = db.execute 'SELECT GameID, GROUP_CONCAT(g.PlayerID), GROUP_CONCAT(p.DisplayName), GROUP_CONCAT(g.Score), timestamp FROM Game g JOIN Player p using (PlayerID) WHERE g.LeagueID = :league_id GROUP BY g.GameID ORDER BY timestamp DESC', league_id the_games = [] games.each do |game| game_id = game[0] player_ids = game[1].split(',') names = game[2].split(',') scores = game[3].split(',') timestamp = game[4] looking_for = ids.split(',') # skip to next game if doesn't contain the same players # skip if a doubles game and teams don't match next if looking_for.sort != player_ids.sort || (looking_for.length == 4 && scores[player_ids.index(looking_for[0])] != scores[player_ids.index(looking_for[1])]) response = { gameID: game_id, timestamp: timestamp, teams: [] } player_ids.each_with_index do |player_id, idx| i = response[:teams].index { |t| t[:score] == scores[idx].to_i } if i # team exists in hash response[:teams][i][:players] << { playerID: player_id.to_i, displayName: names[idx] } else response[:teams] << { players: [{ playerID: player_id.to_i, displayName: names[idx] }], score: scores[idx].to_i, delta: elo_change(player_id, game_id, league_id).to_i } end end response[:teams] = response[:teams].sort! { |a, b| b[:score] <=> a[:score] } the_games << response end return the_games end end # returns an array of game ids involving player with id player_id def games_with_player(player_id, league_id) database do |db| return db.execute('SELECT GameID From Game WHERE PlayerID = :player_id AND LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', player_id, league_id).flatten end end # returns an array of game ids involving only both player1 and player2 def games(player1_id, player2_id, league_id) database do |db| return db.execute('SELECT GameID FROM ( SELECT GameID FROM Game WHERE PlayerID IN (:player1_id, :player2_id) AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T1 JOIN ( SELECT GameID FROM Game AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T2 USING (GameID)', player1_id, player2_id, league_id).flatten end end # returns the id of a player, given their display name def id(name, league_id) database do |db| # return id return db.get_first_value 'SELECT PlayerID FROM Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end # returns the elo change over the last 24 hours for the specified player def daily_elo_change(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return today - 1200 unless prev return today - prev end end def daily_ladder_move(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return 0 unless prev return today - prev end end def games_this_week(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i week_ago = midnight - 604_800 return db.get_first_value('SELECT COUNT(GameID) FROM Game g WHERE g.PlayerID = :player_id AND g.LeagueID = :league_id AND g.Timestamp >= :week_ago', player_id, league_id, week_ago) end end def extended_stats(player_id, league_id) database do |db| allies = Hash.new(0) # key -> player_id, value -> wins nemeses = Hash.new(0) # key -> player_id, value -> losses singles_games = 0 singles_wins = 0 doubles_games = 0 doubles_wins = 0 db.execute('SELECT DISTINCT GameID FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) case game.length when 2 singles_games += 1 if game[1]['PlayerID'] == player_id # this player won singles_wins += 1 else # this player lost nemeses[game[1]['PlayerID']] += 1 end when 4 doubles_games += 1 idx = game.index { |g| g['PlayerID'] == player_id } if idx >= 2 # this player won doubles_wins += 1 allies[game[idx == 2 ? 3 : 2]['PlayerID']] += 1 end end end ally = allies.max_by { |_k, v| v } || ['Nobody', 0] nemesis = nemeses.max_by { |_k, v| v } || ['Nobody', 0] doubles_win_rate = doubles_wins / doubles_games.to_f singles_win_rate = singles_wins / singles_games.to_f return { ally: name(ally[0], league_id), allyCount: ally[1], doublesWinRate: doubles_win_rate.nan? ? nil : doubles_win_rate, doublesTotal: doubles_games, nemesis: name(nemesis[0], league_id), nemesisCount: nemesis[1], singlesWinRate: singles_win_rate.nan? ? nil : singles_win_rate, singlesTotal: singles_games, pastWeek: games_this_week(player_id, league_id) } end end def elo(player_id, game_id, league_id) database do |db| game_id ||= game_ids(league_id).last elo = db.get_first_value 'SELECT Elo FROM EloHistory WHERE PlayerID = :player_id AND LeagueID = :league_id AND GameID = :game_id', player_id, league_id, game_id # 1200 in case they have no games return elo || 1200 end end # returns the elo change for player with id player_id from game with id game_id # if the player was not involved in the game, the delta of their last game # before game with id game_id will be returned # if the player doesn't exist or has no games, 0 will be returned def elo_change(player_id, game_id, league_id) database do |db| # get game timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id elos = db.execute('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp <= :timestamp ORDER BY g.Timestamp DESC, g.GameID DESC LIMIT 2', player_id, league_id, timestamp).flatten # safety if player doesn't have any games return 0 if elos.empty? # safety if there is only one game, so we should delta from 1200 return elos.first - 1200 if elos.length == 1 return elos.first - elos.last end end # returns a player's display name, given id def name(player_id, league_id) database do |db| return db.get_first_value 'SELECT DisplayName FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id end end # returns an array of active players # sorted by PlayerID # NOTE: index != PlayerID def names(league_id) database do |db| return db.execute('SELECT DisplayName FROM Player WHERE ACTIVE = 1 AND LeagueID = :league_id', league_id).flatten end end # returns an array of elo/names def player_elos(league_id) database do |db| return db.execute('SELECT DisplayName, Elo from Player WHERE ACTIVE = 1 AND LeagueID = :league_id AND GamesPlayed >= 10 ORDER BY Elo DESC', league_id) end end # returns true if a player with DisplayName name is in the database # false otherwise def player_exists?(name, league_id, player_id = 0) database do |db| player = db.get_first_value 'SELECT * from Player WHERE DisplayName = :name AND LeagueID = :league_id AND PlayerID != :player_id COLLATE NOCASE', name, league_id, player_id return !player.nil? end end # returns an array of all player ids def player_ids(league_id) database do |db| # return id return db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id ORDER BY PlayerID', league_id).flatten end end # returns the id of the winning player (or players) in game with id id def winner(game_id, league_id) database do |db| # get max score winner = db.execute('SELECT PlayerID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id AND Score = ( SELECT MAX(Score) FROM Game WHERE GameID = :game_id AND LeagueID = :league_id GROUP BY GameID )', game_id, league_id).flatten winner = winner.first if winner.length == 1 # return the winner(s) return winner end end # add a game to the database and update the history tables # outcome is hash containing key/value pairs where # key = player id # value = score # it's a little wonky but we need to support games of any number of # players/score combinations, so i think it's best def add_game(outcome, league_id, timestamp) database do |db| # get unix time timestamp ||= Time.now.to_i # get next game id game_id = 1 + db.get_first_value('SELECT GameID FROM Game ORDER BY GameID DESC LIMIT 1') # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end # calling recalc with timestamp means we update elo properly for the # new game, regardless of the time it was played recalc(league_id, timestamp) players = outcome.keys.collect do |player_id| { name: name(player_id, league_id), elo: elo(player_id, game_id, league_id), delta: elo_change(player_id, game_id, league_id) } end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' unless (league_id != 1 && league_id != 41) || slack_url.empty? text = "Game added: #{game_to_s(game_id, false, league_id)}" attachments = [{ author_name: "See the leaderboard", author_link: "http://foosey.futbol/#/redirect/" + (league_id == 1 ? "wca-dev" : "wca-cornhole"), fields: players.collect do |p| delta = p[:delta] >= 0 ? "+#{p[:delta]}" : p[:delta] { title: p[:name], value: "#{p[:elo]} (#{delta})", short: true } end }] message_slack(text, attachments, slack_url, league_id) end return { gameID: game_id, players: players } end end # adds a player to the database def add_player(league_id, name, slack_name = '', admin = false, active = true) database do |db| db.execute 'INSERT INTO Player (LeagueID, DisplayName, SlackName, Admin, Active) VALUES (:league_id, :name, :slack_name, :admin, :active)', league_id, name, slack_name, admin ? 1 : 0, active ? 1 : 0 recalc_elo(Time.now.to_i, league_id) return db.get_first_value 'SELECT PlayerID from Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end def add_league(league_name, display_name) database do |db| return db.execute 'INSERT INTO League (LeagueName, DisplayName) VALUES (:league_name, :display_name)', league_name, display_name end end # changes properties of game with id game_id def edit_game(league_id, game_id, outcome, timestamp = nil, rec = true) database do |db| # get timestamp if we need to keep it unchanged timestamp ||= db.get_first_value 'SELECT Timestamp FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # delete game with id game_id db.execute 'DELETE FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game edited: #{game_to_s(game_id, false, league_id)}", [], slack_url, league_id) if league_id == 1 || league_id == 41 end recalc(league_id) if rec end def edit_player(league_id, player_id, display_name = nil, slack_name = nil, admin = nil, active = nil) database do |db| # update the defined fields unless player_exists?(display_name, league_id, player_id) || display_name.nil? db.execute 'UPDATE Player SET DisplayName = :display_name WHERE PlayerID = :player_id AND LeagueID = :league_id', display_name, player_id, league_id end unless slack_name.nil? db.execute 'UPDATE Player SET SlackName = :slack_name WHERE PlayerID = :player_id AND LeagueID = :league_id', slack_name, player_id, league_id end unless admin.nil? db.execute 'UPDATE Player SET Admin = :admin WHERE PlayerID = :player_id AND LeagueID = :league_id', admin ? 1 : 0, player_id, league_id end unless active.nil? db.execute 'UPDATE Player SET Active = :active WHERE PlayerID = :player_id AND LeagueID = :league_id', active ? 1 : 0, player_id, league_id recalc_elo(0, league_id) end end end # recalculate all the stats and populate the history stat tables # if timestamp is specified, recalcs all games after timestamp def recalc(league_id, timestamp = 0, silent = true) unless silent start = Time.now.to_f puts 'Calculating Elo' end recalc_elo(timestamp, league_id) unless silent printf("Took %.3f seconds\n", Time.now.to_f - start) start = Time.now.to_f puts 'Calculating win rate' end recalc_win_rate(league_id) printf("Took %.3f seconds\n", Time.now.to_f - start) unless silent end def recalc_elo(timestamp, league_id) database do |db| # init transaction for zoom db.transaction db.execute 'DELETE FROM EloHistory WHERE GameID IN ( SELECT GameID FROM Game WHERE Timestamp >= :timestamp ) AND LeagueID = :league_id', timestamp, league_id win_weight = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "WinWeight"' max_score = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "MaxScore"' k_factor = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "KFactor"' # temporary array of hashes to keep track of player rankings elos = {} ladder = {} active = {} # find the last rung on the ladder so we can set any future players to be on the bottom of the ladder last_rung = db.get_first_value('SELECT Ladder FROM EloHistory WHERE Ladder is not null AND LeagueID = :league_id ORDER by Ladder desc limit 1', league_id) last_rung ||= 0 player_ids(league_id).each do |player_id| elos[player_id] = db.get_first_value('SELECT Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) ladder[player_id] = db.get_first_value('SELECT Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) active[player_id] = db.get_first_value('SELECT Active FROM Player WHERE PlayerID = :player_id', player_id) # in case they had no games before timestamp elos[player_id] ||= 1200 if ladder[player_id].nil? ladder[player_id] = last_rung + 1 last_rung += 1 end end # for each game db.execute('SELECT DISTINCT GameID FROM Game WHERE Timestamp >= :timestamp AND LeagueID = :league_id ORDER BY Timestamp, GameID', timestamp, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) # calculate the leaderboard rankings case game.length when 2 score_a = game[0]['Score'] score_b = game[1]['Score'] # elo rating_a = elos[game[0]['PlayerID']] rating_b = elos[game[1]['PlayerID']] # ladder - only applies to active players if active[game[0]['PlayerID']] == 1 && active[game[1]['PlayerID']] == 1 old_a = ladder[game[0]['PlayerID']] old_b = ladder[game[1]['PlayerID']] ladder_jump = ((old_a - old_b).abs / 2.0).ceil # player a is lower on the ladder and they won if old_a > old_b && score_a > score_b new_a = ladder[game[0]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_a && ladder_value >= new_a ladder[player_id] += 1 end end ladder[game[0]['PlayerID']] = new_a end # player b is lower on the ladder and they won if old_b > old_a && score_b > score_a new_b = ladder[game[1]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_b && ladder_value >= new_b ladder[player_id] += 1 end end ladder[game[1]['PlayerID']] = new_b end end when 4 rating_a = ((elos[game[0]['PlayerID']] + elos[game[1]['PlayerID']]) / 2).round rating_b = ((elos[game[2]['PlayerID']] + elos[game[3]['PlayerID']]) / 2).round score_a = game[0]['Score'] score_b = game[2]['Score'] else # fuck trips next end delta_a, delta_b = elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # insert into history table game.each_with_index do |player, idx| case game.length when 2 elos[player['PlayerID']] += idx < 1 ? delta_a : delta_b when 4 elos[player['PlayerID']] += idx < 2 ? delta_a : delta_b end db.execute 'INSERT INTO EloHistory VALUES (:game_id, :player_id, :league_id, :elo, :ladder)', game_id, player['PlayerID'], league_id, elos[player['PlayerID']], ladder[player['PlayerID']] end end # update the player table player_ids(league_id).each do |player_id| db.execute 'UPDATE Player SET Elo = :elo, Ladder = :ladder WHERE PlayerID = :player_id', elos[player_id], ladder[player_id], player_id end # end transaction db.commit end end def recalc_win_rate(league_id) database do |db| db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id', league_id) do |player_id| db.execute('UPDATE Player SET GamesPlayed = ( SELECT COUNT(*) FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) db.execute('UPDATE Player SET GamesWon = ( SELECT COUNT(*) FROM Game JOIN ( SELECT GameID, MAX(Score) AS Score FROM Game WHERE LeagueID = :league_id GROUP BY GameID ) USING (GameID, Score) WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', league_id, player_id) end end end # remove a game by game_id def remove_game(game_id, league_id) database do |db| # get timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id removed = game_to_s(game_id, false, league_id) # remove the game db.execute 'DELETE FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id db.execute 'DELETE FROM EloHistory WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game removed: #{removed}", [], slack_url, league_id) if league_id == 1 || league_id == 41 recalc(league_id, timestamp) end end def slack_url(url) database do |db| db.execute 'UPDATE Config SET Value = :url WHERE Setting = "SlackUrl"', url end end Revert "Tacos" This reverts commit 35453d56d9c3ca3b6fff3f102bc636b869a72094. # Lower-level foosey functions # database wrapper function that makes it so we don't have to copy code later # also makes sure the block is performed in a transaction for thread safety # note that you must use the return keyword at the end of these blocks because # the transaction block returns its own values def database db = SQLite3::Database.new 'foosey.db' yield db rescue SQLite3::Exception => e puts e puts e.backtrace ensure db.close if db end # dank helper function that returns an array of hashes from execute2 output def create_query_hash(array) names = array.shift rval = [] array.each do |r| row = {} names.each_with_index { |column, idx| row[column] = r[idx] } rval << row end rval end # takes a game_id and returns a string of the game results useful for slack # if date = true, it will be prepended with a nicely formatted date def game_to_s(game_id, date, league_id) database do |db| game = create_query_hash(db.execute2('SELECT p.DisplayName, g.Score, g.Timestamp FROM Game g JOIN Player p USING (PlayerID) WHERE g.GameID = :game_id AND g.LeagueID = :league_id AND p.LeagueID = :league_id ORDER BY g.Score DESC', game_id, league_id)) s = if date Time.at(game.first['Timestamp']).strftime '%b %d, %Y - ' else '' end game.each do |player| s << "#{player['DisplayName']} #{player['Score']} " end return s.strip end end def message_slack(text, attach, url, league_id) data = { username: league_id == 1 ? 'Foosey' : 'Foosey for Cornhole', channel: '#foosey', text: text, attachments: attach, icon_url: league_id == 1 ? 'http://foosey.futbol/icon.png' : 'https://i2.wp.com/tailorspot.com/wp-content/uploads/2015/09/TailorSpot_Cornhole_Bag_Turquoise1.jpg' } uri = URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.ssl_version = :TLSv1 http.verify_mode = OpenSSL::SSL::VERIFY_PEER req = Net::HTTP::Post.new(uri.request_uri) req.body = data.to_json req['Content-Type'] = 'application/json' http.request(req) end # true if a game with the given id exists, false otherwise def valid_game?(game_id, league_id) database do |db| game = db.get_first_value 'SELECT GameID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id return !game.nil? end end # true if a player with the given id exists, false otherwise def valid_player?(player_id, league_id) database do |db| player = db.get_first_value 'SELECT PlayerID FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id return !player.nil? end end # true if league exists def league_exists?(league_name) database do |db| league = db.get_first_value 'SELECT * FROM League WHERE LeagueName = :league_name', league_name return !league.nil? end end # pull and load # hot hot hot deploys def update app_dir = app_dir # there's probably a git gem we could use here system "cd #{app_dir} && git pull" unless app_dir.nil? system "cd #{File.dirname(__FILE__)} && git pull" end def admin?(slack_name, league_id = 1) database do |db| admin = db.get_first_value 'SELECT Admin from Player WHERE SlackName = :slack_name AND LeagueID = :league_id COLLATE NOCASE', slack_name, league_id return admin == 1 end end def app_dir database do |db| # return dir return db.get_first_value 'SELECT Value FROM Config WHERE Setting = "AppDirectory"' end end # returns array of players and their badges in a given league def badges(league_id, player_id) # get players players = player_ids league_id badges = Hash.new { |h, k| h[k] = [] } all_games = game_ids(league_id) # tournament hack # badges[12] << badge('🏆', 'Dec 6th Champs') #adam # badges[36] << badge('🏆', 'Dec 6th Champs') #colin # badges[9] << badge('🥈', 'Dec 6th - 2nd Place') #peter # badges[453] << badge('🥈', 'Dec 6th - 2nd Place') #james # badges[13] << badge('🥉', 'Dec 6th - 3rd Place') #erich # badges[8] << badge('🥉', 'Dec 6th - 3rd Place') #greg # plays a lot players.each do |p| badges[p] << badge('⚠️', 'Very Active') if games_this_week(p, league_id) > 50 end # fire badge # best daily change best_change = players.group_by { |p| daily_elo_change(p, league_id) }.max best_change.last.each { |b| badges[b] << badge('🔥', 'On Fire') } if !best_change.nil? && best_change.first >= 10 # poop badge # worst daily change worst_change = players.group_by { |p| daily_elo_change(p, league_id) }.min worst_change.last.each { |b| badges[b] << badge('💩', 'Rough Day') } if !worst_change.nil? && worst_change.first <= -10 # baby badge # 10-15 games played babies = players.select do |p| games_with_player(p, league_id).length.between?(10, 15) end babies.each { |b| badges[b] << badge('👶🏼', 'Newly Ranked') } unless all_games.length < 100 || babies.nil? # monkey badge # won last game but elo went down # flexing badge # won last game and gained 10+ elo players.select do |p| games = games_with_player(p, league_id) next if games.empty? last_game = api_game(games.first, league_id) winner = last_game[:teams][0][:players].any? { |a| a[:playerID] == p } badges[p] << badge('🙈', 'Monkey\'d') if last_game[:teams][0][:delta] < 0 && winner badges[p] << badge('🍌', 'Graceful Loss') if last_game[:teams][0][:delta] < 0 && !winner badges[p] << badge('💪🏼', 'Hefty Win') if last_game[:teams][0][:delta] >= 10 && winner badges[p] << badge('🤕', 'Hospital Bound') if last_game[:teams][0][:delta] >= 10 && !winner end # toilet badge # last skunk (lost w/ 0 points) toilet_game = all_games.find do |g| (api_game(g, league_id)[:teams][1][:score]).zero? end toilets = api_game(toilet_game, league_id)[:teams][1][:players] if toilet_game toilets.each { |b| badges[b[:playerID]] << badge('🚽', 'Get Rekt') } unless toilets.nil? # win streak badges # 5 and 10 current win streak win_streaks = {} players.each do |p| games = games_with_player(p, league_id) last_wins = games.take_while do |g| game = api_game(g, league_id) game[:teams][0][:players].any? { |a| a[:playerID] == p } end win_streaks[p] = last_wins.length end win_streaks.each do |p, s| badges[p] << badge("#{s}⃣", "#{s}-Win Streak") if s.between?(3, 9) badges[p] << badge('🔟', "#{s}-Win Streak") if s == 10 badges[p] << badge('💰', "#{s}-Win Streak") if s > 10 end # zzz badge # hasn't played a game in 2 weeks if league_id == 1 sleepers = players.select do |p| player_snoozin(p, league_id) end sleepers.each { |b| badges[b] << badge('💤', 'Snoozin\'') } end # nemesis and ally badges if player_id > 0 nemeses = [] allies = [] you = api_player(player_id, true, league_id) players.each do |p| this_player = api_player(p, false, league_id) nemeses << p if this_player[:displayName] == you[:nemesis] allies << p if this_player[:displayName] == you[:ally] end nemeses.each { |b| badges[b] << badge('😈', 'Your Nemesis') } allies.each { |b| badges[b] << badge('😇', 'Your Ally') } end # build hash badges.collect do |k, v| { playerID: k, badges: v } end end def badge(emoji, definition) { emoji: emoji, definition: definition } end def player_snoozin(player_id, league_id) games = games_with_player(player_id, league_id) return false if games.length < 10 last_game = api_game(games.first, league_id) Time.now.to_i - last_game[:timestamp] > 2_419_200 # 4 weeks end # returns the respective elo deltas given two ratings and two scores def elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # elo math please never quiz me on this expected_a = 1 / (1 + 10**((rating_b - rating_a) / 800.to_f)) expected_b = 1 / (1 + 10**((rating_a - rating_b) / 800.to_f)) outcome_a = score_a / (score_a + score_b).to_f if outcome_a < 0.5 # a won outcome_a **= win_weight outcome_b = 1 - outcome_a else # b won outcome_b = (1 - outcome_a)**win_weight outcome_a = 1 - outcome_b end # divide elo change to be smaller if it wasn't a full game to 10 ratio = [score_a, score_b].max / max_score.to_f # calculate elo change delta_a = (k_factor * (outcome_a - expected_a) * ratio).round delta_b = (k_factor * (outcome_b - expected_b) * ratio).round [delta_a, delta_b] end # returns an array of all game ids def game_ids(league_id) database do |db| # return id return db.execute('SELECT DISTINCT GameID FROM Game WHERE LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', league_id).flatten end end def history(league_id, ids) database do |db| games = db.execute 'SELECT GameID, GROUP_CONCAT(g.PlayerID), GROUP_CONCAT(p.DisplayName), GROUP_CONCAT(g.Score), timestamp FROM Game g JOIN Player p using (PlayerID) WHERE g.LeagueID = :league_id GROUP BY g.GameID ORDER BY timestamp DESC', league_id the_games = [] games.each do |game| game_id = game[0] player_ids = game[1].split(',') names = game[2].split(',') scores = game[3].split(',') timestamp = game[4] looking_for = ids.split(',') # skip to next game if doesn't contain the same players # skip if a doubles game and teams don't match next if looking_for.sort != player_ids.sort || (looking_for.length == 4 && scores[player_ids.index(looking_for[0])] != scores[player_ids.index(looking_for[1])]) response = { gameID: game_id, timestamp: timestamp, teams: [] } player_ids.each_with_index do |player_id, idx| i = response[:teams].index { |t| t[:score] == scores[idx].to_i } if i # team exists in hash response[:teams][i][:players] << { playerID: player_id.to_i, displayName: names[idx] } else response[:teams] << { players: [{ playerID: player_id.to_i, displayName: names[idx] }], score: scores[idx].to_i, delta: elo_change(player_id, game_id, league_id).to_i } end end response[:teams] = response[:teams].sort! { |a, b| b[:score] <=> a[:score] } the_games << response end return the_games end end # returns an array of game ids involving player with id player_id def games_with_player(player_id, league_id) database do |db| return db.execute('SELECT GameID From Game WHERE PlayerID = :player_id AND LeagueID = :league_id ORDER BY Timestamp DESC, GameID DESC', player_id, league_id).flatten end end # returns an array of game ids involving only both player1 and player2 def games(player1_id, player2_id, league_id) database do |db| return db.execute('SELECT GameID FROM ( SELECT GameID FROM Game WHERE PlayerID IN (:player1_id, :player2_id) AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T1 JOIN ( SELECT GameID FROM Game AND LeagueID = :league_id GROUP BY GameID HAVING COUNT(*) = 2 ) AS T2 USING (GameID)', player1_id, player2_id, league_id).flatten end end # returns the id of a player, given their display name def id(name, league_id) database do |db| # return id return db.get_first_value 'SELECT PlayerID FROM Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end # returns the elo change over the last 24 hours for the specified player def daily_elo_change(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return today - 1200 unless prev return today - prev end end def daily_ladder_move(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i prev = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp < :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) today = db.get_first_value('SELECT e.Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp >= :midnight ORDER BY g.Timestamp DESC LIMIT 1', player_id, league_id, midnight) # corner cases return 0 unless today return 0 unless prev return today - prev end end def games_this_week(player_id, league_id) database do |db| midnight = DateTime.new(Time.now.year, Time.now.month, Time.now.day, 0, 0, 0, '-6').to_time.to_i week_ago = midnight - 604_800 return db.get_first_value('SELECT COUNT(GameID) FROM Game g WHERE g.PlayerID = :player_id AND g.LeagueID = :league_id AND g.Timestamp >= :week_ago', player_id, league_id, week_ago) end end def extended_stats(player_id, league_id) database do |db| allies = Hash.new(0) # key -> player_id, value -> wins nemeses = Hash.new(0) # key -> player_id, value -> losses singles_games = 0 singles_wins = 0 doubles_games = 0 doubles_wins = 0 db.execute('SELECT DISTINCT GameID FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) case game.length when 2 singles_games += 1 if game[1]['PlayerID'] == player_id # this player won singles_wins += 1 else # this player lost nemeses[game[1]['PlayerID']] += 1 end when 4 doubles_games += 1 idx = game.index { |g| g['PlayerID'] == player_id } if idx >= 2 # this player won doubles_wins += 1 allies[game[idx == 2 ? 3 : 2]['PlayerID']] += 1 end end end ally = allies.max_by { |_k, v| v } || ['Nobody', 0] nemesis = nemeses.max_by { |_k, v| v } || ['Nobody', 0] doubles_win_rate = doubles_wins / doubles_games.to_f singles_win_rate = singles_wins / singles_games.to_f return { ally: name(ally[0], league_id), allyCount: ally[1], doublesWinRate: doubles_win_rate.nan? ? nil : doubles_win_rate, doublesTotal: doubles_games, nemesis: name(nemesis[0], league_id), nemesisCount: nemesis[1], singlesWinRate: singles_win_rate.nan? ? nil : singles_win_rate, singlesTotal: singles_games, pastWeek: games_this_week(player_id, league_id) } end end def elo(player_id, game_id, league_id) database do |db| game_id ||= game_ids(league_id).last elo = db.get_first_value 'SELECT Elo FROM EloHistory WHERE PlayerID = :player_id AND LeagueID = :league_id AND GameID = :game_id', player_id, league_id, game_id # 1200 in case they have no games return elo || 1200 end end # returns the elo change for player with id player_id from game with id game_id # if the player was not involved in the game, the delta of their last game # before game with id game_id will be returned # if the player doesn't exist or has no games, 0 will be returned def elo_change(player_id, game_id, league_id) database do |db| # get game timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id elos = db.execute('SELECT e.Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE e.PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND g.Timestamp <= :timestamp ORDER BY g.Timestamp DESC, g.GameID DESC LIMIT 2', player_id, league_id, timestamp).flatten # safety if player doesn't have any games return 0 if elos.empty? # safety if there is only one game, so we should delta from 1200 return elos.first - 1200 if elos.length == 1 return elos.first - elos.last end end # returns a player's display name, given id def name(player_id, league_id) database do |db| return db.get_first_value 'SELECT DisplayName FROM Player WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id end end # returns an array of active players # sorted by PlayerID # NOTE: index != PlayerID def names(league_id) database do |db| return db.execute('SELECT DisplayName FROM Player WHERE ACTIVE = 1 AND LeagueID = :league_id', league_id).flatten end end # returns an array of elo/names def player_elos(league_id) database do |db| return db.execute('SELECT DisplayName, Elo from Player WHERE ACTIVE = 1 AND LeagueID = :league_id AND GamesPlayed >= 10 ORDER BY Elo DESC', league_id) end end # returns true if a player with DisplayName name is in the database # false otherwise def player_exists?(name, league_id, player_id = 0) database do |db| player = db.get_first_value 'SELECT * from Player WHERE DisplayName = :name AND LeagueID = :league_id AND PlayerID != :player_id COLLATE NOCASE', name, league_id, player_id return !player.nil? end end # returns an array of all player ids def player_ids(league_id) database do |db| # return id return db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id ORDER BY PlayerID', league_id).flatten end end # returns the id of the winning player (or players) in game with id id def winner(game_id, league_id) database do |db| # get max score winner = db.execute('SELECT PlayerID FROM Game WHERE GameID = :game_id AND LeagueID = :league_id AND Score = ( SELECT MAX(Score) FROM Game WHERE GameID = :game_id AND LeagueID = :league_id GROUP BY GameID )', game_id, league_id).flatten winner = winner.first if winner.length == 1 # return the winner(s) return winner end end # add a game to the database and update the history tables # outcome is hash containing key/value pairs where # key = player id # value = score # it's a little wonky but we need to support games of any number of # players/score combinations, so i think it's best def add_game(outcome, league_id, timestamp) database do |db| # get unix time timestamp ||= Time.now.to_i # get next game id game_id = 1 + db.get_first_value('SELECT GameID FROM Game ORDER BY GameID DESC LIMIT 1') # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end # calling recalc with timestamp means we update elo properly for the # new game, regardless of the time it was played recalc(league_id, timestamp) players = outcome.keys.collect do |player_id| { name: name(player_id, league_id), elo: elo(player_id, game_id, league_id), delta: elo_change(player_id, game_id, league_id) } end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' unless (league_id != 1 && league_id != 41) || slack_url.empty? text = "Game added: #{game_to_s(game_id, false, league_id)}" attachments = [{ author_name: "See the leaderboard", author_link: "http://foosey.futbol/#/redirect/" + (league_id == 1 ? "wca-dev" : "wca-cornhole"), fields: players.collect do |p| delta = p[:delta] >= 0 ? "+#{p[:delta]}" : p[:delta] { title: p[:name], value: "#{p[:elo]} (#{delta})", short: true } end }] message_slack(text, attachments, slack_url, league_id) end return { gameID: game_id, players: players } end end # adds a player to the database def add_player(league_id, name, slack_name = '', admin = false, active = true) database do |db| db.execute 'INSERT INTO Player (LeagueID, DisplayName, SlackName, Admin, Active) VALUES (:league_id, :name, :slack_name, :admin, :active)', league_id, name, slack_name, admin ? 1 : 0, active ? 1 : 0 recalc_elo(Time.now.to_i, league_id) return db.get_first_value 'SELECT PlayerID from Player WHERE DisplayName = :name AND LeagueID = :league_id COLLATE NOCASE', name, league_id end end def add_league(league_name, display_name) database do |db| return db.execute 'INSERT INTO League (LeagueName, DisplayName) VALUES (:league_name, :display_name)', league_name, display_name end end # changes properties of game with id game_id def edit_game(league_id, game_id, outcome, timestamp = nil, rec = true) database do |db| # get timestamp if we need to keep it unchanged timestamp ||= db.get_first_value 'SELECT Timestamp FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # delete game with id game_id db.execute 'DELETE FROM Game WHERE GameId = :game_id AND LeagueID = :league_id', game_id, league_id # insert new game into Game table outcome.each do |player_id, score| db.execute 'INSERT INTO Game VALUES (:game_id, :player_id, :league_id, :score, :timestamp)', game_id, player_id, league_id, score, timestamp end slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game edited: #{game_to_s(game_id, false, league_id)}", [], slack_url, league_id) if league_id == 1 || league_id == 41 end recalc(league_id) if rec end def edit_player(league_id, player_id, display_name = nil, slack_name = nil, admin = nil, active = nil) database do |db| # update the defined fields unless player_exists?(display_name, league_id, player_id) || display_name.nil? db.execute 'UPDATE Player SET DisplayName = :display_name WHERE PlayerID = :player_id AND LeagueID = :league_id', display_name, player_id, league_id end unless slack_name.nil? db.execute 'UPDATE Player SET SlackName = :slack_name WHERE PlayerID = :player_id AND LeagueID = :league_id', slack_name, player_id, league_id end unless admin.nil? db.execute 'UPDATE Player SET Admin = :admin WHERE PlayerID = :player_id AND LeagueID = :league_id', admin ? 1 : 0, player_id, league_id end unless active.nil? db.execute 'UPDATE Player SET Active = :active WHERE PlayerID = :player_id AND LeagueID = :league_id', active ? 1 : 0, player_id, league_id recalc_elo(0, league_id) end end end # recalculate all the stats and populate the history stat tables # if timestamp is specified, recalcs all games after timestamp def recalc(league_id, timestamp = 0, silent = true) unless silent start = Time.now.to_f puts 'Calculating Elo' end recalc_elo(timestamp, league_id) unless silent printf("Took %.3f seconds\n", Time.now.to_f - start) start = Time.now.to_f puts 'Calculating win rate' end recalc_win_rate(league_id) printf("Took %.3f seconds\n", Time.now.to_f - start) unless silent end def recalc_elo(timestamp, league_id) database do |db| # init transaction for zoom db.transaction db.execute 'DELETE FROM EloHistory WHERE GameID IN ( SELECT GameID FROM Game WHERE Timestamp >= :timestamp ) AND LeagueID = :league_id', timestamp, league_id win_weight = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "WinWeight"' max_score = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "MaxScore"' k_factor = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "KFactor"' # temporary array of hashes to keep track of player rankings elos = {} ladder = {} active = {} # find the last rung on the ladder so we can set any future players to be on the bottom of the ladder last_rung = db.get_first_value('SELECT Ladder FROM EloHistory WHERE Ladder is not null AND LeagueID = :league_id ORDER by Ladder desc limit 1', league_id) last_rung ||= 0 player_ids(league_id).each do |player_id| elos[player_id] = db.get_first_value('SELECT Elo FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) ladder[player_id] = db.get_first_value('SELECT Ladder FROM EloHistory e JOIN Game g USING (GameID, PlayerID) WHERE PlayerID = :player_id AND e.LeagueID = :league_id AND g.LeagueID = :league_id AND Timestamp <= :timestamp ORDER BY Timestamp DESC, GameID DESC LIMIT 1', player_id, league_id, timestamp) active[player_id] = db.get_first_value('SELECT Active FROM Player WHERE PlayerID = :player_id', player_id) # in case they had no games before timestamp elos[player_id] ||= 1200 if ladder[player_id].nil? ladder[player_id] = last_rung + 1 last_rung += 1 end end # for each game db.execute('SELECT DISTINCT GameID FROM Game WHERE Timestamp >= :timestamp AND LeagueID = :league_id ORDER BY Timestamp, GameID', timestamp, league_id) do |game_id| game = create_query_hash(db.execute2('SELECT PlayerID, Score FROM Game WHERE GameID = :game_id ORDER BY Score', game_id)) # calculate the leaderboard rankings case game.length when 2 score_a = game[0]['Score'] score_b = game[1]['Score'] # elo rating_a = elos[game[0]['PlayerID']] rating_b = elos[game[1]['PlayerID']] # ladder - only applies to active players if active[game[0]['PlayerID']] == 1 && active[game[1]['PlayerID']] == 1 old_a = ladder[game[0]['PlayerID']] old_b = ladder[game[1]['PlayerID']] ladder_jump = ((old_a - old_b).abs / 2.0).ceil # player a is lower on the ladder and they won if old_a > old_b && score_a > score_b new_a = ladder[game[0]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_a && ladder_value >= new_a ladder[player_id] += 1 end end ladder[game[0]['PlayerID']] = new_a end # player b is lower on the ladder and they won if old_b > old_a && score_b > score_a new_b = ladder[game[1]['PlayerID']] - ladder_jump ladder.each do |player_id, ladder_value| if ladder_value < old_b && ladder_value >= new_b ladder[player_id] += 1 end end ladder[game[1]['PlayerID']] = new_b end end when 4 rating_a = ((elos[game[0]['PlayerID']] + elos[game[1]['PlayerID']]) / 2).round rating_b = ((elos[game[2]['PlayerID']] + elos[game[3]['PlayerID']]) / 2).round score_a = game[0]['Score'] score_b = game[2]['Score'] else # fuck trips next end delta_a, delta_b = elo_delta(rating_a, score_a, rating_b, score_b, k_factor, win_weight, max_score) # insert into history table game.each_with_index do |player, idx| case game.length when 2 elos[player['PlayerID']] += idx < 1 ? delta_a : delta_b when 4 elos[player['PlayerID']] += idx < 2 ? delta_a : delta_b end db.execute 'INSERT INTO EloHistory VALUES (:game_id, :player_id, :league_id, :elo, :ladder)', game_id, player['PlayerID'], league_id, elos[player['PlayerID']], ladder[player['PlayerID']] end end # update the player table player_ids(league_id).each do |player_id| db.execute 'UPDATE Player SET Elo = :elo, Ladder = :ladder WHERE PlayerID = :player_id', elos[player_id], ladder[player_id], player_id end # end transaction db.commit end end def recalc_win_rate(league_id) database do |db| db.execute('SELECT PlayerID FROM Player WHERE LeagueID = :league_id', league_id) do |player_id| db.execute('UPDATE Player SET GamesPlayed = ( SELECT COUNT(*) FROM Game WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', player_id, league_id) db.execute('UPDATE Player SET GamesWon = ( SELECT COUNT(*) FROM Game JOIN ( SELECT GameID, MAX(Score) AS Score FROM Game WHERE LeagueID = :league_id GROUP BY GameID ) USING (GameID, Score) WHERE PlayerID = :player_id AND LeagueID = :league_id ) WHERE PlayerID = :player_id AND LeagueID = :league_id', league_id, player_id) end end end # remove a game by game_id def remove_game(game_id, league_id) database do |db| # get timestamp timestamp = db.get_first_value 'SELECT Timestamp FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id removed = game_to_s(game_id, false, league_id) # remove the game db.execute 'DELETE FROM Game WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id db.execute 'DELETE FROM EloHistory WHERE GameID = :game_id AND LeagueID = :league_id', game_id, league_id slack_url = db.get_first_value 'SELECT Value FROM Config WHERE Setting = "SlackUrl"' message_slack("Game removed: #{removed}", [], slack_url, league_id) if league_id == 1 || league_id == 41 recalc(league_id, timestamp) end end def slack_url(url) database do |db| db.execute 'UPDATE Config SET Value = :url WHERE Setting = "SlackUrl"', url end end
class HocSurvey2014 def self.claim_prize_code(type, user_id, params={}) ip_address = params[:ip_address] || request.ip begin rows_updated = DB[:hoc_survey_prizes].where(claimant:nil, type:type).limit(1).update( claimant:user_id, claimed_at:DateTime.now, claimed_ip:ip_address, ) raise StandardError, "Out of '#{type}' codes." if rows_updated == 0 rescue Sequel::UniqueConstraintViolation # This user has already claimed a prize, the query below will return that existing prize. rescue raise end DB[:hoc_survey_prizes].where(claimant:user_id).first end end Added field definitions for survey form. class HocSurvey2014 def self.normalize(data) result = {} result[:name_s] = required stripped data[:name_s] result[:email_s] = required stripped data[:email_s] result[:country_s] = enum(data[:country_s].to_s.strip.downcase, HOC_COUNTRIES.keys) result[:user_description_s] = required stripped data[:user_description_s] result[:event_location_type_s] = stripped data[:event_location_type_s] result[:students_number_i] = required stripped data[:students_number_i] result[:students_number_girls_i] = required stripped data[:students_number_girls_i] result[:students_number_ethnicity_i] = required stripped data[:students_number_ethnicity_i] result[:students_grade_levels_ss] = stripped data[:students_grade_levels_ss] result[:event_tutorial_ss] = stripped data[:event_tutorial_ss] result[:event_technology_ss] = stripped data[:event_technology_ss] result[:event_experience_s] = required stripped data[:event_experience_s] result[:event_improvement_s] = stripped data[:event_improvement_s] result[:event_annual_s] = stripped data[:event_annual_s] result[:teacher_plan_teach_cs_s] = stripped data[:teacher_plan_teach_cs] result[:teacher_first_year_s] = stripped data[:teacher_first_year_s] result[:teacher_how_heard_s] = stripped data[:teacher_how_heard_s] result end def self.claim_prize_code(type, user_id, params={}) ip_address = params[:ip_address] || request.ip begin rows_updated = DB[:hoc_survey_prizes].where(claimant:nil, type:type).limit(1).update( claimant:user_id, claimed_at:DateTime.now, claimed_ip:ip_address, ) raise StandardError, "Out of '#{type}' codes." if rows_updated == 0 rescue Sequel::UniqueConstraintViolation # This user has already claimed a prize, the query below will return that existing prize. rescue raise end DB[:hoc_survey_prizes].where(claimant:user_id).first end end
Add spec for de_cocs # frozen_string_literal: true require "rails_helper" RSpec.describe Api::V2::DeCocsController, type: :controller do include WebmockDhis2Helpers let(:program) { create :program } let(:token) { "123456789" } let(:project) do project = build :project project.project_anchor = program.build_project_anchor(token: token) project.save! user.program = program user.save! user.reload project end describe "#index" do include_context "basic_context" include WebmockDhis2Helpers before do stub_all_data_compound(project) stub_dhis2_system_info_success(project.dhis2_url) Dhis2SnapshotWorker.new.perform(project.project_anchor_id, filter: ["data_elements"]) end it "returns matching de based on term" do get :index, params: { term: "ANC 1st", token: token } resp = JSON.parse(response.body) puts(resp) names = resp["data"].map { |h| h["attributes"]["displayName"] } expect(names).to eq(["ANC 1st visit", "LLITN given at ANC 1st"]) end it "returns matching de based on id" do get :index, params: { id: "fbfJHSPpUQD", token: token } resp = JSON.parse(response.body) names = resp["data"].map { |h| h["attributes"]["displayName"] } expect(names).to eq(["ANC 1st visit"]) end it "returns empty array on 0 results" do get :index, params: { term: "nothing-here", token: token } resp = JSON.parse(response.body) expect(resp["data"]).to eq([]) end it "returns everything without query parameters" do get :index, params: { token: token } resp = JSON.parse(response.body) expect(resp["data"].length).to be > 10 end end end
# encoding: utf-8 require 'spec_helper' describe ManifestationsController do fixtures :all describe "GET index", :solr => true do shared_examples_for 'index can get a collation' do describe "When no record found" do let(:exact_title) { "RailsによるアジャイルWebアプリケーション開発" } let(:typo_title) { "RailsによるアジイャルWebアプリケーション開発" } before do Sunspot.remove_all! @manifestation = FactoryGirl.create( :manifestation, :original_title => exact_title, :manifestation_type => FactoryGirl.create(:manifestation_type)) @item = FactoryGirl.create( :item_book, :retention_period => FactoryGirl.create(:retention_period), :manifestation => @manifestation) Sunspot.commit end it "assings a collation as @collation" do get :index, :query => typo_title assigns(:manifestations).should be_empty assigns(:collation).should be_present assigns(:collation).should == exact_title end it "doesn't assing @collation" do get :index, :query => exact_title assigns(:collation).should be_blank end end end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end include_examples 'index can get a collation' end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end end describe "When not logged in" do it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations in sru format without operation" do get :index, :format => 'sru' assert_response :success assigns(:manifestations).should be_nil response.should render_template('manifestations/explain') end it "assigns all manifestations as @manifestations in sru format with operation" do get :index, :format => 'sru', :operation => 'searchRetrieve', :query => 'ruby' assigns(:manifestations).should_not be_nil response.should render_template('manifestations/index') end it "assigns all manifestations as @manifestations in sru format with operation and title" do get :index, :format => 'sru', :query => 'title=ruby', :operation => 'searchRetrieve' assigns(:manifestations).should_not be_nil response.should render_template('manifestations/index') end it "assigns all manifestations as @manifestations in openurl" do get :index, :api => 'openurl', :title => 'ruby' assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations when pub_date_from and pub_date_to are specified" do get :index, :pub_date_from => '2000', :pub_date_to => '2007' assigns(:query).should eq "pub_date_sm:[#{Time.zone.parse('2000-01-01').utc.iso8601} TO #{Time.zone.parse('2007-12-31').end_of_year.utc.iso8601}]" assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations when acquired_from and pub_date_to are specified" do get :index, :acquired_from => '2000', :acquired_to => '2007' assigns(:query).should eq "acquired_at_sm:[#{Time.zone.parse('2000-01-01').utc.iso8601} TO #{Time.zone.parse('2007-12-31').end_of_day.utc.iso8601}]" assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations when number_of_pages_at_least and number_of_pages_at_most are specified" do get :index, :number_of_pages_at_least => '100', :number_of_pages_at_least => '200' assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations in mods format" do get :index, :format => 'mods' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/index") end it "assigns all manifestations as @manifestations in rdf format" do get :index, :format => 'rdf' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/index") end it "assigns all manifestations as @manifestations in oai format without verb" do get :index, :format => 'oai' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/index") end it "assigns all manifestations as @manifestations in oai format with ListRecords" do get :index, :format => 'oai', :verb => 'ListRecords' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/list_records") end it "assigns all manifestations as @manifestations in oai format with ListIdentifiers" do get :index, :format => 'oai', :verb => 'ListIdentifiers' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/list_identifiers") end it "assigns all manifestations as @manifestations in oai format with GetRecord without identifier" do get :index, :format => 'oai', :verb => 'GetRecord' assigns(:manifestations).should be_nil assigns(:manifestation).should be_nil response.should render_template('manifestations/index') end it "assigns all manifestations as @manifestations in oai format with GetRecord with identifier" do get :index, :format => 'oai', :verb => 'GetRecord', :identifier => 'oai:localhost:manifestations-1' assigns(:manifestations).should be_nil assigns(:manifestation).should_not be_nil response.should render_template('manifestations/show') end end end describe "GET show" do describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end end describe "When not logged in" do it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end it "guest should show manifestation mods template" do get :show, :id => 22, :format => 'mods' assigns(:manifestation).should eq Manifestation.find(22) response.should render_template("manifestations/show") end it "should show manifestation rdf template" do get :show, :id => 22, :format => 'rdf' assigns(:manifestation).should eq Manifestation.find(22) response.should render_template("manifestations/show") end it "should_show_manifestation_with_isbn" do get :show, :isbn => "4798002062" response.should redirect_to manifestation_url(assigns(:manifestation)) end it "should_show_manifestation_with_isbn" do get :show, :isbn => "47980020620" response.should be_missing end end end describe "GET new" do describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "should not assign the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid response.should be_forbidden end end describe "When not logged in" do it "should not assign the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid response.should redirect_to(new_user_session_url) end end end describe "GET edit" do describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id assigns(:manifestation).should eq(manifestation) end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id assigns(:manifestation).should eq(manifestation) end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "assigns the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id response.should be_forbidden end end describe "When not logged in" do it "should not assign the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id response.should redirect_to(new_user_session_url) end end end describe "POST create" do before(:each) do @attrs = FactoryGirl.attributes_for(:manifestation) @invalid_attrs = {:original_title => ''} end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "redirects to the created manifestation" do post :create, :manifestation => @attrs response.should redirect_to(manifestation_url(assigns(:manifestation))) end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "re-renders the 'new' template" do post :create, :manifestation => @invalid_attrs response.should render_template("new") end end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "redirects to the created manifestation" do post :create, :manifestation => @attrs response.should redirect_to(manifestation_url(assigns(:manifestation))) end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "re-renders the 'new' template" do post :create, :manifestation => @invalid_attrs response.should render_template("new") end end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "should be forbidden" do post :create, :manifestation => @attrs response.should be_forbidden end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "should be forbidden" do post :create, :manifestation => @invalid_attrs response.should be_forbidden end end end describe "When not logged in" do describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "should be forbidden" do post :create, :manifestation => @attrs response.should redirect_to(new_user_session_url) end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "should be forbidden" do post :create, :manifestation => @invalid_attrs response.should redirect_to(new_user_session_url) end end end end describe "PUT update" do before(:each) do @manifestation = FactoryGirl.create(:manifestation) @attrs = FactoryGirl.attributes_for(:manifestation) @invalid_attrs = {:original_title => ''} end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs assigns(:manifestation).should eq(@manifestation) end end describe "with invalid params" do it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @invalid_attrs response.should render_template("edit") end end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs assigns(:manifestation).should eq(@manifestation) response.should redirect_to(@manifestation) end end describe "with invalid params" do it "assigns the manifestation as @manifestation" do put :update, :id => @manifestation, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "re-renders the 'edit' template" do put :update, :id => @manifestation, :manifestation => @invalid_attrs response.should render_template("edit") end end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs assigns(:manifestation).should eq(@manifestation) response.should be_forbidden end end describe "with invalid params" do it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @invalid_attrs response.should be_forbidden end end end describe "When not logged in" do describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "should be forbidden" do put :update, :id => @manifestation.id, :manifestation => @attrs response.should redirect_to(new_user_session_url) end end describe "with invalid params" do it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @invalid_attrs response.should redirect_to(new_user_session_url) end end end end describe "DELETE destroy" do before(:each) do @manifestation = FactoryGirl.create(:manifestation) end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "redirects to the manifestations list" do delete :destroy, :id => @manifestation.id response.should redirect_to(manifestations_url) end it "should not destroy the reserved manifestation" do delete :destroy, :id => 2 response.should be_forbidden end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "should be forbidden" do delete :destroy, :id => @manifestation.id response.should redirect_to(manifestations_url) end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "should be forbidden" do delete :destroy, :id => @manifestation.id response.should be_forbidden end end describe "When not logged in" do it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "should be forbidden" do delete :destroy, :id => @manifestation.id response.should redirect_to(new_user_session_url) end end end end コントローラの仕様変更に追従した コントローラの機能追加にspecが追従できていなかったのを修正した。 # encoding: utf-8 require 'spec_helper' describe ManifestationsController do fixtures :all describe "GET index", :solr => true do shared_examples_for 'index can get a collation' do describe "When no record found" do let(:exact_title) { "RailsによるアジャイルWebアプリケーション開発" } let(:typo_title) { "RailsによるアジイャルWebアプリケーション開発" } before do Sunspot.remove_all! @manifestation = FactoryGirl.create( :manifestation, :original_title => exact_title, :manifestation_type => FactoryGirl.create(:manifestation_type)) @item = FactoryGirl.create( :item_book, :retention_period => FactoryGirl.create(:retention_period), :manifestation => @manifestation) Sunspot.commit end it "assings a collation as @collation" do get :index, :query => typo_title, :all_manifestations => 'true' assigns(:manifestations).should be_empty assigns(:collation).should be_present assigns(:collation).should == [exact_title] end it "doesn't assing @collation" do get :index, :query => exact_title, :all_manifestations => 'true' assigns(:manifestations).should be_present assigns(:collation).should be_blank end end end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end include_examples 'index can get a collation' end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end end describe "When not logged in" do it "assigns all manifestations as @manifestations" do get :index assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations in sru format without operation" do get :index, :format => 'sru' assert_response :success assigns(:manifestations).should be_nil response.should render_template('manifestations/explain') end it "assigns all manifestations as @manifestations in sru format with operation" do get :index, :format => 'sru', :operation => 'searchRetrieve', :query => 'ruby' assigns(:manifestations).should_not be_nil response.should render_template('manifestations/index') end it "assigns all manifestations as @manifestations in sru format with operation and title" do get :index, :format => 'sru', :query => 'title=ruby', :operation => 'searchRetrieve' assigns(:manifestations).should_not be_nil response.should render_template('manifestations/index') end it "assigns all manifestations as @manifestations in openurl" do get :index, :api => 'openurl', :title => 'ruby' assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations when pub_date_from and pub_date_to are specified" do get :index, :pub_date_from => '2000', :pub_date_to => '2007' assigns(:query).should eq "pub_date_sm:[#{Time.zone.parse('2000-01-01').utc.iso8601} TO #{Time.zone.parse('2007-12-31').end_of_year.utc.iso8601}]" assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations when acquired_from and pub_date_to are specified" do get :index, :acquired_from => '2000', :acquired_to => '2007' assigns(:query).should eq "acquired_at_sm:[#{Time.zone.parse('2000-01-01').utc.iso8601} TO #{Time.zone.parse('2007-12-31').end_of_day.utc.iso8601}]" assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations when number_of_pages_at_least and number_of_pages_at_most are specified" do get :index, :number_of_pages_at_least => '100', :number_of_pages_at_least => '200' assigns(:manifestations).should_not be_nil end it "assigns all manifestations as @manifestations in mods format" do get :index, :format => 'mods' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/index") end it "assigns all manifestations as @manifestations in rdf format" do get :index, :format => 'rdf' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/index") end it "assigns all manifestations as @manifestations in oai format without verb" do get :index, :format => 'oai' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/index") end it "assigns all manifestations as @manifestations in oai format with ListRecords" do get :index, :format => 'oai', :verb => 'ListRecords' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/list_records") end it "assigns all manifestations as @manifestations in oai format with ListIdentifiers" do get :index, :format => 'oai', :verb => 'ListIdentifiers' assigns(:manifestations).should_not be_nil response.should render_template("manifestations/list_identifiers") end it "assigns all manifestations as @manifestations in oai format with GetRecord without identifier" do get :index, :format => 'oai', :verb => 'GetRecord' assigns(:manifestations).should be_nil assigns(:manifestation).should be_nil response.should render_template('manifestations/index') end it "assigns all manifestations as @manifestations in oai format with GetRecord with identifier" do get :index, :format => 'oai', :verb => 'GetRecord', :identifier => 'oai:localhost:manifestations-1' assigns(:manifestations).should be_nil assigns(:manifestation).should_not be_nil response.should render_template('manifestations/show') end end end describe "GET show" do describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end end describe "When not logged in" do it "assigns the requested manifestation as @manifestation" do get :show, :id => 1 assigns(:manifestation).should eq(Manifestation.find(1)) end it "guest should show manifestation mods template" do get :show, :id => 22, :format => 'mods' assigns(:manifestation).should eq Manifestation.find(22) response.should render_template("manifestations/show") end it "should show manifestation rdf template" do get :show, :id => 22, :format => 'rdf' assigns(:manifestation).should eq Manifestation.find(22) response.should render_template("manifestations/show") end it "should_show_manifestation_with_isbn" do get :show, :isbn => "4798002062" response.should redirect_to manifestation_url(assigns(:manifestation)) end it "should_show_manifestation_with_isbn" do get :show, :isbn => "47980020620" response.should be_missing end end end describe "GET new" do describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "should not assign the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid response.should be_forbidden end end describe "When not logged in" do it "should not assign the requested manifestation as @manifestation" do get :new assigns(:manifestation).should_not be_valid response.should redirect_to(new_user_session_url) end end end describe "GET edit" do describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "assigns the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id assigns(:manifestation).should eq(manifestation) end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "assigns the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id assigns(:manifestation).should eq(manifestation) end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "assigns the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id response.should be_forbidden end end describe "When not logged in" do it "should not assign the requested manifestation as @manifestation" do manifestation = FactoryGirl.create(:manifestation) get :edit, :id => manifestation.id response.should redirect_to(new_user_session_url) end end end describe "POST create" do before(:each) do @attrs = FactoryGirl.attributes_for(:manifestation) @invalid_attrs = {:original_title => ''} end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "redirects to the created manifestation" do post :create, :manifestation => @attrs response.should redirect_to(manifestation_url(assigns(:manifestation))) end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "re-renders the 'new' template" do post :create, :manifestation => @invalid_attrs response.should render_template("new") end end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "redirects to the created manifestation" do post :create, :manifestation => @attrs response.should redirect_to(manifestation_url(assigns(:manifestation))) end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "re-renders the 'new' template" do post :create, :manifestation => @invalid_attrs response.should render_template("new") end end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "should be forbidden" do post :create, :manifestation => @attrs response.should be_forbidden end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "should be forbidden" do post :create, :manifestation => @invalid_attrs response.should be_forbidden end end end describe "When not logged in" do describe "with valid params" do it "assigns a newly created manifestation as @manifestation" do post :create, :manifestation => @attrs assigns(:manifestation).should be_valid end it "should be forbidden" do post :create, :manifestation => @attrs response.should redirect_to(new_user_session_url) end end describe "with invalid params" do it "assigns a newly created but unsaved manifestation as @manifestation" do post :create, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "should be forbidden" do post :create, :manifestation => @invalid_attrs response.should redirect_to(new_user_session_url) end end end end describe "PUT update" do before(:each) do @manifestation = FactoryGirl.create(:manifestation) @attrs = FactoryGirl.attributes_for(:manifestation) @invalid_attrs = {:original_title => ''} end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs assigns(:manifestation).should eq(@manifestation) end end describe "with invalid params" do it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @invalid_attrs response.should render_template("edit") end end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs assigns(:manifestation).should eq(@manifestation) response.should redirect_to(@manifestation) end end describe "with invalid params" do it "assigns the manifestation as @manifestation" do put :update, :id => @manifestation, :manifestation => @invalid_attrs assigns(:manifestation).should_not be_valid end it "re-renders the 'edit' template" do put :update, :id => @manifestation, :manifestation => @invalid_attrs response.should render_template("edit") end end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs assigns(:manifestation).should eq(@manifestation) response.should be_forbidden end end describe "with invalid params" do it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @invalid_attrs response.should be_forbidden end end end describe "When not logged in" do describe "with valid params" do it "updates the requested manifestation" do put :update, :id => @manifestation.id, :manifestation => @attrs end it "should be forbidden" do put :update, :id => @manifestation.id, :manifestation => @attrs response.should redirect_to(new_user_session_url) end end describe "with invalid params" do it "assigns the requested manifestation as @manifestation" do put :update, :id => @manifestation.id, :manifestation => @invalid_attrs response.should redirect_to(new_user_session_url) end end end end describe "DELETE destroy" do before(:each) do @manifestation = FactoryGirl.create(:manifestation) end describe "When logged in as Administrator" do before(:each) do sign_in FactoryGirl.create(:admin) end it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "redirects to the manifestations list" do delete :destroy, :id => @manifestation.id response.should redirect_to(manifestations_url) end it "should not destroy the reserved manifestation" do delete :destroy, :id => 2 response.should be_forbidden end end describe "When logged in as Librarian" do before(:each) do sign_in FactoryGirl.create(:librarian) end it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "should be forbidden" do delete :destroy, :id => @manifestation.id response.should redirect_to(manifestations_url) end end describe "When logged in as User" do before(:each) do sign_in FactoryGirl.create(:user) end it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "should be forbidden" do delete :destroy, :id => @manifestation.id response.should be_forbidden end end describe "When not logged in" do it "destroys the requested manifestation" do delete :destroy, :id => @manifestation.id end it "should be forbidden" do delete :destroy, :id => @manifestation.id response.should redirect_to(new_user_session_url) end end end end
require 'spec_helper' describe Projects::ForksController do let(:user) { create(:user) } let(:project) { create(:project, :public) } let(:forked_project) { Projects::ForkService.new(project, user).execute } let(:group) { create(:group, owner: forked_project.creator) } describe 'GET index' do def get_forks get :index, namespace_id: project.namespace.to_param, project_id: project.to_param end context 'when fork is public' do before { forked_project.update_attribute(:visibility_level, Project::PUBLIC) } it 'is visible for non logged in users' do get_forks expect(assigns[:forks]).to be_present end end context 'when fork is private' do before do forked_project.update_attributes(visibility_level: Project::PRIVATE, group: group) end it 'is not be visible for non logged in users' do get_forks expect(assigns[:forks]).to be_blank end context 'when user is logged in' do before { sign_in(project.creator) } context 'when user is not a Project member neither a group member' do it 'does not see the Project listed' do get_forks expect(assigns[:forks]).to be_blank end end context 'when user is a member of the Project' do before { forked_project.team << [project.creator, :developer] } it 'sees the project listed' do get_forks expect(assigns[:forks]).to be_present end end context 'when user is a member of the Group' do before { forked_project.group.add_developer(project.creator) } it 'sees the project listed' do get_forks expect(assigns[:forks]).to be_present end end end end end describe 'GET new' do context 'when user is not logged in' do it 'redirects to the sign-in page' do sign_out(user) get :new, namespace_id: project.namespace.to_param, project_id: project.to_param expect(response).to redirect_to(root_path + 'users/sign_in') end end end end Move sign_out out of it into before require 'spec_helper' describe Projects::ForksController do let(:user) { create(:user) } let(:project) { create(:project, :public) } let(:forked_project) { Projects::ForkService.new(project, user).execute } let(:group) { create(:group, owner: forked_project.creator) } describe 'GET index' do def get_forks get :index, namespace_id: project.namespace.to_param, project_id: project.to_param end context 'when fork is public' do before { forked_project.update_attribute(:visibility_level, Project::PUBLIC) } it 'is visible for non logged in users' do get_forks expect(assigns[:forks]).to be_present end end context 'when fork is private' do before do forked_project.update_attributes(visibility_level: Project::PRIVATE, group: group) end it 'is not be visible for non logged in users' do get_forks expect(assigns[:forks]).to be_blank end context 'when user is logged in' do before { sign_in(project.creator) } context 'when user is not a Project member neither a group member' do it 'does not see the Project listed' do get_forks expect(assigns[:forks]).to be_blank end end context 'when user is a member of the Project' do before { forked_project.team << [project.creator, :developer] } it 'sees the project listed' do get_forks expect(assigns[:forks]).to be_present end end context 'when user is a member of the Group' do before { forked_project.group.add_developer(project.creator) } it 'sees the project listed' do get_forks expect(assigns[:forks]).to be_present end end end end end describe 'GET new' do context 'when user is not logged in' do before { sign_out(user) } it 'redirects to the sign-in page' do get :new, namespace_id: project.namespace.to_param, project_id: project.to_param expect(response).to redirect_to(root_path + 'users/sign_in') end end end end
require 'spec_helper' describe TrayPositionsController do include_examples "every authenticated controller" describe "POST 'create'" do before(:each) do request.env["HTTP_REFERER"] = "http://test.host/" post 'create', { :user_id => 1, :tray_position => {:clipboard_type => 'something'} } end it { response.should redirect_to(:back) } it "should capitalize the clipboard_type attribute" do TrayPosition.all.last.clipboard_type.should eq('something'.capitalize) end end end make TrayPositions controller specs pass again there were some slight changes for tray positions, this makes the specs work again require 'spec_helper' describe TrayPositionsController do before(:each) do @mock_user = mock_model(User, {:tray_positions => double(TrayPosition, {:maximum => 1})}).as_null_object end include_examples "every authenticated controller" describe "POST 'create'" do before(:each) do request.env["HTTP_REFERER"] = "http://test.host/" post 'create', { :user_id => 1, :tray_position => {:clipboard_type => 'something'} } end it { response.should redirect_to(:back) } it "should capitalize the clipboard_type attribute" do TrayPosition.all.last.clipboard_type.should eq('something'.capitalize) end end end
describe Users::DossiersController, type: :controller do let(:user) { create(:user) } describe 'before_actions' do it 'are present' do before_actions = Users::DossiersController ._process_action_callbacks .filter { |process_action_callbacks| process_action_callbacks.kind == :before } .map(&:filter) expect(before_actions).to include(:ensure_ownership!, :ensure_ownership_or_invitation!, :forbid_invite_submission!) end end shared_examples_for 'does not redirect nor flash' do before { @controller.send(ensure_authorized) } it { expect(@controller).not_to have_received(:redirect_to) } it { expect(flash.alert).to eq(nil) } end shared_examples_for 'redirects and flashes' do before { @controller.send(ensure_authorized) } it { expect(@controller).to have_received(:redirect_to).with(root_path) } it { expect(flash.alert).to eq("Vous n'avez pas accès à ce dossier") } end describe '#ensure_ownership!' do let(:user) { create(:user) } let(:asked_dossier) { create(:dossier) } let(:ensure_authorized) { :ensure_ownership! } before do @controller.params = @controller.params.merge(dossier_id: asked_dossier.id) expect(@controller).to receive(:current_user).and_return(user) allow(@controller).to receive(:redirect_to) end context 'when a user asks for their own dossier' do let(:asked_dossier) { create(:dossier, user: user) } it_behaves_like 'does not redirect nor flash' end context 'when a user asks for another dossier' do it_behaves_like 'redirects and flashes' end context 'when an invite asks for a dossier where they were invited' do before { create(:invite, dossier: asked_dossier, user: user) } it_behaves_like 'redirects and flashes' end context 'when an invite asks for another dossier' do before { create(:invite, dossier: create(:dossier), user: user) } it_behaves_like 'redirects and flashes' end end describe '#ensure_ownership_or_invitation!' do let(:user) { create(:user) } let(:asked_dossier) { create(:dossier) } let(:ensure_authorized) { :ensure_ownership_or_invitation! } before do @controller.params = @controller.params.merge(dossier_id: asked_dossier.id) expect(@controller).to receive(:current_user).and_return(user) allow(@controller).to receive(:redirect_to) end context 'when a user asks for their own dossier' do let(:asked_dossier) { create(:dossier, user: user) } it_behaves_like 'does not redirect nor flash' end context 'when a user asks for another dossier' do it_behaves_like 'redirects and flashes' end context 'when an invite asks for a dossier where they were invited' do before { create(:invite, dossier: asked_dossier, user: user) } it_behaves_like 'does not redirect nor flash' end context 'when an invite asks for another dossier' do before { create(:invite, dossier: create(:dossier), user: user) } it_behaves_like 'redirects and flashes' end end describe "#forbid_invite_submission!" do let(:user) { create(:user) } let(:asked_dossier) { create(:dossier) } let(:ensure_authorized) { :forbid_invite_submission! } let(:submit) { true } before do @controller.params = @controller.params.merge(dossier_id: asked_dossier.id, submit_draft: submit) allow(@controller).to receive(:current_user).and_return(user) allow(@controller).to receive(:redirect_to) end context 'when a user save their own draft' do let(:asked_dossier) { create(:dossier, user: user) } let(:submit) { false } it_behaves_like 'does not redirect nor flash' end context 'when a user submit their own dossier' do let(:asked_dossier) { create(:dossier, user: user) } let(:submit) { true } it_behaves_like 'does not redirect nor flash' end context 'when an invite save the draft for a dossier where they where invited' do before { create(:invite, dossier: asked_dossier, user: user) } let(:submit) { false } it_behaves_like 'does not redirect nor flash' end context 'when an invite submit a dossier where they where invited' do before { create(:invite, dossier: asked_dossier, user: user) } let(:submit) { true } it_behaves_like 'redirects and flashes' end end describe 'attestation' do before { sign_in(user) } context 'when a dossier has an attestation' do let(:dossier) { create(:dossier, :accepte, attestation: create(:attestation, :with_pdf), user: user) } it 'redirects to attestation pdf' do get :attestation, params: { id: dossier.id } expect(response.location).to match '/rails/active_storage/disk/' end end end describe 'update_identite' do let(:procedure) { create(:procedure, :for_individual) } let(:dossier) { create(:dossier, user: user, procedure: procedure) } subject { post :update_identite, params: { id: dossier.id, individual: individual_params } } before do sign_in(user) subject end context 'with correct individual and dossier params' do let(:individual_params) { { gender: 'M', nom: 'Mouse', prenom: 'Mickey' } } it do expect(response).to redirect_to(brouillon_dossier_path(dossier)) end end context 'when the identite cannot be updated by the user' do let(:dossier) { create(:dossier, :with_individual, :en_instruction, user: user, procedure: procedure) } let(:individual_params) { { gender: 'M', nom: 'Mouse', prenom: 'Mickey' } } it 'redirects to the dossiers list' do expect(response).to redirect_to(dossiers_path) expect(flash.alert).to eq('Votre dossier ne peut plus être modifié') end end context 'with incorrect individual and dossier params' do let(:individual_params) { { gender: '', nom: '', prenom: '' } } it do expect(response).not_to have_http_status(:redirect) expect(flash[:alert]).to include("Civilité doit être rempli", "Nom doit être rempli", "Prénom doit être rempli") end end end describe '#siret' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user) } subject { get :siret, params: { id: dossier.id } } it { is_expected.to render_template(:siret) } end describe '#update_siret' do let(:dossier) { create(:dossier, user: user) } let(:siret) { params_siret.delete(' ') } let(:siren) { siret[0..8] } let(:api_etablissement_status) { 200 } let(:api_etablissement_body) { File.read('spec/fixtures/files/api_entreprise/etablissements.json') } let(:token_expired) { false } before do sign_in(user) stub_request(:get, /https:\/\/entreprise.api.gouv.fr\/v2\/etablissements\/#{siret}?.*token=/) .to_return(status: api_etablissement_status, body: api_etablissement_body) allow_any_instance_of(ApiEntrepriseToken).to receive(:roles) .and_return(["attestations_fiscales", "attestations_sociales", "bilans_entreprise_bdf"]) allow_any_instance_of(ApiEntrepriseToken).to receive(:expired?).and_return(token_expired) end subject! { post :update_siret, params: { id: dossier.id, user: { siret: params_siret } } } shared_examples 'SIRET informations are successfully saved' do it do dossier.reload user.reload expect(dossier.etablissement).to be_present expect(dossier.autorisation_donnees).to be(true) expect(user.siret).to eq(siret) expect(response).to redirect_to(etablissement_dossier_path) end end shared_examples 'the request fails with an error' do |error| it 'doesn’t save an etablissement' do expect(dossier.reload.etablissement).to be_nil end it 'displays the SIRET that was sent by the user in the form' do expect(controller.current_user.siret).to eq(siret) end it 'renders an error' do expect(flash.alert).to eq(error) expect(response).to render_template(:siret) end end context 'with an invalid SIRET' do let(:params_siret) { '000 000' } it_behaves_like 'the request fails with an error', ['Siret Le numéro SIRET doit comporter 14 chiffres'] end context 'with a valid SIRET' do let(:params_siret) { '418 166 096 00051' } context 'When API-Entreprise is down' do let(:api_etablissement_status) { 502 } it_behaves_like 'the request fails with an error', I18n.t('errors.messages.siret_network_error') end context 'when API-Entreprise doesn’t know this SIRET' do let(:api_etablissement_status) { 404 } it_behaves_like 'the request fails with an error', I18n.t('errors.messages.siret_unknown') end context 'when default token has expired' do let(:api_etablissement_status) { 200 } let(:token_expired) { true } it_behaves_like 'the request fails with an error', I18n.t('errors.messages.siret_unknown') end context 'when all API informations available' do it_behaves_like 'SIRET informations are successfully saved' it 'saves the associated informations on the etablissement' do dossier.reload expect(dossier.etablissement.entreprise).to be_present end end end end describe '#etablissement' do let(:dossier) { create(:dossier, :with_entreprise, user: user) } before { sign_in(user) } subject { get :etablissement, params: { id: dossier.id } } it { is_expected.to render_template(:etablissement) } context 'when the dossier has no etablissement yet' do let(:dossier) { create(:dossier, user: user) } it { is_expected.to redirect_to siret_dossier_path(dossier) } end end describe '#brouillon' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user, autorisation_donnees: true) } subject { get :brouillon, params: { id: dossier.id } } context 'when autorisation_donnees is checked' do it { is_expected.to render_template(:brouillon) } end context 'when autorisation_donnees is not checked' do before { dossier.update_columns(autorisation_donnees: false) } context 'when the dossier is for personne morale' do it { is_expected.to redirect_to(siret_dossier_path(dossier)) } end context 'when the dossier is for an personne physique' do before { dossier.procedure.update(for_individual: true) } it { is_expected.to redirect_to(identite_dossier_path(dossier)) } end end end describe '#edit' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user) } it 'returns the edit page' do get :brouillon, params: { id: dossier.id } expect(response).to have_http_status(:success) end end describe '#update_brouillon' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user) } let(:first_champ) { dossier.champs.first } let(:value) { 'beautiful value' } let(:now) { Time.zone.parse('01/01/2100') } let(:submit_payload) do { id: dossier.id, dossier: { champs_attributes: { id: first_champ.id, value: value } } } end let(:payload) { submit_payload.merge(submit_draft: true) } subject do Timecop.freeze(now) do patch :update_brouillon, params: payload end end context 'when the dossier cannot be updated by the user' do let!(:dossier) { create(:dossier, :en_instruction, user: user) } it 'redirects to the dossiers list' do subject expect(response).to redirect_to(dossiers_path) expect(flash.alert).to eq('Votre dossier ne peut plus être modifié') end end context 'when dossier can be updated by the owner' do it 'updates the champs' do subject expect(response).to redirect_to(merci_dossier_path(dossier)) expect(first_champ.reload.value).to eq('beautiful value') expect(dossier.reload.updated_at.year).to eq(2100) expect(dossier.reload.state).to eq(Dossier.states.fetch(:en_construction)) end context 'with instructeurs ok to be notified instantly' do let!(:instructeur_with_instant_email_dossier) { create(:instructeur) } let!(:instructeur_without_instant_email_dossier) { create(:instructeur) } before do allow(DossierMailer).to receive(:notify_new_dossier_depose_to_instructeur).and_return(double(deliver_later: nil)) create(:assign_to, instructeur: instructeur_with_instant_email_dossier, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: true, groupe_instructeur: dossier.procedure.defaut_groupe_instructeur) create(:assign_to, instructeur: instructeur_without_instant_email_dossier, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: false, groupe_instructeur: dossier.procedure.defaut_groupe_instructeur) end it "sends notification mail to instructeurs" do subject expect(DossierMailer).to have_received(:notify_new_dossier_depose_to_instructeur).once.with(dossier, instructeur_with_instant_email_dossier.email) expect(DossierMailer).not_to have_received(:notify_new_dossier_depose_to_instructeur).with(dossier, instructeur_without_instant_email_dossier.email) end end context 'with procedure routee' do let(:procedure) { create(:procedure, :routee, :with_type_de_champ) } let(:dossier_group) { create(:groupe_instructeur, procedure: procedure) } let(:another_group) { create(:groupe_instructeur, procedure: procedure) } let(:instructeur_of_dossier) { create(:instructeur) } let(:instructeur_in_another_group) { create(:instructeur) } let!(:dossier) { create(:dossier, groupe_instructeur: dossier_group, user: user) } before do allow(DossierMailer).to receive(:notify_new_dossier_depose_to_instructeur).and_return(double(deliver_later: nil)) create(:assign_to, instructeur: instructeur_of_dossier, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: true, groupe_instructeur: dossier_group) create(:assign_to, instructeur: instructeur_in_another_group, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: true, groupe_instructeur: another_group) end it "sends notification mail to instructeurs in the correct group instructeur" do subject expect(DossierMailer).to have_received(:notify_new_dossier_depose_to_instructeur).once.with(dossier, instructeur_of_dossier.email) expect(DossierMailer).not_to have_received(:notify_new_dossier_depose_to_instructeur).with(dossier, instructeur_in_another_group.email) end end context "on an closed procedure" do before { dossier.procedure.close! } it "it does not change state" do subject expect(response).not_to redirect_to(merci_dossier_path(dossier)) expect(dossier.reload.state).to eq(Dossier.states.fetch(:brouillon)) end end end it 'sends an email only on the first #update_brouillon' do delivery = double expect(delivery).to receive(:deliver_later).with(no_args) expect(NotificationMailer).to receive(:send_initiated_notification) .and_return(delivery) subject expect(NotificationMailer).not_to receive(:send_initiated_notification) subject end context 'when the update fails' do before do expect_any_instance_of(Dossier).to receive(:save).and_return(false) expect_any_instance_of(Dossier).to receive(:errors) .and_return(double(full_messages: ['nop'])) subject end it { expect(response).to render_template(:brouillon) } it { expect(flash.alert).to eq(['nop']) } it 'does not send an email' do expect(NotificationMailer).not_to receive(:send_initiated_notification) subject end end context 'when a mandatory champ is missing' do let(:value) { nil } before do first_champ.type_de_champ.update(mandatory: true, libelle: 'l') subject end it { expect(response).to render_template(:brouillon) } it { expect(flash.alert).to eq(['Le champ l doit être rempli.']) } context 'and the user saves a draft' do let(:payload) { submit_payload.except(:submit_draft) } it { expect(response).to render_template(:brouillon) } it { expect(flash.notice).to eq('Votre brouillon a bien été sauvegardé.') } it { expect(dossier.reload.state).to eq(Dossier.states.fetch(:brouillon)) } context 'and the dossier is in construction' do let!(:dossier) { create(:dossier, :en_construction, user: user) } it { expect(response).to render_template(:brouillon) } it { expect(flash.alert).to eq(['Le champ l doit être rempli.']) } end end end context 'when dossier has no champ' do let(:submit_payload) { { id: dossier.id } } it 'does not raise any errors' do subject expect(response).to redirect_to(merci_dossier_path(dossier)) end end context 'when the user has an invitation but is not the owner' do let(:dossier) { create(:dossier) } let!(:invite) { create(:invite, dossier: dossier, user: user) } context 'and the invite saves a draft' do let(:payload) { submit_payload.except(:submit_draft) } before do first_champ.type_de_champ.update(mandatory: true, libelle: 'l') subject end it { expect(response).to render_template(:brouillon) } it { expect(flash.notice).to eq('Votre brouillon a bien été sauvegardé.') } it { expect(dossier.reload.state).to eq(Dossier.states.fetch(:brouillon)) } end context 'and the invite tries to submit the dossier' do before { subject } it { expect(response).to redirect_to(root_path) } it { expect(flash.alert).to eq("Vous n'avez pas accès à ce dossier") } end end end describe '#update' do before { sign_in(user) } let(:procedure) { create(:procedure, :published, :with_type_de_champ, :with_piece_justificative) } let!(:dossier) { create(:dossier, :en_construction, user: user, procedure: procedure) } let(:first_champ) { dossier.champs.first } let(:piece_justificative_champ) { dossier.champs.last } let(:value) { 'beautiful value' } let(:file) { fixture_file_upload('spec/fixtures/files/piece_justificative_0.pdf', 'application/pdf') } let(:now) { Time.zone.parse('01/01/2100') } let(:submit_payload) do { id: dossier.id, dossier: { champs_attributes: { id: first_champ.id, value: value } } } end let(:payload) { submit_payload } subject do Timecop.freeze(now) do patch :update, params: payload end end context 'when the dossier cannot be updated by the user' do let!(:dossier) { create(:dossier, :en_instruction, user: user) } it 'redirects to the dossiers list' do subject expect(response).to redirect_to(dossiers_path) expect(flash.alert).to eq('Votre dossier ne peut plus être modifié') end end context 'when dossier can be updated by the owner' do it 'updates the champs' do subject expect(response).to redirect_to(demande_dossier_path(dossier)) expect(first_champ.reload.value).to eq('beautiful value') expect(dossier.reload.updated_at.year).to eq(2100) expect(dossier.reload.state).to eq(Dossier.states.fetch(:en_construction)) end context 'when only files champs are modified' do let(:submit_payload) do { id: dossier.id, dossier: { champs_attributes: { id: piece_justificative_champ.id, piece_justificative_file: file } } } end it 'updates the dossier modification date' do subject expect(dossier.reload.updated_at.year).to eq(2100) end end end context 'when the update fails' do before do expect_any_instance_of(Dossier).to receive(:save).and_return(false) expect_any_instance_of(Dossier).to receive(:errors) .and_return(double(full_messages: ['nop'])) subject end it { expect(response).to render_template(:modifier) } it { expect(flash.alert).to eq(['nop']) } it 'does not send an email' do expect(NotificationMailer).not_to receive(:send_initiated_notification) subject end end context 'when a mandatory champ is missing' do let(:value) { nil } before do first_champ.type_de_champ.update(mandatory: true, libelle: 'l') subject end it { expect(response).to render_template(:modifier) } it { expect(flash.alert).to eq(['Le champ l doit être rempli.']) } end context 'when dossier has no champ' do let(:submit_payload) { { id: dossier.id } } it 'does not raise any errors' do subject expect(response).to redirect_to(demande_dossier_path(dossier)) end end context 'when the user has an invitation but is not the owner' do let(:dossier) { create(:dossier) } let!(:invite) { create(:invite, dossier: dossier, user: user) } before do dossier.en_construction! subject end it { expect(first_champ.reload.value).to eq('beautiful value') } it { expect(dossier.reload.state).to eq(Dossier.states.fetch(:en_construction)) } it { expect(response).to redirect_to(demande_dossier_path(dossier)) } end end describe '#index' do before { sign_in(user) } context 'when the user does not have any dossiers' do before { get(:index) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } end context 'when the user only have its own dossiers' do let!(:own_dossier) { create(:dossier, user: user) } before { get(:index) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } it { expect(assigns(:dossiers)).to match([own_dossier]) } end context 'when the user only have some dossiers invites' do let!(:invite) { create(:invite, dossier: create(:dossier), user: user) } before { get(:index) } it { expect(assigns(:current_tab)).to eq('dossiers-invites') } it { expect(assigns(:dossiers)).to match([invite.dossier]) } end context 'when the user has both' do let!(:own_dossier) { create(:dossier, user: user) } let!(:invite) { create(:invite, dossier: create(:dossier), user: user) } context 'and there is no current_tab param' do before { get(:index) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } end context 'and there is "dossiers-invites" param' do before { get(:index, params: { current_tab: 'dossiers-invites' }) } it { expect(assigns(:current_tab)).to eq('dossiers-invites') } end context 'and there is "mes-dossiers" param' do before { get(:index, params: { current_tab: 'mes-dossiers' }) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } end end describe 'sort order' do before do Timecop.freeze(4.days.ago) { create(:dossier, user: user) } Timecop.freeze(2.days.ago) { create(:dossier, user: user) } Timecop.freeze(4.days.ago) { create(:invite, dossier: create(:dossier), user: user) } Timecop.freeze(2.days.ago) { create(:invite, dossier: create(:dossier), user: user) } get(:index) end it 'displays the most recently updated dossiers first' do expect(assigns(:user_dossiers).first.updated_at.to_date).to eq(2.days.ago.to_date) expect(assigns(:user_dossiers).second.updated_at.to_date).to eq(4.days.ago.to_date) expect(assigns(:dossiers_invites).first.updated_at.to_date).to eq(2.days.ago.to_date) expect(assigns(:dossiers_invites).second.updated_at.to_date).to eq(4.days.ago.to_date) end end end describe '#show' do before do sign_in(user) end context 'with default output' do subject! { get(:show, params: { id: dossier.id }) } context 'when the dossier is a brouillon' do let(:dossier) { create(:dossier, user: user) } it { is_expected.to redirect_to(brouillon_dossier_path(dossier)) } end context 'when the dossier has been submitted' do let(:dossier) { create(:dossier, :en_construction, user: user) } it { expect(assigns(:dossier)).to eq(dossier) } it { is_expected.to render_template(:show) } end end context "with PDF output" do let(:procedure) { create(:procedure) } let(:dossier) { create(:dossier, :accepte, :with_all_champs, :with_motivation, :with_commentaires, procedure: procedure, user: user) } subject! { get(:show, params: { id: dossier.id, format: :pdf }) } context 'when the dossier is a brouillon' do let(:dossier) { create(:dossier, user: user) } it { is_expected.to redirect_to(brouillon_dossier_path(dossier)) } end context 'when the dossier has been submitted' do it { expect(assigns(:include_infos_administration)).to eq(false) } it { expect(response).to render_template 'dossiers/show' } end end end describe '#formulaire' do let(:dossier) { create(:dossier, :en_construction, user: user) } before do sign_in(user) end subject! { get(:demande, params: { id: dossier.id }) } it { expect(assigns(:dossier)).to eq(dossier) } it { is_expected.to render_template(:demande) } end describe "#create_commentaire" do let(:instructeur_with_instant_message) { create(:instructeur) } let(:instructeur_without_instant_message) { create(:instructeur) } let(:procedure) { create(:procedure, :published) } let(:dossier) { create(:dossier, :en_construction, procedure: procedure, user: user) } let(:saved_commentaire) { dossier.commentaires.first } let(:body) { "avant\napres" } let(:file) { fixture_file_upload('spec/fixtures/files/piece_justificative_0.pdf', 'application/pdf') } let(:scan_result) { true } subject { post :create_commentaire, params: { id: dossier.id, commentaire: { body: body, piece_jointe: file } } } before do sign_in(user) allow(ClamavService).to receive(:safe_file?).and_return(scan_result) allow(DossierMailer).to receive(:notify_new_commentaire_to_instructeur).and_return(double(deliver_later: nil)) instructeur_with_instant_message.follow(dossier) instructeur_without_instant_message.follow(dossier) create(:assign_to, instructeur: instructeur_with_instant_message, procedure: procedure, instant_email_message_notifications_enabled: true, groupe_instructeur: procedure.defaut_groupe_instructeur) create(:assign_to, instructeur: instructeur_without_instant_message, procedure: procedure, instant_email_message_notifications_enabled: false, groupe_instructeur: procedure.defaut_groupe_instructeur) end it "creates a commentaire" do expect { subject }.to change(Commentaire, :count).by(1) expect(response).to redirect_to(messagerie_dossier_path(dossier)) expect(DossierMailer).to have_received(:notify_new_commentaire_to_instructeur).with(dossier, instructeur_with_instant_message.email) expect(DossierMailer).not_to have_received(:notify_new_commentaire_to_instructeur).with(dossier, instructeur_without_instant_message.email) expect(flash.notice).to be_present end end describe '#ask_deletion' do before { sign_in(user) } subject { post :ask_deletion, params: { id: dossier.id } } shared_examples_for "the dossier can not be deleted" do it "doesn’t notify the deletion" do expect(DossierMailer).not_to receive(:notify_deletion_to_administration) expect(DossierMailer).not_to receive(:notify_deletion_to_user) subject end it "doesn’t delete the dossier" do subject expect(Dossier.find_by(id: dossier.id)).not_to eq(nil) expect(dossier.procedure.deleted_dossiers.count).to eq(0) end end context 'when dossier is owned by signed in user' do let(:dossier) { create(:dossier, :en_construction, user: user, autorisation_donnees: true) } it "notifies the user and the admin of the deletion" do expect(DossierMailer).to receive(:notify_deletion_to_administration).with(kind_of(DeletedDossier), dossier.procedure.administrateurs.first.email).and_return(double(deliver_later: nil)) expect(DossierMailer).to receive(:notify_deletion_to_user).with(kind_of(DeletedDossier), dossier.user.email).and_return(double(deliver_later: nil)) subject end it "deletes the dossier" do procedure = dossier.procedure dossier_id = dossier.id subject expect(Dossier.find_by(id: dossier_id)).to eq(nil) expect(procedure.deleted_dossiers.count).to eq(1) expect(procedure.deleted_dossiers.first.dossier_id).to eq(dossier_id) end it { is_expected.to redirect_to(dossiers_path) } context "and the instruction has started" do let(:dossier) { create(:dossier, :en_instruction, user: user, autorisation_donnees: true) } it_behaves_like "the dossier can not be deleted" it { is_expected.to redirect_to(dossier_path(dossier)) } end end context 'when dossier is not owned by signed in user' do let(:user2) { create(:user) } let(:dossier) { create(:dossier, user: user2, autorisation_donnees: true) } it_behaves_like "the dossier can not be deleted" it { is_expected.to redirect_to(root_path) } end end describe '#new' do let(:procedure) { create(:procedure, :published) } let(:procedure_id) { procedure.id } subject { get :new, params: { procedure_id: procedure_id } } it 'clears the stored procedure context' do subject expect(controller.stored_location_for(:user)).to be nil end context 'when params procedure_id is present' do context 'when procedure_id is valid' do context 'when user is logged in' do before do sign_in user end it { is_expected.to have_http_status(302) } it { expect { subject }.to change(Dossier, :count).by 1 } context 'when procedure is for entreprise' do it { is_expected.to redirect_to siret_dossier_path(id: Dossier.last) } end context 'when procedure is for particulier' do let(:procedure) { create(:procedure, :published, :for_individual) } it { is_expected.to redirect_to identite_dossier_path(id: Dossier.last) } end context 'when procedure is closed' do let(:procedure) { create(:procedure, :closed) } it { is_expected.to redirect_to dossiers_path } end end context 'when user is not logged' do it { is_expected.to have_http_status(302) } it { is_expected.to redirect_to new_user_session_path } end end context 'when procedure_id is not valid' do let(:procedure_id) { 0 } before do sign_in user end it { is_expected.to redirect_to dossiers_path } end context 'when procedure is not published' do let(:procedure) { create(:procedure) } before do sign_in user end it { is_expected.to redirect_to dossiers_path } context 'and brouillon param is passed' do subject { get :new, params: { procedure_id: procedure_id, brouillon: true } } it { is_expected.to have_http_status(302) } it { is_expected.to redirect_to siret_dossier_path(id: Dossier.last) } end end end end describe "#dossier_for_help" do before do sign_in(user) controller.params[:dossier_id] = dossier_id.to_s end subject { controller.dossier_for_help } context 'when the id matches an existing dossier' do let(:dossier) { create(:dossier) } let(:dossier_id) { dossier.id } it { is_expected.to eq dossier } end context 'when the id doesn’t match an existing dossier' do let(:dossier_id) { 9999999 } it { is_expected.to be nil } end context 'when the id is empty' do let(:dossier_id) { nil } it { is_expected.to be_falsy } end end end specs: refactor dossiers_controller_spec describe Users::DossiersController, type: :controller do let(:user) { create(:user) } describe 'before_actions' do it 'are present' do before_actions = Users::DossiersController ._process_action_callbacks .filter { |process_action_callbacks| process_action_callbacks.kind == :before } .map(&:filter) expect(before_actions).to include(:ensure_ownership!, :ensure_ownership_or_invitation!, :forbid_invite_submission!) end end shared_examples_for 'does not redirect nor flash' do before { @controller.send(ensure_authorized) } it { expect(@controller).not_to have_received(:redirect_to) } it { expect(flash.alert).to eq(nil) } end shared_examples_for 'redirects and flashes' do before { @controller.send(ensure_authorized) } it { expect(@controller).to have_received(:redirect_to).with(root_path) } it { expect(flash.alert).to eq("Vous n'avez pas accès à ce dossier") } end describe '#ensure_ownership!' do let(:user) { create(:user) } let(:asked_dossier) { create(:dossier) } let(:ensure_authorized) { :ensure_ownership! } before do @controller.params = @controller.params.merge(dossier_id: asked_dossier.id) expect(@controller).to receive(:current_user).and_return(user) allow(@controller).to receive(:redirect_to) end context 'when a user asks for their own dossier' do let(:asked_dossier) { create(:dossier, user: user) } it_behaves_like 'does not redirect nor flash' end context 'when a user asks for another dossier' do it_behaves_like 'redirects and flashes' end context 'when an invite asks for a dossier where they were invited' do before { create(:invite, dossier: asked_dossier, user: user) } it_behaves_like 'redirects and flashes' end context 'when an invite asks for another dossier' do before { create(:invite, dossier: create(:dossier), user: user) } it_behaves_like 'redirects and flashes' end end describe '#ensure_ownership_or_invitation!' do let(:user) { create(:user) } let(:asked_dossier) { create(:dossier) } let(:ensure_authorized) { :ensure_ownership_or_invitation! } before do @controller.params = @controller.params.merge(dossier_id: asked_dossier.id) expect(@controller).to receive(:current_user).and_return(user) allow(@controller).to receive(:redirect_to) end context 'when a user asks for their own dossier' do let(:asked_dossier) { create(:dossier, user: user) } it_behaves_like 'does not redirect nor flash' end context 'when a user asks for another dossier' do it_behaves_like 'redirects and flashes' end context 'when an invite asks for a dossier where they were invited' do before { create(:invite, dossier: asked_dossier, user: user) } it_behaves_like 'does not redirect nor flash' end context 'when an invite asks for another dossier' do before { create(:invite, dossier: create(:dossier), user: user) } it_behaves_like 'redirects and flashes' end end describe "#forbid_invite_submission!" do let(:user) { create(:user) } let(:asked_dossier) { create(:dossier) } let(:ensure_authorized) { :forbid_invite_submission! } let(:submit) { true } before do @controller.params = @controller.params.merge(dossier_id: asked_dossier.id, submit_draft: submit) allow(@controller).to receive(:current_user).and_return(user) allow(@controller).to receive(:redirect_to) end context 'when a user save their own draft' do let(:asked_dossier) { create(:dossier, user: user) } let(:submit) { false } it_behaves_like 'does not redirect nor flash' end context 'when a user submit their own dossier' do let(:asked_dossier) { create(:dossier, user: user) } let(:submit) { true } it_behaves_like 'does not redirect nor flash' end context 'when an invite save the draft for a dossier where they where invited' do before { create(:invite, dossier: asked_dossier, user: user) } let(:submit) { false } it_behaves_like 'does not redirect nor flash' end context 'when an invite submit a dossier where they where invited' do before { create(:invite, dossier: asked_dossier, user: user) } let(:submit) { true } it_behaves_like 'redirects and flashes' end end describe 'attestation' do before { sign_in(user) } context 'when a dossier has an attestation' do let(:dossier) { create(:dossier, :accepte, attestation: create(:attestation, :with_pdf), user: user) } it 'redirects to attestation pdf' do get :attestation, params: { id: dossier.id } expect(response.location).to match '/rails/active_storage/disk/' end end end describe 'update_identite' do let(:procedure) { create(:procedure, :for_individual) } let(:dossier) { create(:dossier, user: user, procedure: procedure) } subject { post :update_identite, params: { id: dossier.id, individual: individual_params } } before do sign_in(user) subject end context 'with correct individual and dossier params' do let(:individual_params) { { gender: 'M', nom: 'Mouse', prenom: 'Mickey' } } it do expect(response).to redirect_to(brouillon_dossier_path(dossier)) end end context 'when the identite cannot be updated by the user' do let(:dossier) { create(:dossier, :with_individual, :en_instruction, user: user, procedure: procedure) } let(:individual_params) { { gender: 'M', nom: 'Mouse', prenom: 'Mickey' } } it 'redirects to the dossiers list' do expect(response).to redirect_to(dossiers_path) expect(flash.alert).to eq('Votre dossier ne peut plus être modifié') end end context 'with incorrect individual and dossier params' do let(:individual_params) { { gender: '', nom: '', prenom: '' } } it do expect(response).not_to have_http_status(:redirect) expect(flash[:alert]).to include("Civilité doit être rempli", "Nom doit être rempli", "Prénom doit être rempli") end end end describe '#siret' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user) } subject { get :siret, params: { id: dossier.id } } it { is_expected.to render_template(:siret) } end describe '#update_siret' do let(:dossier) { create(:dossier, user: user) } let(:siret) { params_siret.delete(' ') } let(:siren) { siret[0..8] } let(:api_etablissement_status) { 200 } let(:api_etablissement_body) { File.read('spec/fixtures/files/api_entreprise/etablissements.json') } let(:token_expired) { false } before do sign_in(user) stub_request(:get, /https:\/\/entreprise.api.gouv.fr\/v2\/etablissements\/#{siret}?.*token=/) .to_return(status: api_etablissement_status, body: api_etablissement_body) allow_any_instance_of(ApiEntrepriseToken).to receive(:roles) .and_return(["attestations_fiscales", "attestations_sociales", "bilans_entreprise_bdf"]) allow_any_instance_of(ApiEntrepriseToken).to receive(:expired?).and_return(token_expired) end subject! { post :update_siret, params: { id: dossier.id, user: { siret: params_siret } } } shared_examples 'SIRET informations are successfully saved' do it do dossier.reload user.reload expect(dossier.etablissement).to be_present expect(dossier.autorisation_donnees).to be(true) expect(user.siret).to eq(siret) expect(response).to redirect_to(etablissement_dossier_path) end end shared_examples 'the request fails with an error' do |error| it 'doesn’t save an etablissement' do expect(dossier.reload.etablissement).to be_nil end it 'displays the SIRET that was sent by the user in the form' do expect(controller.current_user.siret).to eq(siret) end it 'renders an error' do expect(flash.alert).to eq(error) expect(response).to render_template(:siret) end end context 'with an invalid SIRET' do let(:params_siret) { '000 000' } it_behaves_like 'the request fails with an error', ['Siret Le numéro SIRET doit comporter 14 chiffres'] end context 'with a valid SIRET' do let(:params_siret) { '418 166 096 00051' } context 'When API-Entreprise is down' do let(:api_etablissement_status) { 502 } it_behaves_like 'the request fails with an error', I18n.t('errors.messages.siret_network_error') end context 'when API-Entreprise doesn’t know this SIRET' do let(:api_etablissement_status) { 404 } it_behaves_like 'the request fails with an error', I18n.t('errors.messages.siret_unknown') end context 'when default token has expired' do let(:api_etablissement_status) { 200 } let(:token_expired) { true } it_behaves_like 'the request fails with an error', I18n.t('errors.messages.siret_unknown') end context 'when all API informations available' do it_behaves_like 'SIRET informations are successfully saved' it 'saves the associated informations on the etablissement' do dossier.reload expect(dossier.etablissement.entreprise).to be_present end end end end describe '#etablissement' do let(:dossier) { create(:dossier, :with_entreprise, user: user) } before { sign_in(user) } subject { get :etablissement, params: { id: dossier.id } } it { is_expected.to render_template(:etablissement) } context 'when the dossier has no etablissement yet' do let(:dossier) { create(:dossier, user: user) } it { is_expected.to redirect_to siret_dossier_path(dossier) } end end describe '#brouillon' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user, autorisation_donnees: true) } subject { get :brouillon, params: { id: dossier.id } } context 'when autorisation_donnees is checked' do it { is_expected.to render_template(:brouillon) } end context 'when autorisation_donnees is not checked' do before { dossier.update_columns(autorisation_donnees: false) } context 'when the dossier is for personne morale' do it { is_expected.to redirect_to(siret_dossier_path(dossier)) } end context 'when the dossier is for an personne physique' do before { dossier.procedure.update(for_individual: true) } it { is_expected.to redirect_to(identite_dossier_path(dossier)) } end end end describe '#edit' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user) } it 'returns the edit page' do get :brouillon, params: { id: dossier.id } expect(response).to have_http_status(:success) end end describe '#update_brouillon' do before { sign_in(user) } let!(:dossier) { create(:dossier, user: user) } let(:first_champ) { dossier.champs.first } let(:value) { 'beautiful value' } let(:now) { Time.zone.parse('01/01/2100') } let(:submit_payload) do { id: dossier.id, dossier: { champs_attributes: { id: first_champ.id, value: value } } } end let(:payload) { submit_payload.merge(submit_draft: true) } subject do Timecop.freeze(now) do patch :update_brouillon, params: payload end end context 'when the dossier cannot be updated by the user' do let!(:dossier) { create(:dossier, :en_instruction, user: user) } it 'redirects to the dossiers list' do subject expect(response).to redirect_to(dossiers_path) expect(flash.alert).to eq('Votre dossier ne peut plus être modifié') end end context 'when dossier can be updated by the owner' do it 'updates the champs' do subject expect(response).to redirect_to(merci_dossier_path(dossier)) expect(first_champ.reload.value).to eq('beautiful value') expect(dossier.reload.updated_at.year).to eq(2100) expect(dossier.reload.state).to eq(Dossier.states.fetch(:en_construction)) end context 'with instructeurs ok to be notified instantly' do let!(:instructeur_with_instant_email_dossier) { create(:instructeur) } let!(:instructeur_without_instant_email_dossier) { create(:instructeur) } before do allow(DossierMailer).to receive(:notify_new_dossier_depose_to_instructeur).and_return(double(deliver_later: nil)) create(:assign_to, instructeur: instructeur_with_instant_email_dossier, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: true, groupe_instructeur: dossier.procedure.defaut_groupe_instructeur) create(:assign_to, instructeur: instructeur_without_instant_email_dossier, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: false, groupe_instructeur: dossier.procedure.defaut_groupe_instructeur) end it "sends notification mail to instructeurs" do subject expect(DossierMailer).to have_received(:notify_new_dossier_depose_to_instructeur).once.with(dossier, instructeur_with_instant_email_dossier.email) expect(DossierMailer).not_to have_received(:notify_new_dossier_depose_to_instructeur).with(dossier, instructeur_without_instant_email_dossier.email) end end context 'with procedure routee' do let(:procedure) { create(:procedure, :routee, :with_type_de_champ) } let(:dossier_group) { create(:groupe_instructeur, procedure: procedure) } let(:another_group) { create(:groupe_instructeur, procedure: procedure) } let(:instructeur_of_dossier) { create(:instructeur) } let(:instructeur_in_another_group) { create(:instructeur) } let!(:dossier) { create(:dossier, groupe_instructeur: dossier_group, user: user) } before do allow(DossierMailer).to receive(:notify_new_dossier_depose_to_instructeur).and_return(double(deliver_later: nil)) create(:assign_to, instructeur: instructeur_of_dossier, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: true, groupe_instructeur: dossier_group) create(:assign_to, instructeur: instructeur_in_another_group, procedure: dossier.procedure, instant_email_dossier_notifications_enabled: true, groupe_instructeur: another_group) end it "sends notification mail to instructeurs in the correct group instructeur" do subject expect(DossierMailer).to have_received(:notify_new_dossier_depose_to_instructeur).once.with(dossier, instructeur_of_dossier.email) expect(DossierMailer).not_to have_received(:notify_new_dossier_depose_to_instructeur).with(dossier, instructeur_in_another_group.email) end end context "on an closed procedure" do before { dossier.procedure.close! } it "it does not change state" do subject expect(response).not_to redirect_to(merci_dossier_path(dossier)) expect(dossier.reload.state).to eq(Dossier.states.fetch(:brouillon)) end end end it 'sends an email only on the first #update_brouillon' do delivery = double expect(delivery).to receive(:deliver_later).with(no_args) expect(NotificationMailer).to receive(:send_initiated_notification) .and_return(delivery) subject expect(NotificationMailer).not_to receive(:send_initiated_notification) subject end context 'when the update fails' do before do expect_any_instance_of(Dossier).to receive(:save).and_return(false) expect_any_instance_of(Dossier).to receive(:errors) .and_return(double(full_messages: ['nop'])) subject end it { expect(response).to render_template(:brouillon) } it { expect(flash.alert).to eq(['nop']) } it 'does not send an email' do expect(NotificationMailer).not_to receive(:send_initiated_notification) subject end end context 'when a mandatory champ is missing' do let(:value) { nil } before do first_champ.type_de_champ.update(mandatory: true, libelle: 'l') subject end it { expect(response).to render_template(:brouillon) } it { expect(flash.alert).to eq(['Le champ l doit être rempli.']) } context 'and the user saves a draft' do let(:payload) { submit_payload.except(:submit_draft) } it { expect(response).to render_template(:brouillon) } it { expect(flash.notice).to eq('Votre brouillon a bien été sauvegardé.') } it { expect(dossier.reload.state).to eq(Dossier.states.fetch(:brouillon)) } context 'and the dossier is in construction' do let!(:dossier) { create(:dossier, :en_construction, user: user) } it { expect(response).to render_template(:brouillon) } it { expect(flash.alert).to eq(['Le champ l doit être rempli.']) } end end end context 'when dossier has no champ' do let(:submit_payload) { { id: dossier.id } } it 'does not raise any errors' do subject expect(response).to redirect_to(merci_dossier_path(dossier)) end end context 'when the user has an invitation but is not the owner' do let(:dossier) { create(:dossier) } let!(:invite) { create(:invite, dossier: dossier, user: user) } context 'and the invite saves a draft' do let(:payload) { submit_payload.except(:submit_draft) } before do first_champ.type_de_champ.update(mandatory: true, libelle: 'l') subject end it { expect(response).to render_template(:brouillon) } it { expect(flash.notice).to eq('Votre brouillon a bien été sauvegardé.') } it { expect(dossier.reload.state).to eq(Dossier.states.fetch(:brouillon)) } end context 'and the invite tries to submit the dossier' do before { subject } it { expect(response).to redirect_to(root_path) } it { expect(flash.alert).to eq("Vous n'avez pas accès à ce dossier") } end end end describe '#update' do before { sign_in(user) } let(:procedure) { create(:procedure, :published, :with_type_de_champ, :with_piece_justificative) } let!(:dossier) { create(:dossier, :en_construction, user: user, procedure: procedure) } let(:first_champ) { dossier.champs.first } let(:piece_justificative_champ) { dossier.champs.last } let(:value) { 'beautiful value' } let(:file) { fixture_file_upload('spec/fixtures/files/piece_justificative_0.pdf', 'application/pdf') } let(:now) { Time.zone.parse('01/01/2100') } let(:submit_payload) do { id: dossier.id, dossier: { champs_attributes: [ { id: first_champ.id, value: value }, { id: piece_justificative_champ.id, piece_justificative_file: file } ] } } end let(:payload) { submit_payload } subject do Timecop.freeze(now) do patch :update, params: payload end end context 'when the dossier cannot be updated by the user' do let!(:dossier) { create(:dossier, :en_instruction, user: user) } it 'redirects to the dossiers list' do subject expect(response).to redirect_to(dossiers_path) expect(flash.alert).to eq('Votre dossier ne peut plus être modifié') end end context 'when dossier can be updated by the owner' do it 'updates the champs' do subject expect(first_champ.reload.value).to eq('beautiful value') expect(piece_justificative_champ.reload.piece_justificative_file).to be_attached end it 'updates the dossier modification date' do subject expect(dossier.reload.updated_at.year).to eq(2100) end it 'updates the dossier state' do subject expect(dossier.reload.state).to eq(Dossier.states.fetch(:en_construction)) end it { is_expected.to redirect_to(demande_dossier_path(dossier)) } context 'when only files champs are modified' do let(:submit_payload) do { id: dossier.id, dossier: { champs_attributes: { id: piece_justificative_champ.id, piece_justificative_file: file } } } end it 'updates the dossier modification date' do subject expect(dossier.reload.updated_at.year).to eq(2100) end end end context 'when the update fails' do before do expect_any_instance_of(Dossier).to receive(:save).and_return(false) expect_any_instance_of(Dossier).to receive(:errors) .and_return(double(full_messages: ['nop'])) subject end it { expect(response).to render_template(:modifier) } it { expect(flash.alert).to eq(['nop']) } it 'does not send an email' do expect(NotificationMailer).not_to receive(:send_initiated_notification) subject end end context 'when a mandatory champ is missing' do let(:value) { nil } before do first_champ.type_de_champ.update(mandatory: true, libelle: 'l') subject end it { expect(response).to render_template(:modifier) } it { expect(flash.alert).to eq(['Le champ l doit être rempli.']) } end context 'when dossier has no champ' do let(:submit_payload) { { id: dossier.id } } it 'does not raise any errors' do subject expect(response).to redirect_to(demande_dossier_path(dossier)) end end context 'when the user has an invitation but is not the owner' do let(:dossier) { create(:dossier) } let!(:invite) { create(:invite, dossier: dossier, user: user) } before do dossier.en_construction! subject end it { expect(first_champ.reload.value).to eq('beautiful value') } it { expect(dossier.reload.state).to eq(Dossier.states.fetch(:en_construction)) } it { expect(response).to redirect_to(demande_dossier_path(dossier)) } end end describe '#index' do before { sign_in(user) } context 'when the user does not have any dossiers' do before { get(:index) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } end context 'when the user only have its own dossiers' do let!(:own_dossier) { create(:dossier, user: user) } before { get(:index) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } it { expect(assigns(:dossiers)).to match([own_dossier]) } end context 'when the user only have some dossiers invites' do let!(:invite) { create(:invite, dossier: create(:dossier), user: user) } before { get(:index) } it { expect(assigns(:current_tab)).to eq('dossiers-invites') } it { expect(assigns(:dossiers)).to match([invite.dossier]) } end context 'when the user has both' do let!(:own_dossier) { create(:dossier, user: user) } let!(:invite) { create(:invite, dossier: create(:dossier), user: user) } context 'and there is no current_tab param' do before { get(:index) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } end context 'and there is "dossiers-invites" param' do before { get(:index, params: { current_tab: 'dossiers-invites' }) } it { expect(assigns(:current_tab)).to eq('dossiers-invites') } end context 'and there is "mes-dossiers" param' do before { get(:index, params: { current_tab: 'mes-dossiers' }) } it { expect(assigns(:current_tab)).to eq('mes-dossiers') } end end describe 'sort order' do before do Timecop.freeze(4.days.ago) { create(:dossier, user: user) } Timecop.freeze(2.days.ago) { create(:dossier, user: user) } Timecop.freeze(4.days.ago) { create(:invite, dossier: create(:dossier), user: user) } Timecop.freeze(2.days.ago) { create(:invite, dossier: create(:dossier), user: user) } get(:index) end it 'displays the most recently updated dossiers first' do expect(assigns(:user_dossiers).first.updated_at.to_date).to eq(2.days.ago.to_date) expect(assigns(:user_dossiers).second.updated_at.to_date).to eq(4.days.ago.to_date) expect(assigns(:dossiers_invites).first.updated_at.to_date).to eq(2.days.ago.to_date) expect(assigns(:dossiers_invites).second.updated_at.to_date).to eq(4.days.ago.to_date) end end end describe '#show' do before do sign_in(user) end context 'with default output' do subject! { get(:show, params: { id: dossier.id }) } context 'when the dossier is a brouillon' do let(:dossier) { create(:dossier, user: user) } it { is_expected.to redirect_to(brouillon_dossier_path(dossier)) } end context 'when the dossier has been submitted' do let(:dossier) { create(:dossier, :en_construction, user: user) } it { expect(assigns(:dossier)).to eq(dossier) } it { is_expected.to render_template(:show) } end end context "with PDF output" do let(:procedure) { create(:procedure) } let(:dossier) { create(:dossier, :accepte, :with_all_champs, :with_motivation, :with_commentaires, procedure: procedure, user: user) } subject! { get(:show, params: { id: dossier.id, format: :pdf }) } context 'when the dossier is a brouillon' do let(:dossier) { create(:dossier, user: user) } it { is_expected.to redirect_to(brouillon_dossier_path(dossier)) } end context 'when the dossier has been submitted' do it { expect(assigns(:include_infos_administration)).to eq(false) } it { expect(response).to render_template 'dossiers/show' } end end end describe '#formulaire' do let(:dossier) { create(:dossier, :en_construction, user: user) } before do sign_in(user) end subject! { get(:demande, params: { id: dossier.id }) } it { expect(assigns(:dossier)).to eq(dossier) } it { is_expected.to render_template(:demande) } end describe "#create_commentaire" do let(:instructeur_with_instant_message) { create(:instructeur) } let(:instructeur_without_instant_message) { create(:instructeur) } let(:procedure) { create(:procedure, :published) } let(:dossier) { create(:dossier, :en_construction, procedure: procedure, user: user) } let(:saved_commentaire) { dossier.commentaires.first } let(:body) { "avant\napres" } let(:file) { fixture_file_upload('spec/fixtures/files/piece_justificative_0.pdf', 'application/pdf') } let(:scan_result) { true } subject { post :create_commentaire, params: { id: dossier.id, commentaire: { body: body, piece_jointe: file } } } before do sign_in(user) allow(ClamavService).to receive(:safe_file?).and_return(scan_result) allow(DossierMailer).to receive(:notify_new_commentaire_to_instructeur).and_return(double(deliver_later: nil)) instructeur_with_instant_message.follow(dossier) instructeur_without_instant_message.follow(dossier) create(:assign_to, instructeur: instructeur_with_instant_message, procedure: procedure, instant_email_message_notifications_enabled: true, groupe_instructeur: procedure.defaut_groupe_instructeur) create(:assign_to, instructeur: instructeur_without_instant_message, procedure: procedure, instant_email_message_notifications_enabled: false, groupe_instructeur: procedure.defaut_groupe_instructeur) end it "creates a commentaire" do expect { subject }.to change(Commentaire, :count).by(1) expect(response).to redirect_to(messagerie_dossier_path(dossier)) expect(DossierMailer).to have_received(:notify_new_commentaire_to_instructeur).with(dossier, instructeur_with_instant_message.email) expect(DossierMailer).not_to have_received(:notify_new_commentaire_to_instructeur).with(dossier, instructeur_without_instant_message.email) expect(flash.notice).to be_present end end describe '#ask_deletion' do before { sign_in(user) } subject { post :ask_deletion, params: { id: dossier.id } } shared_examples_for "the dossier can not be deleted" do it "doesn’t notify the deletion" do expect(DossierMailer).not_to receive(:notify_deletion_to_administration) expect(DossierMailer).not_to receive(:notify_deletion_to_user) subject end it "doesn’t delete the dossier" do subject expect(Dossier.find_by(id: dossier.id)).not_to eq(nil) expect(dossier.procedure.deleted_dossiers.count).to eq(0) end end context 'when dossier is owned by signed in user' do let(:dossier) { create(:dossier, :en_construction, user: user, autorisation_donnees: true) } it "notifies the user and the admin of the deletion" do expect(DossierMailer).to receive(:notify_deletion_to_administration).with(kind_of(DeletedDossier), dossier.procedure.administrateurs.first.email).and_return(double(deliver_later: nil)) expect(DossierMailer).to receive(:notify_deletion_to_user).with(kind_of(DeletedDossier), dossier.user.email).and_return(double(deliver_later: nil)) subject end it "deletes the dossier" do procedure = dossier.procedure dossier_id = dossier.id subject expect(Dossier.find_by(id: dossier_id)).to eq(nil) expect(procedure.deleted_dossiers.count).to eq(1) expect(procedure.deleted_dossiers.first.dossier_id).to eq(dossier_id) end it { is_expected.to redirect_to(dossiers_path) } context "and the instruction has started" do let(:dossier) { create(:dossier, :en_instruction, user: user, autorisation_donnees: true) } it_behaves_like "the dossier can not be deleted" it { is_expected.to redirect_to(dossier_path(dossier)) } end end context 'when dossier is not owned by signed in user' do let(:user2) { create(:user) } let(:dossier) { create(:dossier, user: user2, autorisation_donnees: true) } it_behaves_like "the dossier can not be deleted" it { is_expected.to redirect_to(root_path) } end end describe '#new' do let(:procedure) { create(:procedure, :published) } let(:procedure_id) { procedure.id } subject { get :new, params: { procedure_id: procedure_id } } it 'clears the stored procedure context' do subject expect(controller.stored_location_for(:user)).to be nil end context 'when params procedure_id is present' do context 'when procedure_id is valid' do context 'when user is logged in' do before do sign_in user end it { is_expected.to have_http_status(302) } it { expect { subject }.to change(Dossier, :count).by 1 } context 'when procedure is for entreprise' do it { is_expected.to redirect_to siret_dossier_path(id: Dossier.last) } end context 'when procedure is for particulier' do let(:procedure) { create(:procedure, :published, :for_individual) } it { is_expected.to redirect_to identite_dossier_path(id: Dossier.last) } end context 'when procedure is closed' do let(:procedure) { create(:procedure, :closed) } it { is_expected.to redirect_to dossiers_path } end end context 'when user is not logged' do it { is_expected.to have_http_status(302) } it { is_expected.to redirect_to new_user_session_path } end end context 'when procedure_id is not valid' do let(:procedure_id) { 0 } before do sign_in user end it { is_expected.to redirect_to dossiers_path } end context 'when procedure is not published' do let(:procedure) { create(:procedure) } before do sign_in user end it { is_expected.to redirect_to dossiers_path } context 'and brouillon param is passed' do subject { get :new, params: { procedure_id: procedure_id, brouillon: true } } it { is_expected.to have_http_status(302) } it { is_expected.to redirect_to siret_dossier_path(id: Dossier.last) } end end end end describe "#dossier_for_help" do before do sign_in(user) controller.params[:dossier_id] = dossier_id.to_s end subject { controller.dossier_for_help } context 'when the id matches an existing dossier' do let(:dossier) { create(:dossier) } let(:dossier_id) { dossier.id } it { is_expected.to eq dossier } end context 'when the id doesn’t match an existing dossier' do let(:dossier_id) { 9999999 } it { is_expected.to be nil } end context 'when the id is empty' do let(:dossier_id) { nil } it { is_expected.to be_falsy } end end end
#!/usr/bin/env ruby # Unofficial Pitchfork API for the Ruby language. # Ported from Python Pitchfork API: (https://github.com/michalczaplinski/pitchfork) # Author: Christopher Selden # Email: cbpselden@gmail.com # require 'nokogiri' # require 'nokogiri-styles' # def replace_breaks(html) # # Replaces all the <br> tags in the html with newlines '\n' # breakline.styles = html['br'] # while html['br'] != nil # breakline = ['\n'] # html.br.decompose() # breakline.styles = html['br'] # return html # end class Review # # Class representing the fetched review. # # Includes methods for getting the score, the text of the review # # (editorial), the album cover, label, year as well as the true # # (matched) album and artist names. def initialize(blob) # def initialize(searched_artist, searched_album, matched_artist, # matched_album, query, url, blob) # @searched_artist = searched_artist # @searched_album = searched_album # @matched_artist = matched_artist # @matched_album = matched_album # @query = query # @url = url @blob = blob end def score # Returns the album score. # rating = @blob.xpath(@class='score') # puts rating # rating = rating[0].to_f # return rating end # def self.editorial # # Returns the text of the review. # review_html = @blob.find(class_='editorial') # review_html = replace_breaks(review_html).find_all('p') # review_text = '' # for paragraph in review_html # review_text += paragraph.text + '\n\n' # return review_text # end # def self.cover # # Returns the link to the album cover on the Pitchfork review page. # artwork = @blob.find(class_='artwork') # image_link = artwork.img['src'].strip # return image_link # end # def self.artist # # Returns the artist name that Pitchfork matched to our search. # artist = @matched_artist.strip # return artist # end # def album # # Returns the album name that Pitchfork matched to our search. # album = @matched_album.strip # return album # end # def label # # Returns the name of the record label that released the album. # label = @soup.find(class_='info').h3.get_text # label = label[:label.index(';')].strip # return label # end end require "json" require "httparty" require "nokogiri" def search(artist, album) query = (artist + "%20" + album) query = query.gsub!(" ", "%20") request = HTTParty.get("http://pitchfork.com/search/ac/?query=" + query, headers: {"User-Agent" => "chrisseldo/pitchfork-ruby-v0.1"}) responses = JSON.parse(request.body) begin response = responses.collect {|x| x if x["label"] == "Reviews"} review_hash = response[1]['objects'][0] rescue puts "Found no reviews for this artist/album!" end url = review_hash["url"] matched_artist = review_hash["name"].split(' - ')[0] full_url = 'http://pitchfork.com/' + url request = HTTParty.get(full_url, headers: {"User-Agent" => "chrisseldo/pitchfork-ruby-v0.1"}) response = request.body puts response blob = Nokogiri::HTML(response) do |config| config.noerror end if blob.css('review-multi').empty? matched_album = review_hash['name'].split(' - ')[1] # puts blob a = Review.new(blob) # puts a # puts a.score else # puts blob.css('review-multi') end end Now, to work with Nokogiri :( #!/usr/bin/env ruby # Unofficial Pitchfork API for the Ruby language. # Ported from Python Pitchfork API: (https://github.com/michalczaplinski/pitchfork) # Author: Christopher Selden # Email: cbpselden@gmail.com require "nokogiri" # require 'nokogiri-styles' require "json" require "httparty" require "uri" # def replace_breaks(html) # # Replaces all the <br> tags in the html with newlines '\n' # breakline.styles = html['br'] # while html['br'] != nil # breakline = ['\n'] # html.br.decompose() # breakline.styles = html['br'] # return html # end class Review # # Class representing the fetched review. # # Includes methods for getting the score, the text of the review # # (editorial), the album cover, label, year as well as the true # # (matched) album and artist names. def initialize(blob) # def initialize(searched_artist, searched_album, matched_artist, # matched_album, query, url, blob) # @searched_artist = searched_artist # @searched_album = searched_album # @matched_artist = matched_artist # @matched_album = matched_album # @query = query # @url = url @blob = blob end def score # Returns the album score. # rating = @blob.xpath(@class='score') # puts rating # rating = rating[0].to_f # return rating end # def self.editorial # # Returns the text of the review. # review_html = @blob.find(class_='editorial') # review_html = replace_breaks(review_html).find_all('p') # review_text = '' # for paragraph in review_html # review_text += paragraph.text + '\n\n' # return review_text # end # def self.cover # # Returns the link to the album cover on the Pitchfork review page. # artwork = @blob.find(class_='artwork') # image_link = artwork.img['src'].strip # return image_link # end # def self.artist # # Returns the artist name that Pitchfork matched to our search. # artist = @matched_artist.strip # return artist # end # def album # # Returns the album name that Pitchfork matched to our search. # album = @matched_album.strip # return album # end # def label # # Returns the name of the record label that released the album. # label = @soup.find(class_='info').h3.get_text # label = label[:label.index(';')].strip # return label # end end def search(artist, album) # subbing spaces with '%20' query = (artist + "%20" + album) query = query.gsub(" ", "%20") # making request to Pitchfork API request = HTTParty.get("http://pitchfork.com/search/ac/?query=" + query, headers: {"User-Agent" => "chrisseldo/pitchfork-ruby-v0.1"}) responses = JSON.parse(request.body) begin # creating array of reviews if there exists review(s) response = responses.collect {|x| x if x["label"] == "Reviews"} review_hash = response[1]['objects'][0] rescue puts "Found no reviews for this artist/album!" end url = review_hash["url"] matched_artist = review_hash["name"].split(' - ')[0] full_url = URI::join('http://pitchfork.com', url) request = HTTParty.get(full_url, headers: {"User-Agent" => "chrisseldo/pitchfork-ruby-v0.1"}) response = request.body blob = Nokogiri::HTML(response) do |config| config.noerror end if blob.css('review-multi').empty? matched_album = review_hash['name'].split(' - ')[1] a = Review.new(blob) else puts blob end end
Add tests for example settings and example APIv1 catalog builder # frozen_string_literal: true require_relative '../tests/spec_helper' require 'open3' require 'stringio' describe 'examples/octocatalog-diff.cfg.rb' do let(:script) { File.expand_path('../../../examples/octocatalog-diff.cfg.rb', File.dirname(__FILE__)) } let(:ls_l) { Open3.capture2e("ls -l '#{script}'").first } it 'should exist' do expect(File.file?(script)).to eq(true), ls_l end it 'should not raise errors when loaded' do load script end it 'should create OctocatalogDiff::Config namespace and .config method' do k = Kernel.const_get('OctocatalogDiff::Config') expect(k.to_s).to eq('OctocatalogDiff::Config') end it 'should return a hash from the .config method' do result = OctocatalogDiff::Config.config expect(result).to be_a_kind_of(Hash) end end describe 'examples/api/v1/catalog-builder-local-files.rb' do let(:script) { File.expand_path('../../../examples/api/v1/catalog-builder-local-files.rb', File.dirname(__FILE__)) } let(:ls_l) { Open3.capture2e("ls -l '#{script}'").first } it 'should exist' do expect(File.file?(script)).to eq(true), ls_l end context 'executing' do before(:each) do @stdout_obj = StringIO.new @old_stdout = $stdout $stdout = @stdout_obj end after(:each) do $stdout = @old_stdout end it 'should compile and run' do load script output = @stdout_obj.string.split("\n") expect(output).to include('Object returned from OctocatalogDiff::API::V1.catalog is: OctocatalogDiff::API::V1::Catalog') expect(output).to include('The catalog is valid.') expect(output).to include('The catalog was built using OctocatalogDiff::Catalog::Computed') expect(output).to include('- System::User - bob') expect(output).to include('The resources are equal!') end end end
# encoding: utf-8 require_relative '../../../spec_helper' require_relative '../../api/json/imports_controller_shared_examples' require_relative '../../../../app/controllers/carto/api/imports_controller' require 'helpers/unique_names_helper' describe Carto::Api::ImportsController do include UniqueNamesHelper it_behaves_like 'imports controllers' do end @headers = { 'CONTENT_TYPE' => 'application/json' } before(:all) do @user = FactoryGirl.create(:valid_user) host! "#{@user.username}.localhost.lan" end after(:all) do @user.destroy end before(:each) do bypass_named_maps delete_user_data @user end let(:params) { { api_key: @user.api_key } } it 'gets a list of all pending imports' do Resque.inline = false serve_file(Rails.root.join('spec/support/data/ESP_adm.zip')) do |url| post api_v1_imports_create_url, params.merge(url: url, table_name: 'wadus') end get api_v1_imports_index_url, params response.code.should be == '200' response_json = JSON.parse(response.body) response_json.should_not be_nil imports = response_json['imports'] imports.should have(1).items Resque.inline = true end it "doesn't return old pending imports" do Resque.inline = false serve_file(Rails.root.join('spec/support/data/ESP_adm.zip')) do |url| post api_v1_imports_create_url, params.merge(url: url, table_name: 'wadus') end Delorean.jump(7.hours) get api_v1_imports_index_url, params response.code.should be == '200' response_json = JSON.parse(response.body) response_json.should_not be_nil imports = response_json['imports'] imports.should have(0).items Resque.inline = true Delorean.back_to_the_present end it 'gets the detail of an import' do post api_v1_imports_create_url(api_key: @user.api_key, table_name: 'wadus'), filename: upload_file('db/fake_data/column_number_to_boolean.csv', 'text/csv') item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'complete' import['display_name'].should be == 'column_number_to_boolean.csv' end it 'gets the detail of an import stuck unpacking' do post api_v1_imports_create_url(api_key: @user.api_key, table_name: 'wadus'), filename: upload_file('db/fake_data/column_number_to_boolean.csv', 'text/csv') response_json = JSON.parse(response.body) last_import = DataImport[response_json['item_queue_id']] last_import.state = DataImport::STATE_UNPACKING last_import.created_at -= 5.years last_import.save get api_v1_imports_show_url(:id => last_import.id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'stuck' end it 'tries to import a tgz' do post api_v1_imports_create_url, params.merge(filename: upload_file('spec/support/data/Weird Filename (2).tgz', 'application/octet-stream')) item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'complete' import['display_name'].should be == 'Weird_Filename_(2).tgz' end it 'fails with password protected files' do post api_v1_imports_create_url, params.merge(filename: upload_file('spec/support/data/alldata-pass.zip', 'application/octet-stream')) item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'failure' end it 'imports files with weird filenames' do post api_v1_imports_create_url, params.merge(filename: upload_file('spec/support/data/Weird Filename (2).csv', 'application/octet-stream')) item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'complete' end it 'creates a table from a sql query' do post api_v1_imports_create_url(params.merge(table_name: 'wadus_2')), filename: upload_file('spec/support/data/_penguins_below_80.zip', 'application/octet-stream') response.code.should be == '200' @table_from_import = UserTable.all.last.service post api_v1_imports_create_url(:api_key => @user.api_key, table_name: 'wadus_2', :sql => "SELECT * FROM #{@table_from_import.name}") response.code.should be == '200' response_json = JSON.parse(response.body) last_import = DataImport[response_json['item_queue_id']] last_import.state.should be == 'complete' import_table = UserTable.all.last.service import_table.rows_counted.should be == @table_from_import.rows_counted import_table.should have_required_indexes_and_triggers end it 'returns derived visualization id if created with create_vis flag' do @user.update private_tables_enabled: false post api_v1_imports_create_url, params.merge({filename: upload_file('spec/support/data/csv_with_lat_lon.csv', 'application/octet-stream'), create_vis: true}) response.code.should be == '200' item_queue_id = ::JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(id: item_queue_id), params import = DataImport[item_queue_id] import.state.should be == 'complete' import.visualization_id.nil?.should eq false import.create_visualization.should eq true vis = CartoDB::Visualization::Member.new(id: import.visualization_id).fetch vis.nil?.should eq false vis.name =~ /csv_with_lat_lon/ # just in case we change the prefix @user.update private_tables_enabled: true end describe 'service_token_valid?' do it 'returns oauth_valid false for unknown service tokens' do get api_v1_imports_service_token_valid_url(id: 'kk'), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['oauth_valid'].should == false response_json['success'].should == true end it 'returns 400 for known service token without known service datasource' do synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'kk-s', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns 400 for known service token for a service datasource which is not BaseOAuth' do synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'arcgis', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns oauth_valid false for not valid tokens and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:token_valid?).returns(false) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['oauth_valid'].should == false response_json['success'].should == true SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end it 'returns 401 for expired tokens on assignment and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:token=).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params, @headers response.code.should == '401' SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end it 'returns 401 for expired tokens on validation and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:token_valid?).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params, @headers response.code.should == '401' SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end end describe 'list_files_for_service' do def fake_item_data(datasource_name = 'fake_datasource') id = unique_integer { id: id, title: "title_#{id}", filename: "filename_#{id}", service: datasource_name, checksum: id, size: rand(50) } end def fake_resource_list(datasource_name = 'fake_datasource') [ fake_item_data(datasource_name), fake_item_data(datasource_name) ] end it 'returns datasource resources list for known, valid tokens' do service = 'mailchimp' fake_files = fake_resource_list(service) CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_resources_list).returns(fake_files) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_list_files_url(id: service), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == true response_json['files'].map(&:symbolize_keys).should == fake_files synchronization_oauth.destroy end it 'returns 401 for expired tokens on resource listing and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_resources_list).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_list_files_url(id: 'mailchimp'), params response.code.should == '401' SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end end describe 'auth_url' do it 'returns 400 for existing tokens services' do service = 'mailchimp' synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_auth_url_url(id: service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns auth url for known, valid tokens' do service = 'mailchimp' fake_url = 'http://www.fakeurl.com' CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_auth_url).returns(fake_url) get api_v1_imports_service_auth_url_url(id: service), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == true response_json['url'].should == fake_url end it 'returns 401 for expired tokens on url and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_auth_url).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) get api_v1_imports_service_auth_url_url(id: 'mailchimp'), params response.code.should == '401' # INFO: this can never happen with the current implementation of get_service_auth_url, since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end end describe 'validate_service_oauth_code' do it 'returns 400 for existing tokens services' do service = 'mailchimp' synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_validate_code_url(id: service, code: 'kk'), params response.code.should == '400' synchronization_oauth.destroy end it 'returns 400 if it does not find datasource' do CartoDB::Datasources::DatasourcesFactory.stubs(:get_datasource).returns(nil) get api_v1_imports_service_validate_code_url(id: 'kk', code: 'kk'), params response.code.should == '400' end it 'returns 401 for expired tokens on url and deletes them' do CartoDB::Datasources::DatasourcesFactory.stubs(:get_datasource).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '401' # INFO: this can never happen with the current implementation since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns not success 200 and does not store oauth for not valid codes' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_auth_code).raises(CartoDB::Datasources::AuthError.new) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == false SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns 400 if validation fails catastrophically' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_auth_code).raises(StandardError.new) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '400' # INFO: this can never happen with the current implementation since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns success 200 and stores oauth for valid codes' do token = 'kk' CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_auth_code).returns(token) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == true synchronization_oauth = SynchronizationOauth.where(service: 'mailchimp').first synchronization_oauth.token.should eq token synchronization_oauth.user_id.should eq @user.id synchronization_oauth.destroy end end describe 'service_oauth_callback' do it 'returns 400 for existing tokens services' do service = 'mailchimp' synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_oauth_callback_url(id: service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns 401 for expired tokens and deletes them' do CartoDB::Datasources::DatasourcesFactory.stubs(:get_datasource).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) get api_v1_imports_service_oauth_callback_url(id: 'mailchimp'), params response.code.should == '401' # INFO: this can never happen with the current implementation since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns success 200 and stores oauth for valid params' do token = 'kk' CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_callback).returns(token) get api_v1_imports_service_oauth_callback_url(id: 'mailchimp'), params response.code.should == '200' response.body.should == '<script>window.close();</script>' synchronization_oauth = SynchronizationOauth.where(service: 'mailchimp').first synchronization_oauth.token.should eq token synchronization_oauth.user_id.should eq @user.id synchronization_oauth.destroy end end end fix tests # encoding: utf-8 require_relative '../../../spec_helper' require_relative '../../api/json/imports_controller_shared_examples' require_relative '../../../../app/controllers/carto/api/imports_controller' require 'helpers/unique_names_helper' describe Carto::Api::ImportsController do include UniqueNamesHelper it_behaves_like 'imports controllers' do end @headers = { 'CONTENT_TYPE' => 'application/json' } before(:all) do @user = FactoryGirl.create(:valid_user) host! "#{@user.username}.localhost.lan" end after(:all) do @user.destroy end before(:each) do bypass_named_maps delete_user_data @user end let(:params) { { api_key: @user.api_key } } it 'gets a list of all pending imports' do Resque.inline = false serve_file(Rails.root.join('spec/support/data/ESP_adm.zip')) do |url| post api_v1_imports_create_url, params.merge(url: url, table_name: 'wadus') end get api_v1_imports_index_url, params response.code.should be == '200' response_json = JSON.parse(response.body) response_json.should_not be_nil imports = response_json['imports'] imports.should have(1).items Resque.inline = true end it "doesn't return old pending imports" do Resque.inline = false serve_file(Rails.root.join('spec/support/data/ESP_adm.zip')) do |url| post api_v1_imports_create_url, params.merge(url: url, table_name: 'wadus') end Delorean.jump(7.hours) get api_v1_imports_index_url, params response.code.should be == '200' response_json = JSON.parse(response.body) response_json.should_not be_nil imports = response_json['imports'] imports.should have(0).items Resque.inline = true Delorean.back_to_the_present end it 'gets the detail of an import' do post api_v1_imports_create_url(api_key: @user.api_key, table_name: 'wadus'), filename: upload_file('db/fake_data/column_number_to_boolean.csv', 'text/csv') item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'complete' import['display_name'].should be == 'column_number_to_boolean.csv' end it 'gets the detail of an import stuck unpacking' do post api_v1_imports_create_url(api_key: @user.api_key, table_name: 'wadus'), filename: upload_file('db/fake_data/column_number_to_boolean.csv', 'text/csv') response_json = JSON.parse(response.body) last_import = DataImport[response_json['item_queue_id']] last_import.state = DataImport::STATE_UNPACKING last_import.created_at -= 5.years last_import.save get api_v1_imports_show_url(:id => last_import.id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'failure' import['error_code'].should be 6671 end it 'tries to import a tgz' do post api_v1_imports_create_url, params.merge(filename: upload_file('spec/support/data/Weird Filename (2).tgz', 'application/octet-stream')) item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'complete' import['display_name'].should be == 'Weird_Filename_(2).tgz' end it 'fails with password protected files' do post api_v1_imports_create_url, params.merge(filename: upload_file('spec/support/data/alldata-pass.zip', 'application/octet-stream')) item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'failure' end it 'imports files with weird filenames' do post api_v1_imports_create_url, params.merge(filename: upload_file('spec/support/data/Weird Filename (2).csv', 'application/octet-stream')) item_queue_id = JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(:id => item_queue_id), params response.code.should be == '200' import = JSON.parse(response.body) import['state'].should be == 'complete' end it 'creates a table from a sql query' do post api_v1_imports_create_url(params.merge(table_name: 'wadus_2')), filename: upload_file('spec/support/data/_penguins_below_80.zip', 'application/octet-stream') response.code.should be == '200' @table_from_import = UserTable.all.last.service post api_v1_imports_create_url(:api_key => @user.api_key, table_name: 'wadus_2', :sql => "SELECT * FROM #{@table_from_import.name}") response.code.should be == '200' response_json = JSON.parse(response.body) last_import = DataImport[response_json['item_queue_id']] last_import.state.should be == 'complete' import_table = UserTable.all.last.service import_table.rows_counted.should be == @table_from_import.rows_counted import_table.should have_required_indexes_and_triggers end it 'returns derived visualization id if created with create_vis flag' do @user.update private_tables_enabled: false post api_v1_imports_create_url, params.merge({filename: upload_file('spec/support/data/csv_with_lat_lon.csv', 'application/octet-stream'), create_vis: true}) response.code.should be == '200' item_queue_id = ::JSON.parse(response.body)['item_queue_id'] get api_v1_imports_show_url(id: item_queue_id), params import = DataImport[item_queue_id] import.state.should be == 'complete' import.visualization_id.nil?.should eq false import.create_visualization.should eq true vis = CartoDB::Visualization::Member.new(id: import.visualization_id).fetch vis.nil?.should eq false vis.name =~ /csv_with_lat_lon/ # just in case we change the prefix @user.update private_tables_enabled: true end describe 'service_token_valid?' do it 'returns oauth_valid false for unknown service tokens' do get api_v1_imports_service_token_valid_url(id: 'kk'), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['oauth_valid'].should == false response_json['success'].should == true end it 'returns 400 for known service token without known service datasource' do synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'kk-s', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns 400 for known service token for a service datasource which is not BaseOAuth' do synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'arcgis', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns oauth_valid false for not valid tokens and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:token_valid?).returns(false) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['oauth_valid'].should == false response_json['success'].should == true SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end it 'returns 401 for expired tokens on assignment and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:token=).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params, @headers response.code.should == '401' SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end it 'returns 401 for expired tokens on validation and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:token_valid?).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_token_valid_url(id: synchronization_oauth.service), params, @headers response.code.should == '401' SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end end describe 'list_files_for_service' do def fake_item_data(datasource_name = 'fake_datasource') id = unique_integer { id: id, title: "title_#{id}", filename: "filename_#{id}", service: datasource_name, checksum: id, size: rand(50) } end def fake_resource_list(datasource_name = 'fake_datasource') [ fake_item_data(datasource_name), fake_item_data(datasource_name) ] end it 'returns datasource resources list for known, valid tokens' do service = 'mailchimp' fake_files = fake_resource_list(service) CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_resources_list).returns(fake_files) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_list_files_url(id: service), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == true response_json['files'].map(&:symbolize_keys).should == fake_files synchronization_oauth.destroy end it 'returns 401 for expired tokens on resource listing and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_resources_list).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: 'mailchimp', token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_list_files_url(id: 'mailchimp'), params response.code.should == '401' SynchronizationOauth.where(id: synchronization_oauth.id).first.should eq nil synchronization_oauth.destroy end end describe 'auth_url' do it 'returns 400 for existing tokens services' do service = 'mailchimp' synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_auth_url_url(id: service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns auth url for known, valid tokens' do service = 'mailchimp' fake_url = 'http://www.fakeurl.com' CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_auth_url).returns(fake_url) get api_v1_imports_service_auth_url_url(id: service), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == true response_json['url'].should == fake_url end it 'returns 401 for expired tokens on url and deletes them' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:get_auth_url).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) get api_v1_imports_service_auth_url_url(id: 'mailchimp'), params response.code.should == '401' # INFO: this can never happen with the current implementation of get_service_auth_url, since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end end describe 'validate_service_oauth_code' do it 'returns 400 for existing tokens services' do service = 'mailchimp' synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_validate_code_url(id: service, code: 'kk'), params response.code.should == '400' synchronization_oauth.destroy end it 'returns 400 if it does not find datasource' do CartoDB::Datasources::DatasourcesFactory.stubs(:get_datasource).returns(nil) get api_v1_imports_service_validate_code_url(id: 'kk', code: 'kk'), params response.code.should == '400' end it 'returns 401 for expired tokens on url and deletes them' do CartoDB::Datasources::DatasourcesFactory.stubs(:get_datasource).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '401' # INFO: this can never happen with the current implementation since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns not success 200 and does not store oauth for not valid codes' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_auth_code).raises(CartoDB::Datasources::AuthError.new) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == false SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns 400 if validation fails catastrophically' do CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_auth_code).raises(StandardError.new) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '400' # INFO: this can never happen with the current implementation since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns success 200 and stores oauth for valid codes' do token = 'kk' CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_auth_code).returns(token) get api_v1_imports_service_validate_code_url(id: 'mailchimp', code: 'kk'), params response.code.should == '200' response_json = JSON.parse(response.body) response_json['success'].should == true synchronization_oauth = SynchronizationOauth.where(service: 'mailchimp').first synchronization_oauth.token.should eq token synchronization_oauth.user_id.should eq @user.id synchronization_oauth.destroy end end describe 'service_oauth_callback' do it 'returns 400 for existing tokens services' do service = 'mailchimp' synchronization_oauth = Carto::SynchronizationOauth.new(user_id: @user.id, service: service, token: 'kk-t') synchronization_oauth.save get api_v1_imports_service_oauth_callback_url(id: service), params response.code.should == '400' synchronization_oauth.destroy end it 'returns 401 for expired tokens and deletes them' do CartoDB::Datasources::DatasourcesFactory.stubs(:get_datasource).raises(CartoDB::Datasources::TokenExpiredOrInvalidError.new('kk', 'mailchimp')) get api_v1_imports_service_oauth_callback_url(id: 'mailchimp'), params response.code.should == '401' # INFO: this can never happen with the current implementation since it first checks there's no previous SynchronizationOauth SynchronizationOauth.where(service: 'mailchimp').first.should eq nil end it 'returns success 200 and stores oauth for valid params' do token = 'kk' CartoDB::Datasources::Url::MailChimp.any_instance.stubs(:validate_callback).returns(token) get api_v1_imports_service_oauth_callback_url(id: 'mailchimp'), params response.code.should == '200' response.body.should == '<script>window.close();</script>' synchronization_oauth = SynchronizationOauth.where(service: 'mailchimp').first synchronization_oauth.token.should eq token synchronization_oauth.user_id.should eq @user.id synchronization_oauth.destroy end end end
require 'spec_helper_min' require 'support/helpers' require 'factories/carto_visualizations' require_dependency 'carto/uuidhelper' describe Carto::Api::AnalysesController do include Carto::Factories::Visualizations include HelperMethods before(:all) do FactoryGirl.create(:carto_feature_flag, name: 'editor-3', restricted: false) @user = FactoryGirl.create(:carto_user) @intruder = FactoryGirl.create(:carto_user) _, _, _, @visualization = create_full_visualization(@user) end before(:each) { bypass_named_maps } after(:all) do Carto::FeatureFlag.destroy_all @visualization.destroy @user.destroy @intruder.destroy end def mapcap_should_be_correct(response) response_body = response.body new_mapcap_id = response_body[:id] new_mapcap_id.should_not be_nil mapcap = Carto::Mapcap.find(new_mapcap_id) expected_response = JSON.load(Carto::Api::MapcapPresenter.new(mapcap).to_poro.to_json).deep_symbolize_keys response_body.should eq expected_response end describe '#create' do after(:all) { Carto::Mapcap.all.each(&:destroy) } def create_mapcap_url(user: @user, visualization: @visualization) mapcaps_url(user_domain: user.subdomain, visualization_id: visualization.id, api_key: user.api_key) end it 'creates new mapcap' do post_json create_mapcap_url, {} do |response| response.status.should eq 201 mapcap_should_be_correct(response) end end it 'returns 403 if user does not own the visualization' do post_json create_mapcap_url(user: @intruder), {} do |response| response.status.should eq 403 end end end describe '#show' do before (:all) { @mapcap = Carto::Mapcap.create(visualization_id: @visualization.id) } after (:all) { @mapcap.destroy } def show_mapcap_url(user: @user, visualization: @visualization, mapcap: @mapcap) mapcap_url( user_domain: user.subdomain, visualization_id: visualization.id, id: mapcap.id, api_key: user.api_key ) end it 'shows a mapcap' do get show_mapcap_url, {} do |response| response.status.should eq 200 mapcap_should_be_correct(response) end end it 'returns 404 for an inexistent mapcap' do get show_mapcap_url, mapcap: Carto::Mapcap.new do |response| response.status.should eq 404 end end it 'returns 403 if user does not own the visualization' do get show_mapcap_url(user: @intruder), {} do |response| response.status.should eq 403 response.body.should be_empty end end end # describe '#show' do # it 'returns 403 if user does not own the visualization' do # get_json mapcap(@user2, @visualization, @analysis.id) do |response| # response.status.should eq 403 # end # end # def verify_analysis_response_body(response_body, analysis) # response_body[:id].should eq analysis.id # analysis_definition = response_body[:analysis_definition] # analysis_definition.deep_symbolize_keys.should eq analysis.analysis_definition.deep_symbolize_keys # analysis_definition[:id].should eq analysis.natural_id # end # it 'returns existing analysis by uuid' do # get_json viz_analysis_url(@user, @visualization, @analysis.id) do |response| # response.status.should eq 200 # verify_analysis_response_body(response[:body], @analysis) # end # end # it 'returns 404 for nonexisting analysis' do # get_json viz_analysis_url(@user, @visualization, 'wadus') do |response| # response.status.should eq 404 # end # end # it 'returns existing analysis by json first id' do # get_json viz_analysis_url(@user, @visualization, @analysis.natural_id) do |response| # response.status.should eq 200 # verify_analysis_response_body(response[:body], @analysis) # end # end # it 'returns existing analysis by json first id with uuid ids' do # bypass_named_maps # analysis2 = FactoryGirl.create( # :source_analysis, # visualization_id: @visualization.id, # user_id: @user.id, # analysis_definition: { id: UUIDTools::UUID.random_create.to_s } # ) # get_json viz_analysis_url(@user, @visualization, analysis2.natural_id) do |response| # response.status.should eq 200 # verify_analysis_response_body(response[:body], analysis2) # end # analysis2.destroy # end # end # describe '#update' do # let(:new_natural_id) { "#{natural_id}_2" } # let(:new_key) { :whatever } # let(:new_payload) do # payload.delete(:id) # payload.merge(whatever: 'really?') # payload[:analysis_definition][:id] = new_natural_id # payload[:analysis_definition][new_key] = 'really' # payload # end # it 'updates existing analysis' do # @analysis.reload # @analysis.analysis_definition[:id].should_not eq new_payload[:analysis_definition][:id] # @analysis.analysis_definition[new_key].should be_nil # bypass_named_maps # put_json viz_analysis_url(@user, @visualization, @analysis), new_payload do |response| # response.status.should eq 200 # response.body[:analysis_definition].symbolize_keys.should eq new_payload[:analysis_definition] # a = Carto::Analysis.find(@analysis.id) # a.analysis_definition[:id].should eq new_payload[:analysis_definition][:id] # a.analysis_definition[new_key].should eq new_payload[:analysis_definition][new_key] # a.analysis_definition.deep_symbolize_keys.should eq new_payload[:analysis_definition].deep_symbolize_keys # end # end # it 'returns 422 if payload visualization_id or id do not match' do # put_json viz_analysis_url(@user, @visualization, @analysis), # new_payload.merge(visualization_id: 'x') do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), new_payload.merge(id: 'x') do |response| # response.status.should eq 422 # end # end # it 'returns 403 if user does not own the visualization' do # put_json viz_analysis_url(@user2, @visualization, @analysis), new_payload do |response| # response.status.should eq 403 # end # end # it 'returns 422 if payload is not valid json' do # put_json viz_analysis_url(@user, @visualization, @analysis), nil do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), "" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), "wadus" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), "wadus: 1" do |response| # response.status.should eq 422 # end # end # it 'returns 422 if payload is empty json' do # put_json viz_analysis_url(@user, @visualization, @analysis), {} do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), [] do |response| # response.status.should eq 422 # end # end # it 'returns 422 if analysis definition is not valid json' do # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: nil do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: "" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: "wadus" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: "wadus: 1" do |response| # response.status.should eq 422 # end # end # it 'returns 422 if analysis_definition is empty json' do # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: {} do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: [] do |response| # response.status.should eq 422 # end # end # end # describe '#destroy' do # it 'destroys existing analysis' do # bypass_named_maps # delete_json viz_analysis_url(@user, @visualization, @analysis) do |response| # response.status.should eq 200 # Carto::Analysis.where(id: @analysis.id).first.should be_nil # end # end # it 'returns 403 if user does not own the visualization' do # delete_json viz_analysis_url(@user2, @visualization, @analysis) do |response| # response.status.should eq 403 # end # end # end end add test for destroy require 'spec_helper_min' require 'support/helpers' require 'factories/carto_visualizations' require_dependency 'carto/uuidhelper' describe Carto::Api::MapcapsController do include Carto::Factories::Visualizations include HelperMethods before(:all) do FactoryGirl.create(:carto_feature_flag, name: 'editor-3', restricted: false) @user = FactoryGirl.create(:carto_user) @intruder = FactoryGirl.create(:carto_user) _, _, _, @visualization = create_full_visualization(@user) end before(:each) { bypass_named_maps } after(:all) do Carto::FeatureFlag.destroy_all @visualization.destroy @user.destroy @intruder.destroy end def mapcap_should_be_correct(response) response_body = response.body new_mapcap_id = response_body[:id] new_mapcap_id.should_not be_nil mapcap = Carto::Mapcap.find(new_mapcap_id) expected_response = JSON.load(Carto::Api::MapcapPresenter.new(mapcap).to_poro.to_json).deep_symbolize_keys response_body.should eq expected_response end describe '#create' do after(:all) { Carto::Mapcap.all.each(&:destroy) } def create_mapcap_url(user: @user, visualization: @visualization) mapcaps_url(user_domain: user.subdomain, visualization_id: visualization.id, api_key: user.api_key) end it 'creates new mapcap' do post_json create_mapcap_url, {} do |response| response.status.should eq 201 mapcap_should_be_correct(response) end end it 'returns 403 if user does not own the visualization' do post_json create_mapcap_url(user: @intruder), {} do |response| response.status.should eq 403 end end end describe '#show' do before (:all) { @mapcap = Carto::Mapcap.create(visualization_id: @visualization.id) } after (:all) { @mapcap.destroy } def show_mapcap_url(user: @user, visualization: @visualization, mapcap: @mapcap) mapcap_url( user_domain: user.subdomain, visualization_id: visualization.id, id: mapcap.id, api_key: user.api_key ) end it 'shows a mapcap' do get show_mapcap_url, {} do |response| response.status.should eq 200 mapcap_should_be_correct(response) end end it 'returns 404 for an inexistent mapcap' do get show_mapcap_url(mapcap: Carto::Mapcap.new) do |response| response.status.should eq 404 end end it 'returns 403 if user does not own the visualization' do get show_mapcap_url(user: @intruder), {} do |response| response.status.should eq 403 response.body.should be_empty end end end describe '#destroy' do before (:each) { @mapcap = Carto::Mapcap.create(visualization_id: @visualization.id) } after (:each) { @mapcap.destroy if @mapcap } def destroy_mapcap_url(user: @user, visualization: @visualization, mapcap: @mapcap) mapcap_url( user_domain: user.subdomain, visualization_id: visualization.id, id: mapcap.id, api_key: user.api_key ) end it 'destroy a mapcap' do get destroy_mapcap_url, {} do |response| response.status.should eq 200 Carto::Mapcap.exists?(response.body[:id]).should_not be_true end end it 'returns 404 for an inexistent mapcap' do get destroy_mapcap_url(mapcap: Carto::Mapcap.new) do |response| response.status.should eq 404 end end it 'returns 403 if user does not own the visualization' do get destroy_mapcap_url(user: @intruder), {} do |response| response.status.should eq 403 response.body.should be_empty end end end # describe '#show' do # it 'returns 403 if user does not own the visualization' do # get_json mapcap(@user2, @visualization, @analysis.id) do |response| # response.status.should eq 403 # end # end # def verify_analysis_response_body(response_body, analysis) # response_body[:id].should eq analysis.id # analysis_definition = response_body[:analysis_definition] # analysis_definition.deep_symbolize_keys.should eq analysis.analysis_definition.deep_symbolize_keys # analysis_definition[:id].should eq analysis.natural_id # end # it 'returns existing analysis by uuid' do # get_json viz_analysis_url(@user, @visualization, @analysis.id) do |response| # response.status.should eq 200 # verify_analysis_response_body(response[:body], @analysis) # end # end # it 'returns 404 for nonexisting analysis' do # get_json viz_analysis_url(@user, @visualization, 'wadus') do |response| # response.status.should eq 404 # end # end # it 'returns existing analysis by json first id' do # get_json viz_analysis_url(@user, @visualization, @analysis.natural_id) do |response| # response.status.should eq 200 # verify_analysis_response_body(response[:body], @analysis) # end # end # it 'returns existing analysis by json first id with uuid ids' do # bypass_named_maps # analysis2 = FactoryGirl.create( # :source_analysis, # visualization_id: @visualization.id, # user_id: @user.id, # analysis_definition: { id: UUIDTools::UUID.random_create.to_s } # ) # get_json viz_analysis_url(@user, @visualization, analysis2.natural_id) do |response| # response.status.should eq 200 # verify_analysis_response_body(response[:body], analysis2) # end # analysis2.destroy # end # end # describe '#update' do # let(:new_natural_id) { "#{natural_id}_2" } # let(:new_key) { :whatever } # let(:new_payload) do # payload.delete(:id) # payload.merge(whatever: 'really?') # payload[:analysis_definition][:id] = new_natural_id # payload[:analysis_definition][new_key] = 'really' # payload # end # it 'updates existing analysis' do # @analysis.reload # @analysis.analysis_definition[:id].should_not eq new_payload[:analysis_definition][:id] # @analysis.analysis_definition[new_key].should be_nil # bypass_named_maps # put_json viz_analysis_url(@user, @visualization, @analysis), new_payload do |response| # response.status.should eq 200 # response.body[:analysis_definition].symbolize_keys.should eq new_payload[:analysis_definition] # a = Carto::Analysis.find(@analysis.id) # a.analysis_definition[:id].should eq new_payload[:analysis_definition][:id] # a.analysis_definition[new_key].should eq new_payload[:analysis_definition][new_key] # a.analysis_definition.deep_symbolize_keys.should eq new_payload[:analysis_definition].deep_symbolize_keys # end # end # it 'returns 422 if payload visualization_id or id do not match' do # put_json viz_analysis_url(@user, @visualization, @analysis), # new_payload.merge(visualization_id: 'x') do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), new_payload.merge(id: 'x') do |response| # response.status.should eq 422 # end # end # it 'returns 403 if user does not own the visualization' do # put_json viz_analysis_url(@user2, @visualization, @analysis), new_payload do |response| # response.status.should eq 403 # end # end # it 'returns 422 if payload is not valid json' do # put_json viz_analysis_url(@user, @visualization, @analysis), nil do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), "" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), "wadus" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), "wadus: 1" do |response| # response.status.should eq 422 # end # end # it 'returns 422 if payload is empty json' do # put_json viz_analysis_url(@user, @visualization, @analysis), {} do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), [] do |response| # response.status.should eq 422 # end # end # it 'returns 422 if analysis definition is not valid json' do # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: nil do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: "" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: "wadus" do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: "wadus: 1" do |response| # response.status.should eq 422 # end # end # it 'returns 422 if analysis_definition is empty json' do # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: {} do |response| # response.status.should eq 422 # end # put_json viz_analysis_url(@user, @visualization, @analysis), analysis_definition: [] do |response| # response.status.should eq 422 # end # end # end # describe '#destroy' do # it 'destroys existing analysis' do # bypass_named_maps # delete_json viz_analysis_url(@user, @visualization, @analysis) do |response| # response.status.should eq 200 # Carto::Analysis.where(id: @analysis.id).first.should be_nil # end # end # it 'returns 403 if user does not own the visualization' do # delete_json viz_analysis_url(@user2, @visualization, @analysis) do |response| # response.status.should eq 403 # end # end # end end
# # Author:: Stephen Haynes (<sh@nomitor.com>) # Copyright:: Copyright (c) 2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe Chef::Provider::Service::Systemd do before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::Service.new('rsyslog.service') @provider = Chef::Provider::Service::Systemd.new(@new_resource, @run_context) @shell_out_success = double('shell_out_with_systems_locale', :exitstatus => 0, :error? => false) @shell_out_failure = double('shell_out_with_systems_locale', :exitstatus => 1, :error? => true) end describe "load_current_resource" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) @provider.stub(:is_active?).and_return(false) @provider.stub(:is_enabled?).and_return(false) end it "should create a current resource with the name of the new resource" do Chef::Resource::Service.should_receive(:new).and_return(@current_resource) @provider.load_current_resource end it "should set the current resources service name to the new resources service name" do @current_resource.should_receive(:service_name).with(@new_resource.service_name) @provider.load_current_resource end it "should check if the service is running" do @provider.should_receive(:is_active?) @provider.load_current_resource end it "should set running to true if the service is running" do @provider.stub(:is_active?).and_return(true) @current_resource.should_receive(:running).with(true) @provider.load_current_resource end it "should set running to false if the service is not running" do @provider.stub(:is_active?).and_return(false) @current_resource.should_receive(:running).with(false) @provider.load_current_resource end describe "when a status command has been specified" do before do @new_resource.stub(:status_command).and_return("/bin/chefhasmonkeypants status") end it "should run the services status command if one has been specified" do @provider.stub(:shell_out_with_systems_locale).and_return(@shell_out_success) @current_resource.should_receive(:running).with(true) @provider.load_current_resource end it "should run the services status command if one has been specified and properly set status check state" do @provider.stub(:shell_out_with_systems_locale).with("/bin/chefhasmonkeypants status").and_return(@shell_out_success) @provider.load_current_resource @provider.instance_variable_get("@status_check_success").should be_true end it "should set running to false if a status command fails" do @provider.stub(:shell_out_with_systems_locale).and_return(@shell_out_failure) @current_resource.should_receive(:running).with(false) @provider.load_current_resource end it "should update state to indicate status check failed when a status command fails" do @provider.stub(:shell_out_with_systems_locale).and_return(@shell_out_failure) @provider.load_current_resource @provider.instance_variable_get("@status_check_success").should be_false end end it "should check if the service is enabled" do @provider.should_receive(:is_enabled?) @provider.load_current_resource end it "should set enabled to true if the service is enabled" do @provider.stub(:is_enabled?).and_return(true) @current_resource.should_receive(:enabled).with(true) @provider.load_current_resource end it "should set enabled to false if the service is not enabled" do @provider.stub(:is_enabled?).and_return(false) @current_resource.should_receive(:enabled).with(false) @provider.load_current_resource end it "should return the current resource" do @provider.load_current_resource.should eql(@current_resource) end end describe "start and stop service" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) @provider.current_resource = @current_resource end it "should call the start command if one is specified" do @new_resource.stub(:start_command).and_return("/sbin/rsyslog startyousillysally") @provider.should_receive(:shell_out!).with("/sbin/rsyslog startyousillysally") @provider.start_service end it "should call '/bin/systemctl start service_name' if no start command is specified" do @provider.should_receive(:shell_out_with_systems_locale).with("/bin/systemctl start #{@new_resource.service_name}").and_return(@shell_out_success) @provider.start_service end it "should not call '/bin/systemctl start service_name' if it is already running" do @current_resource.stub(:running).and_return(true) @provider.should_not_receive(:shell_out_with_systems_locale).with("/bin/systemctl start #{@new_resource.service_name}") @provider.start_service end it "should call the restart command if one is specified" do @current_resource.stub(:running).and_return(true) @new_resource.stub(:restart_command).and_return("/sbin/rsyslog restartyousillysally") @provider.should_receive(:shell_out!).with("/sbin/rsyslog restartyousillysally") @provider.restart_service end it "should call '/bin/systemctl restart service_name' if no restart command is specified" do @current_resource.stub(:running).and_return(true) @provider.should_receive(:shell_out_with_systems_locale).with("/bin/systemctl restart #{@new_resource.service_name}").and_return(@shell_out_success) @provider.restart_service end describe "reload service" do context "when a reload command is specified" do it "should call the reload command" do @current_resource.stub(:running).and_return(true) @new_resource.stub(:reload_command).and_return("/sbin/rsyslog reloadyousillysally") @provider.should_receive(:shell_out!).with("/sbin/rsyslog reloadyousillysally") @provider.reload_service end end context "when a reload command is not specified" do it "should call '/bin/systemctl reload service_name' if the service is running" do @current_resource.stub(:running).and_return(true) @provider.should_receive(:shell_out_with_systems_locale).with("/bin/systemctl reload #{@new_resource.service_name}").and_return(@shell_out_success) @provider.reload_service end it "should start the service if the service is not running" do @current_resource.stub(:running).and_return(false) @provider.should_receive(:start_service).and_return(true) @provider.reload_service end end end it "should call the stop command if one is specified" do @current_resource.stub(:running).and_return(true) @new_resource.stub(:stop_command).and_return("/sbin/rsyslog stopyousillysally") @provider.should_receive(:shell_out!).with("/sbin/rsyslog stopyousillysally") @provider.stop_service end it "should call '/bin/systemctl stop service_name' if no stop command is specified" do @current_resource.stub(:running).and_return(true) @provider.should_receive(:shell_out_with_systems_locale).with("/bin/systemctl stop #{@new_resource.service_name}").and_return(@shell_out_success) @provider.stop_service end it "should not call '/bin/systemctl stop service_name' if it is already stopped" do @current_resource.stub(:running).and_return(false) @provider.should_not_receive(:shell_out_with_systems_locale).with("/bin/systemctl stop #{@new_resource.service_name}") @provider.stop_service end end describe "enable and disable service" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) @provider.current_resource = @current_resource end it "should call '/bin/systemctl enable service_name' to enable the service" do @provider.should_receive(:shell_out_with_systems_locale).with("/bin/systemctl enable #{@new_resource.service_name}").and_return(@shell_out_success) @provider.enable_service end it "should call '/bin/systemctl disable service_name' to disable the service" do @provider.should_receive(:shell_out_with_systems_locale).with("/bin/systemctl disable #{@new_resource.service_name}").and_return(@shell_out_success) @provider.disable_service end end describe "is_active?" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) end it "should return true if '/bin/systemctl is-active service_name' returns 0" do @provider.should_receive(:shell_out_with_systems_locale).with('/bin/systemctl is-active rsyslog.service --quiet').and_return(@shell_out_success) @provider.is_active?.should be_true end it "should return false if '/bin/systemctl is-active service_name' returns anything except 0" do @provider.should_receive(:shell_out_with_systems_locale).with('/bin/systemctl is-active rsyslog.service --quiet').and_return(@shell_out_failure) @provider.is_active?.should be_false end end describe "is_enabled?" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) end it "should return true if '/bin/systemctl is-enabled service_name' returns 0" do @provider.should_receive(:shell_out_with_systems_locale).with('/bin/systemctl is-enabled rsyslog.service --quiet').and_return(@shell_out_success) @provider.is_enabled?.should be_true end it "should return false if '/bin/systemctl is-enabled service_name' returns anything except 0" do @provider.should_receive(:shell_out_with_systems_locale).with('/bin/systemctl is-enabled rsyslog.service --quiet').and_return(@shell_out_failure) @provider.is_enabled?.should be_false end end end spec fixes for systemd provider # # Author:: Stephen Haynes (<sh@nomitor.com>) # Copyright:: Copyright (c) 2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'spec_helper' describe Chef::Provider::Service::Systemd do before(:each) do @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @new_resource = Chef::Resource::Service.new('rsyslog.service') @provider = Chef::Provider::Service::Systemd.new(@new_resource, @run_context) @shell_out_success = double('shell_out_with_systems_locale', :exitstatus => 0, :error? => false) @shell_out_failure = double('shell_out_with_systems_locale', :exitstatus => 1, :error? => true) end describe "load_current_resource" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) @provider.stub(:is_active?).and_return(false) @provider.stub(:is_enabled?).and_return(false) end it "should create a current resource with the name of the new resource" do Chef::Resource::Service.should_receive(:new).and_return(@current_resource) @provider.load_current_resource end it "should set the current resources service name to the new resources service name" do @current_resource.should_receive(:service_name).with(@new_resource.service_name) @provider.load_current_resource end it "should check if the service is running" do @provider.should_receive(:is_active?) @provider.load_current_resource end it "should set running to true if the service is running" do @provider.stub(:is_active?).and_return(true) @current_resource.should_receive(:running).with(true) @provider.load_current_resource end it "should set running to false if the service is not running" do @provider.stub(:is_active?).and_return(false) @current_resource.should_receive(:running).with(false) @provider.load_current_resource end describe "when a status command has been specified" do before do @new_resource.stub(:status_command).and_return("/bin/chefhasmonkeypants status") end it "should run the services status command if one has been specified" do @provider.stub(:shell_out).and_return(@shell_out_success) @current_resource.should_receive(:running).with(true) @provider.load_current_resource end it "should run the services status command if one has been specified and properly set status check state" do @provider.stub(:shell_out).with("/bin/chefhasmonkeypants status").and_return(@shell_out_success) @provider.load_current_resource @provider.instance_variable_get("@status_check_success").should be_true end it "should set running to false if a status command fails" do @provider.stub(:shell_out).and_return(@shell_out_failure) @current_resource.should_receive(:running).with(false) @provider.load_current_resource end it "should update state to indicate status check failed when a status command fails" do @provider.stub(:shell_out).and_return(@shell_out_failure) @provider.load_current_resource @provider.instance_variable_get("@status_check_success").should be_false end end it "should check if the service is enabled" do @provider.should_receive(:is_enabled?) @provider.load_current_resource end it "should set enabled to true if the service is enabled" do @provider.stub(:is_enabled?).and_return(true) @current_resource.should_receive(:enabled).with(true) @provider.load_current_resource end it "should set enabled to false if the service is not enabled" do @provider.stub(:is_enabled?).and_return(false) @current_resource.should_receive(:enabled).with(false) @provider.load_current_resource end it "should return the current resource" do @provider.load_current_resource.should eql(@current_resource) end end describe "start and stop service" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) @provider.current_resource = @current_resource end it "should call the start command if one is specified" do @new_resource.stub(:start_command).and_return("/sbin/rsyslog startyousillysally") @provider.should_receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog startyousillysally") @provider.start_service end it "should call '/bin/systemctl start service_name' if no start command is specified" do @provider.should_receive(:shell_out_with_systems_locale!).with("/bin/systemctl start #{@new_resource.service_name}").and_return(@shell_out_success) @provider.start_service end it "should not call '/bin/systemctl start service_name' if it is already running" do @current_resource.stub(:running).and_return(true) @provider.should_not_receive(:shell_out_with_systems_locale!).with("/bin/systemctl start #{@new_resource.service_name}") @provider.start_service end it "should call the restart command if one is specified" do @current_resource.stub(:running).and_return(true) @new_resource.stub(:restart_command).and_return("/sbin/rsyslog restartyousillysally") @provider.should_receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog restartyousillysally") @provider.restart_service end it "should call '/bin/systemctl restart service_name' if no restart command is specified" do @current_resource.stub(:running).and_return(true) @provider.should_receive(:shell_out_with_systems_locale!).with("/bin/systemctl restart #{@new_resource.service_name}").and_return(@shell_out_success) @provider.restart_service end describe "reload service" do context "when a reload command is specified" do it "should call the reload command" do @current_resource.stub(:running).and_return(true) @new_resource.stub(:reload_command).and_return("/sbin/rsyslog reloadyousillysally") @provider.should_receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog reloadyousillysally") @provider.reload_service end end context "when a reload command is not specified" do it "should call '/bin/systemctl reload service_name' if the service is running" do @current_resource.stub(:running).and_return(true) @provider.should_receive(:shell_out_with_systems_locale!).with("/bin/systemctl reload #{@new_resource.service_name}").and_return(@shell_out_success) @provider.reload_service end it "should start the service if the service is not running" do @current_resource.stub(:running).and_return(false) @provider.should_receive(:start_service).and_return(true) @provider.reload_service end end end it "should call the stop command if one is specified" do @current_resource.stub(:running).and_return(true) @new_resource.stub(:stop_command).and_return("/sbin/rsyslog stopyousillysally") @provider.should_receive(:shell_out_with_systems_locale!).with("/sbin/rsyslog stopyousillysally") @provider.stop_service end it "should call '/bin/systemctl stop service_name' if no stop command is specified" do @current_resource.stub(:running).and_return(true) @provider.should_receive(:shell_out_with_systems_locale!).with("/bin/systemctl stop #{@new_resource.service_name}").and_return(@shell_out_success) @provider.stop_service end it "should not call '/bin/systemctl stop service_name' if it is already stopped" do @current_resource.stub(:running).and_return(false) @provider.should_not_receive(:shell_out_with_systems_locale!).with("/bin/systemctl stop #{@new_resource.service_name}") @provider.stop_service end end describe "enable and disable service" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) @provider.current_resource = @current_resource end it "should call '/bin/systemctl enable service_name' to enable the service" do @provider.should_receive(:shell_out!).with("/bin/systemctl enable #{@new_resource.service_name}").and_return(@shell_out_success) @provider.enable_service end it "should call '/bin/systemctl disable service_name' to disable the service" do @provider.should_receive(:shell_out!).with("/bin/systemctl disable #{@new_resource.service_name}").and_return(@shell_out_success) @provider.disable_service end end describe "is_active?" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) end it "should return true if '/bin/systemctl is-active service_name' returns 0" do @provider.should_receive(:shell_out).with('/bin/systemctl is-active rsyslog.service --quiet').and_return(@shell_out_success) @provider.is_active?.should be_true end it "should return false if '/bin/systemctl is-active service_name' returns anything except 0" do @provider.should_receive(:shell_out).with('/bin/systemctl is-active rsyslog.service --quiet').and_return(@shell_out_failure) @provider.is_active?.should be_false end end describe "is_enabled?" do before(:each) do @current_resource = Chef::Resource::Service.new('rsyslog.service') Chef::Resource::Service.stub(:new).and_return(@current_resource) end it "should return true if '/bin/systemctl is-enabled service_name' returns 0" do @provider.should_receive(:shell_out).with('/bin/systemctl is-enabled rsyslog.service --quiet').and_return(@shell_out_success) @provider.is_enabled?.should be_true end it "should return false if '/bin/systemctl is-enabled service_name' returns anything except 0" do @provider.should_receive(:shell_out).with('/bin/systemctl is-enabled rsyslog.service --quiet').and_return(@shell_out_failure) @provider.is_enabled?.should be_false end end end
#require 'spec_helper' # ensure default apache html directory is absent describe command('/bin/bash -c "[[ ! -e /var/www/html ]]"') do its(:exit_status) { should eq 0 } end # declare securedrop app directories securedrop_app_directories = [ '/var/www/securedrop', '/var/lib/securedrop', '/var/lib/securedrop/store', '/var/lib/securedrop/keys', '/var/lib/securedrop/tmp', ] # ensure securedrop app directories exist with correct permissions securedrop_app_directories.each do |securedrop_app_directory| describe file(securedrop_app_directory) do it { should be_directory } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } it { should be_mode '700' } end end # ensure securedrop-app-code package is installed describe package('securedrop-app-code') do it { should be_installed } end # declare securedrop-app package dependencies securedrop_package_dependencies = [ 'apparmor-utils', 'gnupg2', 'haveged', 'python', 'python-pip', 'redis-server', 'secure-delete', 'sqlite', 'supervisor', ] # ensure securedrop-app dependencies are installed securedrop_package_dependencies.each do |securedrop_package_dependency| describe package(securedrop_package_dependency) do it { should be_installed } end end # ensure the securedrop application gpg pubkey is present describe file('/var/lib/securedrop/test_journalist_key.pub') do it { should be_file } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } it { should be_mode '644' } end describe command('su -s /bin/bash -c "gpg --homedir /var/lib/securedrop/keys --import /var/lib/securedrop/test_journalist_key.pub" www-data') do its(:exit_status) { should eq 0 } expected_output = <<-eos gpg: key 28271441: "SecureDrop Test/Development (DO NOT USE IN PRODUCTION)" not changed gpg: Total number processed: 1 gpg: unchanged: 1 eos # gpg dumps a lot of output to stderr, rather than stdout its(:stderr) { should eq expected_output } end # ensure config.py (settings for securedrop app) exists describe file('/var/www/securedrop/config.py') do it { should be_file } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } it { should be_mode '600' } its(:content) { should match /^JOURNALIST_KEY = '65A1B5FF195B56353CC63DFFCC40EF1228271441'$/ } end # ensure sqlite database exists for application describe file('/var/lib/securedrop/db.sqlite') do it { should be_file } # TODO: perhaps 640 perms would work here it { should be_mode '644' } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } end # ensure default logo header file exists # TODO: add check for custom logo header file describe file('/var/www/securedrop/static/i/logo.png') do it { should be_file } # TODO: ansible task declares mode 400 but the file ends up as 644 on host it { should be_mode '644' } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } end adds test for worker config #require 'spec_helper' # ensure default apache html directory is absent describe command('/bin/bash -c "[[ ! -e /var/www/html ]]"') do its(:exit_status) { should eq 0 } end # declare securedrop app directories securedrop_app_directories = [ '/var/www/securedrop', '/var/lib/securedrop', '/var/lib/securedrop/store', '/var/lib/securedrop/keys', '/var/lib/securedrop/tmp', ] # ensure securedrop app directories exist with correct permissions securedrop_app_directories.each do |securedrop_app_directory| describe file(securedrop_app_directory) do it { should be_directory } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } it { should be_mode '700' } end end # ensure securedrop-app-code package is installed describe package('securedrop-app-code') do it { should be_installed } end # declare securedrop-app package dependencies securedrop_package_dependencies = [ 'apparmor-utils', 'gnupg2', 'haveged', 'python', 'python-pip', 'redis-server', 'secure-delete', 'sqlite', 'supervisor', ] # ensure securedrop-app dependencies are installed securedrop_package_dependencies.each do |securedrop_package_dependency| describe package(securedrop_package_dependency) do it { should be_installed } end end # ensure the securedrop application gpg pubkey is present describe file('/var/lib/securedrop/test_journalist_key.pub') do it { should be_file } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } it { should be_mode '644' } end describe command('su -s /bin/bash -c "gpg --homedir /var/lib/securedrop/keys --import /var/lib/securedrop/test_journalist_key.pub" www-data') do its(:exit_status) { should eq 0 } expected_output = <<-eos gpg: key 28271441: "SecureDrop Test/Development (DO NOT USE IN PRODUCTION)" not changed gpg: Total number processed: 1 gpg: unchanged: 1 eos # gpg dumps a lot of output to stderr, rather than stdout its(:stderr) { should eq expected_output } end # ensure config.py (settings for securedrop app) exists describe file('/var/www/securedrop/config.py') do it { should be_file } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } it { should be_mode '600' } its(:content) { should match /^JOURNALIST_KEY = '65A1B5FF195B56353CC63DFFCC40EF1228271441'$/ } end # ensure sqlite database exists for application describe file('/var/lib/securedrop/db.sqlite') do it { should be_file } # TODO: perhaps 640 perms would work here it { should be_mode '644' } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } end # ensure default logo header file exists # TODO: add check for custom logo header file describe file('/var/www/securedrop/static/i/logo.png') do it { should be_file } # TODO: ansible task declares mode 400 but the file ends up as 644 on host it { should be_mode '644' } it { should be_owned_by 'www-data' } it { should be_grouped_into 'www-data' } end # declare config options for securedrop worker securedrop_worker_config_options = [ '[program:securedrop_worker]', 'command=/usr/local/bin/rqworker', 'directory=/var/www/securedrop', 'autostart=true', 'autorestart=true', 'startretries=3', 'stderr_logfile=/var/log/securedrop_worker/err.log', 'stdout_logfile=/var/log/securedrop_worker/out.log', 'user=www-data', 'environment=HOME="/tmp/python-gnupg"', ] # ensure securedrop worker config for supervisor is present describe file('/etc/supervisor/conf.d/securedrop_worker.conf') do it { should be_file } it { should be_mode '644' } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } securedrop_worker_config_options.each do |securedrop_worker_config_option| securedrop_worker_config_option_regex = Regexp.quote(securedrop_worker_config_option) its(:content) { should match /^#{securedrop_worker_config_option_regex}$/ } end end # ensure directory for worker logs is present describe file('/var/log/securedrop_worker') do it { should be_directory } it { should be_mode '644' } it { should be_owned_by 'root' } it { should be_grouped_into 'root' } end
# -------------------------------------------------------------------------- # # Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs # # # # 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 'xmlrpc/client' require 'bigdecimal' require 'stringio' module OpenNebula def self.pool_page_size @@pool_page_size end if OpenNebula::OX class OxStreamParser < XMLRPC::XMLParser::AbstractStreamParser def initialize @parser_class = OxParser end class OxParser < Ox::Sax include XMLRPC::XMLParser::StreamParserMixin alias :text :character alias :end_element :endElement alias :start_element :startElement def parse(str) Ox.sax_parse(self, StringIO.new(str), :symbolize => false, :convert_special => true) end end end elsif OpenNebula::NOKOGIRI class NokogiriStreamParser < XMLRPC::XMLParser::AbstractStreamParser def initialize @parser_class = NokogiriParser end class NokogiriParser < Nokogiri::XML::SAX::Document include XMLRPC::XMLParser::StreamParserMixin alias :cdata_block :character alias :characters :character alias :end_element :endElement alias :start_element :startElement def parse(str) parser = Nokogiri::XML::SAX::Parser.new(self) parser.parse(str) end end end end DEFAULT_POOL_PAGE_SIZE = 2000 if size=ENV['ONE_POOL_PAGE_SIZE'] if size.strip.match(/^\d+$/) && size.to_i >= 2 @@pool_page_size = size.to_i else @@pool_page_size = nil end else @@pool_page_size = DEFAULT_POOL_PAGE_SIZE end # The client class, represents the connection with the core and handles the # xml-rpc calls. class Client attr_accessor :one_auth attr_reader :one_endpoint begin require 'xmlparser' XMLPARSER=true rescue LoadError XMLPARSER=false end # Creates a new client object that will be used to call OpenNebula # functions. # # @param [String, nil] secret user credentials ("user:password") or # nil to get the credentials from user auth file # @param [String, nil] endpoint OpenNebula server endpoint # (http://host:2633/RPC2) or nil to get it form the environment # variable ONE_XMLRPC or use the default endpoint # @param [Hash] options # @option params [Integer] :timeout connection timeout in seconds, # defaults to 30 # @option params [String] :http_proxy HTTP proxy string used for # connecting to the endpoint; defaults to no proxy # # @return [OpenNebula::Client] def initialize(secret=nil, endpoint=nil, options={}) if secret @one_auth = secret elsif ENV["ONE_AUTH"] and !ENV["ONE_AUTH"].empty? and File.file?(ENV["ONE_AUTH"]) @one_auth = File.read(ENV["ONE_AUTH"]) elsif ENV["HOME"] and File.file?(ENV["HOME"]+"/.one/one_auth") @one_auth = File.read(ENV["HOME"]+"/.one/one_auth") elsif File.file?("/var/lib/one/.one/one_auth") @one_auth = File.read("/var/lib/one/.one/one_auth") else raise "ONE_AUTH file not present" end @one_auth.rstrip! if endpoint @one_endpoint = endpoint elsif ENV["ONE_XMLRPC"] @one_endpoint = ENV["ONE_XMLRPC"] elsif ENV['HOME'] and File.exists?(ENV['HOME']+"/.one/one_endpoint") @one_endpoint = File.read(ENV['HOME']+"/.one/one_endpoint") elsif File.exists?("/var/lib/one/.one/one_endpoint") @one_endpoint = File.read("/var/lib/one/.one/one_endpoint") else @one_endpoint = "http://localhost:2633/RPC2" end timeout=nil timeout=options[:timeout] if options[:timeout] http_proxy=nil http_proxy=options[:http_proxy] if options[:http_proxy] @server = XMLRPC::Client.new2(@one_endpoint, http_proxy, timeout) @server.http_header_extra = {'accept-encoding' => 'identity'} if defined?(OxStreamParser) @server.set_parser(OxStreamParser.new) elsif OpenNebula::NOKOGIRI @server.set_parser(NokogiriStreamParser.new) elsif XMLPARSER @server.set_parser(XMLRPC::XMLParser::XMLStreamParser.new) end end def call(action, *args) begin response = @server.call_async("one."+action, @one_auth, *args) if response[0] == false Error.new(response[1], response[2]) else response[1] #response[1..-1] end rescue Exception => e Error.new(e.message) end end def get_version() call("system.version") end end end feature #3180: options for SSL certs in OCA ONE_CERT_DIR: adds an extra directory with trusted CA certificates ONE_DISABLE_SSL_VERIFY: disable certificate verification Both of these options make the calls change from asynchronous (one http connection per call) to synchronous (same http connection for all calls). XMLRPC library creates a new HTTP object per asynchronous connection and there is no way of passing configuration options to it. # -------------------------------------------------------------------------- # # Copyright 2002-2014, OpenNebula Project (OpenNebula.org), C12G Labs # # # # 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 'xmlrpc/client' require 'bigdecimal' require 'stringio' require 'openssl' module OpenNebula def self.pool_page_size @@pool_page_size end if OpenNebula::OX class OxStreamParser < XMLRPC::XMLParser::AbstractStreamParser def initialize @parser_class = OxParser end class OxParser < Ox::Sax include XMLRPC::XMLParser::StreamParserMixin alias :text :character alias :end_element :endElement alias :start_element :startElement def parse(str) Ox.sax_parse(self, StringIO.new(str), :symbolize => false, :convert_special => true) end end end elsif OpenNebula::NOKOGIRI class NokogiriStreamParser < XMLRPC::XMLParser::AbstractStreamParser def initialize @parser_class = NokogiriParser end class NokogiriParser < Nokogiri::XML::SAX::Document include XMLRPC::XMLParser::StreamParserMixin alias :cdata_block :character alias :characters :character alias :end_element :endElement alias :start_element :startElement def parse(str) parser = Nokogiri::XML::SAX::Parser.new(self) parser.parse(str) end end end end DEFAULT_POOL_PAGE_SIZE = 2000 if size=ENV['ONE_POOL_PAGE_SIZE'] if size.strip.match(/^\d+$/) && size.to_i >= 2 @@pool_page_size = size.to_i else @@pool_page_size = nil end else @@pool_page_size = DEFAULT_POOL_PAGE_SIZE end # The client class, represents the connection with the core and handles the # xml-rpc calls. class Client attr_accessor :one_auth attr_reader :one_endpoint begin require 'xmlparser' XMLPARSER=true rescue LoadError XMLPARSER=false end # Creates a new client object that will be used to call OpenNebula # functions. # # @param [String, nil] secret user credentials ("user:password") or # nil to get the credentials from user auth file # @param [String, nil] endpoint OpenNebula server endpoint # (http://host:2633/RPC2) or nil to get it form the environment # variable ONE_XMLRPC or use the default endpoint # @param [Hash] options # @option params [Integer] :timeout connection timeout in seconds, # defaults to 30 # @option params [String] :http_proxy HTTP proxy string used for # connecting to the endpoint; defaults to no proxy # # @return [OpenNebula::Client] def initialize(secret=nil, endpoint=nil, options={}) if secret @one_auth = secret elsif ENV["ONE_AUTH"] and !ENV["ONE_AUTH"].empty? and File.file?(ENV["ONE_AUTH"]) @one_auth = File.read(ENV["ONE_AUTH"]) elsif ENV["HOME"] and File.file?(ENV["HOME"]+"/.one/one_auth") @one_auth = File.read(ENV["HOME"]+"/.one/one_auth") elsif File.file?("/var/lib/one/.one/one_auth") @one_auth = File.read("/var/lib/one/.one/one_auth") else raise "ONE_AUTH file not present" end @one_auth.rstrip! if endpoint @one_endpoint = endpoint elsif ENV["ONE_XMLRPC"] @one_endpoint = ENV["ONE_XMLRPC"] elsif ENV['HOME'] and File.exists?(ENV['HOME']+"/.one/one_endpoint") @one_endpoint = File.read(ENV['HOME']+"/.one/one_endpoint") elsif File.exists?("/var/lib/one/.one/one_endpoint") @one_endpoint = File.read("/var/lib/one/.one/one_endpoint") else @one_endpoint = "http://localhost:2633/RPC2" end @async = true timeout=nil timeout=options[:timeout] if options[:timeout] http_proxy=nil http_proxy=options[:http_proxy] if options[:http_proxy] @server = XMLRPC::Client.new2(@one_endpoint, http_proxy, timeout) @server.http_header_extra = {'accept-encoding' => 'identity'} http = @server.instance_variable_get("@http") if options['cert_dir'] || ENV['ONE_CERT_DIR'] @async = false cert_dir = options['cert_dir'] || ENV['ONE_CERT_DIR'] cert_files = Dir["#{cert_dir}/*"] cert_store = OpenSSL::X509::Store.new cert_store.set_default_paths cert_files.each {|cert| cert_store.add_file(cert) } http.cert_store = cert_store end if options['disable_ssl_verify'] || ENV['ONE_DISABLE_SSL_VERIFY'] @async = false http.verify_mode = OpenSSL::SSL::VERIFY_NONE end if defined?(OxStreamParser) @server.set_parser(OxStreamParser.new) elsif OpenNebula::NOKOGIRI @server.set_parser(NokogiriStreamParser.new) elsif XMLPARSER @server.set_parser(XMLRPC::XMLParser::XMLStreamParser.new) end end def call(action, *args) begin if @async response = @server.call_async("one."+action, @one_auth, *args) else response = @server.call("one."+action, @one_auth, *args) end if response[0] == false Error.new(response[1], response[2]) else response[1] #response[1..-1] end rescue Exception => e Error.new(e.message) end end def get_version() call("system.version") end end end
# TO RUN THIS: # $ rspec calculator_spec.rb # YOU MAY NEED TO: # $ gem install rspec # (and get v 2.14 or higher) require_relative 'calculator' describe Calculator do let(:calculator) { Calculator.new } describe "addition" do it "puts two and two together" do expect( calculator.add(2, 2) ).to eq(4) end it "puts two and two and two together" do expect( calculator.add(2, 2, 2) ).to eq(6) end end describe "subtraction" do it "takes one from two" do expect( calculator.subtract(2, 1) ).to eq(1) end it "subtracts all subsequent arguments from the first one" do expect( calculator.subtract(13, 8, 5, 3, 2, 1, 1) ).to eq(-7) end end describe "multiplication" do it "multiplies six by nine (but does not get forty-two)" do expect( calculator.multiply(6, 9) ).to eq(54) end it "does factorials the long way" do expect( calculator.multiply(1, 2, 3, 4, 5, 6) ).to eq(720) end end describe "division" do it "halves" do expect( calculator.divide(4, 2) ).to eq(2) end it "subdivides" do expect( calculator.divide(128, 2, 2, 2) ).to eq(16) end end # IF YOU'RE BORED... describe "parsing for fun and profit" do it "does simple addition" do expect( calculator.evaluate("2+2") ).to eq(4) end xit "copes well with spaces" do expect( calculator.evaluate(" 2 + 2") ).to eq(4) end xit "understands order of operations" do expect( calculator.evaluate("2+2*5") ).to eq(12) end end end add spec for multiple add/subtract (technically a freebie, since it passes) # TO RUN THIS: # $ rspec calculator_spec.rb # YOU MAY NEED TO: # $ gem install rspec # (and get v 2.14 or higher) require_relative 'calculator' describe Calculator do let(:calculator) { Calculator.new } describe "addition" do it "puts two and two together" do expect( calculator.add(2, 2) ).to eq(4) end it "puts two and two and two together" do expect( calculator.add(2, 2, 2) ).to eq(6) end end describe "subtraction" do it "takes one from two" do expect( calculator.subtract(2, 1) ).to eq(1) end it "subtracts all subsequent arguments from the first one" do expect( calculator.subtract(13, 8, 5, 3, 2, 1, 1) ).to eq(-7) end end describe "multiplication" do it "multiplies six by nine (but does not get forty-two)" do expect( calculator.multiply(6, 9) ).to eq(54) end it "does factorials the long way" do expect( calculator.multiply(1, 2, 3, 4, 5, 6) ).to eq(720) end end describe "division" do it "halves" do expect( calculator.divide(4, 2) ).to eq(2) end it "subdivides" do expect( calculator.divide(128, 2, 2, 2) ).to eq(16) end end # IF YOU'RE BORED... describe "parsing for fun and profit" do it "does simple addition" do expect( calculator.evaluate("2+2") ).to eq(4) end it "does repeated addition and subtraction" do expect( calculator.evaluate("2+2-1+4-7+5") ).to eq(5) end xit "copes well with spaces" do expect( calculator.evaluate(" 2 + 2") ).to eq(4) end xit "understands order of operations" do expect( calculator.evaluate("2+2*5") ).to eq(12) end end end
require '/Users/Albert/Repos/Scripts/ruby/lib/utilities.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo.rb' class NimzoCreateDelete # The point of entry! # @param route # @param type # @param action def initialize(route, type, action) @route = route @type = type @action = action @errors = false @output = Array.new self.validateParameters self.validateRoute self.run end # Validate the input parameters def validateParameters # Make sure the particular controller type is valid. # This error cannot be reached through incorrect user input. unless inArray(%w(app modal overlay system widget), @type) @errors = true self.error("\x1B[33m#{@type}\x1B[0m is not a valid controller type. There is an error in your bash script, not your input.") end # Make sure the particular action is valid. # This error cannot be reached through incorrect user input. unless inArray(%w(create delete), @action) @errors = true self.error("\x1B[33m#{@action}\x1B[0m is not a valid action. There is an error in your bash script, not your input.") end # Make sure route doesn't start with API or AJAX. routeFirstParameter = @route.split('/') routeFirstParameter = routeFirstParameter[0] if inArray(%w(api ajax), routeFirstParameter, true) self.error("Request route cannot start with: \x1B[33m#{routeFirstParameter}\x1B[0m") end end # Make sure the route doesn't already exist and that it isn't a nested path with blank previous paths (if that makes sense). def validateRoute end # If an error occurs, it's added to the @OUTPUT array and if 'exit' flag set to TRUE, # the script goes straight to run & subsequently displays output & dies. # @param text # @param exit def error(text = '', exit = true) @errors = true @output.push("\x1B[41m ERROR \x1B[0m #{text}") if exit self.run end end # The final function which doesn all the processing. If errors are present, no processing will be done. def run unless @errors end self.displayOutput end # No matter what, at the end of EVERY script run, whatever's in the @OUTPUT buffer will # get echoed to Terminal. def displayOutput unless @output.empty? puts @output.each { |message| puts "#{message}\x1B[0m" } if @errors puts " \x1B[90mScript aborted.\x1B[0m" end puts end exit end end NimzoCreateDelete.new(ARGV[0].sub(/^[\/]*/, '').sub(/(\/)+$/, ''), ARGV[1], ARGV[2]) Nimzo create/delete script now checks that all characters withing route are AlphaNumeric. require '/Users/Albert/Repos/Scripts/ruby/lib/utilities.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo.rb' class NimzoCreateDelete # The point of entry! # @param route # @param type # @param action def initialize(route, type, action) @route = route @type = type @action = action @errors = false @output = Array.new @filenameUpperCase = '' @filenameLowerCase = '' @pathToRepo = '/Users/Albert/Repos/Nimzo/httpdocs' @pathToRepoSlash = '/Users/Albert/Repos/Nimzo/httpdocs/' @pathToTests = '/Users/Albert/Repos/Nimzo/tests-php' self.validateParameters self.validateRoute self.run end # Validate the input parameters def validateParameters # Make sure the particular controller type is valid. # This error cannot be reached through incorrect user input. unless inArray(%w(app modal overlay system widget), @type) @errors = true self.error("\x1B[33m#{@type}\x1B[0m is not a valid controller type. There is an error in your bash script, not your input.") end # Make sure the particular action is valid. # This error cannot be reached through incorrect user input. unless inArray(%w(create delete), @action) @errors = true self.error("\x1B[33m#{@action}\x1B[0m is not a valid action. There is an error in your bash script, not your input.") end # Make sure route doesn't start with API or AJAX. routeFirstParameter = @route.split('/') routeFirstParameter = routeFirstParameter[0] if inArray(%w(api ajax), routeFirstParameter, true) self.error("Request route cannot start with: \x1B[33m#{routeFirstParameter}\x1B[0m") end end # Make sure the route doesn't already exist and that it isn't a nested path with blank previous paths (if that makes sense). def validateRoute # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@route.gsub('/', '')) @errors = true self.error("Name must be alphanumeric and contain only slashes ('/'). You passed: \x1B[33m#{@route}\x1B[0m") end end # If an error occurs, it's added to the @OUTPUT array and if 'exit' flag set to TRUE, # the script goes straight to run & subsequently displays output & dies. # @param text # @param exit def error(text = '', exit = true) @errors = true @output.push("\x1B[41m ERROR \x1B[0m #{text}") if exit self.run end end # The final function which doesn all the processing. If errors are present, no processing will be done. def run unless @errors puts 'No errors!' end self.displayOutput end # No matter what, at the end of EVERY script run, whatever's in the @OUTPUT buffer will # get echoed to Terminal. def displayOutput unless @output.empty? puts @output.each { |message| puts "#{message}\x1B[0m" } if @errors puts " \x1B[90mScript aborted.\x1B[0m" end puts end exit end end NimzoCreateDelete.new(ARGV[0].sub(/^[\/]*/, '').sub(/(\/)+$/, ''), ARGV[1], ARGV[2])
require '/Users/Albert/Repos/Scripts/ruby/lib/utilities.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-maker.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-rewriter.rb' class NimzoCreateRemove LIB = 'lib' CREATE = 'create' REMOVE = 'remove' SCRIPT = 'script' SLEEK = 'sleek' # The point of entry! # @param route # @param type # @param action def initialize(type, route, action, helper = nil) @type = type.downcase @route = route.sub(/^[\/]*/, '').sub(/(\/)+$/, '').squeeze('/') @action = action.downcase @helper = helper @errors = false @output = Array.new @pathToRepo = $PATH_TO_REPO @pathToPhp = "#{@pathToRepo}/httpdocs/private/#{@type}/" @pathToDev = "#{@pathToRepo}/httpdocs/public/dev/#{@type}/" @pathToMin = "#{@pathToRepo}/httpdocs/public/min/#{@type}/" @pathToTest = "#{@pathToRepo}/tests-php/private/#{@type}/" @paths = Array.new @files = Array.new self.validateParameters if @type == LIB || @type == SCRIPT self.createLibScript elsif @type == SLEEK self.creatSleekClass else if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type) self.createHelper else self.createRoute end end end # Validate the input parameters def validateParameters # Make sure the particular controller type is valid. # This error cannot be reached through incorrect user input. unless inArray(%w(page pagehelper lib script sleek modal modalhelper overlay overlayhelper system systemhelper widget widgethelper), @type) self.error("\x1B[33m#{@type.upcase}\x1B[0m is not a valid type. There is an error in your bash script, not your input.") end # Make sure the particular action is valid. # This error cannot be reached through incorrect user input. unless inArray([CREATE, REMOVE], @action) self.error("\x1B[33m#{@action}\x1B[0m is not a valid action. There is an error in your bash script, not your input.") end if @type == LIB || @type == SCRIPT || @type == SLEEK # Make sure the route consists of a parent directory and a classname unless @route.include?('/') self.error("You must specify a \x1B[33mfolder\x1B[0m and a \x1B[33mclassname\x1B[0m (IE: core/AjaxRequest)") end # If more than 1 slash is present, this cuts it down to only 1. Everything after the 2nd will be ommited. # IE: 'something/to/create' becomes 'something/to'. # Also capitalizes the 2nd part & removes file extension (if exists) routeSplit = @route.split('/') className = File.basename(routeSplit[1], File.extname(routeSplit[1])) className[0] = className.upcase[0..0] @route = "#{routeSplit[0].downcase}/#{className}" # Make sure folder doesn't start with following values. These will just create confusion. if inArray(%w(bin lib script scripts sleek), routeSplit[0], true) && self.error("Namespace/preceeding folder shouldn't be \x1B[33m#{routeSplit[0].upcase}\x1B[0m due to possible confusion.") end # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@route.gsub('/', '')) self.error("\x1B[33mFolder\x1B[0m and a \x1B[33mclassname\x1B[0m must be alphanumeric and seperated by a slash ('/'). You passed: \x1B[33m#{@route}\x1B[0m") end if @type == SLEEK # Make sure all SLEEK classes are prefixed with 'Sleek' if routeSplit[1][0..4].downcase != 'sleek' self.error("Classes within this namespace must have prefix \x1B[35m'Sleek'\x1B[0m. You passed: \x1B[33m #{routeSplit[1]}\x1B[0m") end end else # Make sure route doesn't start with API or AJAX routeSplit = @route.split('/') if inArray(%w(api ajax script), routeSplit[0], true) && self.error("Request route cannot start with \x1B[33m#{routeSplit[0]}\x1B[0m as these are parameters the system uses.") end # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@route.gsub('/', '')) self.error("Route parameters must be alphanumeric and seperated by slashes ('/'). You passed: \x1B[33m#{@route}\x1B[0m") end # Make sure that the FIRST character of ANY route parameter is a letter, not a number. @route.split('/').each { |routeParameter| if (routeParameter[0, 1] =~ /[A-Za-z]/) != 0 self.error("Route parameters cannot start with a digit (IE: 0-9). You passed: \x1B[33m#{@route}\x1B[0m") end } # Make sure the helper parameter is correct (if this is a 'helper' run) if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type) # Make sure @helper is not nil if @helper.nil? || @helper == '' self.error('@helper variable is nil or not set.') end @helper = File.basename(@helper, File.extname(@helper)) @helper[0] = @helper.upcase[0..0] # Make sure helper is alphanumeric. # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@helper) self.error("Helper name must be alphanumeric. You passed: \x1B[33m#{@helper}\x1B[0m") end end end end # Creates a helper class. def createHelper case @type when 'pagehelper' @type = 'page' when 'modalhelper' @type = 'modal' when 'overlayhelper' @type = 'overlay' when 'systemhelper' @type = 'system' when 'widgethelper' @type = 'widget' else self.error('Type not supported.') end helperPath = "#{$PATH_TO_PHP}#{@type}/helpers/#{@route}/" helperPathTest = "#{$PATH_TO_TESTS}#{@type}/helpers/#{@route}/" helperFile = "#{helperPath}#{@helper}.php" helperFileTest = "#{helperPathTest}#{@helper}Test.php" if @action == CREATE # Check that the helper paths even exist. unless File.directory?(helperPath) self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m") end unless File.directory?(helperPathTest) self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m") end # Now check that the helper files DON'T exist. if File.file?(helperFile) self.error("The file \x1B[33m#{helperFile}\x1B[0m already exists.") end if File.file?(helperFileTest) self.error("The file \x1B[33m#{helperFileTest}\x1B[0m already exists.") end @files.push(helperFile) @files.push(helperFileTest) @output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") @output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") @output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts elsif @action == REMOVE filesToDelete = Array.new # Check that the helper files we're trying to delete exist. if File.file?(helperFile) filesToDelete.push(helperFile) @output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end if File.file?(helperFileTest) filesToDelete.push(helperFileTest) @output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end # If helper files don't exist, abandon ship! if filesToDelete.empty? self.error("The helper \x1B[35m#{@helper}\x1B[0m doesn't exist for \x1B[44m #{@type.capitalize} \x1B[0m \x1B[35m#{@route}\x1B[0m") end @output.push('') @output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") unless filesToDelete.empty? filesToDelete.each { |file| @output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") # Remove file from Git. system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1") FileUtils.rm_rf(file) # When deleting the last file in a direcotry, Ruby for some stupid reason deletes # the parent directory as well. This in turn crashed the unit tests so instead of trying to # figure this out, I'm just going to check & re-create the directory if it's been wiped. Easy peasy. dir = File.dirname(file) unless File.directory?(dir) FileUtils::mkdir_p(dir) end } end @output.push('') self.flushBuffer end self.runUnitTests end # Create Sleek classes + tests def creatSleekClass routeSplit = @route.split('/') if routeSplit.size > 2 self.error('Size of split route should not be greater than 2!') end pathName = routeSplit[0].downcase className = routeSplit[1] className[0] = className[0..0].upcase filename = "#{$PATH_TO_PHP}lib/sleek/library/#{pathName}/#{className}.php" filenameTest = "#{$PATH_TO_TESTS}lib/sleek/library/#{pathName}/#{className}Test.php" if @action == CREATE # Make sure the files don't already exist. # The last thing we want to do is overwrite files. if File.file?(filename) self.error("File already exists: \x1B[33m#{filename}\x1B[0m") exit elsif File.file?(filenameTest) self.error("File already exists: \x1B[33m#{filenameTest}\x1B[0m") exit end @files.push(filename) @files.push(filenameTest) @output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") @output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") @output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts elsif @action == REMOVE # @todo REMOVE THIS puts 'REMOVE CODE GOES HERE!' exit end self.runUnitTests end # Creates a class within the /lib directory + also creates the UNIT Test boiler plate. def createLibScript routeSplit = @route.split('/') filename = '' filenameTest ='' if @type == LIB filename = "#{$PATH_TO_PHP}lib/#{routeSplit[0]}/#{routeSplit[1]}.php" filenameTest = "#{$PATH_TO_TESTS}lib/#{routeSplit[0]}/#{routeSplit[1]}Test.php" elsif @type == SCRIPT filename = "#{$PATH_TO_PHP}script/#{routeSplit[0]}/#{routeSplit[1]}.php" filenameTest = "#{$PATH_TO_TESTS}script/#{routeSplit[0]}/#{routeSplit[1]}Test.php" else self.error('Type is not supported.') end if @action == CREATE # Make sure the files don't already exist. # The last thing we want to do is overwrite files. if File.file?(filename) self.error("File already exists: \x1B[33m#{filename}\x1B[0m") exit elsif File.file?(filenameTest) self.error("File already exists: \x1B[33m#{filenameTest}\x1B[0m") exit end @files.push(filename) @files.push(filenameTest) @output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") @output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") @output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts elsif @action == REMOVE filesToDelete = Array.new # Check that the files we're trying to delete actually exist. if File.file?(filename) filesToDelete.push(filename) @output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end if File.file?(filenameTest) filesToDelete.push(filenameTest) @output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end # If helper files don't exist, abandon ship! if filesToDelete.empty? self.error("The file \x1B[35m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m doesn't exist.") end @output.push('') @output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") unless filesToDelete.empty? filesToDelete.each { |file| @output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") # Remove file from Git. system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1") FileUtils.rm_rf(file) } end @output.push('') self.flushBuffer end self.runUnitTests end # IF CREATE: Scans the route and creates all the files (that don't exist yet) along the way. # Has ability to create nested paths (IE: if only '/dashboard' exists you can still create '/dashboard/messages/new'). # IF REMOVE: Scans ONLY the last directory in the route and removes all the files recursively (if they exist). def createRoute baseDirs = Array[ "#{@pathToPhp}helpers/", "#{@pathToTest}helpers/", "#{@pathToTest}controllers/", "#{@pathToPhp}controllers/", "#{@pathToPhp}views/", "#{@pathToDev}", "#{@pathToMin}" ] routeCount = 0 subDir = '' subDirs = Array.new filename = '' @route.split('/').each { |routeParameter| routeCount = routeCount + 1 subDir = "#{subDir}#{routeParameter}/" filename = "#{filename}#{routeParameter.slice(0, 1).capitalize + routeParameter.slice(1..-1)}" # If this is a 'remove' run, only spring to life once we're on the last loop (if that makes sense). # We don't want to be deleting recursively.. if @action == REMOVE && routeCount < @route.split('/').size next end pseudoOutput = Array.new pseudoPaths = Array.new pseudoFiles = Array.new baseDirs.each { |dir| dir = "#{dir}#{subDir}" # If deleting, this checks if there are any FURTHER files/directories deeper in the 'route'. # If so, adds them to an Array for later checking. if @action == REMOVE subFilesFound = Dir.glob("#{dir}**/*") unless subFilesFound.empty? subDirs.concat(subFilesFound) end end if dir == "#{@pathToPhp}helpers/#{subDir}" || dir == "#{@pathToTest}helpers/#{subDir}" if (@action == CREATE && !File.directory?(dir)) || (@action == REMOVE && File.directory?(dir)) pseudoOutput.push(" \x1B[32m#{dir.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") pseudoPaths.push(dir) end else files = Array.new case dir when "#{@pathToPhp}controllers/#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.php") when "#{@pathToPhp}views/#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.phtml") when "#{@pathToDev}#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.less") files.push("#{dir}#{@type.capitalize}_#{filename}.js") when "#{@pathToMin}#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.min.js") when "#{@pathToTest}controllers/#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}Test.php") else self.error('Path not found.') end files.each { |file| if (@action == CREATE && !File.file?(file)) || ((@action == REMOVE && File.file?(file)) || (@action == REMOVE && File.directory?(File.dirname(file)))) pseudoFiles.push(file) pseudoPaths.push(File.dirname(file)) fileCount = 0 fileDisplay = '' file.split('/').each { |filePart| fileCount = fileCount + 1 if fileCount < file.split('/').length fileDisplay = "#{fileDisplay}/#{filePart}" else fileDisplay = "#{fileDisplay}/\x1B[36m#{filePart}\x1B[0m" end } # Remove preceeding slash (/) as a result of above loop.. fileDisplay[0] = '' pseudoOutput.push(" \x1B[33m#{fileDisplay.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end } end } pseudoPaths.uniq pseudoFiles.uniq unless pseudoPaths.empty? @paths.concat(pseudoPaths) end unless pseudoFiles.empty? @files.concat(pseudoFiles) end unless pseudoPaths.empty? && pseudoFiles.empty? pseudoOutput.unshift(" \x1B[90m#{@type.upcase}\x1B[0m => \x1B[35m#{subDir[0..-2]}\x1B[0m") pseudoOutput.push('') @output.concat(pseudoOutput) end } if @paths.empty? && @files.empty? if @action == CREATE self.error("The route: \x1B[35m#{@route}\x1B[0m already exists..") elsif @action == REMOVE self.error("The route: \x1B[35m#{@route}\x1B[0m doesn't exist..") end else if @action == CREATE @output.unshift("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") elsif @action == REMOVE @output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n") end end # If we're deleting stuff, check if there are subPaths (past the point we're deleting from). if @action == REMOVE && !subDirs.empty? subFiles = Array.new subPaths = Array.new pseudoOutput = Array.new subDirs.each { |subFile| if File.directory?(subFile) unless inArray(@paths, subFile) subPaths.push(subFile) end elsif File.file?(subFile) unless inArray(@files, subFile) subFiles.push(subFile) end end } unless subPaths.empty? && subFiles.empty? subPaths.each { |path| pseudoOutput.push(" \x1B[90m#{path.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") } subFiles.each { |file| pseudoOutput.push(" \x1B[0m#{file.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") } @paths.concat(subPaths) @files.concat(subFiles) @output.push("\x1B[41m NOTICE \x1B[0m\x1B[90m The following files/directories will also be removed:\n") @output.concat(pseudoOutput) @output.push('') end end self.processRoute end # The final function which does all the processing. If errors are present, no processing will be done. def processRoute if @action == CREATE system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts unless @files.empty? && @paths.empty? NimzoRewriter.new(@type) end elsif @action == REMOVE system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") unless @files.empty? @files.each { |file| @output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") # Remove file from Git. system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1") FileUtils.rm_rf(file) FileUtils.rm_rf(File.dirname(file)) } end unless @paths.empty? @paths.each { |path| @output.push("\x1B[31mRemoved: #{path.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") FileUtils.rm_rf(path) } end @output.push('') self.flushBuffer unless @files.empty? && @paths.empty? NimzoRewriter.new(@type) end end self.runUnitTests end # Run (system) unit tests. def runUnitTests puts "\x1B[45m SYSTEM \x1B[0m Initializing tests...\n\n" system('phpunit --bootstrap /Users/Albert/Repos/Nimzo/tests-php/bin/PHPUnit_Bootstrap.php --no-configuration --colors --group System /Users/Albert/Repos/Nimzo/tests-php') end # Aborts the script. def abandonShip(abortTxt = " \x1B[90mScript aborted.\x1B[0m") unless abortTxt.nil? puts abortTxt end puts exit end # Confirmation message. Returns and continues script on 'y' or 'Y'.. exits on anythng else. def confirm(confirmTxt = "\x1B[90mContinue? [y/n]\x1B[0m => ?", abortTxt = nil) STDOUT.flush print confirmTxt continue = STDIN.gets.chomp if continue != 'y' && continue != 'Y' self.abandonShip(abortTxt) end end # If an error occurs, it's added to the @OUTPUT array and if 'exit' flag set to TRUE, # the script goes straight to run & subsequently displays output & dies. # @param text def error(text = '') @output.push("\x1B[41m ERROR \x1B[0m #{text}") self.flushBuffer(true) end # Flushes the output buffer. def flushBuffer(exit = false) unless @output.empty? puts @output.each { |message| puts "#{message}\x1B[0m" } if exit self.abandonShip end @output = Array.new end end # Log something to the output buffer. def output(text = '') @output.push(text) end end NimzoCreateRemove.new(ARGV[0], ARGV[1], ARGV[2], ARGV[3]) Minor fix, removed &&'s require '/Users/Albert/Repos/Scripts/ruby/lib/utilities.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-maker.rb' require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-rewriter.rb' class NimzoCreateRemove LIB = 'lib' CREATE = 'create' REMOVE = 'remove' SCRIPT = 'script' SLEEK = 'sleek' # The point of entry! # @param route # @param type # @param action def initialize(type, route, action, helper = nil) @type = type.downcase @route = route.sub(/^[\/]*/, '').sub(/(\/)+$/, '').squeeze('/') @action = action.downcase @helper = helper @errors = false @output = Array.new @pathToRepo = $PATH_TO_REPO @pathToPhp = "#{@pathToRepo}/httpdocs/private/#{@type}/" @pathToDev = "#{@pathToRepo}/httpdocs/public/dev/#{@type}/" @pathToMin = "#{@pathToRepo}/httpdocs/public/min/#{@type}/" @pathToTest = "#{@pathToRepo}/tests-php/private/#{@type}/" @paths = Array.new @files = Array.new self.validateParameters if @type == LIB || @type == SCRIPT self.createLibScript elsif @type == SLEEK self.creatSleekClass else if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type) self.createHelper else self.createRoute end end end # Validate the input parameters def validateParameters # Make sure the particular controller type is valid. # This error cannot be reached through incorrect user input. unless inArray(%w(page pagehelper lib script sleek modal modalhelper overlay overlayhelper system systemhelper widget widgethelper), @type) self.error("\x1B[33m#{@type.upcase}\x1B[0m is not a valid type. There is an error in your bash script, not your input.") end # Make sure the particular action is valid. # This error cannot be reached through incorrect user input. unless inArray([CREATE, REMOVE], @action) self.error("\x1B[33m#{@action}\x1B[0m is not a valid action. There is an error in your bash script, not your input.") end if @type == LIB || @type == SCRIPT || @type == SLEEK # Make sure the route consists of a parent directory and a classname unless @route.include?('/') self.error("You must specify a \x1B[33mfolder\x1B[0m and a \x1B[33mclassname\x1B[0m (IE: core/AjaxRequest)") end # If more than 1 slash is present, this cuts it down to only 1. Everything after the 2nd will be ommited. # IE: 'something/to/create' becomes 'something/to'. # Also capitalizes the 2nd part & removes file extension (if exists) routeSplit = @route.split('/') className = File.basename(routeSplit[1], File.extname(routeSplit[1])) className[0] = className.upcase[0..0] @route = "#{routeSplit[0].downcase}/#{className}" # Make sure folder doesn't start with following values. These will just create confusion. if inArray(%w(bin lib script scripts sleek), routeSplit[0], true) self.error("Namespace/preceeding folder shouldn't be \x1B[33m#{routeSplit[0].upcase}\x1B[0m due to possible confusion.") end # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@route.gsub('/', '')) self.error("\x1B[33mFolder\x1B[0m and a \x1B[33mclassname\x1B[0m must be alphanumeric and seperated by a slash ('/'). You passed: \x1B[33m#{@route}\x1B[0m") end if @type == SLEEK # Make sure all SLEEK classes are prefixed with 'Sleek' if routeSplit[1][0..4].downcase != 'sleek' self.error("Classes within this namespace must have prefix \x1B[35m'Sleek'\x1B[0m. You passed: \x1B[33m #{routeSplit[1]}\x1B[0m") end end else # Make sure route doesn't start with API or AJAX routeSplit = @route.split('/') if inArray(%w(api ajax script), routeSplit[0], true) self.error("Request route cannot start with \x1B[33m#{routeSplit[0]}\x1B[0m as these are parameters the system uses.") end # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@route.gsub('/', '')) self.error("Route parameters must be alphanumeric and seperated by slashes ('/'). You passed: \x1B[33m#{@route}\x1B[0m") end # Make sure that the FIRST character of ANY route parameter is a letter, not a number. @route.split('/').each { |routeParameter| if (routeParameter[0, 1] =~ /[A-Za-z]/) != 0 self.error("Route parameters cannot start with a digit (IE: 0-9). You passed: \x1B[33m#{@route}\x1B[0m") end } # Make sure the helper parameter is correct (if this is a 'helper' run) if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type) # Make sure @helper is not nil if @helper.nil? || @helper == '' self.error('@helper variable is nil or not set.') end @helper = File.basename(@helper, File.extname(@helper)) @helper[0] = @helper.upcase[0..0] # Make sure helper is alphanumeric. # Make sure that ALL characters within the route are AlphaNumeric. unless isAlphaNumeric(@helper) self.error("Helper name must be alphanumeric. You passed: \x1B[33m#{@helper}\x1B[0m") end end end end # Creates a helper class. def createHelper case @type when 'pagehelper' @type = 'page' when 'modalhelper' @type = 'modal' when 'overlayhelper' @type = 'overlay' when 'systemhelper' @type = 'system' when 'widgethelper' @type = 'widget' else self.error('Type not supported.') end helperPath = "#{$PATH_TO_PHP}#{@type}/helpers/#{@route}/" helperPathTest = "#{$PATH_TO_TESTS}#{@type}/helpers/#{@route}/" helperFile = "#{helperPath}#{@helper}.php" helperFileTest = "#{helperPathTest}#{@helper}Test.php" if @action == CREATE # Check that the helper paths even exist. unless File.directory?(helperPath) self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m") end unless File.directory?(helperPathTest) self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m") end # Now check that the helper files DON'T exist. if File.file?(helperFile) self.error("The file \x1B[33m#{helperFile}\x1B[0m already exists.") end if File.file?(helperFileTest) self.error("The file \x1B[33m#{helperFileTest}\x1B[0m already exists.") end @files.push(helperFile) @files.push(helperFileTest) @output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") @output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") @output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts elsif @action == REMOVE filesToDelete = Array.new # Check that the helper files we're trying to delete exist. if File.file?(helperFile) filesToDelete.push(helperFile) @output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end if File.file?(helperFileTest) filesToDelete.push(helperFileTest) @output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end # If helper files don't exist, abandon ship! if filesToDelete.empty? self.error("The helper \x1B[35m#{@helper}\x1B[0m doesn't exist for \x1B[44m #{@type.capitalize} \x1B[0m \x1B[35m#{@route}\x1B[0m") end @output.push('') @output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") unless filesToDelete.empty? filesToDelete.each { |file| @output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") # Remove file from Git. system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1") FileUtils.rm_rf(file) # When deleting the last file in a direcotry, Ruby for some stupid reason deletes # the parent directory as well. This in turn crashed the unit tests so instead of trying to # figure this out, I'm just going to check & re-create the directory if it's been wiped. Easy peasy. dir = File.dirname(file) unless File.directory?(dir) FileUtils::mkdir_p(dir) end } end @output.push('') self.flushBuffer end self.runUnitTests end # Create Sleek classes + tests def creatSleekClass routeSplit = @route.split('/') if routeSplit.size > 2 self.error('Size of split route should not be greater than 2!') end pathName = routeSplit[0].downcase className = routeSplit[1] className[0] = className[0..0].upcase filename = "#{$PATH_TO_PHP}lib/sleek/library/#{pathName}/#{className}.php" filenameTest = "#{$PATH_TO_TESTS}lib/sleek/library/#{pathName}/#{className}Test.php" if @action == CREATE # Make sure the files don't already exist. # The last thing we want to do is overwrite files. if File.file?(filename) self.error("File already exists: \x1B[33m#{filename}\x1B[0m") exit elsif File.file?(filenameTest) self.error("File already exists: \x1B[33m#{filenameTest}\x1B[0m") exit end @files.push(filename) @files.push(filenameTest) @output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") @output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") @output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts elsif @action == REMOVE # @todo REMOVE THIS puts 'REMOVE CODE GOES HERE!' exit end self.runUnitTests end # Creates a class within the /lib directory + also creates the UNIT Test boiler plate. def createLibScript routeSplit = @route.split('/') filename = '' filenameTest ='' if @type == LIB filename = "#{$PATH_TO_PHP}lib/#{routeSplit[0]}/#{routeSplit[1]}.php" filenameTest = "#{$PATH_TO_TESTS}lib/#{routeSplit[0]}/#{routeSplit[1]}Test.php" elsif @type == SCRIPT filename = "#{$PATH_TO_PHP}script/#{routeSplit[0]}/#{routeSplit[1]}.php" filenameTest = "#{$PATH_TO_TESTS}script/#{routeSplit[0]}/#{routeSplit[1]}Test.php" else self.error('Type is not supported.') end if @action == CREATE # Make sure the files don't already exist. # The last thing we want to do is overwrite files. if File.file?(filename) self.error("File already exists: \x1B[33m#{filename}\x1B[0m") exit elsif File.file?(filenameTest) self.error("File already exists: \x1B[33m#{filenameTest}\x1B[0m") exit end @files.push(filename) @files.push(filenameTest) @output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") @output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") @output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts elsif @action == REMOVE filesToDelete = Array.new # Check that the files we're trying to delete actually exist. if File.file?(filename) filesToDelete.push(filename) @output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end if File.file?(filenameTest) filesToDelete.push(filenameTest) @output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end # If helper files don't exist, abandon ship! if filesToDelete.empty? self.error("The file \x1B[35m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m doesn't exist.") end @output.push('') @output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n") system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") unless filesToDelete.empty? filesToDelete.each { |file| @output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") # Remove file from Git. system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1") FileUtils.rm_rf(file) } end @output.push('') self.flushBuffer end self.runUnitTests end # IF CREATE: Scans the route and creates all the files (that don't exist yet) along the way. # Has ability to create nested paths (IE: if only '/dashboard' exists you can still create '/dashboard/messages/new'). # IF REMOVE: Scans ONLY the last directory in the route and removes all the files recursively (if they exist). def createRoute baseDirs = Array[ "#{@pathToPhp}helpers/", "#{@pathToTest}helpers/", "#{@pathToTest}controllers/", "#{@pathToPhp}controllers/", "#{@pathToPhp}views/", "#{@pathToDev}", "#{@pathToMin}" ] routeCount = 0 subDir = '' subDirs = Array.new filename = '' @route.split('/').each { |routeParameter| routeCount = routeCount + 1 subDir = "#{subDir}#{routeParameter}/" filename = "#{filename}#{routeParameter.slice(0, 1).capitalize + routeParameter.slice(1..-1)}" # If this is a 'remove' run, only spring to life once we're on the last loop (if that makes sense). # We don't want to be deleting recursively.. if @action == REMOVE && routeCount < @route.split('/').size next end pseudoOutput = Array.new pseudoPaths = Array.new pseudoFiles = Array.new baseDirs.each { |dir| dir = "#{dir}#{subDir}" # If deleting, this checks if there are any FURTHER files/directories deeper in the 'route'. # If so, adds them to an Array for later checking. if @action == REMOVE subFilesFound = Dir.glob("#{dir}**/*") unless subFilesFound.empty? subDirs.concat(subFilesFound) end end if dir == "#{@pathToPhp}helpers/#{subDir}" || dir == "#{@pathToTest}helpers/#{subDir}" if (@action == CREATE && !File.directory?(dir)) || (@action == REMOVE && File.directory?(dir)) pseudoOutput.push(" \x1B[32m#{dir.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") pseudoPaths.push(dir) end else files = Array.new case dir when "#{@pathToPhp}controllers/#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.php") when "#{@pathToPhp}views/#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.phtml") when "#{@pathToDev}#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.less") files.push("#{dir}#{@type.capitalize}_#{filename}.js") when "#{@pathToMin}#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}.min.js") when "#{@pathToTest}controllers/#{subDir}" files.push("#{dir}#{@type.capitalize}_#{filename}Test.php") else self.error('Path not found.') end files.each { |file| if (@action == CREATE && !File.file?(file)) || ((@action == REMOVE && File.file?(file)) || (@action == REMOVE && File.directory?(File.dirname(file)))) pseudoFiles.push(file) pseudoPaths.push(File.dirname(file)) fileCount = 0 fileDisplay = '' file.split('/').each { |filePart| fileCount = fileCount + 1 if fileCount < file.split('/').length fileDisplay = "#{fileDisplay}/#{filePart}" else fileDisplay = "#{fileDisplay}/\x1B[36m#{filePart}\x1B[0m" end } # Remove preceeding slash (/) as a result of above loop.. fileDisplay[0] = '' pseudoOutput.push(" \x1B[33m#{fileDisplay.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") end } end } pseudoPaths.uniq pseudoFiles.uniq unless pseudoPaths.empty? @paths.concat(pseudoPaths) end unless pseudoFiles.empty? @files.concat(pseudoFiles) end unless pseudoPaths.empty? && pseudoFiles.empty? pseudoOutput.unshift(" \x1B[90m#{@type.upcase}\x1B[0m => \x1B[35m#{subDir[0..-2]}\x1B[0m") pseudoOutput.push('') @output.concat(pseudoOutput) end } if @paths.empty? && @files.empty? if @action == CREATE self.error("The route: \x1B[35m#{@route}\x1B[0m already exists..") elsif @action == REMOVE self.error("The route: \x1B[35m#{@route}\x1B[0m doesn't exist..") end else if @action == CREATE @output.unshift("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n") elsif @action == REMOVE @output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n") end end # If we're deleting stuff, check if there are subPaths (past the point we're deleting from). if @action == REMOVE && !subDirs.empty? subFiles = Array.new subPaths = Array.new pseudoOutput = Array.new subDirs.each { |subFile| if File.directory?(subFile) unless inArray(@paths, subFile) subPaths.push(subFile) end elsif File.file?(subFile) unless inArray(@files, subFile) subFiles.push(subFile) end end } unless subPaths.empty? && subFiles.empty? subPaths.each { |path| pseudoOutput.push(" \x1B[90m#{path.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") } subFiles.each { |file| pseudoOutput.push(" \x1B[0m#{file.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") } @paths.concat(subPaths) @files.concat(subFiles) @output.push("\x1B[41m NOTICE \x1B[0m\x1B[90m The following files/directories will also be removed:\n") @output.concat(pseudoOutput) @output.push('') end end self.processRoute end # The final function which does all the processing. If errors are present, no processing will be done. def processRoute if @action == CREATE system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") puts NimzoFileMaker.new(@type, @paths, @files, ' ') puts unless @files.empty? && @paths.empty? NimzoRewriter.new(@type) end elsif @action == REMOVE system ('clear') self.flushBuffer self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m") unless @files.empty? @files.each { |file| @output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") # Remove file from Git. system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1") FileUtils.rm_rf(file) FileUtils.rm_rf(File.dirname(file)) } end unless @paths.empty? @paths.each { |path| @output.push("\x1B[31mRemoved: #{path.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m") FileUtils.rm_rf(path) } end @output.push('') self.flushBuffer unless @files.empty? && @paths.empty? NimzoRewriter.new(@type) end end self.runUnitTests end # Run (system) unit tests. def runUnitTests puts "\x1B[45m SYSTEM \x1B[0m Initializing tests...\n\n" system('phpunit --bootstrap /Users/Albert/Repos/Nimzo/tests-php/bin/PHPUnit_Bootstrap.php --no-configuration --colors --group System /Users/Albert/Repos/Nimzo/tests-php') end # Aborts the script. def abandonShip(abortTxt = " \x1B[90mScript aborted.\x1B[0m") unless abortTxt.nil? puts abortTxt end puts exit end # Confirmation message. Returns and continues script on 'y' or 'Y'.. exits on anythng else. def confirm(confirmTxt = "\x1B[90mContinue? [y/n]\x1B[0m => ?", abortTxt = nil) STDOUT.flush print confirmTxt continue = STDIN.gets.chomp if continue != 'y' && continue != 'Y' self.abandonShip(abortTxt) end end # If an error occurs, it's added to the @OUTPUT array and if 'exit' flag set to TRUE, # the script goes straight to run & subsequently displays output & dies. # @param text def error(text = '') @output.push("\x1B[41m ERROR \x1B[0m #{text}") self.flushBuffer(true) end # Flushes the output buffer. def flushBuffer(exit = false) unless @output.empty? puts @output.each { |message| puts "#{message}\x1B[0m" } if exit self.abandonShip end @output = Array.new end end # Log something to the output buffer. def output(text = '') @output.push(text) end end NimzoCreateRemove.new(ARGV[0], ARGV[1], ARGV[2], ARGV[3])
require "matrix/version" module Matrix # The current website ref. Used for verification of rb systems. Url = "https://github.com/Team-Aqua/Matrix-Library/" end # General code convention in this manner - generate documentation via 'rdoc lib'. class TwoDMatrix # The current website ref. Used for verification of rb systems. Url = "https://github.com/Team-Aqua/Matrix-Library/" # Blank setup; setup module. def initialize() @row_ptr = nil @col_ind = nil @val = nil end # Builds when given a 2d array - to be true CSR conversion def build(array) # assume this array is 2d eg. [0 0 2] [1 0 2] [1 0 0] if depth(array) == 2 # 2d verification puts "Array dim is correct.\nBuilding CSR format." # sample design # 1. set col_ind = 0 (0/1/2), row_ptr = 0 # 2. identify the dimensions of the array (3x3, 2x4, etc.) store row_val = row# and col_val = col# end end # Code taken from http://stackoverflow.com/questions/9545613/getting-dimension-of-multidimensional-array-in-ruby def depth(array) return 0 if array.class != Array result = 1 array.each do |sub_a| if sub_a.class == Array dim = depth(sub_a) result = dim + 1 if dim + 1 > result end end return result end # dummy method - used by Ruby to setup 2d array init def demo_show(array) # Loop over each row array. values = array values.each do |x| # Loop over each cell in the row. x.each do |cell| puts cell end # End of row. puts "--" end end # dummy method - used by Ruby to develop subarray by index def demo_by_index(array) # This is an irregular 2D array (a jagged array). values = array # Loop over indexes. values.each_index do |i| # Get subarray and loop over its indexes also. subarray = values[i] subarray.each_index do |x| # Display the cell. puts String(i) << " " << String(x) << "... " << values[i][x] end end end end syntax cleanup require "matrix/version" module Matrix # The current website ref. Used for verification of rb systems. Url = "https://github.com/Team-Aqua/Matrix-Library/" end # General code convention in this manner - generate documentation via 'rdoc lib'. class TwoDMatrix # The current website ref. Used for verification of rb systems. Url = "https://github.com/Team-Aqua/Matrix-Library/" # Blank setup; setup module. def initialize() @row_ptr = nil @col_ind = nil @val = nil end # Builds when given a 2d array - to be true CSR conversion def build_from_array(array) # assume this array is 2d eg. [0 0 2] [1 0 2] [1 0 0] if depth(array) == 2 # 2d verification puts "Array dim is correct.\nBuilding CSR format." # sample design # 1. set col_ind = 0 (0/1/2), row_ptr = 0 # 2. identify the dimensions of the array (3x3, 2x4, etc.) store row_val = row# and col_val = col# # 3. check the first nonzero point and check its location; fill as necessary. # 4. repeat and clean end end # Builds array using user-generated CSR values def build_from_csr(row_ptr, col_ind, val, col_siz, row_siz) # generate end # Identifies the 'column' value of an array (eg. the number of entries in a column) # Todo: optimize system for O(cn), if possible def max_col(array) values = array max_count = 0 # Loop over indexes. values.each_index do |i| counter = 0 # Get subarray and loop over its indexes also. subarray = values[i] subarray.each_index do |x| counter += 1 end if counter > max_count max_count = counter end end return max_count end # Identifies the 'row' value of an array (eg. the number of entries in a row) def max_row(array) values = array max_count = 0 # Loop over indexes. values.each_index do |i| # Get subarray and loop over its indexes also. max_count += 1 end return max_count end def dimensions(array) column = max_col(array) row = max_row(array) puts "Dimensions, by column x row, are #{column} x #{row}" end # Code taken from http://stackoverflow.com/questions/9545613/getting-dimension-of-multidimensional-array-in-ruby def depth(array) return 0 if array.class != Array result = 1 array.each do |sub_a| if sub_a.class == Array dim = depth(sub_a) result = dim + 1 if dim + 1 > result end end return result end # dummy method - used by Ruby to setup 2d array init def demo_show(array) # Loop over each row array. values = array values.each do |x| # Loop over each cell in the row. x.each do |cell| puts cell end # End of row. puts "--" end end # dummy method - used by Ruby to develop subarray by index def demo_by_index(array) # This is an irregular 2D array (a jagged array). values = array # Loop over indexes. values.each_index do |i| # Get subarray and loop over its indexes also. subarray = values[i] subarray.each_index do |x| # Display the cell. puts String(i) << " " << String(x) << "... " << values[i][x] end end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mayhem/rails/version' Gem::Specification.new do |spec| spec.name = 'mayhem-rails' spec.version = Mayhem::Rails::VERSION spec.authors = ['Matthew Hassfurder'] spec.email = ['sephonicus@gmail.com'] spec.description = 'Mayhem is a tool for sowing discord within text. Mayhem Rails makes it easy to include in a Rails project.' spec.summary = 'Mayhem for Rails.' 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_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end Add mayhem gem as a dependency # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mayhem/rails/version' Gem::Specification.new do |spec| spec.name = 'mayhem-rails' spec.version = Mayhem::Rails::VERSION spec.authors = ['Matthew Hassfurder'] spec.email = ['sephonicus@gmail.com'] spec.description = 'Mayhem is a tool for sowing discord within text. Mayhem Rails makes it easy to include in a Rails project.' spec.summary = 'Mayhem for Rails.' 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 'mayhem', '0.0.2' spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/media_magick/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['Lucas Renan', 'Rodrigo Brancher', 'Tiago Rafael Godinho'] gem.email = ['contato@lucasrenan.com', 'rbrancher@gmail.com', 'tiagogodinho3@gmail.com'] gem.description = %q{MediaMagick aims to make dealing with multimedia resources a very easy task – like magic.} gem.summary = %q{MediaMagick aims to make dealing with multimedia resources a very easy task – like magic. It wraps up robust solutions for upload, associate and display images, videos, audios and files to any model in your rails app.} gem.homepage = 'https://github.com/nudesign/media_magick' gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = 'media_magick' gem.require_paths = ['lib'] gem.version = MediaMagick::VERSION gem.add_dependency 'carrierwave', '~> 0.8.0' gem.add_dependency 'mongoid', '>= 2.7.0' gem.add_dependency 'plupload-rails', '~> 1.0.6' gem.add_dependency 'rails', '~> 3.2.0' gem.add_dependency 'mini_magick', '~> 3.6.0' gem.add_development_dependency 'rake', '~> 10.1.0' gem.add_development_dependency 'rspec-rails', '~> 2.13.2' gem.add_development_dependency 'simplecov', '~> 0.7.1' gem.add_development_dependency 'guard-rspec', '~> 3.0.2' gem.add_development_dependency 'rb-fsevent', '~> 0.9.3' end sets mongoid version '>= 2.7.0' # -*- encoding: utf-8 -*- require File.expand_path('../lib/media_magick/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ['Lucas Renan', 'Rodrigo Brancher', 'Tiago Rafael Godinho'] gem.email = ['contato@lucasrenan.com', 'rbrancher@gmail.com', 'tiagogodinho3@gmail.com'] gem.description = %q{MediaMagick aims to make dealing with multimedia resources a very easy task – like magic.} gem.summary = %q{MediaMagick aims to make dealing with multimedia resources a very easy task – like magic. It wraps up robust solutions for upload, associate and display images, videos, audios and files to any model in your rails app.} gem.homepage = 'https://github.com/nudesign/media_magick' gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = 'media_magick' gem.require_paths = ['lib'] gem.version = MediaMagick::VERSION gem.add_dependency 'carrierwave', '~> 0.8.0' gem.add_dependency 'mongoid', '>= 2.7.0' gem.add_dependency 'plupload-rails', '~> 1.0.6' gem.add_dependency 'rails', '~> 3.2.0' gem.add_dependency 'mini_magick', '~> 3.6.0' gem.add_development_dependency 'rake', '~> 10.1.0' gem.add_development_dependency 'rspec-rails', '~> 2.13.2' gem.add_development_dependency 'simplecov', '~> 0.7.1' gem.add_development_dependency 'guard-rspec', '~> 3.0.2' gem.add_development_dependency 'rb-fsevent', '~> 0.9.3' end
# # Copyright 2019 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "go" default_version "1.18.3" license "BSD-3-Clause" license_file "https://raw.githubusercontent.com/golang/go/master/LICENSE" # Defaults platform = "linux" arch = "amd64" ext = "tar.gz" if windows? platform = "windows" ext = "zip" # version_list: url=https://golang.org/dl/ filter=*.windows-amd64.zip version("1.18.3") { source sha256: "9c46023f3ad0300fcfd1e62f2b6c2dfd9667b1f2f5c7a720b14b792af831f071" } version("1.18.2") { source sha256: "41fc44109c39a98e0c3672989ac5ad205cbb5768067e099dc4fb2b75cba922cf" } version("1.17.7") { source sha256: "1b648165d62a2f5399f3c42c7e59de9f4aa457212c4ea763e1b650546fac72e2" } version("1.17.6") { source sha256: "5bf8f87aec7edfc08e6bc845f1c30dba6de32b863f89ae46553ff4bbcc1d4954" } version("1.17.5") { source sha256: "671faf99cd5d81cd7e40936c0a94363c64d654faa0148d2af4bbc262555620b9" } version("1.17.2") { source sha256: "fa6da0b829a66f5fab7e4e312fd6aa1b2d8f045c7ecee83b3d00f6fe5306759a" } version("1.17") { source sha256: "2a18bd65583e221be8b9b7c2fbe3696c40f6e27c2df689bbdcc939d49651d151" } version("1.16.3") { source sha256: "a4400345135b36cb7942e52bbaf978b66814738b855eeff8de879a09fd99de7f" } elsif mac_os_x? platform = "darwin" # version_list: url=https://golang.org/dl/ filter=*.darwin-amd64.tar.gz version("1.18.3") { source sha256: "d9dcf8fc35da54c6f259be41954783a9f4984945a855d03a003a7fd6ea4c5ca1" } version("1.18.2") { source sha256: "1f5f539ce0baa8b65f196ee219abf73a7d9cf558ba9128cc0fe4833da18b04f2" } version("1.18") { source sha256: "70bb4a066997535e346c8bfa3e0dfe250d61100b17ccc5676274642447834969" } version("1.17.7") { source sha256: "7c3d9cc70ee592515d92a44385c0cba5503fd0a9950f78d76a4587916c67a84d" } version("1.17.6") { source sha256: "874bc6f95e07697380069a394a21e05576a18d60f4ba178646e1ebed8f8b1f89" } version("1.17.5") { source sha256: "2db6a5d25815b56072465a2cacc8ed426c18f1d5fc26c1fc8c4f5a7188658264" } version("1.17.2") { source sha256: "7914497a302a132a465d33f5ee044ce05568bacdb390ab805cb75a3435a23f94" } version("1.17") { source sha256: "355bd544ce08d7d484d9d7de05a71b5c6f5bc10aa4b316688c2192aeb3dacfd1" } version("1.16.3") { source sha256: "6bb1cf421f8abc2a9a4e39140b7397cdae6aca3e8d36dcff39a1a77f4f1170ac" } else # version_list: url=https://golang.org/dl/ filter=*.linux-amd64.tar.gz version("1.18.3") { source sha256: "956f8507b302ab0bb747613695cdae10af99bbd39a90cae522b7c0302cc27245" } version("1.18.2") { source sha256: "e54bec97a1a5d230fc2f9ad0880fcbabb5888f30ed9666eca4a91c5a32e86cbc" } version("1.18") { source sha256: "e85278e98f57cdb150fe8409e6e5df5343ecb13cebf03a5d5ff12bd55a80264f" } version("1.17.7") { source sha256: "02b111284bedbfa35a7e5b74a06082d18632eff824fd144312f6063943d49259" } version("1.17.6") { source sha256: "231654bbf2dab3d86c1619ce799e77b03d96f9b50770297c8f4dff8836fc8ca2" } version("1.17.5") { source sha256: "bd78114b0d441b029c8fe0341f4910370925a4d270a6a590668840675b0c653e" } version("1.17.2") { source sha256: "f242a9db6a0ad1846de7b6d94d507915d14062660616a61ef7c808a76e4f1676" } version("1.17") { source sha256: "6bf89fc4f5ad763871cf7eac80a2d594492de7a818303283f1366a7f6a30372d" } version("1.16.3") { source sha256: "951a3c7c6ce4e56ad883f97d9db74d3d6d80d5fec77455c6ada6c1f7ac4776d2" } end source url: "https://dl.google.com/go/go#{version}.%{platform}-%{arch}.%{ext}" % { platform: platform, arch: arch, ext: ext } build do # We do not use 'sync' since we've found multiple errors with other software definitions mkdir "#{install_dir}/embedded/go" copy "#{project_dir}/go/*", "#{install_dir}/embedded/go" mkdir "#{install_dir}/embedded/bin" %w{go gofmt}.each do |bin| link "#{install_dir}/embedded/go/bin/#{bin}", "#{install_dir}/embedded/bin/#{bin}" end end Add linux.arm64 and armv6l Signed-off-by: Poornima <a7322f86f5e36d4220449142092988bf0a437d7d@users.noreply.github.com> # # Copyright 2019 Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # name "go" default_version "1.19" license "BSD-3-Clause" license_file "https://raw.githubusercontent.com/golang/go/master/LICENSE" # Defaults platform = "linux" arch = "amd64" ext = "tar.gz" if windows? platform = "windows" ext = "zip" # version_list: url=https://golang.org/dl/ filter=*.windows-amd64.zip version("1.19") { source sha256: "bcaaf966f91980d35ae93c37a8fe890e4ddfca19448c0d9f66c027d287e2823a" } version("1.18.5") { source sha256: "73753620602d4b4469770040c53db55e5dd6af2ad07ecc18f71f164c3224eaad" } version("1.18.3") { source sha256: "9c46023f3ad0300fcfd1e62f2b6c2dfd9667b1f2f5c7a720b14b792af831f071" } version("1.18.2") { source sha256: "41fc44109c39a98e0c3672989ac5ad205cbb5768067e099dc4fb2b75cba922cf" } version("1.17.7") { source sha256: "1b648165d62a2f5399f3c42c7e59de9f4aa457212c4ea763e1b650546fac72e2" } version("1.17.6") { source sha256: "5bf8f87aec7edfc08e6bc845f1c30dba6de32b863f89ae46553ff4bbcc1d4954" } version("1.17.5") { source sha256: "671faf99cd5d81cd7e40936c0a94363c64d654faa0148d2af4bbc262555620b9" } version("1.17.2") { source sha256: "fa6da0b829a66f5fab7e4e312fd6aa1b2d8f045c7ecee83b3d00f6fe5306759a" } version("1.17") { source sha256: "2a18bd65583e221be8b9b7c2fbe3696c40f6e27c2df689bbdcc939d49651d151" } version("1.16.3") { source sha256: "a4400345135b36cb7942e52bbaf978b66814738b855eeff8de879a09fd99de7f" } elsif mac_os_x? platform = "darwin" # version_list: url=https://golang.org/dl/ filter=*.darwin-amd64.tar.gz version("1.19") { source sha256: "df6509885f65f0d7a4eaf3dfbe7dda327569787e8a0a31cbf99ae3a6e23e9ea8" } version("1.18.5") { source sha256: "828eeca8b5abea3e56921df8fa4b1101380a5ebcfee10acbc8ffe7ec0bf5876b" } version("1.18.3") { source sha256: "d9dcf8fc35da54c6f259be41954783a9f4984945a855d03a003a7fd6ea4c5ca1" } version("1.18.2") { source sha256: "1f5f539ce0baa8b65f196ee219abf73a7d9cf558ba9128cc0fe4833da18b04f2" } version("1.18") { source sha256: "70bb4a066997535e346c8bfa3e0dfe250d61100b17ccc5676274642447834969" } version("1.17.7") { source sha256: "7c3d9cc70ee592515d92a44385c0cba5503fd0a9950f78d76a4587916c67a84d" } version("1.17.6") { source sha256: "874bc6f95e07697380069a394a21e05576a18d60f4ba178646e1ebed8f8b1f89" } version("1.17.5") { source sha256: "2db6a5d25815b56072465a2cacc8ed426c18f1d5fc26c1fc8c4f5a7188658264" } version("1.17.2") { source sha256: "7914497a302a132a465d33f5ee044ce05568bacdb390ab805cb75a3435a23f94" } version("1.17") { source sha256: "355bd544ce08d7d484d9d7de05a71b5c6f5bc10aa4b316688c2192aeb3dacfd1" } version("1.16.3") { source sha256: "6bb1cf421f8abc2a9a4e39140b7397cdae6aca3e8d36dcff39a1a77f4f1170ac" } elsif armhf? arch = "armv6l" # version_list: url=https://golang.org/dl/ filter=*.linux-armv6l.tar.gz version("1.19") { source sha256: "25197c7d70c6bf2b34d7d7c29a2ff92ba1c393f0fb395218f1147aac2948fb93" } version("1.18.5") { source sha256: "d5ac34ac5f060a5274319aa04b7b11e41b123bd7887d64efb5f44ead236957af" } version("1.18.3") { source sha256: "b8f0b5db24114388d5dcba7ca0698510ea05228b0402fcbeb0881f74ae9cb83b" } version("1.18.2") { source sha256: "570dc8df875b274981eaeabe228d0774985de42e533ffc8c7ff0c9a55174f697" } version("1.17.7") { source sha256: "874774f078b182fa21ffcb3878467eb5cb7e78bbffa6343ea5f0fbe47983433b" } version("1.17.6") { source sha256: "9ac723e6b41cb7c3651099a09332a8a778b69aa63a5e6baaa47caf0d818e2d6d" } version("1.17.5") { source sha256: "aa1fb6c53b4fe72f159333362a10aca37ae938bde8adc9c6eaf2a8e87d1e47de" } version("1.17.2") { source sha256: "04d16105008230a9763005be05606f7eb1c683a3dbf0fbfed4034b23889cb7f2" } version("1.17") { source sha256: "ae89d33f4e4acc222bdb04331933d5ece4ae71039812f6ccd7493cb3e8ddfb4e" } version("1.16.3") { source sha256: "0dae30385e3564a557dac7f12a63eedc73543e6da0f6017990e214ce8cc8797c" } elsif arm? arch = "arm64" # version_list: url=https://golang.org/dl/ filter=*.linux-arm64.tar.gz version("1.19") { source sha256: "efa97fac9574fc6ef6c9ff3e3758fb85f1439b046573bf434cccb5e012bd00c8" } version("1.18.5") { source sha256: "006f6622718212363fa1ff004a6ab4d87bbbe772ec5631bab7cac10be346e4f1" } version("1.18.3") { source sha256: "beacbe1441bee4d7978b900136d1d6a71d150f0a9bb77e9d50c822065623a35a" } version("1.18.2") { source sha256: "fc4ad28d0501eaa9c9d6190de3888c9d44d8b5fb02183ce4ae93713f67b8a35b" } version("1.17.7") { source sha256: "a5aa1ed17d45ee1d58b4a4099b12f8942acbd1dd09b2e9a6abb1c4898043c5f5" } version("1.17.6") { source sha256: "82c1a033cce9bc1b47073fd6285233133040f0378439f3c4659fe77cc534622a" } version("1.17.5") { source sha256: "6f95ce3da40d9ce1355e48f31f4eb6508382415ca4d7413b1e7a3314e6430e7e" } version("1.17.2") { source sha256: "a5a43c9cdabdb9f371d56951b14290eba8ce2f9b0db48fb5fc657943984fd4fc" } version("1.17") { source sha256: "01a9af009ada22122d3fcb9816049c1d21842524b38ef5d5a0e2ee4b26d7c3e7" } version("1.16.3") { source sha256: "566b1d6f17d2bc4ad5f81486f0df44f3088c3ed47a3bec4099d8ed9939e90d5d" } else # version_list: url=https://golang.org/dl/ filter=*.linux-amd64.tar.gz version("1.19") { source sha256: "464b6b66591f6cf055bc5df90a9750bf5fbc9d038722bb84a9d56a2bea974be6 " } version("1.18.5") { source sha256: "9e5de37f9c49942c601b191ac5fba404b868bfc21d446d6960acc12283d6e5f2 "} version("1.18.3") { source sha256: "956f8507b302ab0bb747613695cdae10af99bbd39a90cae522b7c0302cc27245" } version("1.18.2") { source sha256: "e54bec97a1a5d230fc2f9ad0880fcbabb5888f30ed9666eca4a91c5a32e86cbc" } version("1.18") { source sha256: "e85278e98f57cdb150fe8409e6e5df5343ecb13cebf03a5d5ff12bd55a80264f" } version("1.17.7") { source sha256: "02b111284bedbfa35a7e5b74a06082d18632eff824fd144312f6063943d49259" } version("1.17.6") { source sha256: "231654bbf2dab3d86c1619ce799e77b03d96f9b50770297c8f4dff8836fc8ca2" } version("1.17.5") { source sha256: "bd78114b0d441b029c8fe0341f4910370925a4d270a6a590668840675b0c653e" } version("1.17.2") { source sha256: "f242a9db6a0ad1846de7b6d94d507915d14062660616a61ef7c808a76e4f1676" } version("1.17") { source sha256: "6bf89fc4f5ad763871cf7eac80a2d594492de7a818303283f1366a7f6a30372d" } version("1.16.3") { source sha256: "951a3c7c6ce4e56ad883f97d9db74d3d6d80d5fec77455c6ada6c1f7ac4776d2" } end source url: "https://dl.google.com/go/go#{version}.%{platform}-%{arch}.%{ext}" % { platform: platform, arch: arch, ext: ext } build do # We do not use 'sync' since we've found multiple errors with other software definitions mkdir "#{install_dir}/embedded/go" copy "#{project_dir}/go/*", "#{install_dir}/embedded/go" mkdir "#{install_dir}/embedded/bin" %w{go gofmt}.each do |bin| link "#{install_dir}/embedded/go/bin/#{bin}", "#{install_dir}/embedded/bin/#{bin}" end end
#!/usr/bin/env ruby # Represents a branch that is being walked in a Git repository # Used to keep track of parallel branches in order to attempt # merges across different branches. Also keeps track of the most # recent commit visited in the branch as the repository is walked. class Branch attr_reader :current_head def initialize(commit) @current_head = commit end def update_head(commit) @current_head = commit end end # A list of parallel branches in a Git repository # This class is used to take care of a lot of the # logic involved in keeping track of the parallel # branches and automatically removing and adding # branches from the list. class Branches def initialize @branches = [] end # Updates the list of branches based on the next commit in the # repository. Also automatically removes branches from the list # as they're merged and adds branches to the list when they're # created. # # Inputs: # commit: The SHA1 hash of the next commit encountered while # walking the repository. # parents: A list of SHA1 hashes for the commits that are the # parents of the commit passed in as the other argument def advance(commit, parents) matching_branches = [] for branch in @branches if parents.include?(branch.current_head) matching_branches.push branch end end if matching_branches.count == 0 @branches.push Branch.new(commit) elsif matching_branches.count == 1 matching_branches[0].update_head(commit) else for matching_branch in matching_branches @branches.delete_if {|b| b.current_head.eql?(matching_branch.current_head)} end @branches.push Branch.new(commit) end end # Returns a list of the SHA1 hashes for the most recently # visited commits in each branch def get_current_heads return @branches.map {|b| b.current_head} end # Returns a list of the SHA1 hashes for the most recently # visited commits in each branch, omitting the commit # passed in as an argument # # Input: # commit: The SHA1 hash of the commit to omit def get_current_heads_except(commit) current_heads = get_current_heads() current_heads.delete(commit) return current_heads end end class Conflict attr_accessor :start attr_accessor :end attr_accessor :conflicting_commit def initialize end end # Gets a list of SHA1 hashes for the commits that are the # parents of the specified commit. # # Input: # commit: The SHA1 hash of the commit for which you want to # find parents def get_commit_parents(commit_hash) out = `git show #{commit_hash} --format="%P" --no-patch`.strip parents = out.strip.split(' ') return parents end # Determines whether or not two commits conflict with # each other by attempting to merge them. # # Input: # commit1: The SHA1 hash of one of the commits to try merging # commit2: The SHA1 hash of the other commit to try merging def do_commits_conflict?(commit1, commit2) result = false `git checkout #{commit1}` merge_output = `git merge #{commit2}` if /CONFLICT/ =~ merge_output result = true `git merge --abort` end `git clean -xdf` `git reset --hard` `git checkout .` return result end Dir.chdir ARGV[0] graph = `git log --format="%H" --graph --no-color --date-order`.split("\n").reverse branches = Branches.new updated_graph = [] commit_regex = /([0-9a-fA-F]+)$/ for row in graph commit_match = commit_regex.match row if commit_match commit_hash = commit_match.captures[0] commit_parents = get_commit_parents(commit_hash) branches.advance(commit_hash, commit_parents) other_commits = branches.get_current_heads_except(commit_hash) conflicting_commits = [] for other_commit in other_commits if do_commits_conflict?(commit_hash, other_commit) conflicting_commits.push other_commit end end new_row = "#{row} | #{conflicting_commits.join(' ')}" updated_graph.push(new_row) else updated_graph.push row end end commits_in_topological_order = [] all_commit_conflicts = {} all_parents = {} commit_regex = /([0-9a-fA-F]+) \| ?([0-9a-fA-F ]*)$/ for row in updated_graph commit_match = commit_regex.match row if commit_match commit_hash = commit_match.captures[0] commit_conflicts = commit_match.captures[1].split(' ').map {|c| c.strip} commit_parents = get_commit_parents(commit_hash) commits_in_topological_order.push commit_hash all_commit_conflicts[commit_hash] = commit_conflicts all_parents[commit_hash] = commit_parents end end conflicts = [] for commit_hash in commits_in_topological_order commit_hash commit_parents = all_parents[commit_hash] commit_conflicts = all_commit_conflicts[commit_hash] or [] parent_conflicts = [] for parent in commit_parents parent_conflicts = parent_conflicts | all_commit_conflicts[parent] end new_conflicts = Array.new(commit_conflicts) # deep copy array resolved_conflicts = Array.new(parent_conflicts) # continued_conflicts = Array.new(parent_conflicts) for parent_conflict in parent_conflicts if commit_conflicts.include? parent_conflict resolved_conflicts.delete parent_conflict # else # continued_conflicts.delete parent_conflict end end for commit_conflict in commit_conflicts if parent_conflicts.include? commit_conflict new_conflicts.delete commit_conflict end end for resolved_conflict in resolved_conflicts selected_conflicts = conflicts.select {|c| c.conflicting_commit == resolved_conflict} for conflict in selected_conflicts conflict.end = commit_hash end end for new_conflict in new_conflicts conflict = Conflict.new conflict.start = commit_hash conflict.conflicting_commit = new_conflict conflicts.push conflict end end for conflict in conflicts start_commit = conflict.start if start_commit == nil start_commit = "nil" end end_commit = conflict.end or "null" if end_commit == nil end_commit = "nil" end puts start_commit + ' ' + end_commit end Added some documentation to conflict-discovery.rb #!/usr/bin/env ruby # Usage: # ./conflict-discovery.rb [path to Git repository] > output.txt # Where [path to Git repository] is the filepath to the Git repository # that you want to find conflicts for and output.txt (or any other # name you desire) is the text file to write conflicts to. # When you run this script, it will output a lot of text to STDERR. # This text is the output of the Git commands that the script runs # and can be safely ignored. If something goes wrong, you can use the # output to see what it was and whether you can potentially fix it with # some Git kung-fu (although hopefully it won't come to that!) # Represents a branch that is being walked in a Git repository # Used to keep track of parallel branches in order to attempt # merges across different branches. Also keeps track of the most # recent commit visited in the branch as the repository is walked. class Branch attr_reader :current_head def initialize(commit) @current_head = commit end def update_head(commit) @current_head = commit end end # A list of parallel branches in a Git repository # This class is used to take care of a lot of the # logic involved in keeping track of the parallel # branches and automatically removing and adding # branches from the list. class Branches def initialize @branches = [] end # Updates the list of branches based on the next commit in the # repository. Also automatically removes branches from the list # as they're merged and adds branches to the list when they're # created. # # Inputs: # commit: The SHA1 hash of the next commit encountered while # walking the repository. # parents: A list of SHA1 hashes for the commits that are the # parents of the commit passed in as the other argument def advance(commit, parents) matching_branches = [] for branch in @branches if parents.include?(branch.current_head) matching_branches.push branch end end if matching_branches.count == 0 @branches.push Branch.new(commit) elsif matching_branches.count == 1 matching_branches[0].update_head(commit) else for matching_branch in matching_branches @branches.delete_if {|b| b.current_head.eql?(matching_branch.current_head)} end @branches.push Branch.new(commit) end end # Returns a list of the SHA1 hashes for the most recently # visited commits in each branch def get_current_heads return @branches.map {|b| b.current_head} end # Returns a list of the SHA1 hashes for the most recently # visited commits in each branch, omitting the commit # passed in as an argument # # Input: # commit: The SHA1 hash of the commit to omit def get_current_heads_except(commit) current_heads = get_current_heads() current_heads.delete(commit) return current_heads end end class Conflict attr_accessor :start attr_accessor :end attr_accessor :conflicting_commit def initialize end end # Gets a list of SHA1 hashes for the commits that are the # parents of the specified commit. # # Input: # commit: The SHA1 hash of the commit for which you want to # find parents def get_commit_parents(commit_hash) out = `git show #{commit_hash} --format="%P" --no-patch`.strip parents = out.strip.split(' ') return parents end # Determines whether or not two commits conflict with # each other by attempting to merge them. # # Input: # commit1: The SHA1 hash of one of the commits to try merging # commit2: The SHA1 hash of the other commit to try merging def do_commits_conflict?(commit1, commit2) result = false `git checkout #{commit1}` merge_output = `git merge #{commit2}` if /CONFLICT/ =~ merge_output result = true `git merge --abort` end `git clean -xdf` `git reset --hard` `git checkout .` return result end Dir.chdir ARGV[0] ___first_commit = `git rev-parse HEAD` graph = `git log --format="%H" --graph --no-color --date-order`.split("\n").reverse branches = Branches.new updated_graph = [] commit_regex = /([0-9a-fA-F]+)$/ for row in graph commit_match = commit_regex.match row if commit_match commit_hash = commit_match.captures[0] commit_parents = get_commit_parents(commit_hash) branches.advance(commit_hash, commit_parents) other_commits = branches.get_current_heads_except(commit_hash) conflicting_commits = [] for other_commit in other_commits if do_commits_conflict?(commit_hash, other_commit) conflicting_commits.push other_commit end end new_row = "#{row} | #{conflicting_commits.join(' ')}" updated_graph.push(new_row) else updated_graph.push row end end commits_in_topological_order = [] all_commit_conflicts = {} all_parents = {} commit_regex = /([0-9a-fA-F]+) \| ?([0-9a-fA-F ]*)$/ for row in updated_graph commit_match = commit_regex.match row if commit_match commit_hash = commit_match.captures[0] commit_conflicts = commit_match.captures[1].split(' ').map {|c| c.strip} commit_parents = get_commit_parents(commit_hash) commits_in_topological_order.push commit_hash all_commit_conflicts[commit_hash] = commit_conflicts all_parents[commit_hash] = commit_parents end end conflicts = [] for commit_hash in commits_in_topological_order commit_hash commit_parents = all_parents[commit_hash] commit_conflicts = all_commit_conflicts[commit_hash] or [] parent_conflicts = [] for parent in commit_parents parent_conflicts = parent_conflicts | all_commit_conflicts[parent] end new_conflicts = Array.new(commit_conflicts) # deep copy array resolved_conflicts = Array.new(parent_conflicts) # continued_conflicts = Array.new(parent_conflicts) for parent_conflict in parent_conflicts if commit_conflicts.include? parent_conflict resolved_conflicts.delete parent_conflict # else # continued_conflicts.delete parent_conflict end end for commit_conflict in commit_conflicts if parent_conflicts.include? commit_conflict new_conflicts.delete commit_conflict end end for resolved_conflict in resolved_conflicts selected_conflicts = conflicts.select {|c| c.conflicting_commit == resolved_conflict} for conflict in selected_conflicts conflict.end = commit_hash end end for new_conflict in new_conflicts conflict = Conflict.new conflict.start = commit_hash conflict.conflicting_commit = new_conflict conflicts.push conflict end end for conflict in conflicts start_commit = conflict.start if start_commit == nil start_commit = "nil" end end_commit = conflict.end or "null" if end_commit == nil end_commit = "nil" end puts start_commit + ' ' + end_commit end `git checkout #{___first_commit}`
# 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{constructable} s.version = "0.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Manuel Korfmann"] s.date = %q{2011-06-15} s.description = %q{ Adds the class macro Class#constructable to easily define what attributes a Class accepts provided as a hash to Class#new. Attributes can be configured in their behaviour in case they are not provided or are in the wrong format. Their default value can also be defined and you have granular control on how accessible your attribute is. See the documentation for Constructable::Constructable#constructable or the README for more information. } s.email = %q{manu@korfmann.info} s.extra_rdoc_files = [ "LICENSE.txt", "README.markdown" ] s.files = [ ".document", ".rvmrc", ".travis.yml", "Gemfile", "LICENSE.txt", "README.markdown", "Rakefile", "VERSION", "constructable.gemspec", "lib/constructable.rb", "lib/constructable/attribute.rb", "lib/constructable/constructor.rb", "lib/constructable/core_ext.rb", "lib/constructable/exceptions.rb", "test/constructable/test_attribute.rb", "test/constructable/test_constructable.rb", "test/constructable/test_constructor.rb", "test/helper.rb" ] s.homepage = %q{http://github.com/mkorfmann/constructable} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.6.2} s.summary = %q{Makes constructing objects through an attributes hash easier} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.0"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<yard>, [">= 0"]) else s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.0"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) end else s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.0"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) end end Regenerate gemspec for version 0.3.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{constructable} s.version = "0.3.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Manuel Korfmann"] s.date = %q{2011-06-15} s.description = %q{ Adds the class macro Class#constructable to easily define what attributes a Class accepts provided as a hash to Class#new. Attributes can be configured in their behaviour in case they are not provided or are in the wrong format. Their default value can also be defined and you have granular control on how accessible your attribute is. See the documentation for Constructable::Constructable#constructable or the README for more information. } s.email = %q{manu@korfmann.info} s.extra_rdoc_files = [ "LICENSE.txt", "README.markdown" ] s.files = [ ".document", ".rvmrc", ".travis.yml", "Gemfile", "LICENSE.txt", "README.markdown", "Rakefile", "VERSION", "constructable.gemspec", "lib/constructable.rb", "lib/constructable/attribute.rb", "lib/constructable/constructor.rb", "lib/constructable/core_ext.rb", "lib/constructable/exceptions.rb", "test/constructable/test_attribute.rb", "test/constructable/test_constructable.rb", "test/constructable/test_constructor.rb", "test/helper.rb" ] s.homepage = %q{http://github.com/mkorfmann/constructable} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.6.2} s.summary = %q{Makes constructing objects through an attributes hash easier} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.6.0"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) s.add_development_dependency(%q<yard>, [">= 0"]) else s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.0"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) end else s.add_dependency(%q<bundler>, ["~> 1.0.0"]) s.add_dependency(%q<jeweler>, ["~> 1.6.0"]) s.add_dependency(%q<simplecov>, [">= 0"]) s.add_dependency(%q<yard>, [">= 0"]) end end
############# # Application set :application, "core" set :keep_releases, 10 ######## # Stages set :stages, %w(testserver staging production) require 'capistrano/ext/multistage' ################# # Bundler support require "bundler/capistrano" ############# # RVM support # Add RVM's lib directory to the load path. $:.unshift(File.expand_path('./lib', ENV['rvm_path'])) # Load RVM's capistrano plugin. require "rvm/capistrano" set :rvm_ruby_string, '1.9.2' set :rvm_bin_path, "/usr/local/rvm/bin" set :user, "deploy" set :use_sudo, false # Repository set :scm, :git set :repository, "git@github.com:Factlink/core.git" set :deploy_to, "/applications/#{application}" set :deploy_via, :remote_cache # only fetch changes since since last ssh_options[:forward_agent] = true # If you are using Passenger mod_rails uncomment this: namespace :deploy do task :all do set_conf_path="export CONFIG_PATH=#{deploy_to}/current; export NODE_ENV=#{deploy_env};" end task :start do ; end task :stop do ; end task :restart, :roles => :app, :except => { :no_release => true } do run "touch #{File.join(current_path,'tmp','restart.txt')}" end task :check_installed_packages do run "sh #{current_release}/bin/server/check_installed_packages.sh" end task :start_recalculate do run "sh #{current_path}/bin/server/start_recalculate.sh #{deploy_env}" end task :stop_recalculate do run "sh #{current_path}/bin/server/stop_recalculate.sh" end task :start_resque do run "sh #{current_path}/bin/server/start_resque_using_monit.sh" end task :stop_resque do run "sudo /usr/sbin/monit stop resque" end task :reindex do run "cd #{current_path}; bundle exec rake sunspot:solr:reindex RAILS_ENV=#{deploy_env}" end task :curl_site do run <<-CMD curl --user deploy:sdU35-YGGdv1tv21jnen3 #{full_url} CMD end # # Only precompile if files have changed # namespace :assets do task :precompile, :roles => :web, :except => { :no_release => true } do # Only precompile if files have changed: http://www.bencurtis.com/2011/12/skipping-asset-compilation-with-capistrano/ from = source.next_revision(current_revision) if capture("cd #{latest_release} && #{source.local.log(from)} vendor/assets/ app/assets/ | wc -l").to_i > 0 run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile} else logger.info "Skipping asset pre-compilation because there were no asset changes" end end end end before 'deploy:all', 'deploy' after 'deploy:all', 'deploy:restart' after 'deploy:all', 'deploy:reindex' before 'deploy:migrate', 'deploy:stop_recalculate' before 'deploy:migrate', 'deploy:stop_resque' after 'deploy', 'deploy:migrate' after 'deploy:migrate', 'deploy:start_recalculate' after 'deploy:migrate', 'deploy:start_resque' after 'deploy:update', 'deploy:check_installed_packages' after 'deploy:check_installed_packages', 'deploy:cleanup' after 'deploy', 'deploy:curl_site' require './config/boot' Added app/backbone, app/template, Gemfile.lock and deploy files to the "should we compile assets" tool Signed-off-by: tomdev <96835dd8bfa718bd6447ccc87af89ae1675daeca@codigy.nl> ############# # Application set :application, "core" set :keep_releases, 10 ######## # Stages set :stages, %w(testserver staging production) require 'capistrano/ext/multistage' ################# # Bundler support require "bundler/capistrano" ############# # RVM support # Add RVM's lib directory to the load path. $:.unshift(File.expand_path('./lib', ENV['rvm_path'])) # Load RVM's capistrano plugin. require "rvm/capistrano" set :rvm_ruby_string, '1.9.2' set :rvm_bin_path, "/usr/local/rvm/bin" set :user, "deploy" set :use_sudo, false # Repository set :scm, :git set :repository, "git@github.com:Factlink/core.git" set :deploy_to, "/applications/#{application}" set :deploy_via, :remote_cache # only fetch changes since since last ssh_options[:forward_agent] = true # If you are using Passenger mod_rails uncomment this: namespace :deploy do task :all do set_conf_path="export CONFIG_PATH=#{deploy_to}/current; export NODE_ENV=#{deploy_env};" end task :start do ; end task :stop do ; end task :restart, :roles => :app, :except => { :no_release => true } do run "touch #{File.join(current_path,'tmp','restart.txt')}" end task :check_installed_packages do run "sh #{current_release}/bin/server/check_installed_packages.sh" end task :start_recalculate do run "sh #{current_path}/bin/server/start_recalculate.sh #{deploy_env}" end task :stop_recalculate do run "sh #{current_path}/bin/server/stop_recalculate.sh" end task :start_resque do run "sh #{current_path}/bin/server/start_resque_using_monit.sh" end task :stop_resque do run "sudo /usr/sbin/monit stop resque" end task :reindex do run "cd #{current_path}; bundle exec rake sunspot:solr:reindex RAILS_ENV=#{deploy_env}" end task :curl_site do run <<-CMD curl --user deploy:sdU35-YGGdv1tv21jnen3 #{full_url} CMD end # # Only precompile if files have changed # namespace :assets do task :precompile, :roles => :web, :except => { :no_release => true } do # Only precompile if files have changed: http://www.bencurtis.com/2011/12/skipping-asset-compilation-with-capistrano/ from = source.next_revision(current_revision) if capture("cd #{latest_release} && #{source.local.log(from)} vendor/assets/ app/assets/ app/backbone/ app/templates/ Gemfile.lock config/deploy.rb config/deploy/ | wc -l").to_i > 0 run %Q{cd #{latest_release} && #{rake} RAILS_ENV=#{rails_env} #{asset_env} assets:precompile} else logger.info "Skipping asset pre-compilation because there were no asset changes" end end end end before 'deploy:all', 'deploy' after 'deploy:all', 'deploy:restart' after 'deploy:all', 'deploy:reindex' before 'deploy:migrate', 'deploy:stop_recalculate' before 'deploy:migrate', 'deploy:stop_resque' after 'deploy', 'deploy:migrate' after 'deploy:migrate', 'deploy:start_recalculate' after 'deploy:migrate', 'deploy:start_resque' after 'deploy:update', 'deploy:check_installed_packages' after 'deploy:check_installed_packages', 'deploy:cleanup' after 'deploy', 'deploy:curl_site' require './config/boot'
require_relative '../../spec_helper' require_relative 'fixtures/common' require_relative 'shared/closed' describe "Dir#read" do before :all do DirSpecs.create_mock_dirs end after :all do DirSpecs.delete_mock_dirs end it "returns the file name in the current seek position" do # an FS does not necessarily impose order ls = Dir.entries DirSpecs.mock_dir dir = Dir.open DirSpecs.mock_dir ls.should include(dir.read) dir.close end it "returns nil when there are no more entries" do dir = Dir.open DirSpecs.mock_dir DirSpecs.expected_paths.size.times do dir.read.should_not == nil end dir.read.should == nil dir.close end it "returns each entry successively" do dir = Dir.open DirSpecs.mock_dir entries = [] while entry = dir.read entries << entry end dir.close entries.sort.should == DirSpecs.expected_paths end platform_is_not :windows do it "returns all directory entries even when encoding conversion will fail" do dir = Dir.open(File.join(DirSpecs.mock_dir, 'special')) utf8_entries = [] begin while entry = dir.read utf8_entries << entry end ensure dir.close end old_internal_encoding = Encoding::default_internal old_external_encoding = Encoding::default_external Encoding.default_internal = Encoding::UTF_8 Encoding.default_external = Encoding::SHIFT_JIS dir = Dir.open(File.join(DirSpecs.mock_dir, 'special')) shift_jis_entries = [] begin -> { while entry = dir.read shift_jis_entries << entry end }.should_not raise_error ensure dir.close Encoding.default_internal = old_internal_encoding Encoding.default_external = old_external_encoding end shift_jis_entries.size.should == utf8_entries.size shift_jis_entries.filter { |f| f.encoding == Encoding::SHIFT_JIS }.size.should == 1 end end it_behaves_like :dir_closed, :read end Small cleanup in directory operations and tests. require_relative '../../spec_helper' require_relative 'fixtures/common' require_relative 'shared/closed' describe "Dir#read" do before :all do DirSpecs.create_mock_dirs end after :all do DirSpecs.delete_mock_dirs end it "returns the file name in the current seek position" do # an FS does not necessarily impose order ls = Dir.entries DirSpecs.mock_dir dir = Dir.open DirSpecs.mock_dir ls.should include(dir.read) dir.close end it "returns nil when there are no more entries" do dir = Dir.open DirSpecs.mock_dir DirSpecs.expected_paths.size.times do dir.read.should_not == nil end dir.read.should == nil dir.close end it "returns each entry successively" do dir = Dir.open DirSpecs.mock_dir entries = [] while entry = dir.read entries << entry end dir.close entries.sort.should == DirSpecs.expected_paths end platform_is_not :windows do it "returns all directory entries even when encoding conversion will fail" do dir = Dir.open(File.join(DirSpecs.mock_dir, 'special')) utf8_entries = [] begin while entry = dir.read utf8_entries << entry end ensure dir.close end old_internal_encoding = Encoding::default_internal old_external_encoding = Encoding::default_external Encoding.default_internal = Encoding::UTF_8 Encoding.default_external = Encoding::SHIFT_JIS shift_jis_entries = [] begin Dir.open(File.join(DirSpecs.mock_dir, 'special')) do |dir| -> { while entry = dir.read shift_jis_entries << entry end }.should_not raise_error end ensure Encoding.default_internal = old_internal_encoding Encoding.default_external = old_external_encoding end shift_jis_entries.size.should == utf8_entries.size shift_jis_entries.filter { |f| f.encoding == Encoding::SHIFT_JIS }.size.should == 1 end end it_behaves_like :dir_closed, :read end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/prime-numbers/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Andrei Ursan"] gem.email = ["ursan.andrei@gmail.com"] gem.description = %q{Prime Numbers Generator} gem.summary = %q{Simply tells if a number is prime or generates al prime numbers from a provided range} gem.homepage = "https://github.com/andreiursan/prime-numbers" gem.add_development_dependency "rspec" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "prime-numbers" gem.require_paths = ["lib"] gem.version = PrimeNumbers::VERSION end changed my email # -*- encoding: utf-8 -*- require File.expand_path('../lib/prime-numbers/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Andrei Ursan"] gem.email = ["hello@andreiursan.com"] gem.description = %q{Prime Numbers Generator} gem.summary = %q{Simply tells if a number is prime or generates al prime numbers from a provided range} gem.homepage = "https://github.com/andreiursan/prime-numbers" gem.add_development_dependency "rspec" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "prime-numbers" gem.require_paths = ["lib"] gem.version = PrimeNumbers::VERSION end
#!/usr/bin/env ruby require "rubygems" require "commander/import" program :version, "0.0.1" program :description, "Command-line tool for copying photographs from somewhere to elsewhere." default_command :copy never_trace! jpeg_extensions = %[.jpg .jpeg .jpe .jif .jfif .jfi] raw_extensions = %[.3fr .ari .arw .bay .crw .cr2 .cap .dcs .dcr .dng .drf .eip .erf .fff .iiq .k25 .kdc .mdc .mef .mos .mrw .nef .nrw .obm .orf .pef .ptx .pxn .r3d .raf .raw .rwl .rw2 .rwz .sr2 .srf .srw .x3f] video_extensions = %[.mov] command :copy do |c| c.syntax = "lajka run <source> <destination>" c.description = "Copies photographs from somewhere to elsewhere" c.action do |args, options| source = "src/**/*" dest = "dest" Dir.glob(source).each do |f| next unless File.file? f filename = File.basename f extension = File.extname(f).downcase modified_at = File.mtime f type = "MISC" if jpeg_extensions.include? extension type = "JPEG" elsif raw_extensions.include? extension type = "RAW" elsif video_extensions.include? extension type = "VIDEO" end dest_full = "#{dest}/#{type}/#{modified_at.year}/#{modified_at.strftime('%F')}" FileUtils.mkdir_p dest_full unless File.directory? dest_full FileUtils.cp f, dest_full unless File.file? "#{dest_full}/#{filename}" puts "Copied photograph #{filename} of type #{type} modified at #{modified_at.strftime('%F')}" end end end Add more video file extensions #!/usr/bin/env ruby require "rubygems" require "commander/import" program :version, "0.0.1" program :description, "Command-line tool for copying photographs from somewhere to elsewhere." default_command :copy never_trace! jpeg_extensions = %[.jpg .jpeg .jpe .jif .jfif .jfi] raw_extensions = %[.3fr .ari .arw .bay .crw .cr2 .cap .dcs .dcr .dng .drf .eip .erf .fff .iiq .k25 .kdc .mdc .mef .mos .mrw .nef .nrw .obm .orf .pef .ptx .pxn .r3d .raf .raw .rwl .rw2 .rwz .sr2 .srf .srw .x3f] video_extensions = %[.avi .mpeg .mpg .mp4 .mov .3gp .mkv] command :copy do |c| c.syntax = "lajka run <source> <destination>" c.description = "Copies photographs from somewhere to elsewhere" c.action do |args, options| source = "src/**/*" dest = "dest" Dir.glob(source).each do |f| next unless File.file? f filename = File.basename f extension = File.extname(f).downcase modified_at = File.mtime f type = "MISC" if jpeg_extensions.include? extension type = "JPEG" elsif raw_extensions.include? extension type = "RAW" elsif video_extensions.include? extension type = "VIDEO" end dest_full = "#{dest}/#{type}/#{modified_at.year}/#{modified_at.strftime('%F')}" FileUtils.mkdir_p dest_full unless File.directory? dest_full FileUtils.cp f, dest_full unless File.file? "#{dest_full}/#{filename}" puts "Copied photograph #{filename} of type #{type} modified at #{modified_at.strftime('%F')}" end end end
Pod::Spec.new do |s| s.name = 'AlgoliaSearch-Client-Swift' s.module_name = 'AlgoliaSearch' s.version = '3.0a1' s.license = 'MIT' s.summary = 'Algolia Search API Client for iOS & OS X written in Swift.' s.homepage = 'https://github.com/algolia/algoliasearch-client-swift' s.author = { 'Algolia' => 'contact@algolia.com' } s.source = { :git => 'https://github.com/algolia/algoliasearch-client-swift.git', :tag => s.version } s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.9' # By default, do not require the offline SDK. s.default_subspec = 'Online' # Online-only API client. s.subspec 'Online' do |online| # No additional dependency. # WARNING: Cocoapods complains when a subspec is empty, so we must define something additional here to keep # it satisfied. online.source_files = [ 'Source/*.swift', 'Source/Helpers/*.swift', ] end # Offline-enabled API client. s.subspec 'Offline' do |offline| offline.dependency 'AlgoliaSearchSDK-iOS' # Activate SDK-dependent code. # WARNING: Specifying the preprocessor macro is not enough; it must be added to Swift flags as well. offline.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => 'ALGOLIA_SDK=1', 'OTHER_SWIFT_FLAGS' => '-DALGOLIA_SDK' } offline.source_files = 'Source/Offline/*.swift' end end Fix OS X deployment target in pod spec The target set in the Xcode project is ignored by Cocoapods. Pod::Spec.new do |s| s.name = 'AlgoliaSearch-Client-Swift' s.module_name = 'AlgoliaSearch' s.version = '3.0a1' s.license = 'MIT' s.summary = 'Algolia Search API Client for iOS & OS X written in Swift.' s.homepage = 'https://github.com/algolia/algoliasearch-client-swift' s.author = { 'Algolia' => 'contact@algolia.com' } s.source = { :git => 'https://github.com/algolia/algoliasearch-client-swift.git', :tag => s.version } s.ios.deployment_target = '8.0' s.osx.deployment_target = '10.10' # By default, do not require the offline SDK. s.default_subspec = 'Online' # Online-only API client. s.subspec 'Online' do |online| # No additional dependency. # WARNING: Cocoapods complains when a subspec is empty, so we must define something additional here to keep # it satisfied. online.source_files = [ 'Source/*.swift', 'Source/Helpers/*.swift', ] end # Offline-enabled API client. s.subspec 'Offline' do |offline| offline.dependency 'AlgoliaSearchSDK-iOS' # Activate SDK-dependent code. # WARNING: Specifying the preprocessor macro is not enough; it must be added to Swift flags as well. offline.pod_target_xcconfig = { 'GCC_PREPROCESSOR_DEFINITIONS' => 'ALGOLIA_SDK=1', 'OTHER_SWIFT_FLAGS' => '-DALGOLIA_SDK' } offline.source_files = 'Source/Offline/*.swift' end end
# Class Warfare, Validate a Credit Card Number # I worked on this challenge with Jackie Feminella. # I spent [#] hours on this challenge. # Pseudocode # Input: Credit card number # Output: If the credit card is valid or not (true or false) # Steps: # Create a class called CreditCard # read the credit card number (variable will be called credit_card_number) #attr_reader :ccnum # initialize a method for credit_card_number # def initialize(ccnum) # @ccnum = ccnum.to_s # print ccnum # create argument argument error if ccnum is not 16 digits #check the length # write a method to separate each number (with spaces and no commas), put this in a list (array) # iterating over index to double every other digit starting at second to last. # even index numbers if going backwards # split the digits into single digits # add the digits together # check if total is divisible by 10 (modulo) # return true is cc is valid and false if not # Initial Solution # Don't forget to check on initialization for a card length # of exactly 16 digits class CreditCard attr_reader :ccnum def initialize(ccnum) @ccnum = ccnum.to_s.split('').map(&:to_i) if @ccnum.length != 16 raise ArgumentError.new("This credit card number is not 16 digits.") else puts "That's the right length!" end end def double_digit digits = @ccnum.length position = -2 while position >= -digits @ccnum[position] = @ccnum[position] * 2 position -= 2 end #p ccnum end def check_card double_digit @ccnum = ccnum.to_s.split('').map(&:to_i) #p ccnum sum = 0 @ccnum.each { |num| sum += num } #return sum if sum % 10 == 0 return true else return false end end end # Refactored Solution # Reflection Complete Credit Card - refactored & refllection # Class Warfare, Validate a Credit Card Number # I worked on this challenge with Jackie Feminella. # I spent [#] hours on this challenge. # Pseudocode # Input: Credit card number # Output: If the credit card is valid or not (true or false) # Steps: # Create a class called CreditCard # read the credit card number (variable will be called credit_card_number) #attr_reader :ccnum # initialize a method for credit_card_number # def initialize(ccnum) # @ccnum = ccnum.to_s # print ccnum # create argument argument error if ccnum is not 16 digits #check the length # write a method to separate each number (with spaces and no commas), put this in a list (array) # iterating over index to double every other digit starting at second to last. # even index numbers if going backwards # split the digits into single digits # add the digits together # check if total is divisible by 10 (modulo) # return true is cc is valid and false if not # Initial Solution # Don't forget to check on initialization for a card length # of exactly 16 digits =begin class CreditCard attr_reader :ccnum def initialize(ccnum) @ccnum = ccnum.to_s.split('').map(&:to_i) if @ccnum.length != 16 raise ArgumentError.new("This credit card number is not 16 digits.") else puts "That's the right length!" end end def double_digit digits = @ccnum.length position = -2 while position >= -digits @ccnum[position] = @ccnum[position] * 2 position -= 2 end #p ccnum end def check_card double_digit @ccnum = ccnum.to_s.split('').map(&:to_i) #p ccnum sum = 0 @ccnum.each { |num| sum += num } #return sum if sum % 10 == 0 return true else return false end end end =end # Refactored Solution class CreditCard attr_reader :ccnum def initialize(ccnum) @ccnum = ccnum.to_s raise ArgumentError.new("This credit card number is not 16 digits.") unless @ccnum.length == 16 end def check_card @ccnum = @ccnum.reverse!.split('').map!.with_index do |num, index| if index.odd? (num.to_i * 2).to_s else num end end sum = 0 @ccnum.join.split('').each { |num| sum += num.to_i } if sum % 10 == 0 true else false end end end # Reflection =begin What was the most difficult part of this challenge for you and your pair? The most difficult part for us was figuring out how to properly iterate through the array to only multiply the proper digits. We also had some trouble with conversions between strings and integers - which was difficult when performing multiplication and division operations. In our initial solution, we had to call double_digit, but did not realize at first that it needed to be called in the check_card method. What new methods did you find to help you when you refactored? For refactoring, we used the reverse, split, map, with_index, and join method. The reverse helped us reverse the order of the array (since we wanted every odd index once reversed) and we used split to separate each number into a single item in the array. Map allowed us to create a new array and iterate through it at the same time, in conjunction with with_index, we were able to search the indexes. Join allowed us to join the numbers together after they were doubled, so we could then re-split them as individual items. What concepts or learnings were you able to solidify in this challenge? I was able to solidfy the concept of being able to combine multiple Ruby methods in one line. In our initial solution, it was helpful to write out the longer loops so that we could solidfy the concepts. It was also helpful to see how it is important to keep track of when you switch between strings and integers. =end
# -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'whenever-elasticbeanstalk/version' Gem::Specification.new do |gem| gem.name = "whenever-elasticbeanstalk" gem.version = Whenever::Elasticbeanstalk::VERSION gem.authors = ["Chad McGimpsey"] gem.email = ["chad.mcgimpsey@gmail.com"] gem.description = %q{Use whenever on AWS Elastic Beanstalk} gem.summary = %q{Allows you to run cron jobs easily on one or all AWS Elastic Beanstalk instances.} gem.homepage = "" gem.add_dependency('whenever') gem.add_dependency('aws-sdk') gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] end added git repository as homepage in gemspec # -*- encoding: utf-8 -*- lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'whenever-elasticbeanstalk/version' Gem::Specification.new do |gem| gem.name = "whenever-elasticbeanstalk" gem.version = Whenever::Elasticbeanstalk::VERSION gem.authors = ["Chad McGimpsey"] gem.email = ["chad.mcgimpsey@gmail.com"] gem.description = %q{Use whenever on AWS Elastic Beanstalk} gem.summary = %q{Allows you to run cron jobs easily on one or all AWS Elastic Beanstalk instances.} gem.homepage = "https://github.com/dignoe/whenever-elasticbeanstalk" gem.add_dependency('whenever') gem.add_dependency('aws-sdk') gem.files = `git ls-files`.split($/) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.require_paths = ["lib"] end