CombinedText
stringlengths
4
3.42M
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-sitemap" spec.summary = "Automatically generate a sitemap.xml for your Jekyll site." spec.version = "0.8.1" spec.authors = ["GitHub, Inc."] spec.email = "support@github.com" spec.homepage = "https://github.com/jekyll/jekyll-sitemap" spec.licenses = ["MIT"] spec.files = `git ls-files -z`.split("\x0") 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 "jekyll", "~> 2.0" spec.add_development_dependency "jekyll-last-modified-at", "0.3.4" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "rake" spec.add_development_dependency "bundler", "~> 1.6" end Loosen Jekyll requirement for jekyll/docker-jekyll -> jekyll/beta. # coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-sitemap" spec.summary = "Automatically generate a sitemap.xml for your Jekyll site." spec.version = "0.8.1" spec.authors = ["GitHub, Inc."] spec.email = "support@github.com" spec.homepage = "https://github.com/jekyll/jekyll-sitemap" spec.licenses = ["MIT"] spec.files = `git ls-files -z`.split("\x0") 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 "jekyll", ">= 2.0" spec.add_development_dependency "jekyll-last-modified-at", "0.3.4" spec.add_development_dependency "rspec", "~> 3.0" spec.add_development_dependency "rake" spec.add_development_dependency "bundler", "~> 1.6" end
class MetacriticGames::Game extend MetacriticGames::Concerns::Nameable::ClassMethods extend MetacriticGames::Concerns::Findable::ClassMethods extend MetacriticGames::Concerns::Persistable::ClassMethods include MetacriticGames::Concerns::Persistable::InstanceMethods attr_accessor :name, :genre, :metascore, :user_score, :platform, :url @@all = [] def self.all @@all end def initialize self.platform = [] self.url = {} self.genre = [] self.metascore = {} self.user_score = {} end def add_platform(platform) platform.add_game(self) unless platform.games.include?(self) self.platform << platform unless self.platform.include?(platform) end def add_genre(genre) genre.add_game(self) unless genre.games.include?(self) self.genre << genre unless self.genre.include?(genre) end # creates the game object based on the array passed in from the controller. once the game is created, it scrapes it calls the scraper to scrape it's platform-specific page, then assigns the values and creates genre objects based off scrape data def self.create_games(game_array) game_array.each do |game| MetacriticGames::CLI.progressbar.increment if game[:platform] == "XONE" #metacritic naming for the xboxone does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Xbox One"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:XONE]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end elsif game[:platform] == "WIIU" #metacritic naming for the wii u does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Wii U"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:WIIU]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end elsif game[:platform] == "VITA" #metacritic naming for the ps vita does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "PS Vita"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:VITA]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end else platform = MetacriticGames::Platform.all.find {|platform| platform.name == game[:platform]} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end end end end # changes the key of the metacritic and user scores from the generic ":platform" to a unique platform.name key required for multiplatform releases def self.score_by_platform(game, platform) game.metascore[platform.name.to_sym] = game.metascore.delete(:platform) game.user_score[platform.name.to_sym] = game.user_score.delete(:platform) end end found bug overwriting multiplatform user and metascores. working on solution class MetacriticGames::Game extend MetacriticGames::Concerns::Nameable::ClassMethods extend MetacriticGames::Concerns::Findable::ClassMethods extend MetacriticGames::Concerns::Persistable::ClassMethods include MetacriticGames::Concerns::Persistable::InstanceMethods attr_accessor :name, :genre, :metascore, :user_score, :platform, :url @@all = [] def self.all @@all end def initialize self.platform = [] self.url = {} self.genre = [] self.metascore = {} self.user_score = {} end def add_platform(platform) platform.add_game(self) unless platform.games.include?(self) self.platform << platform unless self.platform.include?(platform) end def add_genre(genre) genre.add_game(self) unless genre.games.include?(self) self.genre << genre unless self.genre.include?(genre) end # creates the game object based on the array passed in from the controller. once the game is created, it scrapes it calls the scraper to scrape it's platform-specific page, then assigns the values and creates genre objects based off scrape data def self.create_games(game_array) game_array.each do |game| MetacriticGames::CLI.progressbar.increment if game[:platform] == "XONE" #metacritic naming for the xboxone does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Xbox One"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:XONE]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end # elsif value.fetch(:platform) == "tbd" # value[:platform] = "currently unavailable" # new_game.send(("#{key}="), value) # elsif value.fetch(:platform) == "" # value[:platform] = "currently unavailable" # new_game.send(("#{key}="), value) else binding.pry score_assignment(key,value) end end score_by_platform(new_game, platform) end elsif game[:platform] == "WIIU" #metacritic naming for the wii u does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Wii U"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:WIIU]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end elsif game[:platform] == "VITA" #metacritic naming for the ps vita does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "PS Vita"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:VITA]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end else platform = MetacriticGames::Platform.all.find {|platform| platform.name == game[:platform]} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end elsif value.fetch(:platform) == "tbd" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) elsif value.fetch(:platform) == "" value[:platform] = "currently unavailable" new_game.send(("#{key}="), value) else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end end end end # changes the key of the metacritic and user scores from the generic ":platform" to a unique platform.name key required for multiplatform releases def self.score_by_platform(game, platform) game.metascore[platform.name.to_sym] = game.metascore.delete(:platform) game.user_score[platform.name.to_sym] = game.user_score.delete(:platform) end def self.score_assignment(key, value) if key == :metascore new_game.metascore[key] = value[:platform] else new_game.user_score[key] = value[:platform] end end end
class MetacriticGames::Game extend MetacriticGames::Concerns::Nameable::ClassMethods extend MetacriticGames::Concerns::Findable::ClassMethods extend MetacriticGames::Concerns::Persistable::ClassMethods include MetacriticGames::Concerns::Persistable::InstanceMethods attr_accessor :name, :genre, :metascore, :user_score, :platform, :url @@all = [] def self.all @@all end def initialize self.platform = [] self.url = {} self.genre = [] self.metascore = {} self.user_score = {} end def add_platform(platform) # binding.pry platform.add_game(self) unless platform.games.include?(self) self.platform << platform unless self.platform.include?(platform) end def add_genre(genre) # binding.pry genre.add_game(self) unless genre.games.include?(self) self.genre << genre unless self.genre.include?(genre) end # def genre= (name) # @genre = name # genre.add_game(self) unless self.genre == nil # end def developer= (name) self.developer = name developer.add_game(self) unless self.developer == nil end def self.create_games(game_array) game_array.each do |game| if game[:platform] == "XONE" #metacritic naming for the xboxone does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Xbox One"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| new_game.send(("#{key}="), value) # new_game.("#{key}")[platform.name.to_sym] = value end score_by_platform(new_game, platform) end elsif game[:platform] == "WIIU" #metacritic naming for the wii u does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Wii U"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| new_game.send(("#{key}="), value) # new_game.("#{key}")[platform.name.to_sym] = value end score_by_platform(new_game, platform) end elsif game[:platform] == "VITA" #metacritic naming for the ps vita does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "PS Vita"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| new_game.send(("#{key}="), value) # new_game.("#{key}")[platform.name.to_sym] = value end score_by_platform(new_game, platform) end else platform = MetacriticGames::Platform.all.find {|platform| platform.name == game[:platform]} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) # binding.pry end end end end def self.score_by_platform(game, platform) game.metascore[platform.name.to_sym] = game.metascore.delete(:platform) game.user_score[platform.name.to_sym] = game.user_score.delete(:platform) end def self.assign_details(game_array) end end fixed an overwrite in the Game.create_games method main if loop class MetacriticGames::Game extend MetacriticGames::Concerns::Nameable::ClassMethods extend MetacriticGames::Concerns::Findable::ClassMethods extend MetacriticGames::Concerns::Persistable::ClassMethods include MetacriticGames::Concerns::Persistable::InstanceMethods attr_accessor :name, :genre, :metascore, :user_score, :platform, :url @@all = [] def self.all @@all end def initialize self.platform = [] self.url = {} self.genre = [] self.metascore = {} self.user_score = {} end def add_platform(platform) # binding.pry platform.add_game(self) unless platform.games.include?(self) self.platform << platform unless self.platform.include?(platform) end def add_genre(genre) # binding.pry genre.add_game(self) unless genre.games.include?(self) self.genre << genre unless self.genre.include?(genre) end # def genre= (name) # @genre = name # genre.add_game(self) unless self.genre == nil # end def developer= (name) self.developer = name developer.add_game(self) unless self.developer == nil end def self.create_games(game_array) game_array.each do |game| if game[:platform] == "XONE" #metacritic naming for the xboxone does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Xbox One"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] binding.pry MetacriticGames::Scraper.scrape_game(new_game.url[:XONE]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end elsif game[:platform] == "WIIU" #metacritic naming for the wii u does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "Wii U"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:WIIU]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end elsif game[:platform] == "VITA" #metacritic naming for the ps vita does not follow standard pattern platform = MetacriticGames::Platform.all.find {|platform| platform.name == "PS Vita"} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:VITA]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) end else platform = MetacriticGames::Platform.all.find {|platform| platform.name == game[:platform]} game.tap do |new_game| new_game = self.find_or_create_by_name(game[:name]) # binding.pry new_game.add_platform(platform) new_game.url[:"#{game[:platform]}"] = game[:url] MetacriticGames::Scraper.scrape_game(new_game.url[:"#{platform.name}"]).each do |key,value| if value.is_a? Array value.each do |genre| new_genre = MetacriticGames::Genre.create_genre(genre) new_game.add_genre(new_genre) end else new_game.send(("#{key}="), value) end end score_by_platform(new_game, platform) # binding.pry end end end end def self.score_by_platform(game, platform) game.metascore[platform.name.to_sym] = game.metascore.delete(:platform) game.user_score[platform.name.to_sym] = game.user_score.delete(:platform) end def self.assign_details(game_array) end end
# encoding: utf-8 require './lib/hero.rb' class Game STORAGE = './db/game.json'.freeze WINNERS = './db/winners.json'.freeze attr_reader :hero, :round, :award def start(params) @round = 0 wrong_input! unless params && params['message'] && params['message'] == 'game' @hero = Hero.new(params['name'], params['email']) end def save state = { hero: hero.name, email: hero.email, key: hero.key, round: round } File.open(STORAGE, 'a', encoding: 'utf-8') do |f| f.flock(File::LOCK_EX) f.puts "#{Time.now.to_i}: #{state.to_json}\n" end end def load(key) missing_key! unless key data = nil File.readlines(STORAGE, encoding: 'utf-8').each do |line| matchdata = line.match(/\A(\d+): (.+)\Z/) state = JSON.parse(matchdata[2]) data = state if state["key"].to_s == key end raise ApiError.new('Invalid key!') unless data p "Loaded saved state: #{data}" @hero = Hero.new(data['hero'], data['email'], data['key']) @round = data["round"] end def check(params) case @round.to_s when "0" assert_check = params["answer_1"] == "681" && params["answer_2"].downcase == "botev" && params["answer_3"] == "black" when "1" assert_check = params["name"] == "Chuck Norris" && params["email"] == "chuck@kicks.ass" && params["occupation"] == "ultimate hero" && params["eyes_color"].downcase == "#0000ff" && params["photo"] == "chuck.jpg" puts ' assert_check = ' + params["name"] + ' == "Chuck Norris" && ' + params["email"] + ' == "chuck@kicks.ass" && ' + params["occupation"] + ' == "ultimate hero" && ' + params["eyes_color"].downcase + ' == "#0000ff" && ' + params["photo"] + ' == "chuck.jpg"' when "2" assert_check = params["javascript-rocks"] == "36144" when "3" assert_check = params["result"] == "N189391C" else assert_check = false end p "Params: #{params.inspect}" p "Assert check: #{assert_check}" wrong_input! unless assert_check @round += 1 end def finish wrong_input! unless round == 3 record = nil if File.exists?(WINNERS) File.readlines(WINNERS, encoding: 'utf-8').each do |line| matchdata = line.match(/\A(\d+): (.+)\Z/) if matchdata data = JSON.parse(matchdata[2]) record = data if data["key"].to_s == @hero.key.to_s end end end if record @award = record["award"] else @award = get_award data = { hero: hero.name, email: hero.email, key: hero.key, award: @award } File.open(WINNERS, 'a', encoding: 'utf-8') do |f| f.flock(File::LOCK_EX) f.puts "#{Time.now.to_i}: #{data.to_json}\n" end end end private def get_award Dir.glob('images/catz/*.png')[rand(19)] end def wrong_input! raise ApiError.new("[GAME ROUND #{@round+1}] Wrong input") end def missing_key! raise ApiError.new("Game cant load due to a missing key!") end end fix catz format # encoding: utf-8 require './lib/hero.rb' class Game STORAGE = './db/game.json'.freeze WINNERS = './db/winners.json'.freeze attr_reader :hero, :round, :award def start(params) @round = 0 wrong_input! unless params && params['message'] && params['message'] == 'game' @hero = Hero.new(params['name'], params['email']) end def save state = { hero: hero.name, email: hero.email, key: hero.key, round: round } File.open(STORAGE, 'a', encoding: 'utf-8') do |f| f.flock(File::LOCK_EX) f.puts "#{Time.now.to_i}: #{state.to_json}\n" end end def load(key) missing_key! unless key data = nil File.readlines(STORAGE, encoding: 'utf-8').each do |line| matchdata = line.match(/\A(\d+): (.+)\Z/) state = JSON.parse(matchdata[2]) data = state if state["key"].to_s == key end raise ApiError.new('Invalid key!') unless data p "Loaded saved state: #{data}" @hero = Hero.new(data['hero'], data['email'], data['key']) @round = data["round"] end def check(params) case @round.to_s when "0" assert_check = params["answer_1"] == "681" && params["answer_2"].downcase == "botev" && params["answer_3"] == "black" when "1" assert_check = params["name"] == "Chuck Norris" && params["email"] == "chuck@kicks.ass" && params["occupation"] == "ultimate hero" && params["eyes_color"].downcase == "#0000ff" && params["photo"] == "chuck.jpg" puts ' assert_check = ' + params["name"] + ' == "Chuck Norris" && ' + params["email"] + ' == "chuck@kicks.ass" && ' + params["occupation"] + ' == "ultimate hero" && ' + params["eyes_color"].downcase + ' == "#0000ff" && ' + params["photo"] + ' == "chuck.jpg"' when "2" assert_check = params["javascript-rocks"] == "36144" when "3" assert_check = params["result"] == "N189391C" else assert_check = false end p "Params: #{params.inspect}" p "Assert check: #{assert_check}" wrong_input! unless assert_check @round += 1 end def finish wrong_input! unless round == 3 record = nil if File.exists?(WINNERS) File.readlines(WINNERS, encoding: 'utf-8').each do |line| matchdata = line.match(/\A(\d+): (.+)\Z/) if matchdata data = JSON.parse(matchdata[2]) record = data if data["key"].to_s == @hero.key.to_s end end end if record @award = record["award"] else @award = get_award data = { hero: hero.name, email: hero.email, key: hero.key, award: @award } File.open(WINNERS, 'a', encoding: 'utf-8') do |f| f.flock(File::LOCK_EX) f.puts "#{Time.now.to_i}: #{data.to_json}\n" end end end private def get_award Dir.glob('images/catz/*.jpg')[rand(19)] end def wrong_input! raise ApiError.new("[GAME ROUND #{@round+1}] Wrong input") end def missing_key! raise ApiError.new("Game cant load due to a missing key!") end end
=begin Arachni Copyright (c) 2010 Tasos "Zapotek" Laskos <tasos.laskos@gmail.com> This is free software; you can copy and distribute and modify this program under the term of the GPL v2.0 License (See LICENSE file for details) =end require 'typhoeus' module Arachni require Options.instance.dir['lib'] + 'typhoeus/easy' require Options.instance.dir['lib'] + 'typhoeus/hydra' require Options.instance.dir['lib'] + 'typhoeus/request' require Options.instance.dir['lib'] + 'module/utilities' require Options.instance.dir['lib'] + 'module/trainer' # # Arachni::Module::HTTP class # # Provides a simple, high-performance and thread-safe HTTP interface to modules. # # All requests are run Async (compliments of Typhoeus) # providing great speed and performance. # # === Exceptions # Any exceptions or session corruption is handled by the class.<br/> # Some are ignored, on others the HTTP session is refreshed.<br/> # Point is, you don't need to worry about it. # # @author: Tasos "Zapotek" Laskos # <tasos.laskos@gmail.com> # <zapotek@segfault.gr> # @version: 0.2.2 # class HTTP include Arachni::UI::Output include Singleton include Arachni::Module::Utilities # # @return [URI] # attr_reader :last_url # # The headers with which the HTTP client is initialized<br/> # This is always kept updated. # # @return [Hash] # attr_reader :init_headers # # The user supplied cookie jar # # @return [Hash] # attr_reader :cookie_jar attr_reader :request_count attr_reader :response_count attr_reader :trainer def initialize( ) reset end def reset opts = Options.instance # someone wants to reset us although nothing has been *set* in the first place # otherwise we'd have a url in opts return if !opts.url req_limit = opts.http_req_limit hydra_opts = { :max_concurrency => req_limit, :disable_ssl_peer_verification => true, :username => opts.url.user, :password => opts.url.password, :method => :auto, } @hydra = Typhoeus::Hydra.new( hydra_opts ) @hydra_sync = Typhoeus::Hydra.new( hydra_opts ) @hydra.disable_memoization @hydra_sync.disable_memoization @trainer = Arachni::Module::Trainer.new @trainer.http = self @init_headers = { 'cookie' => '', 'From' => opts.authed_by || '', 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent' => opts.user_agent } @opts = { :user_agent => opts.user_agent, :follow_location => false, :proxy => "#{opts.proxy_addr}:#{opts.proxy_port}", :proxy_username => opts.proxy_user, :proxy_password => opts.proxy_pass, :proxy_type => opts.proxy_type } @request_count = 0 @response_count = 0 # we'll use it to identify our requests @rand_seed = seed( ) end # # Runs Hydra (all the asynchronous queued HTTP requests) # # Should only be called by the framework # after all module threads have beed joined! # def run exception_jail { @hydra.run } end # # Queues a Tyhpoeus::Request and applies an 'on_complete' callback # on behal of the trainer. # # @param [Tyhpoeus::Request] req the request to queue # @param [Bool] async run request async? # def queue( req, async = true ) req.id = @request_count if( !async ) @hydra_sync.queue( req ) else @hydra.queue( req ) end @request_count += 1 print_debug( '------------' ) print_debug( 'Queued request.' ) print_debug( 'ID#: ' + req.id.to_s ) print_debug( 'URL: ' + req.url ) print_debug( 'Method: ' + req.method.to_s ) print_debug( 'Params: ' + req.params.to_s ) print_debug( 'Headers: ' + req.headers.to_s ) print_debug( 'Train?: ' + req.train?.to_s ) print_debug( '------------' ) req.on_complete( true ) { |res| @response_count += 1 print_debug( '------------' ) print_debug( 'Got response.' ) print_debug( 'Request ID#: ' + res.request.id.to_s ) print_debug( 'URL: ' + res.effective_url ) print_debug( 'Method: ' + res.request.method.to_s ) print_debug( 'Params: ' + res.request.params.to_s ) print_debug( 'Headers: ' + res.request.headers.to_s ) print_debug( 'Train?: ' + res.request.train?.to_s ) print_debug( '------------' ) if( req.train? ) # handle redirections if( ( redir = redirect?( res.dup ) ).is_a?( String ) ) req2 = get( redir, :remove_id => true ) req2.on_complete { |res2| @trainer.add_response( res2, true ) } if req2 else @trainer.add_response( res ) end end } exception_jail { @hydra_sync.run if !async } end # # Makes a generic request # # @param [URI] url # @param [Hash] opts # # @return [Typhoeus::Request] # def request( url, opts ) headers = opts[:headers] || {} opts[:headers] = @init_headers.dup.merge( headers ) train = opts[:train] async = opts[:async] async = true if async == nil exception_jail { req = Typhoeus::Request.new( URI.escape( url ), opts.merge( @opts ) ) req.train! if train queue( req, async ) return req } end # # Gets a URL passing the provided query parameters # # @param [URI] url URL to GET # @param [Hash] opts request options # * :params => request parameters || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # * :follow_location => follow redirects || false # # @return [Typhoeus::Request] # def get( url, opts = { } ) params = opts[:params] || {} remove_id = opts[:remove_id] train = opts[:train] follow_location = opts[:follow_location] || false async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup.merge( headers ) params = params.merge( { @rand_seed => '' } ) if !remove_id # # the exception jail function wraps the block passed to it # in exception handling and runs it # # how cool is Ruby? Seriously.... # exception_jail { # # There are cases where the url already has a query and we also have # some params to work with. Some webapp frameworks will break # or get confused...plus the url will not be RFC compliant. # # Thus we need to merge the provided params with the # params of the url query and remove the latter from the url. # cparams = params.dup curl = URI.escape( url.dup ) cparams = q_to_h( curl ).merge( cparams ) begin curl.gsub!( "?#{URI(curl).query}", '' ) if URI(curl).query rescue return end opts = { :headers => headers, :params => cparams.empty? ? nil : cparams, :follow_location => follow_location }.merge( @opts ) req = Typhoeus::Request.new( curl, opts ) req.train! if train queue( req, async ) return req } end # # Posts a form to a URL with the provided query parameters # # @param [URI] url URL to POST # @param [Hash] opts request options # * :params => request parameters || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # # @return [Typhoeus::Request] # def post( url, opts = { } ) params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup.merge( headers ) exception_jail { opts = { :method => :post, :headers => headers, :params => params, :follow_location => false }.merge( @opts ) req = Typhoeus::Request.new( url, opts ) req.train! if train queue( req, async ) return req } end # # Sends an HTTP TRACE request to "url". # # @param [URI] url URL to POST # @param [Hash] opts request options # * :params => request parameters || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # # @return [Typhoeus::Request] # def trace( url, opts = { } ) params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup.merge( headers ) exception_jail { opts = { :method => :trace, :headers => headers, :params => params, :follow_location => false }.merge( @opts ) req = Typhoeus::Request.new( url, opts ) req.train! if train queue( req, async ) return req } end # # Gets a url with cookies and url variables # # @param [URI] url URL to GET # @param [Hash] opts request options # * :params => cookies || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # # @return [Typhoeus::Request] # def cookie( url, opts = { } ) cookies = opts[:params] || {} # params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup. merge( { 'cookie' => get_cookies_str( cookies ) } ).merge( headers ) # wrap the code in exception handling exception_jail { opts = { :headers => headers, :follow_location => false, # :params => params }.merge( @opts ) req = Typhoeus::Request.new( url, opts ) req.train! if train queue( req, async ) return req } end # # Gets a url with optional url variables and modified headers # # @param [URI] url URL to GET # @param [Hash] opts request options # * :params => headers || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # # @return [Typhoeus::Request] # def header( url, opts = { } ) headers = opts[:params] || {} # params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil # wrap the code in exception handling exception_jail { orig_headers = @init_headers.clone @init_headers = @init_headers.merge( headers ) req = Typhoeus::Request.new( url, :headers => @init_headers.dup, :user_agent => @init_headers['User-Agent'], :follow_location => false, # :params => params ) req.train! if train @init_headers = orig_headers.clone queue( req, async ) return req } end def q_to_h( url ) params = {} begin query = URI( url.to_s ).query return params if !query query.split( '&' ).each { |param| k,v = param.split( '=', 2 ) params[k] = v } rescue end return params end # # Sets cookies for the HTTP session # # @param [Hash] cookies name=>value pairs # # @return [void] # def set_cookies( cookies ) @init_headers['cookie'] = '' @cookie_jar = cookies.each_pair { |name, value| @init_headers['cookie'] += "#{name}=#{value};" } end # # Returns a hash of cookies as a string (merged with the cookie-jar) # # @param [Hash] cookies name=>value pairs # # @return [string] # def get_cookies_str( cookies = { } ) jar = parse_cookie_str( @init_headers['cookie'] ) cookies.reject! { |cookie| Options.instance.exclude_cookies.include?( cookie['name'] ) } cookies = jar.merge( cookies ) str = '' cookies.each_pair { |name, value| value = '' if !value val = URI.escape( URI.escape( value ), '+;' ) str += "#{name}=#{val};" } return str end # # Converts HTTP cookies from string to Hash # # @param [String] str # # @return [Hash] # def parse_cookie_str( str ) cookie_jar = Hash.new str.split( ';' ).each { |kvp| cookie_jar[kvp.split( "=" )[0]] = kvp.split( "=" )[1] } return cookie_jar end # # Class method # # Parses netscape HTTP cookie files # # @param [String] cookie_jar the location of the cookie file # # @return [Hash] cookies in name=>value pairs # def HTTP.parse_cookiejar( cookie_jar ) cookies = Hash.new jar = File.open( cookie_jar, 'r' ) jar.each_line { |line| # skip empty lines if (line = line.strip).size == 0 then next end # skip comment lines if line[0] == '#' then next end cookie_arr = line.split( "\t" ) cookies[cookie_arr[-2]] = cookie_arr[-1] } cookies end # # Encodes and parses a URL String # # @param [String] url URL String # # @return [URI] URI object # def parse_url( url ) URI.parse( URI.encode( url ) ) end # # Checks whether or not the provided response is a custom 404 page # # @param [Typhoeus::Response] res the response to check # # @param [Bool] # def custom_404?( res ) @_404 ||= {} ap path = get_path( res.effective_url ) @_404[path] ||= {} if( !@_404[path]['file'] ) # force a 404 and grab the html body force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) @_404[path]['file'] = Typhoeus::Request.get( force_404 ).body # force another 404 and grab the html body force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) not_found2 = Typhoeus::Request.get( force_404 ).body @_404[path]['file_rdiff'] = @_404[path]['file'].rdiff( not_found2 ) end if( !@_404[path]['dir'] ) force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) + '/' @_404[path]['dir'] = Typhoeus::Request.get( force_404 ).body force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) + '/' not_found2 = Typhoeus::Request.get( force_404 ).body @_404[path]['dir_rdiff'] = @_404[path]['dir'].rdiff( not_found2 ) end return @_404[path]['dir'].rdiff( res.body ) == @_404[path]['dir_rdiff'] || @_404[path]['file'].rdiff( res.body ) == @_404[path]['file_rdiff'] end private def redirect?( res ) if loc = res.headers_hash['Location'] return loc end return res end def self.info { :name => 'HTTP' } end end end custom_404?(): removed debugging code =begin Arachni Copyright (c) 2010 Tasos "Zapotek" Laskos <tasos.laskos@gmail.com> This is free software; you can copy and distribute and modify this program under the term of the GPL v2.0 License (See LICENSE file for details) =end require 'typhoeus' module Arachni require Options.instance.dir['lib'] + 'typhoeus/easy' require Options.instance.dir['lib'] + 'typhoeus/hydra' require Options.instance.dir['lib'] + 'typhoeus/request' require Options.instance.dir['lib'] + 'module/utilities' require Options.instance.dir['lib'] + 'module/trainer' # # Arachni::Module::HTTP class # # Provides a simple, high-performance and thread-safe HTTP interface to modules. # # All requests are run Async (compliments of Typhoeus) # providing great speed and performance. # # === Exceptions # Any exceptions or session corruption is handled by the class.<br/> # Some are ignored, on others the HTTP session is refreshed.<br/> # Point is, you don't need to worry about it. # # @author: Tasos "Zapotek" Laskos # <tasos.laskos@gmail.com> # <zapotek@segfault.gr> # @version: 0.2.2 # class HTTP include Arachni::UI::Output include Singleton include Arachni::Module::Utilities # # @return [URI] # attr_reader :last_url # # The headers with which the HTTP client is initialized<br/> # This is always kept updated. # # @return [Hash] # attr_reader :init_headers # # The user supplied cookie jar # # @return [Hash] # attr_reader :cookie_jar attr_reader :request_count attr_reader :response_count attr_reader :trainer def initialize( ) reset end def reset opts = Options.instance # someone wants to reset us although nothing has been *set* in the first place # otherwise we'd have a url in opts return if !opts.url req_limit = opts.http_req_limit hydra_opts = { :max_concurrency => req_limit, :disable_ssl_peer_verification => true, :username => opts.url.user, :password => opts.url.password, :method => :auto, } @hydra = Typhoeus::Hydra.new( hydra_opts ) @hydra_sync = Typhoeus::Hydra.new( hydra_opts ) @hydra.disable_memoization @hydra_sync.disable_memoization @trainer = Arachni::Module::Trainer.new @trainer.http = self @init_headers = { 'cookie' => '', 'From' => opts.authed_by || '', 'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent' => opts.user_agent } @opts = { :user_agent => opts.user_agent, :follow_location => false, :proxy => "#{opts.proxy_addr}:#{opts.proxy_port}", :proxy_username => opts.proxy_user, :proxy_password => opts.proxy_pass, :proxy_type => opts.proxy_type } @request_count = 0 @response_count = 0 # we'll use it to identify our requests @rand_seed = seed( ) end # # Runs Hydra (all the asynchronous queued HTTP requests) # # Should only be called by the framework # after all module threads have beed joined! # def run exception_jail { @hydra.run } end # # Queues a Tyhpoeus::Request and applies an 'on_complete' callback # on behal of the trainer. # # @param [Tyhpoeus::Request] req the request to queue # @param [Bool] async run request async? # def queue( req, async = true ) req.id = @request_count if( !async ) @hydra_sync.queue( req ) else @hydra.queue( req ) end @request_count += 1 print_debug( '------------' ) print_debug( 'Queued request.' ) print_debug( 'ID#: ' + req.id.to_s ) print_debug( 'URL: ' + req.url ) print_debug( 'Method: ' + req.method.to_s ) print_debug( 'Params: ' + req.params.to_s ) print_debug( 'Headers: ' + req.headers.to_s ) print_debug( 'Train?: ' + req.train?.to_s ) print_debug( '------------' ) req.on_complete( true ) { |res| @response_count += 1 print_debug( '------------' ) print_debug( 'Got response.' ) print_debug( 'Request ID#: ' + res.request.id.to_s ) print_debug( 'URL: ' + res.effective_url ) print_debug( 'Method: ' + res.request.method.to_s ) print_debug( 'Params: ' + res.request.params.to_s ) print_debug( 'Headers: ' + res.request.headers.to_s ) print_debug( 'Train?: ' + res.request.train?.to_s ) print_debug( '------------' ) if( req.train? ) # handle redirections if( ( redir = redirect?( res.dup ) ).is_a?( String ) ) req2 = get( redir, :remove_id => true ) req2.on_complete { |res2| @trainer.add_response( res2, true ) } if req2 else @trainer.add_response( res ) end end } exception_jail { @hydra_sync.run if !async } end # # Makes a generic request # # @param [URI] url # @param [Hash] opts # # @return [Typhoeus::Request] # def request( url, opts ) headers = opts[:headers] || {} opts[:headers] = @init_headers.dup.merge( headers ) train = opts[:train] async = opts[:async] async = true if async == nil exception_jail { req = Typhoeus::Request.new( URI.escape( url ), opts.merge( @opts ) ) req.train! if train queue( req, async ) return req } end # # Gets a URL passing the provided query parameters # # @param [URI] url URL to GET # @param [Hash] opts request options # * :params => request parameters || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # * :follow_location => follow redirects || false # # @return [Typhoeus::Request] # def get( url, opts = { } ) params = opts[:params] || {} remove_id = opts[:remove_id] train = opts[:train] follow_location = opts[:follow_location] || false async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup.merge( headers ) params = params.merge( { @rand_seed => '' } ) if !remove_id # # the exception jail function wraps the block passed to it # in exception handling and runs it # # how cool is Ruby? Seriously.... # exception_jail { # # There are cases where the url already has a query and we also have # some params to work with. Some webapp frameworks will break # or get confused...plus the url will not be RFC compliant. # # Thus we need to merge the provided params with the # params of the url query and remove the latter from the url. # cparams = params.dup curl = URI.escape( url.dup ) cparams = q_to_h( curl ).merge( cparams ) begin curl.gsub!( "?#{URI(curl).query}", '' ) if URI(curl).query rescue return end opts = { :headers => headers, :params => cparams.empty? ? nil : cparams, :follow_location => follow_location }.merge( @opts ) req = Typhoeus::Request.new( curl, opts ) req.train! if train queue( req, async ) return req } end # # Posts a form to a URL with the provided query parameters # # @param [URI] url URL to POST # @param [Hash] opts request options # * :params => request parameters || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # # @return [Typhoeus::Request] # def post( url, opts = { } ) params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup.merge( headers ) exception_jail { opts = { :method => :post, :headers => headers, :params => params, :follow_location => false }.merge( @opts ) req = Typhoeus::Request.new( url, opts ) req.train! if train queue( req, async ) return req } end # # Sends an HTTP TRACE request to "url". # # @param [URI] url URL to POST # @param [Hash] opts request options # * :params => request parameters || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # # @return [Typhoeus::Request] # def trace( url, opts = { } ) params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup.merge( headers ) exception_jail { opts = { :method => :trace, :headers => headers, :params => params, :follow_location => false }.merge( @opts ) req = Typhoeus::Request.new( url, opts ) req.train! if train queue( req, async ) return req } end # # Gets a url with cookies and url variables # # @param [URI] url URL to GET # @param [Hash] opts request options # * :params => cookies || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # * :headers => HTTP request headers || {} # # @return [Typhoeus::Request] # def cookie( url, opts = { } ) cookies = opts[:params] || {} # params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil headers = opts[:headers] || {} headers = @init_headers.dup. merge( { 'cookie' => get_cookies_str( cookies ) } ).merge( headers ) # wrap the code in exception handling exception_jail { opts = { :headers => headers, :follow_location => false, # :params => params }.merge( @opts ) req = Typhoeus::Request.new( url, opts ) req.train! if train queue( req, async ) return req } end # # Gets a url with optional url variables and modified headers # # @param [URI] url URL to GET # @param [Hash] opts request options # * :params => headers || {} # * :train => force Arachni to analyze the HTML code || false # * :async => make the request async? || true # # @return [Typhoeus::Request] # def header( url, opts = { } ) headers = opts[:params] || {} # params = opts[:params] train = opts[:train] async = opts[:async] async = true if async == nil # wrap the code in exception handling exception_jail { orig_headers = @init_headers.clone @init_headers = @init_headers.merge( headers ) req = Typhoeus::Request.new( url, :headers => @init_headers.dup, :user_agent => @init_headers['User-Agent'], :follow_location => false, # :params => params ) req.train! if train @init_headers = orig_headers.clone queue( req, async ) return req } end def q_to_h( url ) params = {} begin query = URI( url.to_s ).query return params if !query query.split( '&' ).each { |param| k,v = param.split( '=', 2 ) params[k] = v } rescue end return params end # # Sets cookies for the HTTP session # # @param [Hash] cookies name=>value pairs # # @return [void] # def set_cookies( cookies ) @init_headers['cookie'] = '' @cookie_jar = cookies.each_pair { |name, value| @init_headers['cookie'] += "#{name}=#{value};" } end # # Returns a hash of cookies as a string (merged with the cookie-jar) # # @param [Hash] cookies name=>value pairs # # @return [string] # def get_cookies_str( cookies = { } ) jar = parse_cookie_str( @init_headers['cookie'] ) cookies.reject! { |cookie| Options.instance.exclude_cookies.include?( cookie['name'] ) } cookies = jar.merge( cookies ) str = '' cookies.each_pair { |name, value| value = '' if !value val = URI.escape( URI.escape( value ), '+;' ) str += "#{name}=#{val};" } return str end # # Converts HTTP cookies from string to Hash # # @param [String] str # # @return [Hash] # def parse_cookie_str( str ) cookie_jar = Hash.new str.split( ';' ).each { |kvp| cookie_jar[kvp.split( "=" )[0]] = kvp.split( "=" )[1] } return cookie_jar end # # Class method # # Parses netscape HTTP cookie files # # @param [String] cookie_jar the location of the cookie file # # @return [Hash] cookies in name=>value pairs # def HTTP.parse_cookiejar( cookie_jar ) cookies = Hash.new jar = File.open( cookie_jar, 'r' ) jar.each_line { |line| # skip empty lines if (line = line.strip).size == 0 then next end # skip comment lines if line[0] == '#' then next end cookie_arr = line.split( "\t" ) cookies[cookie_arr[-2]] = cookie_arr[-1] } cookies end # # Encodes and parses a URL String # # @param [String] url URL String # # @return [URI] URI object # def parse_url( url ) URI.parse( URI.encode( url ) ) end # # Checks whether or not the provided response is a custom 404 page # # @param [Typhoeus::Response] res the response to check # # @param [Bool] # def custom_404?( res ) @_404 ||= {} path = get_path( res.effective_url ) @_404[path] ||= {} if( !@_404[path]['file'] ) # force a 404 and grab the html body force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) @_404[path]['file'] = Typhoeus::Request.get( force_404 ).body # force another 404 and grab the html body force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) not_found2 = Typhoeus::Request.get( force_404 ).body @_404[path]['file_rdiff'] = @_404[path]['file'].rdiff( not_found2 ) end if( !@_404[path]['dir'] ) force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) + '/' @_404[path]['dir'] = Typhoeus::Request.get( force_404 ).body force_404 = path + Digest::SHA1.hexdigest( rand( 9999999 ).to_s ) + '/' not_found2 = Typhoeus::Request.get( force_404 ).body @_404[path]['dir_rdiff'] = @_404[path]['dir'].rdiff( not_found2 ) end return @_404[path]['dir'].rdiff( res.body ) == @_404[path]['dir_rdiff'] || @_404[path]['file'].rdiff( res.body ) == @_404[path]['file_rdiff'] end private def redirect?( res ) if loc = res.headers_hash['Location'] return loc end return res end def self.info { :name => 'HTTP' } end end end
require 'fast_stemmer' require 'hunt/util' module Hunt def self.configure(model) model.before_save(:index_search_terms) end module ClassMethods def search_keys @search_keys ||= [] end def searches(*keys) key(:searches, Hash) @search_keys = keys end def search(value) terms = Util.to_stemmed_words(value) return [] if terms.blank? where('searches.default' => terms) end end module InstanceMethods def search_keys self.class.search_keys end def concatted_search_values search_keys.map { |key| send(key) }.flatten.join(' ') end def index_search_terms self.searches['default'] = Util.to_stemmed_words(concatted_search_values) end end end No need for instance method, just calling class method. require 'fast_stemmer' require 'hunt/util' module Hunt def self.configure(model) model.before_save(:index_search_terms) end module ClassMethods def search_keys @search_keys ||= [] end def searches(*keys) key(:searches, Hash) @search_keys = keys end def search(value) terms = Util.to_stemmed_words(value) return [] if terms.blank? where('searches.default' => terms) end end module InstanceMethods def concatted_search_values self.class.search_keys.map { |key| send(key) }.flatten.join(' ') end def index_search_terms self.searches['default'] = Util.to_stemmed_words(concatted_search_values) end end end
module MultiRepo NAME = "git-multirepo" VERSION = "1.0.0.beta44" DESCRIPTION = "Track multiple Git repositories side-by-side." end Bumped version to beta45. module MultiRepo NAME = "git-multirepo" VERSION = "1.0.0.beta45" DESCRIPTION = "Track multiple Git repositories side-by-side." end
#!/usr/bin/env ruby # Saves all source XML data for 2007 into the directory "source". This is used to test the grammar aph-xml.rnc against $:.unshift "#{File.dirname(__FILE__)}/../lib" require 'hansard_parser' from = Date.new(2007, 1, 1) to = Date.new(2008, 1, 1) - 1 # Don't need to set 'people' parser = HansardParser.new(nil) FileUtils.mkdir_p "source" (from..to).each do |date| puts "Downloading and saving XML data for #{date}..." text = parser.hansard_xml_source_data_on_date(date, House.representatives) File.open("source/#{date}-reps.xml", 'w') {|f| f << text } if text text = parser.hansard_xml_source_data_on_date(date, House.senate) File.open("source/#{date}-senate.xml", 'w') {|f| f << text } if text end Added XML tidy #!/usr/bin/env ruby # Saves all source XML data for 2007 into the directory "source". This is used to test the grammar aph-xml.rnc against $:.unshift "#{File.dirname(__FILE__)}/../lib" require 'hansard_parser' from = Date.new(2007, 1, 1) to = Date.new(2008, 1, 1) - 1 # Don't need to set 'people' parser = HansardParser.new(nil) FileUtils.mkdir_p "source" def write_tidied_xml(text, filename) File.open(filename, 'w') {|f| f << text } system("tidy -q -i -w 200 -xml -utf8 -o #{filename} #{filename}") end (from..to).each do |date| puts "Downloading and saving XML data for #{date}..." text = parser.hansard_xml_source_data_on_date(date, House.representatives) write_tidied_xml(text, "source/#{date}-reps.xml") if text text = parser.hansard_xml_source_data_on_date(date, House.senate) write_tidied_xml(text, "source/#{date}-senate.xml") if text end
#!/usr/bin/env ruby # Copyright (c) 2013 Matt Hodges (http://matthodges.com) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'rubygems' require 'date' require 'active_support/all' class Post def initialize(title, slug, filename, publish_date) @title = title @slug = slug @filename = filename @publish_date = publish_date end end class BlogBuilder class << self attr_reader :posts, :json_string def set_post_metadata @posts = [] Dir.foreach('./content/posts/') do |item| # next if item == '.' or item == '..' or item =='.DS_Store' next if item != '*.md' title = File.open("./content/posts/#{item}", &:readline).unpack("C*").pack("U*") title = title.gsub("\n", "") title[0] = '' title = title.strip slug = item[0...-3] publish_date = `git log --format='format:%ci' --diff-filter=A ./content/posts/"#{item}"` @posts.push(Post.new(title, slug, item, publish_date)) end end def jsonify_posts posts = @posts.sort_by { |post| post.instance_variable_get(:@publish_date) } @json_string = posts.reverse.to_json end def create_posts_from_json File.open('./content/posts.json', 'w') { |f| f.write(json_string) } end def commit `git add .` puts `git commit -m "Oracle built on #{Time.now}"` end def build! set_post_metadata jsonify_posts create_posts_from_json commit end end end BlogBuilder.build! Oracle built on 2013-10-20 17:33:28 -0400 #!/usr/bin/env ruby # Copyright (c) 2013 Matt Hodges (http://matthodges.com) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'rubygems' require 'date' require 'active_support/all' class Post def initialize(title, slug, filename, publish_date) @title = title @slug = slug @filename = filename @publish_date = publish_date end end class BlogBuilder class << self attr_reader :posts, :json_string def set_post_metadata @posts = [] Dir.foreach('./content/posts/') do |item| # next if item == '.' or item == '..' or item =='.DS_Store' next if item != '.md' title = File.open("./content/posts/#{item}", &:readline).unpack("C*").pack("U*") title = title.gsub("\n", "") title[0] = '' title = title.strip slug = item[0...-3] publish_date = `git log --format='format:%ci' --diff-filter=A ./content/posts/"#{item}"` @posts.push(Post.new(title, slug, item, publish_date)) end end def jsonify_posts posts = @posts.sort_by { |post| post.instance_variable_get(:@publish_date) } @json_string = posts.reverse.to_json end def create_posts_from_json File.open('./content/posts.json', 'w') { |f| f.write(json_string) } end def commit `git add .` puts `git commit -m "Oracle built on #{Time.now}"` end def build! set_post_metadata jsonify_posts create_posts_from_json commit end end end BlogBuilder.build!
#!/usr/bin/env ruby require 'tmpdir' require 'fileutils' require 'uri' def pipe(command) output = "" IO.popen(command) do |io| until io.eof? buffer = io.gets output << buffer puts buffer end end output end def fetch(url) uri = URI.parse(url) binary = uri.to_s.split("/").last if File.exists?(binary) puts "Using #{binary}" else puts "Fetching #{binary}" `curl #{uri} -s -O` end end workspace_dir = ARGV[0] output_dir = ARGV[1] cache_dir = ARGV[2] LIBYAML_VERSION = "0.1.6" LIBFFI_VERSION = "3.0.10" vendor_url = "https://s3.amazonaws.com/#{ENV['S3_BUCKET_NAME'] ? ENV['S3_BUCKET_NAME'] : 'heroku-buildpack-ruby'}" full_version = ENV['VERSION'] full_name = "ruby-#{full_version}" version = full_version.split('-').first name = "ruby-#{version}" major_ruby = version.match(/\d\.\d/)[0] build = false build = true if ENV["BUILD"] debug = nil debug = true if ENV['DEBUG'] jobs = ENV['JOBS'] || 2 rubygems = ENV['RUBYGEMS_VERSION'] ? ENV['RUBYGEMS_VERSION'] : nil git_url = ENV["GIT_URL"] svn_url = ENV["SVN_URL"] treeish = nil # create cache dir if it doesn't exist FileUtils.mkdir_p(cache_dir) # fetch deps Dir.chdir(cache_dir) do if git_url uri = URI.parse(git_url) treeish = uri.fragment uri.fragment = nil full_name = uri.to_s.split('/').last.sub(".git", "") if File.exists?(full_name) Dir.chdir(full_name) do puts "Updating git repo" pipe "git pull" end else puts "Fetching #{git_url}" pipe "git clone #{uri}" end elsif svn_url uri = URI.parse(svn_url) revision = uri.fragment uri.fragment = nil if File.exists?(full_name) puts "Using existing svn checkout: #{full_name}" pipe "svn update -r#{revision}" else pipe "svn co #{svn_url}@#{revision} #{full_name}" end else tarball = "#{full_name}.tar.gz" fetch("http://ftp.ruby-lang.org/pub/ruby/#{major_ruby}/#{tarball}") end ["libyaml-#{LIBYAML_VERSION}.tgz", "libffi-#{LIBFFI_VERSION}.tgz"].each do |binary| if File.exists?(binary) puts "Using #{binary}" else puts "Fetching #{binary}" fetch("#{vendor_url}/#{binary}") end end if rubygems rubygems_binary = "rubygems-#{rubygems}" fetch("http://production.cf.rubygems.org/rubygems/#{rubygems_binary}.tgz") end end Dir.mktmpdir("ruby-vendor-") do |vendor_dir| if git_url || svn_url FileUtils.cp_r("#{cache_dir}/#{full_name}", ".") else `tar zxf #{cache_dir}/#{full_name}.tar.gz` end Dir.chdir(vendor_dir) do `tar zxf #{cache_dir}/libyaml-#{LIBYAML_VERSION}.tgz` `tar zxf #{cache_dir}/libffi-#{LIBFFI_VERSION}.tgz` `tar zxf #{cache_dir}/rubygems-#{rubygems}.tgz` if rubygems end prefix = "/app/vendor/#{name}" prefix = "/tmp/#{name}" if build puts "prefix: #{prefix}" Dir.chdir(full_name) do pipe "git checkout #{treeish}" if treeish if debug configure_env = "optflags=\"-O0\" debugflags=\"-g3 -ggdb\"" else configure_env = "debugflags=\"-g\"" end configure_opts = "--disable-install-doc --prefix #{prefix}" configure_opts += " --enable-load-relative" if major_ruby != "1.8" && version != "1.9.2" puts "configure env: #{configure_env}" puts "configure opts: #{configure_opts}" cmds = [ "#{configure_env} ./configure #{configure_opts}", "env CPATH=#{vendor_dir}/include:\\$CPATH CPPATH=#{vendor_dir}/include:\\$CPPATH LIBRARY_PATH=#{vendor_dir}/lib:\\$LIBRARY_PATH make -j#{jobs}", "make install" ] cmds.unshift("#{configure_env} autoconf") if git_url || svn_url cmds.unshift("chmod +x ./tool/*") if git_url || svn_url pipe(cmds.join(" && ")) end if rubygems Dir.chdir("#{vendor_dir}/rubygems-#{rubygems}") do pipe("#{prefix}/bin/ruby setup.rb") end gem_bin_file = "#{prefix}/bin/gem" gem = File.read(gem_bin_file) File.open(gem_bin_file, 'w') do |file| file.puts "#!/usr/bin/env ruby" lines = gem.split("\n") lines.shift lines.each {|line| file.puts line } end end Dir.chdir(prefix) do filename = "#{name}.tgz" pipe "ls" puts "Writing #{filename}" pipe("tar czf #{output_dir}/#{filename} *") end end build source tarballs via SVN #!/usr/bin/env ruby require 'tmpdir' require 'fileutils' require 'uri' def pipe(command) output = "" IO.popen(command) do |io| until io.eof? buffer = io.gets output << buffer puts buffer end end output end def fetch(url) uri = URI.parse(url) binary = uri.to_s.split("/").last if File.exists?(binary) puts "Using #{binary}" else puts "Fetching #{binary}" `curl #{uri} -s -O` end end workspace_dir = ARGV[0] output_dir = ARGV[1] cache_dir = ARGV[2] LIBYAML_VERSION = "0.1.6" LIBFFI_VERSION = "3.0.10" vendor_url = "https://s3.amazonaws.com/#{ENV['S3_BUCKET_NAME'] ? ENV['S3_BUCKET_NAME'] : 'heroku-buildpack-ruby'}" full_version = ENV['VERSION'] full_name = "ruby-#{full_version}" version = full_version.split('-').first name = "ruby-#{version}" major_ruby = version.match(/\d\.\d/)[0] build = false build = true if ENV["BUILD"] debug = nil debug = true if ENV['DEBUG'] jobs = ENV['JOBS'] || 2 rubygems = ENV['RUBYGEMS_VERSION'] ? ENV['RUBYGEMS_VERSION'] : nil git_url = ENV["GIT_URL"] svn_url = ENV["SVN_URL"] relname = ENV["RELNAME"] treeish = nil # create cache dir if it doesn't exist FileUtils.mkdir_p(cache_dir) # fetch deps Dir.chdir(cache_dir) do tarball = "#{full_name}.tar.gz" if git_url uri = URI.parse(git_url) treeish = uri.fragment uri.fragment = nil full_name = uri.to_s.split('/').last.sub(".git", "") if File.exists?(full_name) Dir.chdir(full_name) do puts "Updating git repo" pipe "git pull" end else puts "Fetching #{git_url}" pipe "git clone #{uri}" end elsif svn_url uri = URI.parse(svn_url) if File.exists?(full_name) puts "Using existing svn checkout: #{full_name}" pipe "svn update" else pipe "svn co #{svn_url} #{full_name}" end Dir.chdir(full_name) do cmd = "ruby tool/make-snapshot -archname=#{full_name} build #{relname}" puts cmd pipe cmd end FileUtils.mv("#{full_name}/build/#{tarball}", ".") else fetch("http://ftp.ruby-lang.org/pub/ruby/#{major_ruby}/#{tarball}") end ["libyaml-#{LIBYAML_VERSION}.tgz", "libffi-#{LIBFFI_VERSION}.tgz"].each do |binary| if File.exists?(binary) puts "Using #{binary}" else puts "Fetching #{binary}" fetch("#{vendor_url}/#{binary}") end end if rubygems rubygems_binary = "rubygems-#{rubygems}" fetch("http://production.cf.rubygems.org/rubygems/#{rubygems_binary}.tgz") end end Dir.mktmpdir("ruby-vendor-") do |vendor_dir| if git_url FileUtils.cp_r("#{cache_dir}/#{full_name}", ".") else `tar zxf #{cache_dir}/#{full_name}.tar.gz` end Dir.chdir(vendor_dir) do `tar zxf #{cache_dir}/libyaml-#{LIBYAML_VERSION}.tgz` `tar zxf #{cache_dir}/libffi-#{LIBFFI_VERSION}.tgz` `tar zxf #{cache_dir}/rubygems-#{rubygems}.tgz` if rubygems end prefix = "/app/vendor/#{name}" prefix = "/tmp/#{name}" if build puts "prefix: #{prefix}" Dir.chdir(full_name) do pipe "git checkout #{treeish}" if treeish if debug configure_env = "optflags=\"-O0\" debugflags=\"-g3 -ggdb\"" else configure_env = "debugflags=\"-g\"" end configure_opts = "--disable-install-doc --prefix #{prefix}" configure_opts += " --enable-load-relative" if major_ruby != "1.8" && version != "1.9.2" puts "configure env: #{configure_env}" puts "configure opts: #{configure_opts}" cmds = [ "#{configure_env} ./configure #{configure_opts}", "env CPATH=#{vendor_dir}/include:\\$CPATH CPPATH=#{vendor_dir}/include:\\$CPPATH LIBRARY_PATH=#{vendor_dir}/lib:\\$LIBRARY_PATH make -j#{jobs}", "make install" ] cmds.unshift("#{configure_env} autoconf") if git_url cmds.unshift("chmod +x ./tool/*") if git_url pipe(cmds.join(" && ")) end if rubygems Dir.chdir("#{vendor_dir}/rubygems-#{rubygems}") do pipe("#{prefix}/bin/ruby setup.rb") end gem_bin_file = "#{prefix}/bin/gem" gem = File.read(gem_bin_file) File.open(gem_bin_file, 'w') do |file| file.puts "#!/usr/bin/env ruby" lines = gem.split("\n") lines.shift lines.each {|line| file.puts line } end end Dir.chdir(prefix) do filename = "#{name}.tgz" pipe "ls" puts "Writing #{filename}" pipe("tar czf #{output_dir}/#{filename} *") end end
require 'sinatra' require 'json' require 'octokit' #require 'open3' require 'fileutils' require "serialport" $LOAD_PATH << '.' require 'ci_utils.rb' require_relative "bucket" require_relative "cam" set :bind, '0.0.0.0' set :environment, :production # XXX webrick has issues in recent versions accepting non-localhost transfers set :server, :thin set :port, 4567 $aws_key = ENV['AWS_ACCESS_KEY_ID'] $aws_secret = ENV['AWS_SECRET_ACCESS_KEY'] $nshport = ENV['NSHPORT'] $ACCESS_TOKEN = ENV['GITTOKEN'] $logdir = './' $commandlog = 'commandlog.txt' $consolelog = 'consolelog.txt' $bucket_name = 'results.dronetest.io' $host = 'zurich01' $results_url = "" $continuous_branch = nil $clonedir = "Firmware" $hardware_test_timeout = 60 $lf = '.lockfile' def do_lock(board) # XXX put this into a function and check for a free worker # also requires to name directories after the free worker while File.file?(board) # Check if the lock file is really old, if yes, take our chances and wipe it if ((Time.now - File.stat(board).mtime).to_i > (60 * 10)) then do_unlock('boardname') break end # Keep waiting as long as the lock file exists sleep(5) puts 'waiting for lock to be released..' end # This is the critical section - we might want to lock it # using a 2nd file, or something smarter and proper. # XXX for now, we just bet on timing - yay! FileUtils.touch($lf) end def do_unlock(board) # We're done - delete lock file FileUtils.rm_rf(board) end def do_work (command, error_message, work_dir) # :chdir=>"#{work_dir}" Open3.popen2e(command) do |stdin, stdout_err, wait_thr| logfile = File.open($logdir + $commandlog, 'a') while line = stdout_err.gets puts "OUT> " + line logfile << line end exit_status = wait_thr.value unless exit_status.success? do_unlock($lf) set_PR_Status $full_repo_name, $sha, 'failure', error_message failmsg = "The command #{command} failed!" puts failmsg logfile << failmsg logfile.close # Do not run through the standard exit handlers exit!(1) end end end def do_clone (srcdir, branch, html_url) puts "do_clone: " + branch system 'mkdir', '-p', srcdir Dir.chdir(srcdir) do #git clone <url> --branch <branch> --single-branch [<folder>] #result = `git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch ` #puts result do_work "git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch #{$clonedir}", "Cloning repo failed.", "." end end def do_master_merge (srcdir, base_repo, base_branch) puts "do_merge of #{base_repo}/#{base_branch}" Dir.chdir(File.join(srcdir, "#{$clonedir}")) do do_work "git remote add base_repo #{base_repo}.git", "GIT adding upstream failed", "." do_work "git fetch base_repo", "GIT fetching upstream failed", "." do_work "git merge base_repo/#{base_branch} -m 'Merged #{base_repo}/#{base_branch} into test branch'", "Failed merging #{base_repo}/#{base_branch}", "." end end def do_build (srcdir) puts "Starting build" Dir.chdir(File.join(srcdir, "#{$clonedir}")) { system 'rm', '-rf', 'build_px4fmu-v2_default' system 'mkdir', '-p', 'build_px4fmu-v2_default' system 'rm', '-rf', 'build_qurt_eagle_travis' system 'mkdir', '-p', 'build_qurt_eagle_travis' do_work "git submodule update --init --recursive --force", "GIT submodule update failed", "." Dir.chdir("build_px4fmu-v2_default") { do_work "cmake .. -GNinja -DCONFIG=nuttx_px4fmu-v2_default", "FMUv2 cmake run failed", "." do_work "/usr/bin/ninja", "FMUv2 ninja failed", "." } Dir.chdir("build_qurt_eagle_travis") { do_work "cmake .. -GNinja -DCONFIG=qurt_eagle_travis", "Eagle cmake run failed", "." do_work "/usr/bin/ninja", "Eagle ninja failed", "." } } end def openserialport (timeout) #Open serial port - safe #params for serial port port_str = $nshport baud_rate = 57600 data_bits = 8 stop_bits = 1 parity = SerialPort::NONE begin sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity) puts "Opening port: " + port_str sp.read_timeout = timeout return sp rescue Errno::ENOENT puts "Serial port not available! Please (re)connect!" sleep(1) retry end end def make_hwtest (pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link, hw_timeout) # Execute hardware test sender = ENV['MAILSENDER'] testcmd = "Tools/px_uploader.py --port \"/dev/serial/by-id/usb-3D_Robotics*,/dev/tty.usbmodem1\" build_px4fmu-v2_default/src/firmware/nuttx/nuttx-px4fmu-v2-default.px4" #some variables need to be initialized testResult = "" finished = false puts "----------------- Hardware-Test running ----------------" sp = openserialport 100 #Push enter to cause output of remnants sp.write "\n" input = sp.gets() puts "Remnants:" puts input sp.close Dir.chdir(File.join(srcdir, "Firmware")) do #puts "Call: " + testcmd #result = `#{testcmd}` puts "---------------command output---------------" do_work testcmd, "Firmware upload failed", "." puts "---------- end of command output------------" end # Total test timeout in seconds test_timeout_s = hw_timeout; # Wait 0.5 s for new data read_timeout_ms = 500 sp = openserialport read_timeout_ms test_passed = false # XXX prepend each line with a time marker # so we know if output comes in with huge delays test_start_time = Time.now begin begin input = sp.gets() rescue Errno::ENXIO puts "Serial port not available! Please connect" sleep(1) sp = openserialport read_timeout_ms retry end if !input.nil? #if input != nil and !input.empty? testResult = testResult + input if testResult.include? "NuttShell" finished = true puts "---------------- Testresult----------------" #puts testResult # Write test results to console log file File.open($logdir + $consolelog, 'w') {|f| f.write(testResult) } if (testResult.include? "TEST FAILED") || (testResult.include? "Tests FAILED") puts "TEST FAILED!" test_passed = false else test_passed = true puts "Test successful!" end end elsif ((test_timeout_s > 0) && ((Time.now() - test_start_time) > test_timeout_s)) finished = true File.open($logdir + $consolelog, 'w') {|f| f.write(testResult + "\nSERIAL READ TIMEOUT!\n") } puts "Serial port timeout" end end until finished # Send out email make_mmail pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link # Prepare result for upload generate_results_page 'index.html', pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link sp.close # Provide exit status if (test_passed) return 0 else return 1 end end def set_PR_Status (repo, sha, prstatus, description) puts "Access token: " + $ACCESS_TOKEN client = Octokit::Client.new(:access_token => $ACCESS_TOKEN) # XXX replace the URL below with the web server status details URL options = { "state" => prstatus, "target_url" => $results_url, "description" => description, "context" => "continuous-integration/hans-ci" }; puts "Setting commit status on repo: " + repo + " sha: " + sha + " to: " + prstatus + " description: " + description res = client.create_status(repo, sha, prstatus, options) puts res end def fork_hwtest (continuous_branch, pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha) #Starts the hardware test in a subshell pid = Process.fork if pid.nil? then puts "WORKER ACTIVE!" # Lock this board for operations do_lock($lf) # Clean up any mess left behind by a previous potential fail puts "Cleaning up old files.." FileUtils.rm_rf(srcdir) FileUtils.mkdir(srcdir); FileUtils.touch($logdir + $consolelog) # In child puts "Claiming results.." s3_dirname = results_claim_directory($bucket_name, $host, $aws_key, $aws_secret) $results_url = sprintf("http://%s/%s/index.html", $bucket_name, s3_dirname); results_still = sprintf("http://%s/%s/still.jpg", $bucket_name, s3_dirname); # Set relevant global variables for PR status $full_repo_name = full_repo_name $sha = sha tgit_start = Time.now puts "Cloning repository from:" + url do_clone srcdir, branch, url if !pr.nil? do_master_merge srcdir, pr['base']['repo']['html_url'], pr['base']['ref'] end tgit_duration = Time.now - tgit_start tbuild_start = Time.now do_build srcdir tbuild_duration = Time.now - tbuild_start # Run the hardware test hw_timeout = $hardware_test_timeout; # If the continuous integration branch name # is set, indicate that the HW test should # never actually time out if (!continuous_branch.nil?) hw_timeout = 0; end thw_start = Time.now result = make_hwtest pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, $results_url, results_still, hw_timeout thw_duration = Time.now - thw_start # Take webcam image take_picture(".") # Upload still JPEG results_upload($bucket_name, 'still.jpg', '%s/%s' % [s3_dirname, 'still.jpg'], $aws_key, $aws_secret) FileUtils.rm_rf('still.jpg') timingstr = sprintf("%4.2fs", tgit_duration + tbuild_duration + thw_duration) puts "HW TEST RESULT:" + result.to_s if (result == 0) then set_PR_Status full_repo_name, sha, 'success', 'Pixhawk HW test passed: ' + timingstr else set_PR_Status full_repo_name, sha, 'failure', 'Pixhawk HW test FAILED: ' + timingstr end # Logfile results_upload($bucket_name, $logdir + $commandlog, '%s/%s' % [s3_dirname, 'commandlog.txt'], $aws_key, $aws_secret) FileUtils.rm_rf($commandlog) results_upload($bucket_name, $logdir + $consolelog, '%s/%s' % [s3_dirname, 'consolelog.txt'], $aws_key, $aws_secret) FileUtils.rm_rf($logdir + $consolelog) # GIF results_upload($bucket_name, 'animated.gif', '%s/%s' % [s3_dirname, 'animated.gif'], $aws_key, $aws_secret) FileUtils.rm_rf('animated.gif') # Index page results_upload($bucket_name, 'index.html', '%s/%s' % [s3_dirname, 'index.html'], $aws_key, $aws_secret) FileUtils.rm_rf('index.html') # Clean up by deleting the work directory FileUtils.rm_rf(srcdir) # Unlock this board do_unlock($lf) exit! 0 else # In parent puts "Worker PID: " + pid.to_s Process.detach(pid) end end # ---------- Routing ------------ get '/' do "Hello unknown" end get '/payload' do "This URL is intended to be used with POST, not GET" end post '/payload' do body = JSON.parse(request.body.read) github_event = request.env['HTTP_X_GITHUB_EVENT'] case github_event when 'ping' "Hello" when 'pull_request' begin pr = body["pull_request"] number = body['number'] puts pr['state'] action = body['action'] if (['opened', 'reopened'].include?(action)) sha = pr['head']['sha'] srcdir = sha $logdir = Dir.pwd + "/" + srcdir + "/" full_name = pr['base']['repo']['full_name'] puts "Source directory: #{srcdir}" #Set environment vars for sub processes # Pull last commiter email for PR from GH client = Octokit::Client.new(:access_token => $ACCESS_TOKEN) commit = client.commit(full_name, sha) pushername = commit['commit']['author']['name'] pusheremail = commit['commit']['author']['email'] branch = pr['head']['ref'] url = pr['head']['repo']['html_url'] puts "Adding to queue: Pull request: #{number} " + branch + " from "+ url set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest nil, pushername, pusheremail, pr, srcdir, branch, url, full_name, sha puts 'Pull request event queued for testing.' else puts 'Ignoring closing of pull request #' + String(number) end end when 'push' branch = body['ref'] if !(body['head_commit'].nil?) && body['head_commit'] != 'null' sha = body['head_commit']['id'] srcdir = sha $logdir = Dir.pwd + "/" + srcdir + "/"; puts "Source directory: #{srcdir}" #Set environment vars for sub processes pushername = body ['pusher']['name'] pusheremail = body ['pusher']['email'] a = branch.split('/') branch = a[a.count-1] #last part is the bare branchname puts "Adding to queue: Branch: " + branch + " from "+ body['repository']['html_url'] full_name = body['repository']['full_name'] puts "Full name: " + full_name set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest $continuous_branch, pushername, pusheremail, nil, srcdir, branch, body['repository']['html_url'], full_name, sha puts 'Push event queued for testing.' end when 'status' puts "Ignoring GH status event" when 'fork' puts 'Ignoring GH fork repo event' when 'delete' puts 'Ignoring GH delete branch event' when 'issue_comment' puts 'Ignoring comments' when 'issues' puts 'Ignoring issues' when 'pull_request_review_comment' puts 'Ignoring review comment' when 'started' puts 'Ignoring started request' else puts "Unhandled request:" puts "Envelope: " + JSON.pretty_generate(request.env) puts "JSON: " + JSON.pretty_generate(body) puts "Unknown Event: " + github_event end end Replace ninja require 'sinatra' require 'json' require 'octokit' #require 'open3' require 'fileutils' require "serialport" $LOAD_PATH << '.' require 'ci_utils.rb' require_relative "bucket" require_relative "cam" set :bind, '0.0.0.0' set :environment, :production # XXX webrick has issues in recent versions accepting non-localhost transfers set :server, :thin set :port, 4567 $aws_key = ENV['AWS_ACCESS_KEY_ID'] $aws_secret = ENV['AWS_SECRET_ACCESS_KEY'] $nshport = ENV['NSHPORT'] $ACCESS_TOKEN = ENV['GITTOKEN'] $logdir = './' $commandlog = 'commandlog.txt' $consolelog = 'consolelog.txt' $bucket_name = 'results.dronetest.io' $host = 'zurich01' $results_url = "" $continuous_branch = nil $clonedir = "Firmware" $hardware_test_timeout = 60 $lf = '.lockfile' def do_lock(board) # XXX put this into a function and check for a free worker # also requires to name directories after the free worker while File.file?(board) # Check if the lock file is really old, if yes, take our chances and wipe it if ((Time.now - File.stat(board).mtime).to_i > (60 * 10)) then do_unlock('boardname') break end # Keep waiting as long as the lock file exists sleep(5) puts 'waiting for lock to be released..' end # This is the critical section - we might want to lock it # using a 2nd file, or something smarter and proper. # XXX for now, we just bet on timing - yay! FileUtils.touch($lf) end def do_unlock(board) # We're done - delete lock file FileUtils.rm_rf(board) end def do_work (command, error_message, work_dir) # :chdir=>"#{work_dir}" Open3.popen2e(command) do |stdin, stdout_err, wait_thr| logfile = File.open($logdir + $commandlog, 'a') while line = stdout_err.gets puts "OUT> " + line logfile << line end exit_status = wait_thr.value unless exit_status.success? do_unlock($lf) set_PR_Status $full_repo_name, $sha, 'failure', error_message failmsg = "The command #{command} failed!" puts failmsg logfile << failmsg logfile.close # Do not run through the standard exit handlers exit!(1) end end end def do_clone (srcdir, branch, html_url) puts "do_clone: " + branch system 'mkdir', '-p', srcdir Dir.chdir(srcdir) do #git clone <url> --branch <branch> --single-branch [<folder>] #result = `git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch ` #puts result do_work "git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch #{$clonedir}", "Cloning repo failed.", "." end end def do_master_merge (srcdir, base_repo, base_branch) puts "do_merge of #{base_repo}/#{base_branch}" Dir.chdir(File.join(srcdir, "#{$clonedir}")) do do_work "git remote add base_repo #{base_repo}.git", "GIT adding upstream failed", "." do_work "git fetch base_repo", "GIT fetching upstream failed", "." do_work "git merge base_repo/#{base_branch} -m 'Merged #{base_repo}/#{base_branch} into test branch'", "Failed merging #{base_repo}/#{base_branch}", "." end end def do_build (srcdir) puts "Starting build" Dir.chdir(File.join(srcdir, "#{$clonedir}")) { system 'rm', '-rf', 'build_px4fmu-v2_default' system 'mkdir', '-p', 'build_px4fmu-v2_default' system 'rm', '-rf', 'build_qurt_eagle_travis' system 'mkdir', '-p', 'build_qurt_eagle_travis' do_work "git submodule update --init --recursive --force", "GIT submodule update failed", "." Dir.chdir("build_px4fmu-v2_default") { do_work "cmake .. -GNinja -DCONFIG=nuttx_px4fmu-v2_default", "FMUv2 cmake run failed", "." do_work "ninja", "FMUv2 ninja failed", "." } Dir.chdir("build_qurt_eagle_travis") { do_work "cmake .. -GNinja -DCONFIG=qurt_eagle_travis", "Eagle cmake run failed", "." do_work "ninja", "Eagle ninja failed", "." } } end def openserialport (timeout) #Open serial port - safe #params for serial port port_str = $nshport baud_rate = 57600 data_bits = 8 stop_bits = 1 parity = SerialPort::NONE begin sp = SerialPort.new(port_str, baud_rate, data_bits, stop_bits, parity) puts "Opening port: " + port_str sp.read_timeout = timeout return sp rescue Errno::ENOENT puts "Serial port not available! Please (re)connect!" sleep(1) retry end end def make_hwtest (pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link, hw_timeout) # Execute hardware test sender = ENV['MAILSENDER'] testcmd = "Tools/px_uploader.py --port \"/dev/serial/by-id/usb-3D_Robotics*,/dev/tty.usbmodem1\" build_px4fmu-v2_default/src/firmware/nuttx/nuttx-px4fmu-v2-default.px4" #some variables need to be initialized testResult = "" finished = false puts "----------------- Hardware-Test running ----------------" sp = openserialport 100 #Push enter to cause output of remnants sp.write "\n" input = sp.gets() puts "Remnants:" puts input sp.close Dir.chdir(File.join(srcdir, "Firmware")) do #puts "Call: " + testcmd #result = `#{testcmd}` puts "---------------command output---------------" do_work testcmd, "Firmware upload failed", "." puts "---------- end of command output------------" end # Total test timeout in seconds test_timeout_s = hw_timeout; # Wait 0.5 s for new data read_timeout_ms = 500 sp = openserialport read_timeout_ms test_passed = false # XXX prepend each line with a time marker # so we know if output comes in with huge delays test_start_time = Time.now begin begin input = sp.gets() rescue Errno::ENXIO puts "Serial port not available! Please connect" sleep(1) sp = openserialport read_timeout_ms retry end if !input.nil? #if input != nil and !input.empty? testResult = testResult + input if testResult.include? "NuttShell" finished = true puts "---------------- Testresult----------------" #puts testResult # Write test results to console log file File.open($logdir + $consolelog, 'w') {|f| f.write(testResult) } if (testResult.include? "TEST FAILED") || (testResult.include? "Tests FAILED") puts "TEST FAILED!" test_passed = false else test_passed = true puts "Test successful!" end end elsif ((test_timeout_s > 0) && ((Time.now() - test_start_time) > test_timeout_s)) finished = true File.open($logdir + $consolelog, 'w') {|f| f.write(testResult + "\nSERIAL READ TIMEOUT!\n") } puts "Serial port timeout" end end until finished # Send out email make_mmail pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link # Prepare result for upload generate_results_page 'index.html', pushername, pusheremail, sender, testResult, test_passed, srcdir, branch, url, full_repo_name, sha, results_link, results_image_link sp.close # Provide exit status if (test_passed) return 0 else return 1 end end def set_PR_Status (repo, sha, prstatus, description) puts "Access token: " + $ACCESS_TOKEN client = Octokit::Client.new(:access_token => $ACCESS_TOKEN) # XXX replace the URL below with the web server status details URL options = { "state" => prstatus, "target_url" => $results_url, "description" => description, "context" => "continuous-integration/hans-ci" }; puts "Setting commit status on repo: " + repo + " sha: " + sha + " to: " + prstatus + " description: " + description res = client.create_status(repo, sha, prstatus, options) puts res end def fork_hwtest (continuous_branch, pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha) #Starts the hardware test in a subshell pid = Process.fork if pid.nil? then puts "WORKER ACTIVE!" # Lock this board for operations do_lock($lf) # Clean up any mess left behind by a previous potential fail puts "Cleaning up old files.." FileUtils.rm_rf(srcdir) FileUtils.mkdir(srcdir); FileUtils.touch($logdir + $consolelog) # In child puts "Claiming results.." s3_dirname = results_claim_directory($bucket_name, $host, $aws_key, $aws_secret) $results_url = sprintf("http://%s/%s/index.html", $bucket_name, s3_dirname); results_still = sprintf("http://%s/%s/still.jpg", $bucket_name, s3_dirname); # Set relevant global variables for PR status $full_repo_name = full_repo_name $sha = sha tgit_start = Time.now puts "Cloning repository from:" + url do_clone srcdir, branch, url if !pr.nil? do_master_merge srcdir, pr['base']['repo']['html_url'], pr['base']['ref'] end tgit_duration = Time.now - tgit_start tbuild_start = Time.now do_build srcdir tbuild_duration = Time.now - tbuild_start # Run the hardware test hw_timeout = $hardware_test_timeout; # If the continuous integration branch name # is set, indicate that the HW test should # never actually time out if (!continuous_branch.nil?) hw_timeout = 0; end thw_start = Time.now result = make_hwtest pushername, pusheremail, pr, srcdir, branch, url, full_repo_name, sha, $results_url, results_still, hw_timeout thw_duration = Time.now - thw_start # Take webcam image take_picture(".") # Upload still JPEG results_upload($bucket_name, 'still.jpg', '%s/%s' % [s3_dirname, 'still.jpg'], $aws_key, $aws_secret) FileUtils.rm_rf('still.jpg') timingstr = sprintf("%4.2fs", tgit_duration + tbuild_duration + thw_duration) puts "HW TEST RESULT:" + result.to_s if (result == 0) then set_PR_Status full_repo_name, sha, 'success', 'Pixhawk HW test passed: ' + timingstr else set_PR_Status full_repo_name, sha, 'failure', 'Pixhawk HW test FAILED: ' + timingstr end # Logfile results_upload($bucket_name, $logdir + $commandlog, '%s/%s' % [s3_dirname, 'commandlog.txt'], $aws_key, $aws_secret) FileUtils.rm_rf($commandlog) results_upload($bucket_name, $logdir + $consolelog, '%s/%s' % [s3_dirname, 'consolelog.txt'], $aws_key, $aws_secret) FileUtils.rm_rf($logdir + $consolelog) # GIF results_upload($bucket_name, 'animated.gif', '%s/%s' % [s3_dirname, 'animated.gif'], $aws_key, $aws_secret) FileUtils.rm_rf('animated.gif') # Index page results_upload($bucket_name, 'index.html', '%s/%s' % [s3_dirname, 'index.html'], $aws_key, $aws_secret) FileUtils.rm_rf('index.html') # Clean up by deleting the work directory FileUtils.rm_rf(srcdir) # Unlock this board do_unlock($lf) exit! 0 else # In parent puts "Worker PID: " + pid.to_s Process.detach(pid) end end # ---------- Routing ------------ get '/' do "Hello unknown" end get '/payload' do "This URL is intended to be used with POST, not GET" end post '/payload' do body = JSON.parse(request.body.read) github_event = request.env['HTTP_X_GITHUB_EVENT'] case github_event when 'ping' "Hello" when 'pull_request' begin pr = body["pull_request"] number = body['number'] puts pr['state'] action = body['action'] if (['opened', 'reopened'].include?(action)) sha = pr['head']['sha'] srcdir = sha $logdir = Dir.pwd + "/" + srcdir + "/" full_name = pr['base']['repo']['full_name'] puts "Source directory: #{srcdir}" #Set environment vars for sub processes # Pull last commiter email for PR from GH client = Octokit::Client.new(:access_token => $ACCESS_TOKEN) commit = client.commit(full_name, sha) pushername = commit['commit']['author']['name'] pusheremail = commit['commit']['author']['email'] branch = pr['head']['ref'] url = pr['head']['repo']['html_url'] puts "Adding to queue: Pull request: #{number} " + branch + " from "+ url set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest nil, pushername, pusheremail, pr, srcdir, branch, url, full_name, sha puts 'Pull request event queued for testing.' else puts 'Ignoring closing of pull request #' + String(number) end end when 'push' branch = body['ref'] if !(body['head_commit'].nil?) && body['head_commit'] != 'null' sha = body['head_commit']['id'] srcdir = sha $logdir = Dir.pwd + "/" + srcdir + "/"; puts "Source directory: #{srcdir}" #Set environment vars for sub processes pushername = body ['pusher']['name'] pusheremail = body ['pusher']['email'] a = branch.split('/') branch = a[a.count-1] #last part is the bare branchname puts "Adding to queue: Branch: " + branch + " from "+ body['repository']['html_url'] full_name = body['repository']['full_name'] puts "Full name: " + full_name set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest $continuous_branch, pushername, pusheremail, nil, srcdir, branch, body['repository']['html_url'], full_name, sha puts 'Push event queued for testing.' end when 'status' puts "Ignoring GH status event" when 'fork' puts 'Ignoring GH fork repo event' when 'delete' puts 'Ignoring GH delete branch event' when 'issue_comment' puts 'Ignoring comments' when 'issues' puts 'Ignoring issues' when 'pull_request_review_comment' puts 'Ignoring review comment' when 'started' puts 'Ignoring started request' else puts "Unhandled request:" puts "Envelope: " + JSON.pretty_generate(request.env) puts "JSON: " + JSON.pretty_generate(body) puts "Unknown Event: " + github_event end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'yt/annotations/version' Gem::Specification.new do |spec| spec.name = 'yt-annotations' spec.version = Yt::Annotations::VERSION spec.authors = ['claudiob'] spec.email = ['claudiob@gmail.com'] spec.summary = %q{Fetch annotations and cards from YouTube videos.} spec.description = %q{A Ruby library to retrieve every type of annotation from any YouTube video, including branding, featured content and info cards.} spec.homepage = 'https://github.com/fullscreen/yt-annotations' spec.license = 'MIT' spec.required_ruby_version = '>= 2.0' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_dependency 'activesupport', '~> 4.0' spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.3' spec.add_development_dependency 'coveralls', '~> 0.8.2' spec.add_development_dependency 'pry-nav', '~> 0.2.4' end Allow gem to be used with ActiveSupport 5 There seem to be no breaking changes with ActiveSupport with respect to the methods used by the gem. # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'yt/annotations/version' Gem::Specification.new do |spec| spec.name = 'yt-annotations' spec.version = Yt::Annotations::VERSION spec.authors = ['claudiob'] spec.email = ['claudiob@gmail.com'] spec.summary = %q{Fetch annotations and cards from YouTube videos.} spec.description = %q{A Ruby library to retrieve every type of annotation from any YouTube video, including branding, featured content and info cards.} spec.homepage = 'https://github.com/fullscreen/yt-annotations' spec.license = 'MIT' spec.required_ruby_version = '>= 2.0' spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_dependency 'activesupport', '>= 4', '< 6' spec.add_development_dependency 'bundler', '~> 1.7' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.3' spec.add_development_dependency 'coveralls', '~> 0.8.2' spec.add_development_dependency 'pry-nav', '~> 0.2.4' end
# # Cookbook Name:: docker_deploy # # Copyright 2015 TANABE Ken-ichi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'chef/mixin/shell_out' define :docker_deploy do application = params[:name] deploy = params[:deploy_data] opsworks = params[:opsworks_data] container_data = params[:container_data] Chef::Log.info "Start deploying #{application} in #{opsworks['activity']} phase..." opsworks_deploy_dir do user deploy['user'] group deploy['group'] path deploy['deploy_to'] end cur = "#{deploy['deploy_to']}/current" directory cur do user deploy['user'] group deploy['group'] end docker_image container_data['image'] do tag container_data['tag'] notifies :create, "file[#{cur}/id]" only_if { opsworks['activity'] == 'setup' || opsworks['activity'] == 'deploy' } end file "#{cur}/id" do user deploy['user'] group deploy['group'] content lazy { Chef::Mixin::ShellOut.shell_out("docker inspect -f '{{.Id}}' #{container_data['image']}:#{container_data['tag']}", :timeout => 60).stdout } if opsworks['activity'] == 'setup' || opsworks['activity'] == 'deploy' notifies :redeploy, "docker_container[#{application}]" end end template "#{cur}/env" do user deploy['user'] group deploy['group'] mode '0600' action :create backup false source 'envfile.erb' variables :env => deploy['environment'] cookbook 'docker_deploy' if opsworks['action'] == 'setup' || opsworks['action'] == 'deploy' notifies :redeploy, "docker_container[#{application}]" end end docker_container application do image lazy { ::File.open("#{cur}/id") { |f| f.read.strip } } container_name application case opsworks['activity'] when 'setup', 'deploy' # something is wrong with [:redeploy, :run] so just redeploy here action :redeploy when 'undeploy' action [:stop, :remove] end detach true env_file "#{cur}/env" if container_data['cmd'] command container_data['cmd'] end if container_data['net'] net container_data['net'] end end end definitions: Add TLS support for container ssl_certificate will be installed via environment variable TLS_CERT. ssl_certificate_key will be installed via environment variable TLS_CERT_KEY. # # Cookbook Name:: docker_deploy # # Copyright 2015 TANABE Ken-ichi # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'chef/mixin/shell_out' define :docker_deploy do application = params[:name] deploy = params[:deploy_data] opsworks = params[:opsworks_data] container_data = params[:container_data] Chef::Log.info "Start deploying #{application} in #{opsworks['activity']} phase..." opsworks_deploy_dir do user deploy['user'] group deploy['group'] path deploy['deploy_to'] end cur = "#{deploy['deploy_to']}/current" directory cur do user deploy['user'] group deploy['group'] end docker_image container_data['image'] do tag container_data['tag'] notifies :create, "file[#{cur}/id]" only_if { opsworks['activity'] == 'setup' || opsworks['activity'] == 'deploy' } end file "#{cur}/id" do user deploy['user'] group deploy['group'] content lazy { Chef::Mixin::ShellOut.shell_out("docker inspect -f '{{.Id}}' #{container_data['image']}:#{container_data['tag']}", :timeout => 60).stdout } if opsworks['activity'] == 'setup' || opsworks['activity'] == 'deploy' notifies :redeploy, "docker_container[#{application}]" end end template "#{cur}/env" do user deploy['user'] group deploy['group'] mode '0600' action :create backup false source 'envfile.erb' variables :env => deploy['environment'] cookbook 'docker_deploy' if opsworks['action'] == 'setup' || opsworks['action'] == 'deploy' notifies :redeploy, "docker_container[#{application}]" end end if deploy['ssl_support'] file "#{cur}/cert.pem" do user deploy['user'] group deploy['group'] mode '0600' backup false action :create content deploy['ssl_certificate'] end file "#{cur}/cert.key" do user deploy['user'] group deploy['group'] mode '0600' backup false action :create content deploy['ssl_certificate_key'] end end docker_container application do image lazy { ::File.open("#{cur}/id") { |f| f.read.strip } } container_name application case opsworks['activity'] when 'setup', 'deploy' # something is wrong with [:redeploy, :run] so just redeploy here action :redeploy when 'undeploy' action [:stop, :remove] end detach true env_file "#{cur}/env" if container_data['cmd'] command container_data['cmd'] end if container_data['net'] net container_data['net'] end if deploy['ssl_support'] ENV['TLS_CERT'] = deploy['ssl_certificate'] ENV['TLS_CERT_KEY'] = deploy['ssl_certificate_key'] env %w{ TLS_CERT TLS_CERT_KEY } end end end
require 'rubygems' require 'sinatra' require 'json/pure' require 'delta3d' require 'base64' require 'openssl' require 'uri' require "sinatra/reloader" if development? set :environment, :development disable :raise_errors disable :show_exceptions class Delta3DController get '/status' do body Thread.main["thread_exceptions"].inspect end get '/doc' do erb :doc end ['/index', '/'].each do |pattern| get pattern do erb :index end end post '/process' do content_type 'text/html' params['delta_parameters'] json_string = params['file']; json_string = params['file'][:tempfile].read if params['file'][:tempfile] parameters = params.reject { |key,value| key.eql?('file') } tmp_suffix = Time.now.strftime("%Y%m%d%H%M%S") thread = Thread.new(params['delta_parameters']) do |parameters| thread_id = "#{Thread.current.object_id}_#{tmp_suffix}" timeout = Thread.new { sleep(120); kill_thread( thread_id ) } Thread.current["thread_id"] = thread_id begin parameters = parameters.merge(parameters){ |key,old_val| old_val.eql?("") ? "0" : old_val } invalid_params = parameters.reject{ |param, value| Integer(value) rescue false } raise ArgumentError, "Invalid parameter(s) detected, please check: #{prettify(invalid_params)}" if invalid_params.length != 0 parameters = parameters.inject({}){ |memo, (key,value)| memo[key.to_sym]=Integer(value); memo } delta3d = Delta3D.new( json_string ) svgs = delta3d.plot( delta3d.calculate(parameters) ) path = File.expand_path(File.dirname(__FILE__)) svgs_tmp_file = File.new( "#{path}/tmp/#{thread_id}.tmp", "w" ) svgs_tmp_file.write( svgs ) svgs_tmp_file.close rescue Exception => e # puts e.inspect # puts e.backtrace list_exception( thread_id, e ) exit end end token = encrypt_token( "#{thread.object_id}_#{tmp_suffix}" ) Thread.new{ garbage_disposal } body "#{token}" end post '/svg_available' do params["token"].nil? ? svgs_tmp_filename = "" : svgs_tmp_filename = decrypt_token( params["token"] ) path = File.expand_path(File.dirname(__FILE__)) available = ( File.exist?( "#{path}/tmp/#{svgs_tmp_filename}.tmp" ) ? true : false ) if !Thread.main["thread_exceptions"].nil? && !Thread.main["thread_exceptions"][svgs_tmp_filename].nil? resp = Thread.main["thread_exceptions"][svgs_tmp_filename].message else resp = "#{available}" end body resp end post '/svg' do params["token"].nil? ? svgs_tmp_filename = "" : svgs_tmp_filename = decrypt_token( params["token"] ) path = File.expand_path(File.dirname(__FILE__)) svgs_tmp_filename = "#{path}/tmp/#{svgs_tmp_filename}.tmp" if File.exist?( svgs_tmp_filename ) body File.read( svgs_tmp_filename ) else halt 404, "SVG not found" end end error do puts "ouch ie ouch" "Something didn't went quite as expected - error: #{request.env['sinatra.error'].message}" end helpers do def inject_secret( mode ) path = File.expand_path(File.dirname(__FILE__)) secret_hash = JSON.load( File.new( "#{path}/secret.json", "r" ) ) aes = OpenSSL::Cipher.new("AES-256-CFB") aes.send( mode ) aes.key = Base64.decode64( secret_hash["key"] ) aes.iv = secret_hash["inivector"] aes end def encrypt_token( thread_id ) aes = inject_secret( :encrypt ) encrypted = aes.update( thread_id ) + aes.final token = Base64.encode64( encrypted ) token end def decrypt_token( token ) encrypted = Base64.decode64( token ) aes = inject_secret( :decrypt ) decrypted = aes.update( encrypted ) + aes.final decrypted end def list_exception( thread_id, excp ) if Thread.main["thread_exceptions"].nil? Thread.main["thread_exceptions"]={ thread_id => excp } else Thread.main["thread_exceptions"][thread_id] = excp end end def kill_thread( thread_id ) Thread.list.each do |thread| if thread["thread_id"].eql?(thread_id) thread.kill list_exception( thread_id, StandardError.new( "Delta computation execution time out… Try to adjust parameters to realize a less intensive calculation." ) ) end end end def garbage_disposal time_now = Time.now if !Thread.main["thread_exceptions"].nil? Thread.main["thread_exceptions"].each_key { |key| key_time = key[-14,14] exception_time = Time.mktime( key_time[0,4], key_time[4,2], key_time[6,2], key_time[8,2], key_time[10,2], key_time[12,2] ) Thread.main["thread_exceptions"].delete(key) if (time_now - exception_time) > 120 } end path = File.expand_path(File.dirname(__FILE__)) Dir.entries("#{path}/tmp/").reject!{ |f| !f.split("/").last.end_with?(".tmp") }.each { |f| filename_time = f[-18,14] file_time = Time.mktime( filename_time[0,4], filename_time[4,2], filename_time[6,2], filename_time[8,2], filename_time[10,2], filename_time[12,2] ) File.delete( File.join("#{path}/tmp/", f) ) if (time_now - file_time) > 120 } end def prettify( invalid_params ) message ="<div class=\"invalid_params_report\">" invalid_params.each do |key,value| param_name = key.gsub( /_/, " " ) param_name = param_name.slice(0,1).capitalize + param_name.slice(1..-1) message << "<div class=\"invalid_param\">#{param_name}: \"#{value}\"</div>" end message << "</div>" end end end Added auto create tmp dir. require 'rubygems' require 'sinatra' require 'json/pure' require 'delta3d' require 'base64' require 'openssl' require 'uri' require "sinatra/reloader" if development? set :environment, :development disable :raise_errors disable :show_exceptions path = File.expand_path(File.dirname(__FILE__)) Dir.mkdir( "#{path}/tmp" ) if !File.exist?( "#{path}/tmp" ) class Delta3DController get '/status' do body Thread.main["thread_exceptions"].inspect end get '/doc' do erb :doc end ['/index', '/'].each do |pattern| get pattern do erb :index end end post '/process' do content_type 'text/html' params['delta_parameters'] json_string = params['file']; json_string = params['file'][:tempfile].read if params['file'][:tempfile] parameters = params.reject { |key,value| key.eql?('file') } tmp_suffix = Time.now.strftime("%Y%m%d%H%M%S") thread = Thread.new(params['delta_parameters']) do |parameters| thread_id = "#{Thread.current.object_id}_#{tmp_suffix}" timeout = Thread.new { sleep(120); kill_thread( thread_id ) } Thread.current["thread_id"] = thread_id begin parameters = parameters.merge(parameters){ |key,old_val| old_val.eql?("") ? "0" : old_val } invalid_params = parameters.reject{ |param, value| Integer(value) rescue false } raise ArgumentError, "Invalid parameter(s) detected, please check: #{prettify(invalid_params)}" if invalid_params.length != 0 parameters = parameters.inject({}){ |memo, (key,value)| memo[key.to_sym]=Integer(value); memo } delta3d = Delta3D.new( json_string ) svgs = delta3d.plot( delta3d.calculate(parameters) ) path = File.expand_path(File.dirname(__FILE__)) svgs_tmp_file = File.new( "#{path}/tmp/#{thread_id}.tmp", "w" ) svgs_tmp_file.write( svgs ) svgs_tmp_file.close rescue Exception => e # puts e.inspect # puts e.backtrace list_exception( thread_id, e ) exit end end token = encrypt_token( "#{thread.object_id}_#{tmp_suffix}" ) Thread.new{ garbage_disposal } body "#{token}" end post '/svg_available' do params["token"].nil? ? svgs_tmp_filename = "" : svgs_tmp_filename = decrypt_token( params["token"] ) path = File.expand_path(File.dirname(__FILE__)) available = ( File.exist?( "#{path}/tmp/#{svgs_tmp_filename}.tmp" ) ? true : false ) if !Thread.main["thread_exceptions"].nil? && !Thread.main["thread_exceptions"][svgs_tmp_filename].nil? resp = Thread.main["thread_exceptions"][svgs_tmp_filename].message else resp = "#{available}" end body resp end post '/svg' do params["token"].nil? ? svgs_tmp_filename = "" : svgs_tmp_filename = decrypt_token( params["token"] ) path = File.expand_path(File.dirname(__FILE__)) svgs_tmp_filename = "#{path}/tmp/#{svgs_tmp_filename}.tmp" if File.exist?( svgs_tmp_filename ) body File.read( svgs_tmp_filename ) else halt 404, "SVG not found" end end error do puts "ouch ie ouch" "Something didn't went quite as expected - error: #{request.env['sinatra.error'].message}" end helpers do def inject_secret( mode ) path = File.expand_path(File.dirname(__FILE__)) secret_hash = JSON.load( File.new( "#{path}/secret.json", "r" ) ) aes = OpenSSL::Cipher.new("AES-256-CFB") aes.send( mode ) aes.key = Base64.decode64( secret_hash["key"] ) aes.iv = secret_hash["inivector"] aes end def encrypt_token( thread_id ) aes = inject_secret( :encrypt ) encrypted = aes.update( thread_id ) + aes.final token = Base64.encode64( encrypted ) token end def decrypt_token( token ) encrypted = Base64.decode64( token ) aes = inject_secret( :decrypt ) decrypted = aes.update( encrypted ) + aes.final decrypted end def list_exception( thread_id, excp ) if Thread.main["thread_exceptions"].nil? Thread.main["thread_exceptions"]={ thread_id => excp } else Thread.main["thread_exceptions"][thread_id] = excp end end def kill_thread( thread_id ) Thread.list.each do |thread| if thread["thread_id"].eql?(thread_id) thread.kill list_exception( thread_id, StandardError.new( "Delta computation execution time out… Try to adjust parameters to realize a less intensive calculation." ) ) end end end def garbage_disposal time_now = Time.now if !Thread.main["thread_exceptions"].nil? Thread.main["thread_exceptions"].each_key { |key| key_time = key[-14,14] exception_time = Time.mktime( key_time[0,4], key_time[4,2], key_time[6,2], key_time[8,2], key_time[10,2], key_time[12,2] ) Thread.main["thread_exceptions"].delete(key) if (time_now - exception_time) > 120 } end path = File.expand_path(File.dirname(__FILE__)) Dir.entries("#{path}/tmp/").reject!{ |f| !f.split("/").last.end_with?(".tmp") }.each { |f| filename_time = f[-18,14] file_time = Time.mktime( filename_time[0,4], filename_time[4,2], filename_time[6,2], filename_time[8,2], filename_time[10,2], filename_time[12,2] ) File.delete( File.join("#{path}/tmp/", f) ) if (time_now - file_time) > 120 } end def prettify( invalid_params ) message ="<div class=\"invalid_params_report\">" invalid_params.each do |key,value| param_name = key.gsub( /_/, " " ) param_name = param_name.slice(0,1).capitalize + param_name.slice(1..-1) message << "<div class=\"invalid_param\">#{param_name}: \"#{value}\"</div>" end message << "</div>" end end end
module Misc $CONFIG ||= { :domain => "clockingit.com" } # Format minutes => <tt>1w 2d 3h 3m</tt> def format_duration(minutes, duration_format, day_duration, days_per_week = 5) res = '' weeks = days = hours = 0 day_duration ||= 480 minutes ||= 0 if minutes >= 60 days = minutes / day_duration minutes = minutes - (days * day_duration) if days > 0 weeks = days / days_per_week days = days - (weeks * 5) if weeks > 0 hours = minutes / 60 minutes = minutes - (hours * 60) if hours > 0 res += "#{weeks}#{_('w')}#{' ' if duration_format == 0}" if weeks > 0 res += "#{days}#{_('d')}#{' ' if duration_format == 0}" if days > 0 res += "#{hours}#{_('h')}#{' ' if duration_format == 0}" if hours > 0 end res += "#{minutes}#{_('m')}" if minutes > 0 || res == '' if( duration_format == 2 ) res = if weeks > 0 format("%d:%d:%d:%02d", weeks, days, hours, minutes) elsif days > 0 format("%d:%d:%02d", days, hours, minutes) else format("%d:%02d", hours, minutes) end elsif( duration_format == 3 ) res = format("%d:%02d", ((weeks * day_duration * days_per_week) + (days * day_duration))/60 + hours, minutes) end res.strip end # Returns an array of languages codes that the client accepts sorted after # priority. Returns an empty array if the HTTP_ACCEPT_LANGUAGE header is # not present. def accept_locales return [] unless request.env.include? 'HTTP_ACCEPT_LANGUAGE' languages = request.env['HTTP_ACCEPT_LANGUAGE'].split(',').map do |al| al.gsub!(/-/, '_') al = al.split(';') (al.size == 1) ? [al.first, 1.0] : [al.first, al.last.split('=').last.to_f] end languages.reject {|x| x.last == 0 }.sort {|x,y| -(x.last <=> y.last) }.map {|x| x.first } end end class OrderedHash < Hash alias_method :store, :[]= alias_method :each_pair, :each def initialize @keys = [] end def []=(key, val) @keys << key super end def delete(key) @keys.delete(key) super end def each @keys.each { |k| yield k, self[k] } end def each_key @keys.each { |k| yield k } end def each_value @keys.each { |k| yield self[k] } end end Add missing days_per_week replacement module Misc $CONFIG ||= { :domain => "clockingit.com" } # Format minutes => <tt>1w 2d 3h 3m</tt> def format_duration(minutes, duration_format, day_duration, days_per_week = 5) res = '' weeks = days = hours = 0 day_duration ||= 480 minutes ||= 0 if minutes >= 60 days = minutes / day_duration minutes = minutes - (days * day_duration) if days > 0 weeks = days / days_per_week days = days - (weeks * days_per_week) if weeks > 0 hours = minutes / 60 minutes = minutes - (hours * 60) if hours > 0 res += "#{weeks}#{_('w')}#{' ' if duration_format == 0}" if weeks > 0 res += "#{days}#{_('d')}#{' ' if duration_format == 0}" if days > 0 res += "#{hours}#{_('h')}#{' ' if duration_format == 0}" if hours > 0 end res += "#{minutes}#{_('m')}" if minutes > 0 || res == '' if( duration_format == 2 ) res = if weeks > 0 format("%d:%d:%d:%02d", weeks, days, hours, minutes) elsif days > 0 format("%d:%d:%02d", days, hours, minutes) else format("%d:%02d", hours, minutes) end elsif( duration_format == 3 ) res = format("%d:%02d", ((weeks * day_duration * days_per_week) + (days * day_duration))/60 + hours, minutes) end res.strip end # Returns an array of languages codes that the client accepts sorted after # priority. Returns an empty array if the HTTP_ACCEPT_LANGUAGE header is # not present. def accept_locales return [] unless request.env.include? 'HTTP_ACCEPT_LANGUAGE' languages = request.env['HTTP_ACCEPT_LANGUAGE'].split(',').map do |al| al.gsub!(/-/, '_') al = al.split(';') (al.size == 1) ? [al.first, 1.0] : [al.first, al.last.split('=').last.to_f] end languages.reject {|x| x.last == 0 }.sort {|x,y| -(x.last <=> y.last) }.map {|x| x.first } end end class OrderedHash < Hash alias_method :store, :[]= alias_method :each_pair, :each def initialize @keys = [] end def []=(key, val) @keys << key super end def delete(key) @keys.delete(key) super end def each @keys.each { |k| yield k, self[k] } end def each_key @keys.each { |k| yield k } end def each_value @keys.each { |k| yield self[k] } end end
module Misc defaults = { :domain => "getjobsworth.org", :replyto => "admin", :from => "admin", :prefix => "[Jobsworth]" } $CONFIG ||= { } defaults.keys.each do |k| $CONFIG[k] ||= defaults[k] end $CONFIG[:email_domain] = $CONFIG[:domain].gsub(/:\d+/, '') # Format minutes => <tt>1w 2d 3h 3m</tt> def format_duration(minutes, duration_format, day_duration, days_per_week = 5) res = '' weeks = days = hours = 0 day_duration ||= 480 minutes ||= 0 if minutes >= 60 days = minutes / day_duration minutes = minutes - (days * day_duration) if days > 0 weeks = days / days_per_week days = days - (weeks * days_per_week) if weeks > 0 hours = minutes / 60 minutes = minutes - (hours * 60) if hours > 0 weeks = weeks.round(2) if [Float, BigDecimal].include?(weeks.class) days = days.round(2) if [Float, BigDecimal].include?(days.class) hours = hours.round(2) if [Float, BigDecimal].include?(hours.class) res += "#{weeks}#{_('w')}#{' ' if duration_format == 0}" if weeks > 0 res += "#{days}#{_('d')}#{' ' if duration_format == 0}" if days > 0 res += "#{hours}#{_('h')}#{' ' if duration_format == 0}" if hours > 0 end minutes = minutes.round(2) if [Float, BigDecimal].include?(minutes.class) res += "#{minutes}#{_('m')}" if minutes > 0 || res == '' if( duration_format == 2 ) res = if weeks > 0 format("%d:%d:%d:%02d", weeks, days, hours, minutes) elsif days > 0 format("%d:%d:%02d", days, hours, minutes) else format("%d:%02d", hours, minutes) end elsif( duration_format == 3 ) res = format("%d:%02d", ((weeks * day_duration * days_per_week) + (days * day_duration))/60 + hours, minutes) end res.strip end # Returns an array of languages codes that the client accepts sorted after # priority. Returns an empty array if the HTTP_ACCEPT_LANGUAGE header is # not present. def accept_locales return [] unless request.env.include? 'HTTP_ACCEPT_LANGUAGE' languages = request.env['HTTP_ACCEPT_LANGUAGE'].split(',').map do |al| al.gsub!(/-/, '_') al = al.split(';') (al.size == 1) ? [al.first, 1.0] : [al.first, al.last.split('=').last.to_f] end languages.reject {|x| x.last == 0 }.sort {|x,y| -(x.last <=> y.last) }.map {|x| x.first } end def html_encode(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end end class OrderedHash < Hash alias_method :store, :[]= alias_method :each_pair, :each def initialize @keys = [] end def []=(key, val) @keys << key super end def delete(key) @keys.delete(key) super end def each @keys.each { |k| yield k, self[k] } end def each_key @keys.each { |k| yield k } end def each_value @keys.each { |k| yield self[k] } end end Refactoring lib/misc.rb: remove unused class OrderdHash. If some one will need it in future, then use ActiveSupport::OrderHash. module Misc defaults = { :domain => "getjobsworth.org", :replyto => "admin", :from => "admin", :prefix => "[Jobsworth]" } $CONFIG ||= { } defaults.keys.each do |k| $CONFIG[k] ||= defaults[k] end $CONFIG[:email_domain] = $CONFIG[:domain].gsub(/:\d+/, '') # Format minutes => <tt>1w 2d 3h 3m</tt> def format_duration(minutes, duration_format, day_duration, days_per_week = 5) res = '' weeks = days = hours = 0 day_duration ||= 480 minutes ||= 0 if minutes >= 60 days = minutes / day_duration minutes = minutes - (days * day_duration) if days > 0 weeks = days / days_per_week days = days - (weeks * days_per_week) if weeks > 0 hours = minutes / 60 minutes = minutes - (hours * 60) if hours > 0 weeks = weeks.round(2) if [Float, BigDecimal].include?(weeks.class) days = days.round(2) if [Float, BigDecimal].include?(days.class) hours = hours.round(2) if [Float, BigDecimal].include?(hours.class) res += "#{weeks}#{_('w')}#{' ' if duration_format == 0}" if weeks > 0 res += "#{days}#{_('d')}#{' ' if duration_format == 0}" if days > 0 res += "#{hours}#{_('h')}#{' ' if duration_format == 0}" if hours > 0 end minutes = minutes.round(2) if [Float, BigDecimal].include?(minutes.class) res += "#{minutes}#{_('m')}" if minutes > 0 || res == '' if( duration_format == 2 ) res = if weeks > 0 format("%d:%d:%d:%02d", weeks, days, hours, minutes) elsif days > 0 format("%d:%d:%02d", days, hours, minutes) else format("%d:%02d", hours, minutes) end elsif( duration_format == 3 ) res = format("%d:%02d", ((weeks * day_duration * days_per_week) + (days * day_duration))/60 + hours, minutes) end res.strip end # Returns an array of languages codes that the client accepts sorted after # priority. Returns an empty array if the HTTP_ACCEPT_LANGUAGE header is # not present. def accept_locales return [] unless request.env.include? 'HTTP_ACCEPT_LANGUAGE' languages = request.env['HTTP_ACCEPT_LANGUAGE'].split(',').map do |al| al.gsub!(/-/, '_') al = al.split(';') (al.size == 1) ? [al.first, 1.0] : [al.first, al.last.split('=').last.to_f] end languages.reject {|x| x.last == 0 }.sort {|x,y| -(x.last <=> y.last) }.map {|x| x.first } end def html_encode(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end end
require_relative '../../../spec_helper' require_relative '../fixtures/common' describe "Logger::LogDevice#new" do before :each do @file_path = tmp("test_log.log") @log_file = File.open(@file_path, "w+") end after :each do @log_file.close unless @log_file.closed? rm_r @file_path end it "creates a new log device" do l = Logger::LogDevice.new(@log_file) l.dev.should be_kind_of(File) end it "receives an IO object to log there as first argument" do @log_file.should be_kind_of(IO) l = Logger::LogDevice.new(@log_file) l.write("foo") @log_file.rewind @log_file.readlines.first.should == "foo" end it "creates a File if the IO object does not exist" do path = tmp("test_logger_file") l = Logger::LogDevice.new(path) l.write("Test message") l.close File.exist?(path).should be_true File.open(path) do |f| f.readlines.should_not be_empty end rm_r path end it "receives options via a hash as second argument" do -> { Logger::LogDevice.new(STDERR, shift_age: 8, shift_size: 10 )}.should_not raise_error end end Wrap code require_relative '../../../spec_helper' require_relative '../fixtures/common' describe "Logger::LogDevice#new" do before :each do @file_path = tmp("test_log.log") @log_file = File.open(@file_path, "w+") end after :each do @log_file.close unless @log_file.closed? rm_r @file_path end it "creates a new log device" do l = Logger::LogDevice.new(@log_file) l.dev.should be_kind_of(File) end it "receives an IO object to log there as first argument" do @log_file.should be_kind_of(IO) l = Logger::LogDevice.new(@log_file) l.write("foo") @log_file.rewind @log_file.readlines.first.should == "foo" end it "creates a File if the IO object does not exist" do path = tmp("test_logger_file") l = Logger::LogDevice.new(path) l.write("Test message") l.close File.exist?(path).should be_true File.open(path) do |f| f.readlines.should_not be_empty end rm_r path end it "receives options via a hash as second argument" do -> { Logger::LogDevice.new(STDERR, shift_age: 8, shift_size: 10) }.should_not raise_error end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/twitter/version', __FILE__) Gem::Specification.new do |s| s.add_development_dependency('json', '~> 1.5') s.add_development_dependency('nokogiri', '~> 1.4') s.add_development_dependency('maruku', '~> 0.6') s.add_development_dependency('rake', '~> 0.8') s.add_development_dependency('rspec', '~> 2.5') s.add_development_dependency('simplecov', '~> 0.4') s.add_development_dependency('webmock', '~> 1.6') s.add_development_dependency('yard', '~> 0.6') s.add_development_dependency('ZenTest', '~> 4.5') s.add_runtime_dependency('hashie', '~> 1.0.0') s.add_runtime_dependency('faraday', '~> 0.5.4') s.add_runtime_dependency('faraday_middleware', '~> 0.3.2') s.add_runtime_dependency('jruby-openssl', '~> 0.7.2') if RUBY_PLATFORM == 'java' s.add_runtime_dependency('multi_json', '~> 0.0.5') s.add_runtime_dependency('multi_xml', '~> 0.2.0') s.add_runtime_dependency('simple_oauth', '~> 0.1.4') s.authors = ["John Nunemaker", "Wynn Netherland", "Erik Michaels-Ober", "Steve Richert"] s.description = %q{A Ruby wrapper for the Twitter REST and Search APIs} s.post_install_message =<<eos ******************************************************************************** Follow @gem on Twitter for announcements, updates, and news. https://twitter.com/gem Join the mailing list! https://groups.google.com/group/ruby-twitter-gem Add your project or organization to the apps wiki! https://github.com/jnunemaker/twitter/wiki/apps ******************************************************************************** eos s.email = ['nunemaker@gmail.com', 'wynn.netherland@gmail.com', 'sferik@gmail.com', 'steve.richert@gmail.com'] s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.files = `git ls-files`.split("\n") s.homepage = 'https://github.com/jnunemaker/twitter' s.name = 'twitter' s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') if s.respond_to? :required_rubygems_version= s.rubyforge_project = s.name s.summary = %q{Ruby wrapper for the Twitter API} s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.version = Twitter::VERSION.dup end Update faraday and faraday_middleware to 0.6 # -*- encoding: utf-8 -*- require File.expand_path('../lib/twitter/version', __FILE__) Gem::Specification.new do |s| s.add_development_dependency('json', '~> 1.5') s.add_development_dependency('nokogiri', '~> 1.4') s.add_development_dependency('maruku', '~> 0.6') s.add_development_dependency('rake', '~> 0.8') s.add_development_dependency('rspec', '~> 2.5') s.add_development_dependency('simplecov', '~> 0.4') s.add_development_dependency('webmock', '~> 1.6') s.add_development_dependency('yard', '~> 0.6') s.add_development_dependency('ZenTest', '~> 4.5') s.add_runtime_dependency('hashie', '~> 1.0.0') s.add_runtime_dependency('faraday', '~> 0.6.0') s.add_runtime_dependency('faraday_middleware', '~> 0.6.0') s.add_runtime_dependency('jruby-openssl', '~> 0.7.2') if RUBY_PLATFORM == 'java' s.add_runtime_dependency('multi_json', '~> 0.0.5') s.add_runtime_dependency('multi_xml', '~> 0.2.0') s.add_runtime_dependency('simple_oauth', '~> 0.1.4') s.authors = ["John Nunemaker", "Wynn Netherland", "Erik Michaels-Ober", "Steve Richert"] s.description = %q{A Ruby wrapper for the Twitter REST and Search APIs} s.post_install_message =<<eos ******************************************************************************** Follow @gem on Twitter for announcements, updates, and news. https://twitter.com/gem Join the mailing list! https://groups.google.com/group/ruby-twitter-gem Add your project or organization to the apps wiki! https://github.com/jnunemaker/twitter/wiki/apps ******************************************************************************** eos s.email = ['nunemaker@gmail.com', 'wynn.netherland@gmail.com', 'sferik@gmail.com', 'steve.richert@gmail.com'] s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.files = `git ls-files`.split("\n") s.homepage = 'https://github.com/jnunemaker/twitter' s.name = 'twitter' s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') if s.respond_to? :required_rubygems_version= s.rubyforge_project = s.name s.summary = %q{Ruby wrapper for the Twitter API} s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.version = Twitter::VERSION.dup end
# encoding: utf-8 require File.expand_path('../lib/twitter/version', __FILE__) Gem::Specification.new do |gem| gem.add_dependency 'faraday', '~> 0.7.4' gem.add_dependency 'multi_json', '~> 1.0.0' gem.add_dependency 'simple_oauth', '~> 0.1.5' gem.add_dependency 'twitter-text', '~> 1.4.2' gem.add_development_dependency 'json', '~> 1.6' gem.add_development_dependency 'rake', '~> 0.9' gem.add_development_dependency 'rdiscount', '~> 1.6' gem.add_development_dependency 'rspec', '~> 2.6' gem.add_development_dependency 'simplecov', '~> 0.4' gem.add_development_dependency 'webmock', '~> 1.7' gem.add_development_dependency 'yard', '~> 0.7' gem.authors = ["John Nunemaker", "Wynn Netherland", "Erik Michaels-Ober", "Steve Richert"] gem.description = %q{A Ruby wrapper for the Twitter API.} gem.email = ['nunemaker@gmail.com', 'wynn.netherland@gmail.com', 'sferik@gmail.com', 'steve.richert@gmail.com'] gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} gem.files = `git ls-files`.split("\n") gem.homepage = 'https://github.com/jnunemaker/twitter' gem.name = 'twitter' gem.post_install_message =<<eos ******************************************************************************** Follow @gem on Twitter for announcements, updates, and news. https://twitter.com/gem Join the mailing list! https://groups.google.com/group/ruby-twitter-gem Add your project or organization to the apps wiki! https://github.com/jnunemaker/twitter/wiki/apps ******************************************************************************** eos gem.require_paths = ['lib'] gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') gem.summary = %q{Twitter API wrapper} gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.version = Twitter::Version.to_s end Update post install message # encoding: utf-8 require File.expand_path('../lib/twitter/version', __FILE__) Gem::Specification.new do |gem| gem.add_dependency 'faraday', '~> 0.7.4' gem.add_dependency 'multi_json', '~> 1.0.0' gem.add_dependency 'simple_oauth', '~> 0.1.5' gem.add_dependency 'twitter-text', '~> 1.4.2' gem.add_development_dependency 'json', '~> 1.6' gem.add_development_dependency 'rake', '~> 0.9' gem.add_development_dependency 'rdiscount', '~> 1.6' gem.add_development_dependency 'rspec', '~> 2.6' gem.add_development_dependency 'simplecov', '~> 0.4' gem.add_development_dependency 'webmock', '~> 1.7' gem.add_development_dependency 'yard', '~> 0.7' gem.authors = ["John Nunemaker", "Wynn Netherland", "Erik Michaels-Ober", "Steve Richert"] gem.description = %q{A Ruby wrapper for the Twitter API.} gem.email = ['nunemaker@gmail.com', 'wynn.netherland@gmail.com', 'sferik@gmail.com', 'steve.richert@gmail.com'] gem.executables = `git ls-files -- bin/*`.split("\n").map{|f| File.basename(f)} gem.files = `git ls-files`.split("\n") gem.homepage = 'https://github.com/jnunemaker/twitter' gem.name = 'twitter' gem.post_install_message =<<eos ******************************************************************************** You should follow @gem on Twitter for announcements and updates about the gem. https://twitter.com/gem Please direct any questions about the library to the mailing list. https://groups.google.com/group/ruby-twitter-gem Does your project or organization use this gem? Add it to the apps wiki! https://github.com/jnunemaker/twitter/wiki/apps ******************************************************************************** eos gem.require_paths = ['lib'] gem.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') gem.summary = %q{Twitter API wrapper} gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.version = Twitter::Version.to_s end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'typedJS/version' Gem::Specification.new do |spec| spec.name = "typedJS" spec.version = TypedJS::VERSION spec.authors = ["Amit"] spec.email = ["gudeamit148@gmail.com"] spec.summary = %q{This gem allows to users to simulate typing animation for some text} spec.description = %q{This gem allows to users to simulate typing animation for some text} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") 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.7" spec.add_development_dependency "rake", "~> 10.0" end updated gemspec file # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'typedJS/version' Gem::Specification.new do |spec| spec.name = "typedJS" spec.version = TypedJS::VERSION spec.authors = ["Amit"] spec.email = ["gudeamit148@gmail.com"] spec.summary = %q{This gem allows to users to simulate typing animation for some text} spec.description = %q{This gem allows to users to simulate typing animation for some text} spec.homepage = "https://github.com/amitgude/TypedJsGem" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") 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.7" spec.add_development_dependency "rake", "~> 10.0" end
require "spec_helper" require "aruba/matchers/file" RSpec.describe "File Matchers" do include_context "uses aruba API" describe "to_be_an_existing_file" do let(:name) { @file_name } context "when file exists" do before { create_test_files(name) } it { expect(name).to be_an_existing_file } end context "when file does not exist" do it { expect(name).not_to be_an_existing_file } end context "when contains ~" do let(:name) { File.join("~", random_string) } before do @aruba.with_environment "HOME" => expand_path(".") do create_test_files(name) end end it do @aruba.with_environment "HOME" => expand_path(".") do expect(name).to be_an_existing_file end end end end describe "to_have_file_content" do context "when file exists" do before do Aruba.platform.write_file(@file_path, "aba") end context "and file content is exactly equal string " do it { expect(@file_name).to have_file_content("aba") } end context "and file content contains string" do it { expect(@file_name).to have_file_content(/b/) } end context "and file content is not exactly equal string" do it { expect(@file_name).not_to have_file_content("c") } end context "and file content not contains string" do it { expect(@file_name).not_to have_file_content(/c/) } end context 'when other matchers is given which matches a string start with "a"' do it { expect(@file_name).to have_file_content(a_string_starting_with("a")) } end end context "when file does not exist" do it { expect(@file_name).not_to have_file_content("a") } end describe "description" do context "when string" do it { expect(have_file_content("a").description).to eq('have file content: "a"') } end context "when regexp" do it { expect(have_file_content(/a/).description).to eq("have file content: /a/") } end it "is correct when using a matcher" do expect(have_file_content(a_string_starting_with("a")).description) .to eq('have file content: a string starting with "a"') end end describe "failure messages" do def fail_with(message) raise_error(RSpec::Expectations::ExpectationNotMetError, message) end example "for a string" do expect do expect(@file_name).to have_file_content("z") end.to fail_with('expected "test.txt" to have file content: "z"') end example "for a regular expression" do expect do expect(@file_name).to have_file_content(/z/) end.to fail_with('expected "test.txt" to have file content: /z/') end example "for a matcher" do expect { expect(@file_name).to have_file_content(a_string_starting_with("z")) } .to fail_with( 'expected "test.txt" to have file content: a string starting with "z"' ) end end end describe "to have_same_file_content_as" do let(:file_name) { @file_name } let(:file_path) { @file_path } let(:reference_file) { "fixture" } before do @aruba.write_file(@file_name, "foo bar baz") @aruba.write_file(reference_file, reference_file_content) end context "when files are the same" do let(:reference_file_content) { "foo bar baz" } context "and this is expected" do it { expect(file_name).to have_same_file_content_as reference_file } end context "and this is not expected" do it do expect { expect(file_name).not_to have_same_file_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end context "when files are not the same" do let(:reference_file_content) { "bar" } context "and this is expected" do it { expect(file_name).not_to have_same_file_content_as reference_file } end context "and this is not expected" do it do expect { expect(file_name).to have_same_file_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end end describe "include a_file_with_same_content_as" do let(:reference_file) { "fixture" } let(:reference_file_content) { "foo bar baz" } let(:file_with_same_content) { "file_a.txt" } let(:file_with_different_content) { "file_b.txt" } before do @aruba.write_file(file_with_same_content, reference_file_content) @aruba.write_file(reference_file, reference_file_content) @aruba.write_file(file_with_different_content, "Some different content here...") end context "when the array of files includes a file with the same content" do let(:files) { [file_with_different_content, file_with_same_content] } context "and this is expected" do it { expect(files).to include a_file_with_same_content_as reference_file } end context "and this is not expected" do it do expect { expect(files).not_to include a_file_with_same_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end context "when the array of files does not include a file with the same content" do let(:files) { [file_with_different_content] } context "and this is expected" do it { expect(files).not_to include a_file_with_same_content_as reference_file } end context "and this is not expected" do it do expect { expect(files).to include a_file_with_same_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end end describe "to_have_file_size" do context "when file exists" do before do Aruba.platform.write_file(@file_path, "") end context "and file size is equal" do it { expect(@file_name).to have_file_size(0) } end context "and file size is not equal" do it { expect(@file_name).not_to have_file_size(1) } end end context "when file does not exist" do it { expect(@file_name).not_to have_file_size(0) } end end end Fix specs for have_file_content matcher This avoids a rare test failure that seems to happen if the file under test accidentally exists. - Give file under test known contents instead of assuming it does not exist - Update expected failure messages require "spec_helper" require "aruba/matchers/file" RSpec.describe "File Matchers" do include_context "uses aruba API" describe "to_be_an_existing_file" do let(:name) { @file_name } context "when file exists" do before { create_test_files(name) } it { expect(name).to be_an_existing_file } end context "when file does not exist" do it { expect(name).not_to be_an_existing_file } end context "when contains ~" do let(:name) { File.join("~", random_string) } before do @aruba.with_environment "HOME" => expand_path(".") do create_test_files(name) end end it do @aruba.with_environment "HOME" => expand_path(".") do expect(name).to be_an_existing_file end end end end describe "to_have_file_content" do context "when file exists" do before do Aruba.platform.write_file(@file_path, "aba") end context "and file content is exactly equal string " do it { expect(@file_name).to have_file_content("aba") } end context "and file content contains string" do it { expect(@file_name).to have_file_content(/b/) } end context "and file content is not exactly equal string" do it { expect(@file_name).not_to have_file_content("c") } end context "and file content not contains string" do it { expect(@file_name).not_to have_file_content(/c/) } end context 'when other matchers is given which matches a string start with "a"' do it { expect(@file_name).to have_file_content(a_string_starting_with("a")) } end end context "when file does not exist" do it { expect(@file_name).not_to have_file_content("a") } end describe "description" do context "when string" do it { expect(have_file_content("a").description).to eq('have file content: "a"') } end context "when regexp" do it { expect(have_file_content(/a/).description).to eq("have file content: /a/") } end it "is correct when using a matcher" do expect(have_file_content(a_string_starting_with("a")).description) .to eq('have file content: a string starting with "a"') end end describe "failure messages" do before do Aruba.platform.write_file(@file_path, "aba") end def fail_with(message) raise_error(RSpec::Expectations::ExpectationNotMetError, message) end example "for a string" do expect do expect(@file_name).to have_file_content("z") end.to fail_with('expected "aba" to have file content: "z"') end example "for a regular expression" do expect do expect(@file_name).to have_file_content(/z/) end.to fail_with('expected "aba" to have file content: /z/') end example "for a matcher" do expect do expect(@file_name).to have_file_content(a_string_starting_with("z")) end.to fail_with 'expected "aba" to have file content: a string starting with "z"' end end end describe "to have_same_file_content_as" do let(:file_name) { @file_name } let(:file_path) { @file_path } let(:reference_file) { "fixture" } before do @aruba.write_file(@file_name, "foo bar baz") @aruba.write_file(reference_file, reference_file_content) end context "when files are the same" do let(:reference_file_content) { "foo bar baz" } context "and this is expected" do it { expect(file_name).to have_same_file_content_as reference_file } end context "and this is not expected" do it do expect { expect(file_name).not_to have_same_file_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end context "when files are not the same" do let(:reference_file_content) { "bar" } context "and this is expected" do it { expect(file_name).not_to have_same_file_content_as reference_file } end context "and this is not expected" do it do expect { expect(file_name).to have_same_file_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end end describe "include a_file_with_same_content_as" do let(:reference_file) { "fixture" } let(:reference_file_content) { "foo bar baz" } let(:file_with_same_content) { "file_a.txt" } let(:file_with_different_content) { "file_b.txt" } before do @aruba.write_file(file_with_same_content, reference_file_content) @aruba.write_file(reference_file, reference_file_content) @aruba.write_file(file_with_different_content, "Some different content here...") end context "when the array of files includes a file with the same content" do let(:files) { [file_with_different_content, file_with_same_content] } context "and this is expected" do it { expect(files).to include a_file_with_same_content_as reference_file } end context "and this is not expected" do it do expect { expect(files).not_to include a_file_with_same_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end context "when the array of files does not include a file with the same content" do let(:files) { [file_with_different_content] } context "and this is expected" do it { expect(files).not_to include a_file_with_same_content_as reference_file } end context "and this is not expected" do it do expect { expect(files).to include a_file_with_same_content_as reference_file } .to raise_error RSpec::Expectations::ExpectationNotMetError end end end end describe "to_have_file_size" do context "when file exists" do before do Aruba.platform.write_file(@file_path, "") end context "and file size is equal" do it { expect(@file_name).to have_file_size(0) } end context "and file size is not equal" do it { expect(@file_name).not_to have_file_size(1) } end end context "when file does not exist" do it { expect(@file_name).not_to have_file_size(0) } end end end
require "spec_helper" $:.unshift File.dirname(__FILE__) + "/../ext/balance_tags_c" require "balance_tags_c.so" describe "BalanceTagsCExtension" do describe "text without tags" do it "should be left untouched" do text = "Foo bar baz, this is my excellent test text!" Pidgin2Adium.balance_tags_c(text).should == text end end describe "text with tags" do it "should be balanced correctly" do Pidgin2Adium.balance_tags_c('<p><b>this is unbalanced!').should == "<p><b>this is unbalanced!</b></p>" end # Make sure it doesn't segfault it "should be balanced correctly when run many times" do 5_000.times do text = Faker::Lorem.paragraphs(3) Pidgin2Adium.balance_tags_c("<p><b>#{text}").should == "<p><b>#{text}</b></p>" end end end end Only run balance_tags_c 2000 times require "spec_helper" $:.unshift File.dirname(__FILE__) + "/../ext/balance_tags_c" require "balance_tags_c.so" describe "BalanceTagsCExtension" do describe "text without tags" do it "should be left untouched" do text = "Foo bar baz, this is my excellent test text!" Pidgin2Adium.balance_tags_c(text).should == text end end describe "text with tags" do it "should be balanced correctly" do Pidgin2Adium.balance_tags_c('<p><b>this is unbalanced!').should == "<p><b>this is unbalanced!</b></p>" end # Make sure it doesn't segfault it "should be balanced correctly when run many times" do 2_000.times do text = Faker::Lorem.paragraphs(3) Pidgin2Adium.balance_tags_c("<p><b>#{text}").should == "<p><b>#{text}</b></p>" end end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe BasicGem do describe 'version' do it "should return a string formatted '#.#.#'" do BasicGem::version.should match(/(^[\d]+\.[\d]+\.[\d]+$)/) end end # VIM autocmd to remove trailing whitespace # autocmd BufWritePre * :%s/\s\+$//e # describe "code" do def check_for_tab_characters(filename) failing_lines = [] File.readlines(filename).each_with_index do |line,number| failing_lines << number + 1 if line =~ /\t/ end unless failing_lines.empty? "#{filename} has tab characters on lines #{failing_lines.join(', ')}" end end def check_for_extra_spaces(filename) failing_lines = [] File.readlines(filename).each_with_index do |line,number| next if line =~ /^\s+#.*\s+\n$/ failing_lines << number + 1 if line =~ /\s+\n$/ end unless failing_lines.empty? "#{filename} has spaces on the EOL on lines #{failing_lines.join(', ')}" end end Spec::Matchers.define :be_well_formed do failure_message_for_should do |actual| actual.join("\n") end match do |actual| actual.empty? end end it "has no malformed whitespace" do error_messages = [] gemfiles_filename = File.expand_path(File.dirname(__FILE__) + '/../../.gemfiles') files = File.open(gemfiles_filename, "r") {|f| f.read} files.split("\n").each do |filename| error_messages << check_for_tab_characters(filename) error_messages << check_for_extra_spaces(filename) end error_messages.compact.should be_well_formed end end end malformed whitespace spec works with CRLF require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe BasicGem do describe 'version' do it "should return a string formatted '#.#.#'" do BasicGem::version.should match(/(^[\d]+\.[\d]+\.[\d]+$)/) end end # VIM autocmd to remove trailing whitespace # autocmd BufWritePre * :%s/\s\+$//e # describe "code" do before(:each) do @gemfiles_filename = File.expand_path(File.dirname(__FILE__) + '/../../.gemfiles') @gemfiles = File.open(@gemfiles_filename, "r") {|f| f.read} @eol = @gemfiles.match("\r\n") ? "\r\n" : "\n" end def binary?(filename) open filename do |f| f.each_byte { |x| x.nonzero? or return true } end false end def check_for_tab_characters(filename) failing_lines = [] File.readlines(filename).each_with_index do |line,number| failing_lines << number + 1 if line =~ /\t/ end unless failing_lines.empty? "#{filename} has tab characters on lines #{failing_lines.join(', ')}" end end def check_for_extra_spaces(filename) failing_lines = [] File.readlines(filename).each_with_index do |line,number| next if line =~ /^\s+#.*\s+#{@eol}$/ failing_lines << number + 1 if line =~ /\s+#{@eol}$/ end unless failing_lines.empty? "#{filename} has spaces on the EOL on lines #{failing_lines.join(', ')}" end end Spec::Matchers.define :be_well_formed do failure_message_for_should do |actual| actual.join("\n") end match do |actual| actual.empty? end end it "has no malformed whitespace" do error_messages = [] @gemfiles.split(@eol).each do |filename| filename = File.expand_path(File.join(File.dirname(__FILE__), ["..", "..", filename])) next if filename =~ /\.gitmodules/ next if binary?(filename) error_messages << check_for_tab_characters(filename) error_messages << check_for_extra_spaces(filename) end error_messages.compact.should be_well_formed end end end
RSpec.describe 'duse secret' do before :each do FileUtils.mkdir_p Duse::CLIConfig.config_dir open(Duse::CLIConfig.config_file, 'w') do |f| f.puts '---' f.puts 'uri: https://example.com/' f.puts 'token: token' end open(File.join(Duse::CLIConfig.config_dir, 'flower-pot'), 'w') do |f| f.puts "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAmMm3Ovh7gU0rLHK4NiHhWaYRrV9PH6XtHqV0GoiHH7awrjVk\nT1aZiS+nlBxckfuvuQjRXakVCZh18UdQadVQ7FLTWMZNoZ/uh41g4Iv17Wh1I3Fg\nqihdm83cSWvJ81qQCVGBaKeVitSa49zT/MmooBvYFwulaqJjhqFc3862Rl3WowzG\nVqGf+OiYhFrBbnIqXijDmVKsbqkG5AILGo1nng06HIAvMqUcGMebgoju9SuKaR+C\n46KT0K5sPpNw/tNcDEZqZAd25QjAroGnpRHSI9hTEuPopPSyRqz/EVQfbhi0Lbkd\nDW9S5ECw7GfFPFpRp2239fjl/9ybL6TkeZL7AwIDAQABAoIBAQCGSVyLLxRWC/4z\nPc0cfuCyy5xj1g4UEeD7+421OGQTAp39L54vgTzG76SJL/hIsn660b46ZL7BxUd8\nPiK2Mi/C1fU95GUc9hVO/Hq2QS1wcUvrT94XEA1eQCwqN9uy0Nkh54om8owkDkLo\nnRGQ76kOuApQDwNfWsTA8phPeT6JTtr+2K2yc0H4G5G0+py2GDclq56E99SljAqq\nwjFKGazqF0pxJvqLRCR9uVt0FgrRANOLGvxPMNZtnkVBVHmXs1iRD7BUALfESGS1\nHXZxjvD487E2h0Vjkli7rqnu6FZNgQ8Mq5TOfIm5i04LeGCgSTNP9sw7vdZgaYgT\nDPK9BIlZAoGBAMlhenDUOkT1dm28CjGCkygM1kUgDTQDLyBXW/JacotRp3GVZLr2\nV/2rZ3JPxva0cjjs3X4q/CxYsHvqI/ImXbsTBOYIT1/y1fgmXvN6AbiVW5Qne1UD\nneEGqCyB6YfKV2/8CX5Ru01Ay1EYVQDU4APkR1P4H38CuTMeu8SHK/BHAoGBAMI6\nR6TeEIdLprWRmUKU8Iuiwwm0SVxle2trSj6mknsJ93sK7gQkoKNzw0qwZdM6ApKH\nbJo/LiwiZ1Znx1NOyDsKT/ET6CSl59jOBuSUoxqTJ8XvrWlSD8pkbOJ2zWF8WqFR\ncC74bNFgd+n0tftR/7dwkriebITrp5IpF6P2Z9llAoGAAqO3ciEl/l9lRPzw+UMn\n4J+Cc3d/FM5x4K+kceHDnJXeZvu5TUYLUzTa70Gibvtgf+SC5rNziLVE4urnu7XL\nBreyGb3EJJLPQShnmDNiMGQsxh1aXXvlptxqeeLeB7ycNsiL607w8ItH3vE9s/wW\nT5a/ZJdc+lIz0Tq25VWMOuMCgYAejVZZu8izz5WguA94pr8T5/1wGFj13MzGP/FE\n26TtD8tLIpQAONa//2S36fmKeXSQIhdWSBv2O08wC1ESbLEYgG3EyVHZ+fL3aqkw\n6aSieIVoIGSRzaPIPXXXRcLW093ZxFq2OMO9R8R1G9ZIe0STUXTy75C4c+0/E5Gx\nbAA39QKBgDLjtjmG3nJGpQuaftAAjJR+AcA3svSdVug7w5k6D+lxBeM/x4pGP9z4\nkdOrqeD6bv1cctouVVywK/ZQ8dyLczJoGfJIlCvacI1L7fyVUpBp2Lby/uwYMd5w\ngswew+6Xnvtx15SirvYQmDRzA71KBSA4GxpaFwthRIxIwn881m5U\n-----END RSA PRIVATE KEY-----\n" end end describe 'get' do context 'provide secret id from the call' do it 'takes the secrets id from the cli call and does not ask for it' do stub_secret_get stub_user_me_get stub_server_user_get expect(run_cli('secret', 'get', '1').out).to eq( "\nName: test\nSecret: test\nAccess: server, flower-pot\n" ) end it 'outputs the secret content plaintext when using the plain flag' do stub_secret_get stub_user_me_get stub_server_user_get expect(run_cli('secret', 'get', '1', '--plain').out).to eq("test") end end context 'secret does not exist' do it 'shows an error message when getting not existant secrets' do stub_request(:get, "https://example.com/secrets/2"). with(headers: {'Accept'=>'application/vnd.duse.1+json', 'Authorization'=>'token'}). to_return(status: 404, body: { message: 'Not found' }.to_json) expect(run_cli('secret', 'get', '2').err).to eq( "Not found\n" ) end end context 'secret exists' do it 'asks for the secret id' do stub_secret_get stub_user_me_get stub_server_user_get expect(run_cli('secret', 'get') { |i| i.puts('1') }.out).to eq( "Secret to retrieve: \nName: test\nSecret: test\nAccess: server, flower-pot\n" ) end end end describe 'list' do it 'lists secrets' do stub_get_secrets expect(run_cli('secret', 'list').out).to eq( "1: test\n" ) end end describe 'delete' do it 'deletes the provided secret id' do stub_request(:delete, "https://example.com/secrets/1"). with(headers: {'Accept'=>'application/vnd.duse.1+json', 'Authorization'=>'token'}). to_return(status: 204, body: "", headers: {}) expect(run_cli('secret', 'remove', '1').success?).to be true end end describe 'add' do context 'minimal users' do it 'can create a secret' do stub_get_users stub_user_me_get stub_server_user_get stub_create_secret expect(run_cli('secret', 'add') do |i| i.puts 'test' i.puts 'test' i.puts 'n' end.success?).to be true end end context 'multiple users' do it 'can create a secret with multiple users' do stub_get_users stub_user_me_get stub_server_user_get stub_get_other_user stub_create_secret expect(run_cli('secret', 'add') do |i| i.puts 'test' i.puts 'test' i.puts 'Y' i.puts '1' end.success?).to be true end end context 'invalid user input' do it 'repeats asking for a users selection if the previous selection was invalid' do stub_get_users stub_user_me_get stub_server_user_get stub_get_other_user stub_create_secret expect(run_cli('secret', 'add') do |i| i.puts 'test' i.puts 'test' i.puts 'Y' i.puts '3' i.puts '1' end.success?).to be true end end end end fix tests adapt to recent changes RSpec.describe 'duse secret' do before :each do FileUtils.mkdir_p Duse::CLIConfig.config_dir open(Duse::CLIConfig.config_file, 'w') do |f| f.puts '---' f.puts 'uri: https://example.com/' f.puts 'token: token' end open(File.join(Duse::CLIConfig.config_dir, 'flower-pot'), 'w') do |f| f.puts "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAmMm3Ovh7gU0rLHK4NiHhWaYRrV9PH6XtHqV0GoiHH7awrjVk\nT1aZiS+nlBxckfuvuQjRXakVCZh18UdQadVQ7FLTWMZNoZ/uh41g4Iv17Wh1I3Fg\nqihdm83cSWvJ81qQCVGBaKeVitSa49zT/MmooBvYFwulaqJjhqFc3862Rl3WowzG\nVqGf+OiYhFrBbnIqXijDmVKsbqkG5AILGo1nng06HIAvMqUcGMebgoju9SuKaR+C\n46KT0K5sPpNw/tNcDEZqZAd25QjAroGnpRHSI9hTEuPopPSyRqz/EVQfbhi0Lbkd\nDW9S5ECw7GfFPFpRp2239fjl/9ybL6TkeZL7AwIDAQABAoIBAQCGSVyLLxRWC/4z\nPc0cfuCyy5xj1g4UEeD7+421OGQTAp39L54vgTzG76SJL/hIsn660b46ZL7BxUd8\nPiK2Mi/C1fU95GUc9hVO/Hq2QS1wcUvrT94XEA1eQCwqN9uy0Nkh54om8owkDkLo\nnRGQ76kOuApQDwNfWsTA8phPeT6JTtr+2K2yc0H4G5G0+py2GDclq56E99SljAqq\nwjFKGazqF0pxJvqLRCR9uVt0FgrRANOLGvxPMNZtnkVBVHmXs1iRD7BUALfESGS1\nHXZxjvD487E2h0Vjkli7rqnu6FZNgQ8Mq5TOfIm5i04LeGCgSTNP9sw7vdZgaYgT\nDPK9BIlZAoGBAMlhenDUOkT1dm28CjGCkygM1kUgDTQDLyBXW/JacotRp3GVZLr2\nV/2rZ3JPxva0cjjs3X4q/CxYsHvqI/ImXbsTBOYIT1/y1fgmXvN6AbiVW5Qne1UD\nneEGqCyB6YfKV2/8CX5Ru01Ay1EYVQDU4APkR1P4H38CuTMeu8SHK/BHAoGBAMI6\nR6TeEIdLprWRmUKU8Iuiwwm0SVxle2trSj6mknsJ93sK7gQkoKNzw0qwZdM6ApKH\nbJo/LiwiZ1Znx1NOyDsKT/ET6CSl59jOBuSUoxqTJ8XvrWlSD8pkbOJ2zWF8WqFR\ncC74bNFgd+n0tftR/7dwkriebITrp5IpF6P2Z9llAoGAAqO3ciEl/l9lRPzw+UMn\n4J+Cc3d/FM5x4K+kceHDnJXeZvu5TUYLUzTa70Gibvtgf+SC5rNziLVE4urnu7XL\nBreyGb3EJJLPQShnmDNiMGQsxh1aXXvlptxqeeLeB7ycNsiL607w8ItH3vE9s/wW\nT5a/ZJdc+lIz0Tq25VWMOuMCgYAejVZZu8izz5WguA94pr8T5/1wGFj13MzGP/FE\n26TtD8tLIpQAONa//2S36fmKeXSQIhdWSBv2O08wC1ESbLEYgG3EyVHZ+fL3aqkw\n6aSieIVoIGSRzaPIPXXXRcLW093ZxFq2OMO9R8R1G9ZIe0STUXTy75C4c+0/E5Gx\nbAA39QKBgDLjtjmG3nJGpQuaftAAjJR+AcA3svSdVug7w5k6D+lxBeM/x4pGP9z4\nkdOrqeD6bv1cctouVVywK/ZQ8dyLczJoGfJIlCvacI1L7fyVUpBp2Lby/uwYMd5w\ngswew+6Xnvtx15SirvYQmDRzA71KBSA4GxpaFwthRIxIwn881m5U\n-----END RSA PRIVATE KEY-----\n" end end describe 'get' do context 'provide secret id from the call' do it 'takes the secrets id from the cli call and does not ask for it' do stub_secret_get stub_user_me_get stub_server_user_get expect(run_cli('secret', 'get', '1').out).to eq( "\nName: test\nSecret: test\nAccess: flower-pot\n" ) end it 'outputs the secret content plaintext when using the plain flag' do stub_secret_get stub_user_me_get stub_server_user_get expect(run_cli('secret', 'get', '1', '--plain').out).to eq("test") end end context 'secret does not exist' do it 'shows an error message when getting not existant secrets' do stub_request(:get, "https://example.com/secrets/2"). with(headers: {'Accept'=>'application/vnd.duse.1+json', 'Authorization'=>'token'}). to_return(status: 404, body: { message: 'Not found' }.to_json) expect(run_cli('secret', 'get', '2').err).to eq( "Not found\n" ) end end context 'secret exists' do it 'asks for the secret id' do stub_get_secrets stub_secret_get stub_user_me_get stub_server_user_get expect(run_cli('secret', 'get') { |i| i.puts('1') }.out).to eq( "1: test\n\nSelect the id of the secret to retrieve: \nName: test\nSecret: test\nAccess: flower-pot\n" ) end end end describe 'list' do it 'lists secrets' do stub_get_secrets expect(run_cli('secret', 'list').out).to eq( "1: test\n" ) end end describe 'delete' do it 'deletes the provided secret id' do stub_request(:delete, "https://example.com/secrets/1"). with(headers: {'Accept'=>'application/vnd.duse.1+json', 'Authorization'=>'token'}). to_return(status: 204, body: "", headers: {}) expect(run_cli('secret', 'remove', '1').success?).to be true end end describe 'add' do context 'minimal users' do it 'can create a secret' do stub_get_users stub_user_me_get stub_server_user_get stub_create_secret expect(run_cli('secret', 'add') do |i| i.puts 'test' i.puts 'test' i.puts 'n' end.success?).to be true end end context 'multiple users' do it 'can create a secret with multiple users' do stub_get_users stub_user_me_get stub_server_user_get stub_get_other_user stub_create_secret expect(run_cli('secret', 'add') do |i| i.puts 'test' i.puts 'test' i.puts 'Y' i.puts '1' end.success?).to be true end end context 'invalid user input' do it 'repeats asking for a users selection if the previous selection was invalid' do stub_get_users stub_user_me_get stub_server_user_get stub_get_other_user stub_create_secret expect(run_cli('secret', 'add') do |i| i.puts 'test' i.puts 'test' i.puts 'Y' i.puts '3' i.puts '1' end.success?).to be true end end end end
$:.unshift('../ruote/lib') $:.unshift('lib') require 'fileutils' FileUtils.rm_rf('ruote_work') require 'ruote/beanstalk' Ruote::Beanstalk::Storage.new(':11300', 'ruote_work', :fork => true) need to require rubygems for 'ruby serve.rb' require 'rubygems' $:.unshift('../ruote/lib') $:.unshift('lib') require 'fileutils' FileUtils.rm_rf('ruote_work') require 'ruote/beanstalk' Ruote::Beanstalk::Storage.new(':11300', 'ruote_work', :fork => true)
require 'cybersourcery_testing/cybersource_proxy' VCR.configure do |c| c.register_request_matcher :card_type_equality do |request_1, request_2| pattern = /\&card_type=(\d+)\&/i CybersourceryTesting::Vcr.did_it_change?(pattern, request_1.body, request_2.body) end end require sinatra require 'sinatra' # this needs to be here too require 'cybersourcery_testing/cybersource_proxy' VCR.configure do |c| c.register_request_matcher :card_type_equality do |request_1, request_2| pattern = /\&card_type=(\d+)\&/i CybersourceryTesting::Vcr.did_it_change?(pattern, request_1.body, request_2.body) end end
solve problem seven. require "spec_helper" require 'prime' describe "problem seven" do #By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. #What is the 10 001st prime number? class Primes include Enumerable def [](index) each_with_index do |n, current| return n if current == (index - 1) end end def each(&block) prime.each(&block) end private def prime Prime end end subject { Primes.new } it "returns the first 6 primes" do expect(subject.take(6)).to eql([2, 3, 5, 7, 11, 13]) end it "returns 13" do expect(subject[6]).to eql(13) end it "returns the 10_001 prime" do expect(subject[10_001]).to eql(104743) end end
module Patm class NoMatchError < StandardError def initialize(value) super("Pattern not match: value=#{value.inspect}") @value = value end attr_reader :value end class Pattern def self.build_from(plain) case plain when Pattern plain when ::Array build_from_array(plain) when ::Hash Hash.new( plain.each_with_object({}) do|(k, v), h| h[k] = build_from(v) if k != Patm.exact end, plain[Patm.exact] ) else Obj.new(plain) end end def self.build_from_array(plain) array = plain.map{|a| build_from(a)} rest_index = array.index(&:rest?) if rest_index head = array[0...rest_index] rest = array[rest_index] tail = array[(rest_index+1)..-1] Arr.new(head, rest, tail) else Arr.new(array) end end module Util def self.compile_value(value, free_index) if value.nil? || value.is_a?(Numeric) || value.is_a?(String) || value.is_a?(Symbol) [ value.inspect, [], free_index, ] else [ "_ctx[#{free_index}]", [value], free_index + 1, ] end end end # Use in Hash pattern. def opt Opt.new(self) end def execute(match, obj); true; end def opt? false end def rest? false end def &(rhs) And.new([self, Pattern.build_from(rhs)]) end def [](name) self & Named.new(name) end def compile src, context, _ = self.compile_internal(0) Compiled.new(self.inspect, src || "true", context) end # free_index:Numeric -> target_name:String -> [src:String|nil, context:Array, free_index:Numeric] # variables: _ctx, _match, (target_name) def compile_internal(free_index, target_name = "_obj") [ "_ctx[#{free_index}].execute(_match, #{target_name})", [self], free_index + 1 ] end class Compiled < self def initialize(desc, src, context) @desc = desc @context = context singleton_class = class <<self; self; end @src_body = src @src = <<-RUBY def execute(_match, _obj) _ctx = @context #{src} end RUBY singleton_class.class_eval(@src) end attr_reader :src_body attr_reader :src def compile_internal(free_index, target_name = "_obj") raise "already compiled" end def inspect; "<compiled>#{@desc}"; end end class Hash < self def initialize(hash, exact) @pat = hash @exact = exact @non_opt_count = @pat.values.count{|v| !v.opt? } end def execute(match, obj) return false unless obj.is_a?(::Hash) obj.size >= @non_opt_count && (!@exact || obj.keys.all?{|k| @pat.has_key?(k) }) && @pat.all? {|k, pat| if obj.has_key?(k) pat.execute(match, obj[k]) else pat.opt? end } end def inspect; @pat.inspect; end def compile_internal(free_index, target_name = "_obj") i = free_index ctxs = [] src = [] ctxs << [@pat] i += 1 pat = "_ctx[#{free_index}]" src << "#{target_name}.is_a?(::Hash)" src << "#{target_name}.size >= #{@non_opt_count}" if @exact src << "#{target_name}.keys.all?{|k| #{pat}.has_key?(k) }" end tname = "#{target_name}_elm" @pat.each do|k, v| key_src, c, i = Util.compile_value(k, i) ctxs << c s, c, i = v.compile_internal(i, tname) body = if s "(#{tname} = #{target_name}[#{key_src}]; #{s})" else "true" end src << if v.opt? "(!#{target_name}.has_key?(#{key_src}) || #{body})" else "(#{target_name}.has_key?(#{key_src}) && #{body})" end ctxs << c end [ src.join(" &&\n"), ctxs.flatten(1), i, ] end end class Opt < self def initialize(pat) @pat = pat end def opt? true end def execute(match, obj) @pat.execute(match, obj) end def inspect; "?#{@pat.inspect}"; end def compile_internal(free_index, target_name = "_obj") @pat.compile_internal(free_index, target_name) end end class Arr < self def initialize(head, rest = nil, tail = []) @head = head @rest = rest @tail = tail end def execute(mmatch, obj) size_min = @head.size + @tail.size return false unless obj.is_a?(Array) return false unless @rest ? (obj.size >= size_min) : (obj.size == size_min) @head.zip(obj[0..(@head.size - 1)]).all? {|pat, o| pat.execute(mmatch, o) } && @tail.zip(obj[(-@tail.size)..-1]).all? {|pat, o| pat.execute(mmatch, o) } && (!@rest || @rest.execute(mmatch, obj[@head.size..-(@tail.size+1)])) end def inspect if @rest (@head + [@rest] + @tail).inspect else (@head + @tail).inspect end end def compile_internal(free_index, target_name = "_obj") i = free_index srcs = [] ctxs = [] srcs << "#{target_name}.is_a?(::Array)" size_min = @head.size + @tail.size if @rest srcs << "#{target_name}.size >= #{size_min}" else srcs << "#{target_name}.size == #{size_min}" end i = compile_part(target_name, @head, srcs, ctxs, i) unless @tail.empty? srcs << "#{target_name}_t = #{target_name}[(-#{@tail.size})..-1]; true" i = compile_part("#{target_name}_t", @tail, srcs, ctxs, i) end if @rest tname = "#{target_name}_r" s, c, i = @rest.compile_internal(i, tname) srcs << "#{tname} = #{target_name}[#{@head.size}..-(#{@tail.size+1})];#{s}" if s ctxs << c end [ srcs.compact.map{|s| "(#{s})"}.join(" &&\n"), ctxs.flatten(1), i ] end private def compile_part(target_name, part, srcs, ctxs, i) part.each_with_index do|h, hi| if h.is_a?(Obj) s, c, i = h.compile_internal(i, "#{target_name}[#{hi}]") srcs << "#{s}" if s ctxs << c else elm_target_name = "#{target_name}_elm" s, c, i = h.compile_internal(i, elm_target_name) srcs << "#{elm_target_name} = #{target_name}[#{hi}]; #{s}" if s ctxs << c end end i end end class ArrRest < self def execute(mmatch, obj) true end def rest? true end def inspect; "..."; end def compile_internal(free_index, target_name = "_obj") [ nil, [], free_index ] end end class Obj < self def initialize(obj) @obj = obj end def execute(mmatch, obj) @obj === obj end def inspect "OBJ(#{@obj.inspect})" end def compile_internal(free_index, target_name = "_obj") val_src, c, i = Util.compile_value(@obj, free_index) [ "#{val_src} === #{target_name}", c, i ] end end class Any < self def execute(match, obj); true; end def inspect; 'ANY'; end def compile_internal(free_index, target_name = "_obj") [ nil, [], free_index ] end end class Named < self def initialize(name) raise ::ArgumentError unless name.is_a?(Symbol) || name.is_a?(Numeric) @name = name end attr_reader :name alias index name # compatibility def execute(match, obj) match[@name] = obj true end def inspect; "NAMED(#{@name})"; end def compile_internal(free_index, target_name = "_obj") [ "_match[#{@name.inspect}] = #{target_name}; true", [], free_index ] end end class LogicalOp < self def initialize(pats, op_str) @pats = pats @op_str = op_str end def compile_internal(free_index, target_name = "_obj") srcs = [] i = free_index ctxs = [] @pats.each do|pat| s, c, i = pat.compile_internal(i, target_name) if !s && @op_str == '||' # dirty... srcs << 'true' else srcs << s end ctxs << c end [ srcs.compact.map{|s| "(#{s})" }.join(" #{@op_str}\n"), ctxs.flatten(1), i ] end def rest? @pats.any?(&:rest?) end def opt? @pats.any?(&:opt?) end end class Or < LogicalOp def initialize(pats) super(pats, '||') end def execute(mmatch, obj) @pats.any? do|pat| pat.execute(mmatch, obj) end end def inspect "OR(#{@pats.map(&:inspect).join(',')})" end end class And < LogicalOp def initialize(pats) super(pats, '&&') end def execute(mmatch, obj) @pats.all? do|pat| pat.execute(mmatch, obj) end end def inspect "AND(#{@pats.map(&:inspect).join(',')})" end end end def self.or(*pats) Pattern::Or.new(pats.map{|p| Pattern.build_from(p) }) end def self._any @any ||= Pattern::Any.new end def self._xs @xs = Pattern::ArrRest.new end # Use in hash value. # Mark this pattern is optional. def self.opt(pat = _any) Pattern::Opt.new(Pattern.build_from(pat)) end EXACT = Object.new def EXACT.inspect "EXACT" end # Use in Hash key. # Specify exact match or not. def self.exact EXACT end PREDEF_GROUP_SIZE = 100 class <<self PREDEF_GROUP_SIZE.times do|i| define_method "_#{i}" do Pattern::Named.new(i) end end end def self.match(plain_pat) CaseBinder.new Pattern.build_from(plain_pat) end class Rule def initialize(&block) # [[Pattern, Proc]...] @rules = [] @else = nil block[self] end def on(pat, &block) @rules << [Pattern.build_from(pat), block] end def else(&block) @else = block end def apply(obj, _self = nil) match = Match.new @rules.each do|(pat, block)| if pat.execute(match, obj) return block.call(match, _self) end end @else ? @else[obj, _self] : (raise NoMatchError.new(obj)) end def inspect "Rule{#{@rules.map(&:first).map(&:inspect).join(', ')}#{@else ? ', _' : ''}}" end def compile_call(block, *args) "call(#{args[0...block.arity].join(', ')})" end def compile i = 0 ctxs = [] srcs = [] @rules.each do|pat, block| s, c, i = pat.compile_internal(i, '_obj') ctxs << c ctxs << [block] srcs << "if (#{s || 'true'})\n_ctx[#{i}].#{compile_call(block, "::Patm::Match.new(_match)"," _self")}" i += 1 end src = srcs.join("\nels") if @else src << "\nelse\n" unless srcs.empty? src << "_ctx[#{i}].#{compile_call(@else, "_obj"," _self")}" ctxs << [@else] i += 1 else src << "\nelse\n" unless srcs.empty? src << "raise ::Patm::NoMatchError.new(_obj)" end src << "\nend" unless srcs.empty? Compiled.new( src, ctxs.flatten(1) ) end class Compiled def initialize(src_body, context) @src_body = src_body @context = context @src = <<-RUBY def apply(_obj, _self = nil) _ctx = @context _match = {} #{@src_body} end RUBY singleton_class = class <<self; self; end singleton_class.class_eval(@src) end attr_reader :src_body attr_reader :context end end class Match def initialize(data = {}) @data = data end def [](i) @data[i] end def []=(i, val) @data[i] = val end PREDEF_GROUP_SIZE.times.each do|i| define_method "_#{i}" do @data[i] end end end class CaseBinder def initialize(pat) @pat = pat @match = Match.new end def ===(obj) @pat.execute(@match, obj) end def [](i); @match[i]; end PREDEF_GROUP_SIZE.times do|i| define_method "_#{i}" do @match[i] end end end module DSL def define_matcher(name, &rule) rule = Rule.new(&rule).compile ctx = rule.context self.class_variable_set("@@_patm_ctx_#{name}", ctx) src = <<-RUBY def #{name}(_obj) _self = self _ctx = self.#{self.name ? 'class' : 'singleton_class'}.class_variable_get(:@@_patm_ctx_#{name}) _match = {} #{rule.src_body} end RUBY class_eval(src) end end end refactor module Patm class NoMatchError < StandardError def initialize(value) super("Pattern not match: value=#{value.inspect}") @value = value end attr_reader :value end class Pattern def self.build_from(plain) case plain when Pattern plain when ::Array build_from_array(plain) when ::Hash build_from_hash(plain) else Obj.new(plain) end end def self.build_from_array(plain) array = plain.map{|a| build_from(a)} rest_index = array.index(&:rest?) if rest_index head = array[0...rest_index] rest = array[rest_index] tail = array[(rest_index+1)..-1] Arr.new(head, rest, tail) else Arr.new(array) end end def self.build_from_hash(plain) self::Hash.new( plain.each_with_object({}) do|(k, v), h| h[k] = build_from(v) if k != Patm.exact end, plain[Patm.exact] ) end module Util def self.compile_value(value, free_index) if value.nil? || value.is_a?(Numeric) || value.is_a?(String) || value.is_a?(Symbol) [ value.inspect, [], free_index, ] else [ "_ctx[#{free_index}]", [value], free_index + 1, ] end end end # Use in Hash pattern. def opt Opt.new(self) end def execute(match, obj); true; end def opt? false end def rest? false end def &(rhs) And.new([self, Pattern.build_from(rhs)]) end def [](name) self & Named.new(name) end def compile src, context, _ = self.compile_internal(0) Compiled.new(self.inspect, src || "true", context) end # free_index:Numeric -> target_name:String -> [src:String|nil, context:Array, free_index:Numeric] # variables: _ctx, _match, (target_name) def compile_internal(free_index, target_name = "_obj") [ "_ctx[#{free_index}].execute(_match, #{target_name})", [self], free_index + 1 ] end class Compiled < self def initialize(desc, src, context) @desc = desc @context = context singleton_class = class <<self; self; end @src_body = src @src = <<-RUBY def execute(_match, _obj) _ctx = @context #{src} end RUBY singleton_class.class_eval(@src) end attr_reader :src_body attr_reader :src def compile_internal(free_index, target_name = "_obj") raise "already compiled" end def inspect; "<compiled>#{@desc}"; end end class Hash < self def initialize(hash, exact) @pat = hash @exact = exact @non_opt_count = @pat.values.count{|v| !v.opt? } end def execute(match, obj) return false unless obj.is_a?(::Hash) obj.size >= @non_opt_count && (!@exact || obj.keys.all?{|k| @pat.has_key?(k) }) && @pat.all? {|k, pat| if obj.has_key?(k) pat.execute(match, obj[k]) else pat.opt? end } end def inspect; @pat.inspect; end def compile_internal(free_index, target_name = "_obj") i = free_index ctxs = [] src = [] ctxs << [@pat] i += 1 pat = "_ctx[#{free_index}]" src << "#{target_name}.is_a?(::Hash)" src << "#{target_name}.size >= #{@non_opt_count}" if @exact src << "#{target_name}.keys.all?{|k| #{pat}.has_key?(k) }" end tname = "#{target_name}_elm" @pat.each do|k, v| key_src, c, i = Util.compile_value(k, i) ctxs << c s, c, i = v.compile_internal(i, tname) body = if s "(#{tname} = #{target_name}[#{key_src}]; #{s})" else "true" end src << if v.opt? "(!#{target_name}.has_key?(#{key_src}) || #{body})" else "(#{target_name}.has_key?(#{key_src}) && #{body})" end ctxs << c end [ src.join(" &&\n"), ctxs.flatten(1), i, ] end end class Opt < self def initialize(pat) @pat = pat end def opt? true end def execute(match, obj) @pat.execute(match, obj) end def inspect; "?#{@pat.inspect}"; end def compile_internal(free_index, target_name = "_obj") @pat.compile_internal(free_index, target_name) end end class Arr < self def initialize(head, rest = nil, tail = []) @head = head @rest = rest @tail = tail end def execute(mmatch, obj) size_min = @head.size + @tail.size return false unless obj.is_a?(Array) return false unless @rest ? (obj.size >= size_min) : (obj.size == size_min) @head.zip(obj[0..(@head.size - 1)]).all? {|pat, o| pat.execute(mmatch, o) } && @tail.zip(obj[(-@tail.size)..-1]).all? {|pat, o| pat.execute(mmatch, o) } && (!@rest || @rest.execute(mmatch, obj[@head.size..-(@tail.size+1)])) end def inspect if @rest (@head + [@rest] + @tail).inspect else (@head + @tail).inspect end end def compile_internal(free_index, target_name = "_obj") i = free_index srcs = [] ctxs = [] srcs << "#{target_name}.is_a?(::Array)" size_min = @head.size + @tail.size if @rest srcs << "#{target_name}.size >= #{size_min}" else srcs << "#{target_name}.size == #{size_min}" end i = compile_part(target_name, @head, srcs, ctxs, i) unless @tail.empty? srcs << "#{target_name}_t = #{target_name}[(-#{@tail.size})..-1]; true" i = compile_part("#{target_name}_t", @tail, srcs, ctxs, i) end if @rest tname = "#{target_name}_r" s, c, i = @rest.compile_internal(i, tname) srcs << "#{tname} = #{target_name}[#{@head.size}..-(#{@tail.size+1})];#{s}" if s ctxs << c end [ srcs.compact.map{|s| "(#{s})"}.join(" &&\n"), ctxs.flatten(1), i ] end private def compile_part(target_name, part, srcs, ctxs, i) part.each_with_index do|h, hi| if h.is_a?(Obj) s, c, i = h.compile_internal(i, "#{target_name}[#{hi}]") srcs << "#{s}" if s ctxs << c else elm_target_name = "#{target_name}_elm" s, c, i = h.compile_internal(i, elm_target_name) srcs << "#{elm_target_name} = #{target_name}[#{hi}]; #{s}" if s ctxs << c end end i end end class ArrRest < self def execute(mmatch, obj) true end def rest? true end def inspect; "..."; end def compile_internal(free_index, target_name = "_obj") [ nil, [], free_index ] end end class Obj < self def initialize(obj) @obj = obj end def execute(mmatch, obj) @obj === obj end def inspect "OBJ(#{@obj.inspect})" end def compile_internal(free_index, target_name = "_obj") val_src, c, i = Util.compile_value(@obj, free_index) [ "#{val_src} === #{target_name}", c, i ] end end class Any < self def execute(match, obj); true; end def inspect; 'ANY'; end def compile_internal(free_index, target_name = "_obj") [ nil, [], free_index ] end end class Named < self def initialize(name) raise ::ArgumentError unless name.is_a?(Symbol) || name.is_a?(Numeric) @name = name end attr_reader :name alias index name # compatibility def execute(match, obj) match[@name] = obj true end def inspect; "NAMED(#{@name})"; end def compile_internal(free_index, target_name = "_obj") [ "_match[#{@name.inspect}] = #{target_name}; true", [], free_index ] end end class LogicalOp < self def initialize(pats, op_str) @pats = pats @op_str = op_str end def compile_internal(free_index, target_name = "_obj") srcs = [] i = free_index ctxs = [] @pats.each do|pat| s, c, i = pat.compile_internal(i, target_name) if !s && @op_str == '||' # dirty... srcs << 'true' else srcs << s end ctxs << c end [ srcs.compact.map{|s| "(#{s})" }.join(" #{@op_str}\n"), ctxs.flatten(1), i ] end def rest? @pats.any?(&:rest?) end def opt? @pats.any?(&:opt?) end end class Or < LogicalOp def initialize(pats) super(pats, '||') end def execute(mmatch, obj) @pats.any? do|pat| pat.execute(mmatch, obj) end end def inspect "OR(#{@pats.map(&:inspect).join(',')})" end end class And < LogicalOp def initialize(pats) super(pats, '&&') end def execute(mmatch, obj) @pats.all? do|pat| pat.execute(mmatch, obj) end end def inspect "AND(#{@pats.map(&:inspect).join(',')})" end end end def self.or(*pats) Pattern::Or.new(pats.map{|p| Pattern.build_from(p) }) end def self._any @any ||= Pattern::Any.new end def self._xs @xs = Pattern::ArrRest.new end # Use in hash value. # Mark this pattern is optional. def self.opt(pat = _any) Pattern::Opt.new(Pattern.build_from(pat)) end EXACT = Object.new def EXACT.inspect "EXACT" end # Use in Hash key. # Specify exact match or not. def self.exact EXACT end PREDEF_GROUP_SIZE = 100 class <<self PREDEF_GROUP_SIZE.times do|i| define_method "_#{i}" do Pattern::Named.new(i) end end end def self.match(plain_pat) CaseBinder.new Pattern.build_from(plain_pat) end class Rule def initialize(&block) # [[Pattern, Proc]...] @rules = [] @else = nil block[self] end def on(pat, &block) @rules << [Pattern.build_from(pat), block] end def else(&block) @else = block end def apply(obj, _self = nil) match = Match.new @rules.each do|(pat, block)| if pat.execute(match, obj) return block.call(match, _self) end end @else ? @else[obj, _self] : (raise NoMatchError.new(obj)) end def inspect "Rule{#{@rules.map(&:first).map(&:inspect).join(', ')}#{@else ? ', _' : ''}}" end def compile_call(block, *args) "call(#{args[0...block.arity].join(', ')})" end def compile i = 0 ctxs = [] srcs = [] @rules.each do|pat, block| s, c, i = pat.compile_internal(i, '_obj') ctxs << c ctxs << [block] srcs << "if (#{s || 'true'})\n_ctx[#{i}].#{compile_call(block, "::Patm::Match.new(_match)"," _self")}" i += 1 end src = srcs.join("\nels") if @else src << "\nelse\n" unless srcs.empty? src << "_ctx[#{i}].#{compile_call(@else, "_obj"," _self")}" ctxs << [@else] i += 1 else src << "\nelse\n" unless srcs.empty? src << "raise ::Patm::NoMatchError.new(_obj)" end src << "\nend" unless srcs.empty? Compiled.new( src, ctxs.flatten(1) ) end class Compiled def initialize(src_body, context) @src_body = src_body @context = context @src = <<-RUBY def apply(_obj, _self = nil) _ctx = @context _match = {} #{@src_body} end RUBY singleton_class = class <<self; self; end singleton_class.class_eval(@src) end attr_reader :src_body attr_reader :context end end class Match def initialize(data = {}) @data = data end def [](i) @data[i] end def []=(i, val) @data[i] = val end PREDEF_GROUP_SIZE.times.each do|i| define_method "_#{i}" do @data[i] end end end class CaseBinder def initialize(pat) @pat = pat @match = Match.new end def ===(obj) @pat.execute(@match, obj) end def [](i); @match[i]; end PREDEF_GROUP_SIZE.times do|i| define_method "_#{i}" do @match[i] end end end module DSL def define_matcher(name, &rule) rule = Rule.new(&rule).compile ctx = rule.context self.class_variable_set("@@_patm_ctx_#{name}", ctx) src = <<-RUBY def #{name}(_obj) _self = self _ctx = self.#{self.name ? 'class' : 'singleton_class'}.class_variable_get(:@@_patm_ctx_#{name}) _match = {} #{rule.src_body} end RUBY class_eval(src) end end end
require 'builder' require 'plek/version' class Plek DEFAULT_PATTERN = "pattern".freeze SERVICES = { "production.www" => "www.gov.uk", "production.needs" => "needotron.production.alphagov.co.uk", "production.data" => "imminence.production.alphagov.co.uk", "production.assets" => "static.production.alphagov.co.uk", "production.cdn" => "d17tffe05zdvwj.cloudfront.net", "production.publication-preview" => "private-frontend.production.alphagov.co.uk", "production.whitehall" => "whitehall.production.alphagov.co.uk", "production.whitehall-search" => "whitehall-search.production.alphagov.co.uk", "production.#{DEFAULT_PATTERN}" => "%s.production.alphagov.co.uk", "preview.www" => "www.preview.alphagov.co.uk", "preview.needs" => "needotron.preview.alphagov.co.uk", "preview.data" => "imminence.preview.alphagov.co.uk", "preview.assets" => "static.preview.alphagov.co.uk", "preview.cdn" => "djb1962t8apu5.cloudfront.net", "preview.publication-preview" => "private-frontend.preview.alphagov.co.uk", "preview.tariff" => "tariff.preview.alphagov.co.uk", "preview.whitehall" => "whitehall.preview.alphagov.co.uk", "preview.whitehall-search" => "whitehall-search.preview.alphagov.co.uk", "preview.#{DEFAULT_PATTERN}" => "%s.preview.alphagov.co.uk", "staging.frontend" => "demo.alphagov.co.uk", "staging.needs" => "needotron.alpha.gov.uk", "staging.publisher" => "guides.staging.alphagov.co.uk", "staging.data" => "imminence.staging.alphagov.co.uk", "staging.assets" => "static.staging.alphagov.co.uk", "staging.assets" => "static.staging.alphagov.co.uk", "staging.publication-preview" => "private-frontend.staging.alphagov.co.uk", "staging.#{DEFAULT_PATTERN}" => "%s.staging.alphagov.co.uk", "development.needs" => "needotron.dev.gov.uk", "development.data" => "imminence.dev.gov.uk", "development.assets" => "static.dev.gov.uk", "development.cdn" => "static.dev.gov.uk", "development.whitehall" => "whitehall.dev.gov.uk", "development.whitehall-search" => "whitehall-search.dev.gov.uk", "development.publication-preview"=> "www.dev.gov.uk", "development.#{DEFAULT_PATTERN}" => "%s.dev.gov.uk", "test.needs" => "needotron.test.gov.uk", "test.data" => "imminence.test.gov.uk", "test.publication-preview" => "www.test.gov.uk", "test.cdn" => "static.test.gov.uk", "test.whitehall" => "whitehall.test.alphagov.co.uk", "test.whitehall-search" => "whitehall-search.test.alphagov.co.uk", "test.#{DEFAULT_PATTERN}" => "%s.test.gov.uk", }.freeze attr_accessor :environment private :environment= def initialize environment self.environment = environment end # Find the URI for a service. # # Services don't map directly to applications since we may replace an # application but retain the service. # # Currently we have these services: # # frontend: Where the public can see our output. # publisher: Where we write content. # needs: Where we record the needs that we're going to fulfill. # data: Where our datasets live. # def find service name = name_for service host = SERVICES[service_key_for(name)] host ||= SERVICES["#{environment}.#{DEFAULT_PATTERN}"].to_s % name # FIXME: *Everything* should be SSL if whitehall?(service) or search?(service) "http://#{host}" elsif (environment == 'preview' or environment == 'production') "https://#{host}" else "http://#{host}" end end def whitehall?(service) /^whitehall/.match(service) end def search?(service) service == 'search' or service == 'rummager' end def service_key_for name "#{environment}.#{name}" end def name_for service name = service.to_s.dup name.downcase! name.strip! name.gsub!(/[^a-z\.-]+/, '') name end def self.current_env if (ENV['RAILS_ENV'] || ENV['RACK_ENV']) == 'test' 'test' else ENV['FACTER_govuk_platform'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development' end end def self.current Plek.new(current_env) end end Remove erroneous comment on Plek#find require 'builder' require 'plek/version' class Plek DEFAULT_PATTERN = "pattern".freeze SERVICES = { "production.www" => "www.gov.uk", "production.needs" => "needotron.production.alphagov.co.uk", "production.data" => "imminence.production.alphagov.co.uk", "production.assets" => "static.production.alphagov.co.uk", "production.cdn" => "d17tffe05zdvwj.cloudfront.net", "production.publication-preview" => "private-frontend.production.alphagov.co.uk", "production.whitehall" => "whitehall.production.alphagov.co.uk", "production.whitehall-search" => "whitehall-search.production.alphagov.co.uk", "production.#{DEFAULT_PATTERN}" => "%s.production.alphagov.co.uk", "preview.www" => "www.preview.alphagov.co.uk", "preview.needs" => "needotron.preview.alphagov.co.uk", "preview.data" => "imminence.preview.alphagov.co.uk", "preview.assets" => "static.preview.alphagov.co.uk", "preview.cdn" => "djb1962t8apu5.cloudfront.net", "preview.publication-preview" => "private-frontend.preview.alphagov.co.uk", "preview.tariff" => "tariff.preview.alphagov.co.uk", "preview.whitehall" => "whitehall.preview.alphagov.co.uk", "preview.whitehall-search" => "whitehall-search.preview.alphagov.co.uk", "preview.#{DEFAULT_PATTERN}" => "%s.preview.alphagov.co.uk", "staging.frontend" => "demo.alphagov.co.uk", "staging.needs" => "needotron.alpha.gov.uk", "staging.publisher" => "guides.staging.alphagov.co.uk", "staging.data" => "imminence.staging.alphagov.co.uk", "staging.assets" => "static.staging.alphagov.co.uk", "staging.assets" => "static.staging.alphagov.co.uk", "staging.publication-preview" => "private-frontend.staging.alphagov.co.uk", "staging.#{DEFAULT_PATTERN}" => "%s.staging.alphagov.co.uk", "development.needs" => "needotron.dev.gov.uk", "development.data" => "imminence.dev.gov.uk", "development.assets" => "static.dev.gov.uk", "development.cdn" => "static.dev.gov.uk", "development.whitehall" => "whitehall.dev.gov.uk", "development.whitehall-search" => "whitehall-search.dev.gov.uk", "development.publication-preview"=> "www.dev.gov.uk", "development.#{DEFAULT_PATTERN}" => "%s.dev.gov.uk", "test.needs" => "needotron.test.gov.uk", "test.data" => "imminence.test.gov.uk", "test.publication-preview" => "www.test.gov.uk", "test.cdn" => "static.test.gov.uk", "test.whitehall" => "whitehall.test.alphagov.co.uk", "test.whitehall-search" => "whitehall-search.test.alphagov.co.uk", "test.#{DEFAULT_PATTERN}" => "%s.test.gov.uk", }.freeze attr_accessor :environment private :environment= def initialize environment self.environment = environment end # Find the URI for a service/application. def find(service) name = name_for service host = SERVICES[service_key_for(name)] host ||= SERVICES["#{environment}.#{DEFAULT_PATTERN}"].to_s % name # FIXME: *Everything* should be SSL if whitehall?(service) or search?(service) "http://#{host}" elsif (environment == 'preview' or environment == 'production') "https://#{host}" else "http://#{host}" end end def whitehall?(service) /^whitehall/.match(service) end def search?(service) service == 'search' or service == 'rummager' end def service_key_for name "#{environment}.#{name}" end def name_for service name = service.to_s.dup name.downcase! name.strip! name.gsub!(/[^a-z\.-]+/, '') name end def self.current_env if (ENV['RAILS_ENV'] || ENV['RACK_ENV']) == 'test' 'test' else ENV['FACTER_govuk_platform'] || ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development' end end def self.current Plek.new(current_env) end end
require 'riot/reporter' require 'riot/middleware' require 'riot/context' require 'riot/situation' require 'riot/runnable' require 'riot/assertion' require 'riot/assertion_macro' # The namespace for all of Riot. module Riot # A helper for creating/defining root context instances. # # @param [String] description the description of this context # @param [Class] context_class the {Riot::Context} implementation to use # @param [lambda] &definition the context definition # @return [Context] the initialized {Riot::Context} def self.context(description, context_class = Context, &definition) (root_contexts << context_class.new(description, &definition)).last end # The set of {Riot::Context} instances that have no parent. # # @return [Array] instances of {Riot::Context} def self.root_contexts @root_contexts ||= [] end # How to run Riot itself. This should be called +at_exit+ unless you suggested - by calling {Riot.alone!} # that you want to call this method yourself. If no {Riot.reporter} is set, the # {Riot::StoryReporter default} will be used. # # You can change reporters by setting the manually via {Riot.reporter=} or by using one of: {Riot.dots}, # {Riot.silently!}, or {Riot.verbose}. # # @return [Riot::Reporter] the reporter that was used def self.run the_reporter = reporter.new the_reporter.summarize do root_contexts.each { |ctx| ctx.run(the_reporter) } end unless root_contexts.empty? the_reporter end # This means you don't want to see any output from Riot. A "quiet riot". def self.silently! @silent = true end # Reponds to whether Riot is reporting silently. # # @return [Boolean] def self.silently? defined?(@silent) && @silent == true end # This means you don't want Riot to run tests for you. You will execute Riot.run manually. def self.alone! @alone = true end # Responds to whether Riot will run +at_exit+ (false) or manually (true). # # @return [Boolean] def self.alone? defined?(@alone) && @alone == true end # Allows the reporter class to be changed. Do this before tests are started. # # @param [Class] reporter_class the Class that represents a {Riot::Reporter} def self.reporter=(reporter_class) @reporter_class = reporter_class end # Returns the class for the reporter that is currently selected. If no reporter was explicitly selected, # {Riot::StoryReporter} will be used. # # @return [Class] the Class that represents a {Riot::Reporter} def self.reporter if Riot.silently? Riot::SilentReporter else (defined?(@reporter_class) && @reporter_class) || Riot::StoryReporter end end # @todo make this a flag that DotMatrix and Story respect and cause them to print errors/failures # Tells Riot to use {Riot::VerboseStoryReporter} for reporting def self.verbose Riot.reporter = Riot::VerboseStoryReporter end # Tells Riot to use {Riot::DotMatrixReporter} for reporting def self.dots Riot.reporter = Riot::DotMatrixReporter end # Tells Riot to use {Riot::PrettyDotMatrixReporter} for reporting def self.pretty_dots Riot.reporter = Riot::PrettyDotMatrixReporter end at_exit { exit(run.success?) unless Riot.alone? } end # Riot # A little bit of monkey-patch so we can have +context+ available anywhere. class Object # Defining +context+ in Object itself lets us define a root +context+ in any file. Any +context+ defined # within a +context+ is already handled by {Riot::Context#context}. # # @param (see Riot.context) # @return (see Riot.context) def context(description, context_class = Riot::Context, &definition) Riot.context(description, context_class, &definition) end alias_method :describe, :context end # Object class Array def extract_options! last.is_a?(::Hash) ? pop : {} end end Fix issue #29: Failing gracefully if child process fails before running tests require 'riot/reporter' require 'riot/middleware' require 'riot/context' require 'riot/situation' require 'riot/runnable' require 'riot/assertion' require 'riot/assertion_macro' # The namespace for all of Riot. module Riot # A helper for creating/defining root context instances. # # @param [String] description the description of this context # @param [Class] context_class the {Riot::Context} implementation to use # @param [lambda] &definition the context definition # @return [Context] the initialized {Riot::Context} def self.context(description, context_class = Context, &definition) (root_contexts << context_class.new(description, &definition)).last end # The set of {Riot::Context} instances that have no parent. # # @return [Array] instances of {Riot::Context} def self.root_contexts @root_contexts ||= [] end # How to run Riot itself. This should be called +at_exit+ unless you suggested - by calling {Riot.alone!} # that you want to call this method yourself. If no {Riot.reporter} is set, the # {Riot::StoryReporter default} will be used. # # You can change reporters by setting the manually via {Riot.reporter=} or by using one of: {Riot.dots}, # {Riot.silently!}, or {Riot.verbose}. # # @return [Riot::Reporter] the reporter that was used def self.run the_reporter = reporter.new the_reporter.summarize do root_contexts.each { |ctx| ctx.run(the_reporter) } end unless root_contexts.empty? the_reporter end # This means you don't want to see any output from Riot. A "quiet riot". def self.silently! @silent = true end # Reponds to whether Riot is reporting silently. # # @return [Boolean] def self.silently? defined?(@silent) && @silent == true end # This means you don't want Riot to run tests for you. You will execute Riot.run manually. def self.alone! @alone = true end # Responds to whether Riot will run +at_exit+ (false) or manually (true). # # @return [Boolean] def self.alone? defined?(@alone) && @alone == true end # Allows the reporter class to be changed. Do this before tests are started. # # @param [Class] reporter_class the Class that represents a {Riot::Reporter} def self.reporter=(reporter_class) @reporter_class = reporter_class end # Returns the class for the reporter that is currently selected. If no reporter was explicitly selected, # {Riot::StoryReporter} will be used. # # @return [Class] the Class that represents a {Riot::Reporter} def self.reporter if Riot.silently? Riot::SilentReporter else (defined?(@reporter_class) && @reporter_class) || Riot::StoryReporter end end # @todo make this a flag that DotMatrix and Story respect and cause them to print errors/failures # Tells Riot to use {Riot::VerboseStoryReporter} for reporting def self.verbose Riot.reporter = Riot::VerboseStoryReporter end # Tells Riot to use {Riot::DotMatrixReporter} for reporting def self.dots Riot.reporter = Riot::DotMatrixReporter end # Tells Riot to use {Riot::PrettyDotMatrixReporter} for reporting def self.pretty_dots Riot.reporter = Riot::PrettyDotMatrixReporter end # Making sure to account for Riot being run as part of a larger rake task (or something similar). # If a child process exited with a failing status, probably don't want to run Riot tests; just exit # with the child status. at_exit do unless Riot.alone? status = $?.exitstatus unless ($?.nil? || $?.success?) exit(status || run.success?) end end end # Riot # A little bit of monkey-patch so we can have +context+ available anywhere. class Object # Defining +context+ in Object itself lets us define a root +context+ in any file. Any +context+ defined # within a +context+ is already handled by {Riot::Context#context}. # # @param (see Riot.context) # @return (see Riot.context) def context(description, context_class = Riot::Context, &definition) Riot.context(description, context_class, &definition) end alias_method :describe, :context end # Object class Array def extract_options! last.is_a?(::Hash) ? pop : {} end end
module Roar def self.root File.expand_path '../..', __FILE__ end end require version require 'roar/version' module Roar def self.root File.expand_path '../..', __FILE__ end end
require 'rubygems' require 'git' require 'octokit' require 'dotenv' class Sink class << self def load_config puts "Loading GitHub access token…" Dotenv.load "~/.sinkconfig" puts "Done." end end end Auto-sync: 1 file changed. - M lib/sink.rb require 'rubygems' require 'git' require 'octokit' require 'dotenv' class Sink class << self def load_config puts "Loading GitHub access token…" Dotenv.load "~/.sinkconfig" puts "Done." end def setup_sync end end end
class Bpipe < Formula desc "Platform for running bioinformatics pipelines" homepage "https://github.com/ssadedin/bpipe" # doi "10.1093/bioinformatics/bts167" # tag "bioinformatics" url "https://github.com/ssadedin/bpipe/releases/download/0.9.9.0/bpipe-0.9.9.tar.gz" sha256 "3a45abd20cfd563ec68da50589df0310a46c60efeefbe486ba20dede844765e4" head "https://github.com/ssadedin/bpipe.git" bottle do cellar :any_skip_relocation sha256 "4b7bc1bf58deba168b0c3224e5f359a3b69abaac69484d14c780adc988ad06ed" => :el_capitan sha256 "4f1072819acc24c91e9127038853b0458ac6b714992cbe9e9cd08e33366763a1" => :yosemite sha256 "4ebf31154059aad19922532b4e15ce2c3c0e899ec28edae7e196b25ae0ed8e7a" => :mavericks end depends_on :java def install libexec.install Dir["*"] bin.install_symlink Dir["#{libexec}/bin/*"] end test do assert_match "Found 0 currently executing commands", shell_output("#{bin}/bpipe status") end end bpipe: update 0.9.9 bottle for Linuxbrew. Closes Linuxbrew/homebrew-science#47. Signed-off-by: Shaun Jackman <b580dab3251a9622aba3803114310c23fdb42900@gmail.com> class Bpipe < Formula desc "Platform for running bioinformatics pipelines" homepage "https://github.com/ssadedin/bpipe" # doi "10.1093/bioinformatics/bts167" # tag "bioinformatics" url "https://github.com/ssadedin/bpipe/releases/download/0.9.9.0/bpipe-0.9.9.tar.gz" sha256 "3a45abd20cfd563ec68da50589df0310a46c60efeefbe486ba20dede844765e4" head "https://github.com/ssadedin/bpipe.git" bottle do cellar :any_skip_relocation sha256 "4b7bc1bf58deba168b0c3224e5f359a3b69abaac69484d14c780adc988ad06ed" => :el_capitan sha256 "4f1072819acc24c91e9127038853b0458ac6b714992cbe9e9cd08e33366763a1" => :yosemite sha256 "4ebf31154059aad19922532b4e15ce2c3c0e899ec28edae7e196b25ae0ed8e7a" => :mavericks sha256 "fc4fbddefa999ecc2c3f2ac57a1c1296b11f50ed5cb168403f22a44194875072" => :x86_64_linux end depends_on :java def install libexec.install Dir["*"] bin.install_symlink Dir["#{libexec}/bin/*"] end test do assert_match "Found 0 currently executing commands", shell_output("#{bin}/bpipe status") end end
require 'slop/option' require 'slop/commands' class Slop include Enumerable VERSION = '3.4.5' # The main Error class, all Exception classes inherit from this class. class Error < StandardError; end # Raised when an option argument is expected but none are given. class MissingArgumentError < Error; end # Raised when an option is expected/required but not present. class MissingOptionError < Error; end # Raised when an argument does not match its intended match constraint. class InvalidArgumentError < Error; end # Raised when an invalid option is found and the strict flag is enabled. class InvalidOptionError < Error; end # Raised when an invalid command is found and the strict flag is enabled. class InvalidCommandError < Error; end # Returns a default Hash of configuration options this Slop instance uses. DEFAULT_OPTIONS = { :strict => false, :help => false, :banner => nil, :ignore_case => false, :autocreate => false, :arguments => false, :optional_arguments => false, :multiple_switches => true, :longest_flag => 0 } class << self # items - The Array of items to extract options from (default: ARGV). # config - The Hash of configuration options to send to Slop.new(). # block - An optional block used to add options. # # Examples: # # Slop.parse(ARGV, :help => true) do # on '-n', '--name', 'Your username', :argument => true # end # # Returns a new instance of Slop. def parse(items = ARGV, config = {}, &block) parse! items.dup, config, &block end # items - The Array of items to extract options from (default: ARGV). # config - The Hash of configuration options to send to Slop.new(). # block - An optional block used to add options. # # Returns a new instance of Slop. def parse!(items = ARGV, config = {}, &block) config, items = items, ARGV if items.is_a?(Hash) && config.empty? slop = new config, &block slop.parse! items slop end # Build a Slop object from a option specification. # # This allows you to design your options via a simple String rather # than programatically. Do note though that with this method, you're # unable to pass any advanced options to the on() method when creating # options. # # string - The optspec String # config - A Hash of configuration options to pass to Slop.new # # Examples: # # opts = Slop.optspec(<<-SPEC) # ruby foo.rb [options] # --- # n,name= Your name # a,age= Your age # A,auth Sign in with auth # p,passcode= Your secret pass code # SPEC # # opts.fetch_option(:name).description #=> "Your name" # # Returns a new instance of Slop. def optspec(string, config = {}) warn "[DEPRECATED] `Slop.optspec` is deprecated and will be removed in version 4" config[:banner], optspec = string.split(/^--+$/, 2) if string[/^--+$/] lines = optspec.split("\n").reject(&:empty?) opts = Slop.new(config) lines.each do |line| opt, description = line.split(' ', 2) short, long = opt.split(',').map { |s| s.sub(/\A--?/, '') } opt = opts.on(short, long, description) if long && long.end_with?('=') long.sub!(/\=$/, '') opt.config[:argument] = true end end opts end end # The Hash of configuration options for this Slop instance. attr_reader :config # The Array of Slop::Option objects tied to this Slop instance. attr_reader :options # The Hash of sub-commands for this Slop instance. attr_reader :commands # Create a new instance of Slop and optionally build options via a block. # # config - A Hash of configuration options. # block - An optional block used to specify options. def initialize(config = {}, &block) @config = DEFAULT_OPTIONS.merge(config) @options = [] @commands = {} @trash = [] @triggered_options = [] @unknown_options = [] @callbacks = {} @separators = {} @runner = nil @command = config.delete(:command) if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end if config[:help] on('-h', '--help', 'Display this help message.', :tail => true) do puts help exit end end end # Is strict mode enabled? # # Returns true if strict mode is enabled, false otherwise. def strict? config[:strict] end # Set the banner. # # banner - The String to set the banner. def banner=(banner) config[:banner] = banner end # Get or set the banner. # # banner - The String to set the banner. # # Returns the banner String. def banner(banner = nil) config[:banner] = banner if banner config[:banner] end # Set the description (used for commands). # # desc - The String to set the description. def description=(desc) config[:description] = desc end # Get or set the description (used for commands). # # desc - The String to set the description. # # Returns the description String. def description(desc = nil) config[:description] = desc if desc config[:description] end # Add a new command. # # command - The Symbol or String used to identify this command. # options - A Hash of configuration options (see Slop::new) # # Returns a new instance of Slop mapped to this command. def command(command, options = {}, &block) options = @config.merge(options) @commands[command.to_s] = Slop.new(options.merge(:command => command.to_s), &block) end # Parse a list of items, executing and gathering options along the way. # # items - The Array of items to extract options from (default: ARGV). # block - An optional block which when used will yield non options. # # Returns an Array of original items. def parse(items = ARGV, &block) parse! items.dup, &block items end # Parse a list of items, executing and gathering options along the way. # unlike parse() this method will remove any options and option arguments # from the original Array. # # items - The Array of items to extract options from (default: ARGV). # block - An optional block which when used will yield non options. # # Returns an Array of original items with options removed. def parse!(items = ARGV, &block) if items.empty? && @callbacks[:empty] @callbacks[:empty].each { |cb| cb.call(self) } return items end if cmd = @commands[items[0]] items.shift return cmd.parse! items end items.each_with_index do |item, index| @trash << index && break if item == '--' autocreate(items, index) if config[:autocreate] process_item(items, index, &block) unless @trash.include?(index) end items.reject!.with_index { |item, index| @trash.include?(index) } missing_options = options.select { |opt| opt.required? && opt.count < 1 } if missing_options.any? raise MissingOptionError, "Missing required option(s): #{missing_options.map(&:key).join(', ')}" end if @unknown_options.any? raise InvalidOptionError, "Unknown options #{@unknown_options.join(', ')}" end if @triggered_options.empty? && @callbacks[:no_options] @callbacks[:no_options].each { |cb| cb.call(self) } end if @runner.respond_to?(:call) @runner.call(self, items) unless config[:help] and present?(:help) end items end # Add an Option. # # objects - An Array with an optional Hash as the last element. # # Examples: # # on '-u', '--username=', 'Your username' # on :v, :verbose, 'Enable verbose mode' # # Returns the created instance of Slop::Option. def on(*objects, &block) option = build_option(objects, &block) original = options.find do |o| o.long and o.long == option.long or o.short and o.short == option.short end options.delete(original) if original options << option option end alias option on alias opt on # Fetch an options argument value. # # key - The Symbol or String option short or long flag. # # Returns the Object value for this option, or nil. def [](key) option = fetch_option(key) option.value if option end alias get [] # Returns a new Hash with option flags as keys and option values as values. # # include_commands - If true, merge options from all sub-commands. def to_hash(include_commands = false) hash = Hash[options.map { |opt| [opt.key.to_sym, opt.value] }] if include_commands @commands.each { |cmd, opts| hash.merge!(cmd.to_sym => opts.to_hash) } end hash end alias to_h to_hash # Enumerable interface. Yields each Slop::Option. def each(&block) options.each(&block) end # Specify code to be executed when these options are parsed. # # callable - An object responding to a call method. # # yields - The instance of Slop parsing these options # An Array of unparsed arguments # # Example: # # Slop.parse do # on :v, :verbose # # run do |opts, args| # puts "Arguments: #{args.inspect}" if opts.verbose? # end # end def run(callable = nil, &block) @runner = callable || block unless @runner.respond_to?(:call) raise ArgumentError, "You must specify a callable object or a block to #run" end end # Check for an options presence. # # Examples: # # opts.parse %w( --foo ) # opts.present?(:foo) #=> true # opts.present?(:bar) #=> false # # Returns true if all of the keys are present in the parsed arguments. def present?(*keys) keys.all? { |key| (opt = fetch_option(key)) && opt.count > 0 } end # Override this method so we can check if an option? method exists. # # Returns true if this option key exists in our list of options. def respond_to_missing?(method_name, include_private = false) options.any? { |o| o.key == method_name.to_s.chop } || super end # Fetch a list of options which were missing from the parsed list. # # Examples: # # opts = Slop.new do # on :n, :name= # on :p, :password= # end # # opts.parse %w[ --name Lee ] # opts.missing #=> ['password'] # # Returns an Array of Strings representing missing options. def missing (options - @triggered_options).map(&:key) end # Fetch a Slop::Option object. # # key - The Symbol or String option key. # # Examples: # # opts.on(:foo, 'Something fooey', :argument => :optional) # opt = opts.fetch_option(:foo) # opt.class #=> Slop::Option # opt.accepts_optional_argument? #=> true # # Returns an Option or nil if none were found. def fetch_option(key) options.find { |option| [option.long, option.short].include?(clean(key)) } end # Fetch a Slop object associated with this command. # # command - The String or Symbol name of the command. # # Examples: # # opts.command :foo do # on :v, :verbose, 'Enable verbose mode' # end # # # ruby run.rb foo -v # opts.fetch_command(:foo).verbose? #=> true def fetch_command(command) @commands[command.to_s] end # Add a callback. # # label - The Symbol identifier to attach this callback. # # Returns nothing. def add_callback(label, &block) (@callbacks[label] ||= []) << block end # Add string separators between options. # # text - The String text to print. def separator(text) if @separators[options.size] @separators[options.size] << "\n#{text}" else @separators[options.size] = text end end # Print a handy Slop help string. # # Returns the banner followed by available option help strings. def to_s heads = options.reject(&:tail?) tails = (options - heads) opts = (heads + tails).select(&:help).map(&:to_s) optstr = opts.each_with_index.map { |o, i| (str = @separators[i + 1]) ? [o, str].join("\n") : o }.join("\n") if @commands.any? optstr << "\n" if !optstr.empty? optstr << "\nAvailable commands:\n\n" optstr << commands_to_help optstr << "\n\nSee `<command> --help` for more information on a specific command." end banner = config[:banner] if banner.nil? banner = "Usage: #{File.basename($0, '.*')}" banner << " #{@command}" if @command banner << " [command]" if @commands.any? banner << " [options]" end if banner "#{banner}\n#{@separators[0] ? "#{@separators[0]}\n" : ''}#{optstr}" else optstr end end alias help to_s private # Convenience method for present?(:option). # # Examples: # # opts.parse %( --verbose ) # opts.verbose? #=> true # opts.other? #=> false # # Returns true if this option is present. If this method does not end # with a ? character it will instead call super(). def method_missing(method, *args, &block) meth = method.to_s if meth.end_with?('?') meth.chop! present?(meth) || present?(meth.gsub('_', '-')) else super end end # Process a list item, figure out if it's an option, execute any # callbacks, assign any option arguments, and do some sanity checks. # # items - The Array of items to process. # index - The current Integer index of the item we want to process. # block - An optional block which when passed will yield non options. # # Returns nothing. def process_item(items, index, &block) return unless item = items[index] option, argument = extract_option(item) if item.start_with?('-') if option option.count += 1 unless item.start_with?('--no-') option.count += 1 if option.key[0, 3] == "no-" @trash << index @triggered_options << option if option.expects_argument? argument ||= items.at(index + 1) if !argument || argument =~ /\A--?[a-zA-Z][a-zA-Z0-9_-]*\z/ raise MissingArgumentError, "#{option.key} expects an argument" end execute_option(option, argument, index, item) elsif option.accepts_optional_argument? argument ||= items.at(index + 1) if argument && argument =~ /\A([^\-?]|-\d)+/ execute_option(option, argument, index, item) else option.call(nil) end elsif config[:multiple_switches] && argument execute_multiple_switches(option, argument, items, index) else option.value = option.count > 0 option.call(nil) end else @unknown_options << item if strict? && item =~ /\A--?/ block.call(item) if block && !@trash.include?(index) end end # Execute an option, firing off callbacks and assigning arguments. # # option - The Slop::Option object found by #process_item. # argument - The argument Object to assign to this option. # index - The current Integer index of the object we're processing. # item - The optional String item we're processing. # # Returns nothing. def execute_option(option, argument, index, item = nil) if !option if config[:multiple_switches] && strict? raise InvalidOptionError, "Unknown option -#{item}" end return end if argument unless item && item.end_with?("=#{argument}") @trash << index + 1 unless option.argument_in_value end option.value = argument else option.value = option.count > 0 end if option.match? && !argument.match(option.config[:match]) raise InvalidArgumentError, "#{argument} is an invalid argument" end option.call(option.value) end # Execute a `-abc` type option where a, b and c are all options. This # method is only executed if the multiple_switches argument is true. # # option - The first Option object. # argument - The argument to this option. (Split into multiple Options). # items - The Array of items currently being parsed. # index - The index of the current item being processed. # # Returns nothing. def execute_multiple_switches(option, argument, items, index) execute_option(option, nil, index) flags = argument.split('') flags.each do |key| next unless opt = fetch_option(key) opt.count += 1 if (opt.expects_argument? || opt.accepts_optional_argument?) && (flags[-1] == opt.key) && (val = items[index+1]) execute_option(opt, val, index, key) else execute_option(opt, nil, index, key) end end end # Extract an option from a flag. # # flag - The flag key used to extract an option. # # Returns an Array of [option, argument]. def extract_option(flag) option = fetch_option(flag) option ||= fetch_option(flag.downcase) if config[:ignore_case] option ||= fetch_option(flag.gsub(/([^-])-/, '\1_')) unless option case flag when /\A--?([^=]+)=(.+)\z/, /\A-([a-zA-Z])(.+)\z/, /\A--no-(.+)\z/ option, argument = fetch_option($1), ($2 || false) option.argument_in_value = true if option end end [option, argument] end # Autocreate an option on the fly. See the :autocreate Slop config option. # # items - The Array of items we're parsing. # index - The current Integer index for the item we're processing. # # Returns nothing. def autocreate(items, index) flag = items[index] if !fetch_option(flag) && !@trash.include?(index) option = build_option(Array(flag)) argument = items[index + 1] option.config[:argument] = (argument && argument !~ /\A--?/) option.config[:autocreated] = true options << option end end # Build an option from a list of objects. # # objects - An Array of objects used to build this option. # # Returns a new instance of Slop::Option. def build_option(objects, &block) config = {} config[:argument] = true if @config[:arguments] config[:optional_argument] = true if @config[:optional_arguments] if objects.last.is_a?(Hash) config.merge!(objects.last) objects.pop end short = extract_short_flag(objects, config) long = extract_long_flag(objects, config) desc = objects[0].respond_to?(:to_str) ? objects.shift : nil Option.new(self, short, long, desc, config, &block) end # Extract the short flag from an item. # # objects - The Array of objects passed from #build_option. # config - The Hash of configuration options built in #build_option. def extract_short_flag(objects, config) flag = clean(objects.first) if flag.size == 2 && flag.end_with?('=') config[:argument] ||= true flag.chop! end if flag.size == 1 objects.shift flag end end # Extract the long flag from an item. # # objects - The Array of objects passed from #build_option. # config - The Hash of configuration options built in #build_option. def extract_long_flag(objects, config) flag = objects.first.to_s if flag =~ /\A(?:--?)?[a-zA-Z0-9][a-zA-Z0-9_.-]+\=?\??\z/ config[:argument] ||= true if flag.end_with?('=') config[:optional_argument] = true if flag.end_with?('=?') objects.shift clean(flag).sub(/\=\??\z/, '') end end # Remove any leading -- characters from a string. # # object - The Object we want to cast to a String and clean. # # Returns the newly cleaned String with leading -- characters removed. def clean(object) object.to_s.sub(/\A--?/, '') end def commands_to_help padding = 0 @commands.each { |c, _| padding = c.size if c.size > padding } @commands.map do |cmd, opts| " #{cmd}#{' ' * (padding - cmd.size)} #{opts.description}" end.join("\n") end end clean up extract_short_flag require 'slop/option' require 'slop/commands' class Slop include Enumerable VERSION = '3.4.5' # The main Error class, all Exception classes inherit from this class. class Error < StandardError; end # Raised when an option argument is expected but none are given. class MissingArgumentError < Error; end # Raised when an option is expected/required but not present. class MissingOptionError < Error; end # Raised when an argument does not match its intended match constraint. class InvalidArgumentError < Error; end # Raised when an invalid option is found and the strict flag is enabled. class InvalidOptionError < Error; end # Raised when an invalid command is found and the strict flag is enabled. class InvalidCommandError < Error; end # Returns a default Hash of configuration options this Slop instance uses. DEFAULT_OPTIONS = { :strict => false, :help => false, :banner => nil, :ignore_case => false, :autocreate => false, :arguments => false, :optional_arguments => false, :multiple_switches => true, :longest_flag => 0 } class << self # items - The Array of items to extract options from (default: ARGV). # config - The Hash of configuration options to send to Slop.new(). # block - An optional block used to add options. # # Examples: # # Slop.parse(ARGV, :help => true) do # on '-n', '--name', 'Your username', :argument => true # end # # Returns a new instance of Slop. def parse(items = ARGV, config = {}, &block) parse! items.dup, config, &block end # items - The Array of items to extract options from (default: ARGV). # config - The Hash of configuration options to send to Slop.new(). # block - An optional block used to add options. # # Returns a new instance of Slop. def parse!(items = ARGV, config = {}, &block) config, items = items, ARGV if items.is_a?(Hash) && config.empty? slop = new config, &block slop.parse! items slop end # Build a Slop object from a option specification. # # This allows you to design your options via a simple String rather # than programatically. Do note though that with this method, you're # unable to pass any advanced options to the on() method when creating # options. # # string - The optspec String # config - A Hash of configuration options to pass to Slop.new # # Examples: # # opts = Slop.optspec(<<-SPEC) # ruby foo.rb [options] # --- # n,name= Your name # a,age= Your age # A,auth Sign in with auth # p,passcode= Your secret pass code # SPEC # # opts.fetch_option(:name).description #=> "Your name" # # Returns a new instance of Slop. def optspec(string, config = {}) warn "[DEPRECATED] `Slop.optspec` is deprecated and will be removed in version 4" config[:banner], optspec = string.split(/^--+$/, 2) if string[/^--+$/] lines = optspec.split("\n").reject(&:empty?) opts = Slop.new(config) lines.each do |line| opt, description = line.split(' ', 2) short, long = opt.split(',').map { |s| s.sub(/\A--?/, '') } opt = opts.on(short, long, description) if long && long.end_with?('=') long.sub!(/\=$/, '') opt.config[:argument] = true end end opts end end # The Hash of configuration options for this Slop instance. attr_reader :config # The Array of Slop::Option objects tied to this Slop instance. attr_reader :options # The Hash of sub-commands for this Slop instance. attr_reader :commands # Create a new instance of Slop and optionally build options via a block. # # config - A Hash of configuration options. # block - An optional block used to specify options. def initialize(config = {}, &block) @config = DEFAULT_OPTIONS.merge(config) @options = [] @commands = {} @trash = [] @triggered_options = [] @unknown_options = [] @callbacks = {} @separators = {} @runner = nil @command = config.delete(:command) if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end if config[:help] on('-h', '--help', 'Display this help message.', :tail => true) do puts help exit end end end # Is strict mode enabled? # # Returns true if strict mode is enabled, false otherwise. def strict? config[:strict] end # Set the banner. # # banner - The String to set the banner. def banner=(banner) config[:banner] = banner end # Get or set the banner. # # banner - The String to set the banner. # # Returns the banner String. def banner(banner = nil) config[:banner] = banner if banner config[:banner] end # Set the description (used for commands). # # desc - The String to set the description. def description=(desc) config[:description] = desc end # Get or set the description (used for commands). # # desc - The String to set the description. # # Returns the description String. def description(desc = nil) config[:description] = desc if desc config[:description] end # Add a new command. # # command - The Symbol or String used to identify this command. # options - A Hash of configuration options (see Slop::new) # # Returns a new instance of Slop mapped to this command. def command(command, options = {}, &block) options = @config.merge(options) @commands[command.to_s] = Slop.new(options.merge(:command => command.to_s), &block) end # Parse a list of items, executing and gathering options along the way. # # items - The Array of items to extract options from (default: ARGV). # block - An optional block which when used will yield non options. # # Returns an Array of original items. def parse(items = ARGV, &block) parse! items.dup, &block items end # Parse a list of items, executing and gathering options along the way. # unlike parse() this method will remove any options and option arguments # from the original Array. # # items - The Array of items to extract options from (default: ARGV). # block - An optional block which when used will yield non options. # # Returns an Array of original items with options removed. def parse!(items = ARGV, &block) if items.empty? && @callbacks[:empty] @callbacks[:empty].each { |cb| cb.call(self) } return items end if cmd = @commands[items[0]] items.shift return cmd.parse! items end items.each_with_index do |item, index| @trash << index && break if item == '--' autocreate(items, index) if config[:autocreate] process_item(items, index, &block) unless @trash.include?(index) end items.reject!.with_index { |item, index| @trash.include?(index) } missing_options = options.select { |opt| opt.required? && opt.count < 1 } if missing_options.any? raise MissingOptionError, "Missing required option(s): #{missing_options.map(&:key).join(', ')}" end if @unknown_options.any? raise InvalidOptionError, "Unknown options #{@unknown_options.join(', ')}" end if @triggered_options.empty? && @callbacks[:no_options] @callbacks[:no_options].each { |cb| cb.call(self) } end if @runner.respond_to?(:call) @runner.call(self, items) unless config[:help] and present?(:help) end items end # Add an Option. # # objects - An Array with an optional Hash as the last element. # # Examples: # # on '-u', '--username=', 'Your username' # on :v, :verbose, 'Enable verbose mode' # # Returns the created instance of Slop::Option. def on(*objects, &block) option = build_option(objects, &block) original = options.find do |o| o.long and o.long == option.long or o.short and o.short == option.short end options.delete(original) if original options << option option end alias option on alias opt on # Fetch an options argument value. # # key - The Symbol or String option short or long flag. # # Returns the Object value for this option, or nil. def [](key) option = fetch_option(key) option.value if option end alias get [] # Returns a new Hash with option flags as keys and option values as values. # # include_commands - If true, merge options from all sub-commands. def to_hash(include_commands = false) hash = Hash[options.map { |opt| [opt.key.to_sym, opt.value] }] if include_commands @commands.each { |cmd, opts| hash.merge!(cmd.to_sym => opts.to_hash) } end hash end alias to_h to_hash # Enumerable interface. Yields each Slop::Option. def each(&block) options.each(&block) end # Specify code to be executed when these options are parsed. # # callable - An object responding to a call method. # # yields - The instance of Slop parsing these options # An Array of unparsed arguments # # Example: # # Slop.parse do # on :v, :verbose # # run do |opts, args| # puts "Arguments: #{args.inspect}" if opts.verbose? # end # end def run(callable = nil, &block) @runner = callable || block unless @runner.respond_to?(:call) raise ArgumentError, "You must specify a callable object or a block to #run" end end # Check for an options presence. # # Examples: # # opts.parse %w( --foo ) # opts.present?(:foo) #=> true # opts.present?(:bar) #=> false # # Returns true if all of the keys are present in the parsed arguments. def present?(*keys) keys.all? { |key| (opt = fetch_option(key)) && opt.count > 0 } end # Override this method so we can check if an option? method exists. # # Returns true if this option key exists in our list of options. def respond_to_missing?(method_name, include_private = false) options.any? { |o| o.key == method_name.to_s.chop } || super end # Fetch a list of options which were missing from the parsed list. # # Examples: # # opts = Slop.new do # on :n, :name= # on :p, :password= # end # # opts.parse %w[ --name Lee ] # opts.missing #=> ['password'] # # Returns an Array of Strings representing missing options. def missing (options - @triggered_options).map(&:key) end # Fetch a Slop::Option object. # # key - The Symbol or String option key. # # Examples: # # opts.on(:foo, 'Something fooey', :argument => :optional) # opt = opts.fetch_option(:foo) # opt.class #=> Slop::Option # opt.accepts_optional_argument? #=> true # # Returns an Option or nil if none were found. def fetch_option(key) options.find { |option| [option.long, option.short].include?(clean(key)) } end # Fetch a Slop object associated with this command. # # command - The String or Symbol name of the command. # # Examples: # # opts.command :foo do # on :v, :verbose, 'Enable verbose mode' # end # # # ruby run.rb foo -v # opts.fetch_command(:foo).verbose? #=> true def fetch_command(command) @commands[command.to_s] end # Add a callback. # # label - The Symbol identifier to attach this callback. # # Returns nothing. def add_callback(label, &block) (@callbacks[label] ||= []) << block end # Add string separators between options. # # text - The String text to print. def separator(text) if @separators[options.size] @separators[options.size] << "\n#{text}" else @separators[options.size] = text end end # Print a handy Slop help string. # # Returns the banner followed by available option help strings. def to_s heads = options.reject(&:tail?) tails = (options - heads) opts = (heads + tails).select(&:help).map(&:to_s) optstr = opts.each_with_index.map { |o, i| (str = @separators[i + 1]) ? [o, str].join("\n") : o }.join("\n") if @commands.any? optstr << "\n" if !optstr.empty? optstr << "\nAvailable commands:\n\n" optstr << commands_to_help optstr << "\n\nSee `<command> --help` for more information on a specific command." end banner = config[:banner] if banner.nil? banner = "Usage: #{File.basename($0, '.*')}" banner << " #{@command}" if @command banner << " [command]" if @commands.any? banner << " [options]" end if banner "#{banner}\n#{@separators[0] ? "#{@separators[0]}\n" : ''}#{optstr}" else optstr end end alias help to_s private # Convenience method for present?(:option). # # Examples: # # opts.parse %( --verbose ) # opts.verbose? #=> true # opts.other? #=> false # # Returns true if this option is present. If this method does not end # with a ? character it will instead call super(). def method_missing(method, *args, &block) meth = method.to_s if meth.end_with?('?') meth.chop! present?(meth) || present?(meth.gsub('_', '-')) else super end end # Process a list item, figure out if it's an option, execute any # callbacks, assign any option arguments, and do some sanity checks. # # items - The Array of items to process. # index - The current Integer index of the item we want to process. # block - An optional block which when passed will yield non options. # # Returns nothing. def process_item(items, index, &block) return unless item = items[index] option, argument = extract_option(item) if item.start_with?('-') if option option.count += 1 unless item.start_with?('--no-') option.count += 1 if option.key[0, 3] == "no-" @trash << index @triggered_options << option if option.expects_argument? argument ||= items.at(index + 1) if !argument || argument =~ /\A--?[a-zA-Z][a-zA-Z0-9_-]*\z/ raise MissingArgumentError, "#{option.key} expects an argument" end execute_option(option, argument, index, item) elsif option.accepts_optional_argument? argument ||= items.at(index + 1) if argument && argument =~ /\A([^\-?]|-\d)+/ execute_option(option, argument, index, item) else option.call(nil) end elsif config[:multiple_switches] && argument execute_multiple_switches(option, argument, items, index) else option.value = option.count > 0 option.call(nil) end else @unknown_options << item if strict? && item =~ /\A--?/ block.call(item) if block && !@trash.include?(index) end end # Execute an option, firing off callbacks and assigning arguments. # # option - The Slop::Option object found by #process_item. # argument - The argument Object to assign to this option. # index - The current Integer index of the object we're processing. # item - The optional String item we're processing. # # Returns nothing. def execute_option(option, argument, index, item = nil) if !option if config[:multiple_switches] && strict? raise InvalidOptionError, "Unknown option -#{item}" end return end if argument unless item && item.end_with?("=#{argument}") @trash << index + 1 unless option.argument_in_value end option.value = argument else option.value = option.count > 0 end if option.match? && !argument.match(option.config[:match]) raise InvalidArgumentError, "#{argument} is an invalid argument" end option.call(option.value) end # Execute a `-abc` type option where a, b and c are all options. This # method is only executed if the multiple_switches argument is true. # # option - The first Option object. # argument - The argument to this option. (Split into multiple Options). # items - The Array of items currently being parsed. # index - The index of the current item being processed. # # Returns nothing. def execute_multiple_switches(option, argument, items, index) execute_option(option, nil, index) flags = argument.split('') flags.each do |key| next unless opt = fetch_option(key) opt.count += 1 if (opt.expects_argument? || opt.accepts_optional_argument?) && (flags[-1] == opt.key) && (val = items[index+1]) execute_option(opt, val, index, key) else execute_option(opt, nil, index, key) end end end # Extract an option from a flag. # # flag - The flag key used to extract an option. # # Returns an Array of [option, argument]. def extract_option(flag) option = fetch_option(flag) option ||= fetch_option(flag.downcase) if config[:ignore_case] option ||= fetch_option(flag.gsub(/([^-])-/, '\1_')) unless option case flag when /\A--?([^=]+)=(.+)\z/, /\A-([a-zA-Z])(.+)\z/, /\A--no-(.+)\z/ option, argument = fetch_option($1), ($2 || false) option.argument_in_value = true if option end end [option, argument] end # Autocreate an option on the fly. See the :autocreate Slop config option. # # items - The Array of items we're parsing. # index - The current Integer index for the item we're processing. # # Returns nothing. def autocreate(items, index) flag = items[index] if !fetch_option(flag) && !@trash.include?(index) option = build_option(Array(flag)) argument = items[index + 1] option.config[:argument] = (argument && argument !~ /\A--?/) option.config[:autocreated] = true options << option end end # Build an option from a list of objects. # # objects - An Array of objects used to build this option. # # Returns a new instance of Slop::Option. def build_option(objects, &block) config = {} config[:argument] = true if @config[:arguments] config[:optional_argument] = true if @config[:optional_arguments] if objects.last.is_a?(Hash) config.merge!(objects.last) objects.pop end short = extract_short_flag(objects, config) long = extract_long_flag(objects, config) desc = objects[0].respond_to?(:to_str) ? objects.shift : nil Option.new(self, short, long, desc, config, &block) end def extract_short_flag(objects, config) flag = objects[0].to_s if flag =~ /\A-?\w=?\z/ config[:argument] ||= flag.end_with?('=') objects.shift flag.delete('-=') end end # Extract the long flag from an item. # # objects - The Array of objects passed from #build_option. # config - The Hash of configuration options built in #build_option. def extract_long_flag(objects, config) flag = objects.first.to_s if flag =~ /\A(?:--?)?[a-zA-Z0-9][a-zA-Z0-9_.-]+\=?\??\z/ config[:argument] ||= true if flag.end_with?('=') config[:optional_argument] = true if flag.end_with?('=?') objects.shift clean(flag).sub(/\=\??\z/, '') end end # Remove any leading -- characters from a string. # # object - The Object we want to cast to a String and clean. # # Returns the newly cleaned String with leading -- characters removed. def clean(object) object.to_s.sub(/\A--?/, '') end def commands_to_help padding = 0 @commands.each { |c, _| padding = c.size if c.size > padding } @commands.map do |cmd, opts| " #{cmd}#{' ' * (padding - cmd.size)} #{opts.description}" end.join("\n") end end
require 'slop/options' require 'slop/option' class Slop include Enumerable # Raised when an option expects an argument and none is given class MissingArgumentError < RuntimeError; end # Raised when an option specifies the `:match` attribute and this # options argument does not match this regexp class InvalidArgumentError < RuntimeError; end # Raised when the `:strict` option is enabled and an unknown # or unspecified option is used class InvalidOptionError < RuntimeError; end # @return [String] The current version string VERSION = '1.6.0' # Parses the items from a CLI format into a friendly object. # # @param [Array] items Items to parse into options. # @example Specifying three options to parse: # opts = Slops.parse do # on :v, :verbose, 'Enable verbose mode' # on :n, :name, 'Your name' # on :a, :age, 'Your age' # end # @return [Slop] Returns an instance of Slop. def self.parse(items=ARGV, options={}, &block) initialize_and_parse items, false, options, &block end # Identical to {Slop.parse}, but removes parsed options from the original Array. # # @return [Slop] Returns an instance of Slop. def self.parse!(items=ARGV, options={}, &block) initialize_and_parse items, true, options, &block end # @return [Options] attr_reader :options # @return [Hash] attr_reader :commands # @overload banner=(string) # Set the banner # @param [String] string The text to set the banner to attr_writer :banner # @return [Integer] The length of the longest flag slop knows of attr_accessor :longest_flag # @param [Hash] options # @option opts [Boolean] :help Automatically add the `help` option # @option opts [Boolean] :strict Strict mode raises when a non listed # option is found, false by default # @option opts [Boolean] :multiple_switches Allows `-abc` to be processed # as the options 'a', 'b', 'c' and will force their argument values to # true. By default Slop with parse this as 'a' with the argument 'bc' # @option opts [String] :banner The banner text used for the help # @option opts [Proc, #call] :on_empty Any object that respondes to `call` # which is executed when Slop has no items to parse # @option opts [IO, #puts] :io ($stderr) An IO object for writing to when # :help => true is used # @option opts [Boolean] :exit_on_help (true) When false and coupled with # the :help option, Slop will not exit inside of the `help` option # @option opts [Boolean] :ignore_case (false) Ignore options case # @option opts [Proc, #call] :on_noopts Trigger an event when no options # are found def initialize(*opts, &block) sloptions = opts.last.is_a?(Hash) ? opts.pop : {} sloptions[:banner] = opts.shift if opts[0].respond_to? :to_str opts.each { |o| sloptions[o] = true } @options = Options.new @commands = {} @longest_flag = 0 @invalid_options = [] @banner = sloptions[:banner] @strict = sloptions[:strict] @ignore_case = sloptions[:ignore_case] @multiple_switches = sloptions[:multiple_switches] @on_empty = sloptions[:on_empty] @on_noopts = sloptions[:on_noopts] || sloptions[:on_optionless] @sloptions = sloptions if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end if sloptions[:help] on :h, :help, 'Print this help message', :tail => true do (sloptions[:io] || $stderr).puts help exit unless sloptions[:exit_on_help] == false end end end # Set or return banner text. # # @param [String] text Displayed banner text. # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # end # @return [String] The current banner. def banner(text=nil) @banner = text if text @banner end # Parse a list of options, leaving the original Array unchanged. # # @param [Array] items A list of items to parse def parse(items=ARGV, &block) parse_items items, &block end # Parse a list of options, removing parsed options from the original Array. # # @param [Array] items A list of items to parse def parse!(items=ARGV, &block) parse_items items, true, &block end # Enumerable interface def each(&block) @options.each &block end # @param [Symbol] key Option symbol. # @example # opts[:name] #=> "Emily" # opts.get(:name) #=> "Emily" # @return [Object] Returns the value associated with that option. If an # option doesn't exist, a command will instead be searched for def [](key) option = @options[key] option ? option.argument_value : @commands[key] end alias :get :[] # Specify an option with a short or long version, description and type. # # @param [*] args Option configuration. # @option args [Symbol, String] :short_flag Short option name. # @option args [Symbol, String] :long_flag Full option name. # @option args [String] :description Option description for use in Slop#help # @option args [Boolean] :argument Specifies whether this option requires # an argument # @option args [Hash] :options Optional option configurations. # @example # opts = Slop.parse do # on :n, :name, 'Your username', true # Required argument # on :a, :age, 'Your age (optional)', :optional => true # on :g, :gender, 'Your gender', :optional => false # on :V, :verbose, 'Run in verbose mode', :default => true # on :P, :people, 'Your friends', true, :as => Array # on :h, :help, 'Print this help screen' do # puts help # end # end # @return [Slop::Option] def option(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} short, long, desc, arg = clean_options args option = Option.new self, short, long, desc, arg, options, &block @options << option option end alias :opt :option alias :on :option # Namespace options depending on what command is executed # # @param [Symbol, String] label # @param [Hash] options # @example # opts = Slop.new do # command :create do # on :v, :verbose # end # end # # # ARGV is `create -v` # opts.commands[:create].verbose? #=> true # @since 1.5.0 # @return [Slop] a new instance of Slop namespaced to +label+ def command(label, options={}, &block) if @commands[label] raise ArgumentError, "command `#{label}` already exists" end slop = Slop.new @sloptions.merge options @commands[label] = slop if block_given? block.arity == 1 ? yield(slop) : slop.instance_eval(&block) end slop end # Trigger an event when Slop has no values to parse # # @param [Object, #call] obj The object (which can be anything # responding to `call`) # @example # Slop.parse do # on_empty { puts 'No argument given!' } # end # @since 1.5.0 def on_empty(obj=nil, &block) @on_empty ||= (obj || block) end alias :on_empty= :on_empty # Trigger an event when the arguments contain no options # # @param [Object, #call] obj The object to be triggered (anything # responding to `call`) # @example # Slop.parse do # on_noopts { puts 'No options here!' } # end # @since 1.6.0 def on_noopts(obj=nil, &block) @on_noopts ||= (obj || block) end alias :on_optionless :on_noopts # Returns the parsed list into a option/value hash. # # @example # opts.to_hash #=> { 'name' => 'Emily' } # # # symbols! # opts.to_hash(true) #=> { :name => 'Emily' } # @return [Hash] def to_hash(symbols=false) @options.to_hash symbols end alias :to_h :to_hash # Allows you to check whether an option was specified in the parsed list. # Merely sugar for `present?` # # @example # #== ruby foo.rb -v # opts.verbose? #=> true # opts.name? #=> false # @see Slop#present? # @return [Boolean] true if this option is present, false otherwise def method_missing(meth, *args, &block) super unless meth.to_s[-1, 1] == '?' present? meth.to_s.chomp '?' end # Check if an option is specified in the parsed list. Does the same as # Slop#option? but a convenience method for unacceptable method names. # # @param [Object] The object name to check # @since 1.5.0 # @return [Boolean] true if this option is present, false otherwise def present?(option_name) !!get(option_name) end # Returns the banner followed by available options listed on the next line. # # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # on :v, :verbose, "Enable verbose mode" # end # puts opts # @return [String] Help text. def to_s banner = "#{@banner}\n" if @banner (banner || '') + options.to_help end alias :help :to_s def inspect "#<Slop config_options=#{@sloptions.inspect}\n " + options.map(&:inspect).join("\n ") + "\n>" end private class << self private def initialize_and_parse(items, delete, options, &block) if items.is_a?(Hash) && options.empty? options = items items = ARGV end slop = new(options, &block) delete ? slop.parse!(items) : slop.parse(items) slop end end def parse_items(items, delete=false, &block) if items.empty? && @on_empty.respond_to?(:call) @on_empty.call self return items elsif !items.any? {|i| i.to_s[/\A--?/] } && @on_noopts.respond_to?(:call) @on_noopts.call self return items elsif execute_command(items, delete) return items end trash = [] items.each_with_index do |item, index| item = item.to_s flag = item.sub(/\A--?/, '') option, argument = extract_option(item, flag) next if @multiple_switches if option option.count += 1 trash << index next if option.forced option.argument_value = true if option.expects_argument? || option.accepts_optional_argument? argument ||= items.at(index + 1) check_valid_argument!(option, argument) trash << index + 1 if argument check_matching_argument!(option, argument) option.argument_value = argument option.call option.argument_value unless option.omit_exec?(items) else option.argument_value = nil check_optional_argument!(option, flag) end else option.call unless option.omit_exec?(items) end else @invalid_options << flag if item[/\A--?/] && @strict block.call(item) if block_given? && !trash.include?(index) end end items.reject!.with_index { |o, i| trash.include?(i) } if delete raise_if_invalid_options! items end def check_valid_argument!(option, argument) if !option.accepts_optional_argument? && flag?(argument) raise MissingArgumentError, "'#{option.key}' expects an argument, none given" end end def check_matching_argument!(option, argument) if option.match && !argument.match(option.match) raise InvalidArgumentError, "'#{argument}' does not match #{option.match.inspect}" end end def check_optional_argument!(option, flag) if option.accepts_optional_argument? option.call else raise MissingArgumentError, "'#{flag}' expects an argument, none given" end end def raise_if_invalid_options! return if !@strict || @invalid_options.empty? message = "Unknown option" message << 's' if @invalid_options.size > 1 message << ' -- ' << @invalid_options.map { |o| "'#{o}'" }.join(', ') raise InvalidOptionError, message end def enable_multiple_switches(item) item[1..-1].each_char do |switch| if option = @options[switch] if option.expects_argument? raise MissingArgumentError, "'-#{switch}' expects an argument, used in multiple_switch context" else option.argument_value = true end else raise InvalidOptionError, "Unknown option '-#{switch}'" if @strict end end end def extract_option(item, flag) if item[0, 1] == '-' option = @options[flag] option = @options[flag.downcase] if !option && @ignore_case end unless option case item when /\A-[^-]/ if @multiple_switches enable_multiple_switches(item) else flag, argument = flag.split('', 2) option = @options[flag] end when /\A--([^=]+)=(.+)\z/ option, argument = @options[$1], $2 when /\A--no-(.+)\z/ option = @options[$1] option.force_argument_value(false) if option end end [option, argument] end def execute_command(items, delete) command = @commands.keys.find { |cmd| cmd.to_s == items[0].to_s } if @commands.key? command items.shift opts = @commands[command] delete ? opts.parse!(items) : opts.parse(items) true end end def clean_options(args) options = [] short = args.first.to_s.sub /\A--?/, '' if short.size == 1 options.push short args.shift else options.push nil end long = args.first boolean = [true, false].include? long if !boolean && long.to_s =~ /\A(?:--?)?[a-zA-Z][a-zA-Z0-9_-]+\z/ options.push args.shift.to_s.sub /\A--?/, '' else options.push nil end options.push args.first.respond_to?(:to_sym) ? args.shift : nil options.push args.shift ? true : false # force true/false end def flag?(str) str =~ /\A--?[a-zA-Z][a-zA-Z0-9_-]*\z/ end end doc line exceeds 80char, split it require 'slop/options' require 'slop/option' class Slop include Enumerable # Raised when an option expects an argument and none is given class MissingArgumentError < RuntimeError; end # Raised when an option specifies the `:match` attribute and this # options argument does not match this regexp class InvalidArgumentError < RuntimeError; end # Raised when the `:strict` option is enabled and an unknown # or unspecified option is used class InvalidOptionError < RuntimeError; end # @return [String] The current version string VERSION = '1.6.0' # Parses the items from a CLI format into a friendly object. # # @param [Array] items Items to parse into options. # @example Specifying three options to parse: # opts = Slops.parse do # on :v, :verbose, 'Enable verbose mode' # on :n, :name, 'Your name' # on :a, :age, 'Your age' # end # @return [Slop] Returns an instance of Slop. def self.parse(items=ARGV, options={}, &block) initialize_and_parse items, false, options, &block end # Identical to {Slop.parse}, but removes parsed options from the # original Array. # # @return [Slop] Returns an instance of Slop. def self.parse!(items=ARGV, options={}, &block) initialize_and_parse items, true, options, &block end # @return [Options] attr_reader :options # @return [Hash] attr_reader :commands # @overload banner=(string) # Set the banner # @param [String] string The text to set the banner to attr_writer :banner # @return [Integer] The length of the longest flag slop knows of attr_accessor :longest_flag # @param [Hash] options # @option opts [Boolean] :help Automatically add the `help` option # @option opts [Boolean] :strict Strict mode raises when a non listed # option is found, false by default # @option opts [Boolean] :multiple_switches Allows `-abc` to be processed # as the options 'a', 'b', 'c' and will force their argument values to # true. By default Slop with parse this as 'a' with the argument 'bc' # @option opts [String] :banner The banner text used for the help # @option opts [Proc, #call] :on_empty Any object that respondes to `call` # which is executed when Slop has no items to parse # @option opts [IO, #puts] :io ($stderr) An IO object for writing to when # :help => true is used # @option opts [Boolean] :exit_on_help (true) When false and coupled with # the :help option, Slop will not exit inside of the `help` option # @option opts [Boolean] :ignore_case (false) Ignore options case # @option opts [Proc, #call] :on_noopts Trigger an event when no options # are found def initialize(*opts, &block) sloptions = opts.last.is_a?(Hash) ? opts.pop : {} sloptions[:banner] = opts.shift if opts[0].respond_to? :to_str opts.each { |o| sloptions[o] = true } @options = Options.new @commands = {} @longest_flag = 0 @invalid_options = [] @banner = sloptions[:banner] @strict = sloptions[:strict] @ignore_case = sloptions[:ignore_case] @multiple_switches = sloptions[:multiple_switches] @on_empty = sloptions[:on_empty] @on_noopts = sloptions[:on_noopts] || sloptions[:on_optionless] @sloptions = sloptions if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end if sloptions[:help] on :h, :help, 'Print this help message', :tail => true do (sloptions[:io] || $stderr).puts help exit unless sloptions[:exit_on_help] == false end end end # Set or return banner text. # # @param [String] text Displayed banner text. # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # end # @return [String] The current banner. def banner(text=nil) @banner = text if text @banner end # Parse a list of options, leaving the original Array unchanged. # # @param [Array] items A list of items to parse def parse(items=ARGV, &block) parse_items items, &block end # Parse a list of options, removing parsed options from the original Array. # # @param [Array] items A list of items to parse def parse!(items=ARGV, &block) parse_items items, true, &block end # Enumerable interface def each(&block) @options.each &block end # @param [Symbol] key Option symbol. # @example # opts[:name] #=> "Emily" # opts.get(:name) #=> "Emily" # @return [Object] Returns the value associated with that option. If an # option doesn't exist, a command will instead be searched for def [](key) option = @options[key] option ? option.argument_value : @commands[key] end alias :get :[] # Specify an option with a short or long version, description and type. # # @param [*] args Option configuration. # @option args [Symbol, String] :short_flag Short option name. # @option args [Symbol, String] :long_flag Full option name. # @option args [String] :description Option description for use in Slop#help # @option args [Boolean] :argument Specifies whether this option requires # an argument # @option args [Hash] :options Optional option configurations. # @example # opts = Slop.parse do # on :n, :name, 'Your username', true # Required argument # on :a, :age, 'Your age (optional)', :optional => true # on :g, :gender, 'Your gender', :optional => false # on :V, :verbose, 'Run in verbose mode', :default => true # on :P, :people, 'Your friends', true, :as => Array # on :h, :help, 'Print this help screen' do # puts help # end # end # @return [Slop::Option] def option(*args, &block) options = args.last.is_a?(Hash) ? args.pop : {} short, long, desc, arg = clean_options args option = Option.new self, short, long, desc, arg, options, &block @options << option option end alias :opt :option alias :on :option # Namespace options depending on what command is executed # # @param [Symbol, String] label # @param [Hash] options # @example # opts = Slop.new do # command :create do # on :v, :verbose # end # end # # # ARGV is `create -v` # opts.commands[:create].verbose? #=> true # @since 1.5.0 # @return [Slop] a new instance of Slop namespaced to +label+ def command(label, options={}, &block) if @commands[label] raise ArgumentError, "command `#{label}` already exists" end slop = Slop.new @sloptions.merge options @commands[label] = slop if block_given? block.arity == 1 ? yield(slop) : slop.instance_eval(&block) end slop end # Trigger an event when Slop has no values to parse # # @param [Object, #call] obj The object (which can be anything # responding to `call`) # @example # Slop.parse do # on_empty { puts 'No argument given!' } # end # @since 1.5.0 def on_empty(obj=nil, &block) @on_empty ||= (obj || block) end alias :on_empty= :on_empty # Trigger an event when the arguments contain no options # # @param [Object, #call] obj The object to be triggered (anything # responding to `call`) # @example # Slop.parse do # on_noopts { puts 'No options here!' } # end # @since 1.6.0 def on_noopts(obj=nil, &block) @on_noopts ||= (obj || block) end alias :on_optionless :on_noopts # Returns the parsed list into a option/value hash. # # @example # opts.to_hash #=> { 'name' => 'Emily' } # # # symbols! # opts.to_hash(true) #=> { :name => 'Emily' } # @return [Hash] def to_hash(symbols=false) @options.to_hash symbols end alias :to_h :to_hash # Allows you to check whether an option was specified in the parsed list. # Merely sugar for `present?` # # @example # #== ruby foo.rb -v # opts.verbose? #=> true # opts.name? #=> false # @see Slop#present? # @return [Boolean] true if this option is present, false otherwise def method_missing(meth, *args, &block) super unless meth.to_s[-1, 1] == '?' present? meth.to_s.chomp '?' end # Check if an option is specified in the parsed list. Does the same as # Slop#option? but a convenience method for unacceptable method names. # # @param [Object] The object name to check # @since 1.5.0 # @return [Boolean] true if this option is present, false otherwise def present?(option_name) !!get(option_name) end # Returns the banner followed by available options listed on the next line. # # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # on :v, :verbose, "Enable verbose mode" # end # puts opts # @return [String] Help text. def to_s banner = "#{@banner}\n" if @banner (banner || '') + options.to_help end alias :help :to_s def inspect "#<Slop config_options=#{@sloptions.inspect}\n " + options.map(&:inspect).join("\n ") + "\n>" end private class << self private def initialize_and_parse(items, delete, options, &block) if items.is_a?(Hash) && options.empty? options = items items = ARGV end slop = new(options, &block) delete ? slop.parse!(items) : slop.parse(items) slop end end def parse_items(items, delete=false, &block) if items.empty? && @on_empty.respond_to?(:call) @on_empty.call self return items elsif !items.any? {|i| i.to_s[/\A--?/] } && @on_noopts.respond_to?(:call) @on_noopts.call self return items elsif execute_command(items, delete) return items end trash = [] items.each_with_index do |item, index| item = item.to_s flag = item.sub(/\A--?/, '') option, argument = extract_option(item, flag) next if @multiple_switches if option option.count += 1 trash << index next if option.forced option.argument_value = true if option.expects_argument? || option.accepts_optional_argument? argument ||= items.at(index + 1) check_valid_argument!(option, argument) trash << index + 1 if argument check_matching_argument!(option, argument) option.argument_value = argument option.call option.argument_value unless option.omit_exec?(items) else option.argument_value = nil check_optional_argument!(option, flag) end else option.call unless option.omit_exec?(items) end else @invalid_options << flag if item[/\A--?/] && @strict block.call(item) if block_given? && !trash.include?(index) end end items.reject!.with_index { |o, i| trash.include?(i) } if delete raise_if_invalid_options! items end def check_valid_argument!(option, argument) if !option.accepts_optional_argument? && flag?(argument) raise MissingArgumentError, "'#{option.key}' expects an argument, none given" end end def check_matching_argument!(option, argument) if option.match && !argument.match(option.match) raise InvalidArgumentError, "'#{argument}' does not match #{option.match.inspect}" end end def check_optional_argument!(option, flag) if option.accepts_optional_argument? option.call else raise MissingArgumentError, "'#{flag}' expects an argument, none given" end end def raise_if_invalid_options! return if !@strict || @invalid_options.empty? message = "Unknown option" message << 's' if @invalid_options.size > 1 message << ' -- ' << @invalid_options.map { |o| "'#{o}'" }.join(', ') raise InvalidOptionError, message end def enable_multiple_switches(item) item[1..-1].each_char do |switch| if option = @options[switch] if option.expects_argument? raise MissingArgumentError, "'-#{switch}' expects an argument, used in multiple_switch context" else option.argument_value = true end else raise InvalidOptionError, "Unknown option '-#{switch}'" if @strict end end end def extract_option(item, flag) if item[0, 1] == '-' option = @options[flag] option = @options[flag.downcase] if !option && @ignore_case end unless option case item when /\A-[^-]/ if @multiple_switches enable_multiple_switches(item) else flag, argument = flag.split('', 2) option = @options[flag] end when /\A--([^=]+)=(.+)\z/ option, argument = @options[$1], $2 when /\A--no-(.+)\z/ option = @options[$1] option.force_argument_value(false) if option end end [option, argument] end def execute_command(items, delete) command = @commands.keys.find { |cmd| cmd.to_s == items[0].to_s } if @commands.key? command items.shift opts = @commands[command] delete ? opts.parse!(items) : opts.parse(items) true end end def clean_options(args) options = [] short = args.first.to_s.sub /\A--?/, '' if short.size == 1 options.push short args.shift else options.push nil end long = args.first boolean = [true, false].include? long if !boolean && long.to_s =~ /\A(?:--?)?[a-zA-Z][a-zA-Z0-9_-]+\z/ options.push args.shift.to_s.sub /\A--?/, '' else options.push nil end options.push args.first.respond_to?(:to_sym) ? args.shift : nil options.push args.shift ? true : false # force true/false end def flag?(str) str =~ /\A--?[a-zA-Z][a-zA-Z0-9_-]*\z/ end end
require 'slop/option' require 'slop/version' class Slop include Enumerable class MissingArgumentError < ArgumentError; end # Parses the items from a CLI format into a friendly object. # # @param [Array] items Items to parse into options. # @yield Specify available CLI arguments using Slop# methods such as Slop#banner and Slop#option # @return [Slop] Returns an instance of Slop. # @example Specifying three options to parse: # opts = Slops.parse do # on :v, :verbose, 'Enable verbose mode' # on :n, :name, 'Your name' # on :a, :age, 'Your age' # end # ------- # program.rb --verbose -n 'Emily' -a 25 # @see Slop#banner # @see Slop#option def self.parse(items=ARGV, &block) slop = new(&block) slop.parse(items) slop end attr_reader :options attr_writer :banner attr_accessor :longest_flag def initialize(&block) @options = Options.new @banner = nil @longest_flag = 0 if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end end # Set or return banner text. # # @param [String] text Displayed banner text. # @return [String] Returns current banner. # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # end # @see Slop#to_s def banner(text=nil) @banner = text if text @banner end def parse(items=ARGV) parse_items(items) end def parse!(items=ARGV) parse_items(items, true) end # Enumerable interface def each return enum_for(:each) unless block_given? @options.each { |option| yield option } end # Return the value of an option via the subscript operator. # # @param [Symbol] key Option symbol. # @return [Object] Returns the object associated with that option. # @example # opts[:name] # #=> "Emily" # @see Slop#method_missing def [](key) option = @options[key] option ? option.argument_value : nil end # Specify an option with a short or long version, description and type. # # @param [*] args Option configuration. # @option args [Symbol, String] :short_flag Short option name. # @option args [Symbol, String] :long_flag Full option name. # @option args [String] :description Option description for use in Slop#help # @option args [Boolean] :argument Specifies whether a required option or not. # @option args [Hash] :options Optional option configurations. # @example # opts = Slop.parse do # on :n, :name, 'Your username', true # Required argument # on :a, :age, 'Your age (optional)', :optional => true # Optional argument # on :g, :gender, 'Your gender', :optional => false # Required argument # on :V, :verbose, 'Run in verbose mode', :default => true # Runs verbose mode by default # on :P, :people, 'Your friends', true, :as => Array # Required, list of people. # on :h, :help, 'Print this help screen' do # puts help # end # Runs a block # end def option(*args, &block) options = args.pop if args.last.is_a?(Hash) options ||= {} option = Option.new(self, *clean_options(args), options, &block) @options << option option end alias :opt :option alias :on :option # Returns the parsed list into a option/value hash. # # @return [Hash] Returns a hash with each specified option as a symbolic key with an associated value. # @example # opts.to_hash # #=> { :name => 'Emily' } def to_hash @options.to_hash end # Allows you to check whether an option was specified in the parsed list. # # @return [Boolean] Whether the desired option was specified. # @example # #== ruby foo.rb -v # opts.verbose? # #=> true # opts.name? # #=> false # @see Slop#[] def method_missing(meth, *args, &block) if meth.to_s =~ /\?$/ !!self[meth.to_s.chomp('?')] else super end end # Returns the banner followed by available options listed on the next line. # # @return [String] Help text. # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # on :v, :verbose, "Enable verbose mode" # end # opts.to_s # #=> "Usage - ruby foo.rb [options]\n -v, --verbose Enable verbose mode" # @see Slop#banner def to_s banner = "#{@banner}\n" if @banner (banner || '') + options.map(&:to_s).join("\n") end alias :help :to_s private def parse_items(items, delete=false) trash = [] items.each do |item| flag = item.to_s.sub(/^--?/, '') if option = @options[flag] trash << item if delete option.argument_value = true if option.expects_argument? || option.accepts_optional_argument? argument = items.at(items.index(item) + 1) trash << argument if delete if argument option.argument_value = argument option.callback.call(option.argument_value) if option.callback else option.argument_value = nil if option.accepts_optional_argument? option.callback.call(nil) if option.callback else raise MissingArgumentError, "'#{flag}' expects an argument, none given" end end elsif option.callback option.callback.call(nil) end end end items.delete_if { |item| trash.include? item } end # @param [Array] args # @return [Array] def clean_options(args) options = [] short = args.first.to_s.sub(/^--?/, '') if short.size == 1 options.push short args.shift else options.push nil end long = args.first if !long.is_a?(TrueClass) && !long.is_a?(FalseClass) && long.to_s =~ /\A(--?)?[a-zA-Z0-9_-]+\z/ options.push args.shift.to_s.sub(/^--?/, '') else options.push nil end options.push args.first.respond_to?(:to_sym) ? args.shift : nil options.push args.shift ? true : false # force true/false options end end added parse/parse! documentation require 'slop/option' require 'slop/version' class Slop include Enumerable class MissingArgumentError < ArgumentError; end # Parses the items from a CLI format into a friendly object. # # @param [Array] items Items to parse into options. # @yield Specify available CLI arguments using Slop# methods such as Slop#banner and Slop#option # @return [Slop] Returns an instance of Slop. # @example Specifying three options to parse: # opts = Slops.parse do # on :v, :verbose, 'Enable verbose mode' # on :n, :name, 'Your name' # on :a, :age, 'Your age' # end # ------- # program.rb --verbose -n 'Emily' -a 25 # @see Slop#banner # @see Slop#option def self.parse(items=ARGV, &block) slop = new(&block) slop.parse(items) slop end attr_reader :options attr_writer :banner attr_accessor :longest_flag def initialize(&block) @options = Options.new @banner = nil @longest_flag = 0 if block_given? block.arity == 1 ? yield(self) : instance_eval(&block) end end # Set or return banner text. # # @param [String] text Displayed banner text. # @return [String] Returns current banner. # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # end # @see Slop#to_s def banner(text=nil) @banner = text if text @banner end # Parse a list of options, leaving the original Array unchanged. # # @param items def parse(items=ARGV) parse_items(items) end # Parse a list of options, removing parsed options from the original Array. # # @parse items def parse!(items=ARGV) parse_items(items, true) end # Enumerable interface def each return enum_for(:each) unless block_given? @options.each { |option| yield option } end # Return the value of an option via the subscript operator. # # @param [Symbol] key Option symbol. # @return [Object] Returns the object associated with that option. # @example # opts[:name] # #=> "Emily" # @see Slop#method_missing def [](key) option = @options[key] option ? option.argument_value : nil end # Specify an option with a short or long version, description and type. # # @param [*] args Option configuration. # @option args [Symbol, String] :short_flag Short option name. # @option args [Symbol, String] :long_flag Full option name. # @option args [String] :description Option description for use in Slop#help # @option args [Boolean] :argument Specifies whether a required option or not. # @option args [Hash] :options Optional option configurations. # @example # opts = Slop.parse do # on :n, :name, 'Your username', true # Required argument # on :a, :age, 'Your age (optional)', :optional => true # Optional argument # on :g, :gender, 'Your gender', :optional => false # Required argument # on :V, :verbose, 'Run in verbose mode', :default => true # Runs verbose mode by default # on :P, :people, 'Your friends', true, :as => Array # Required, list of people. # on :h, :help, 'Print this help screen' do # puts help # end # Runs a block # end def option(*args, &block) options = args.pop if args.last.is_a?(Hash) options ||= {} option = Option.new(self, *clean_options(args), options, &block) @options << option option end alias :opt :option alias :on :option # Returns the parsed list into a option/value hash. # # @return [Hash] Returns a hash with each specified option as a symbolic key with an associated value. # @example # opts.to_hash # #=> { :name => 'Emily' } def to_hash @options.to_hash end # Allows you to check whether an option was specified in the parsed list. # # @return [Boolean] Whether the desired option was specified. # @example # #== ruby foo.rb -v # opts.verbose? # #=> true # opts.name? # #=> false # @see Slop#[] def method_missing(meth, *args, &block) if meth.to_s =~ /\?$/ !!self[meth.to_s.chomp('?')] else super end end # Returns the banner followed by available options listed on the next line. # # @return [String] Help text. # @example # opts = Slop.parse do # banner "Usage - ruby foo.rb [arguments]" # on :v, :verbose, "Enable verbose mode" # end # opts.to_s # #=> "Usage - ruby foo.rb [options]\n -v, --verbose Enable verbose mode" # @see Slop#banner def to_s banner = "#{@banner}\n" if @banner (banner || '') + options.map(&:to_s).join("\n") end alias :help :to_s private def parse_items(items, delete=false) trash = [] items.each do |item| flag = item.to_s.sub(/^--?/, '') if option = @options[flag] trash << item if delete option.argument_value = true if option.expects_argument? || option.accepts_optional_argument? argument = items.at(items.index(item) + 1) trash << argument if delete if argument option.argument_value = argument option.callback.call(option.argument_value) if option.callback else option.argument_value = nil if option.accepts_optional_argument? option.callback.call(nil) if option.callback else raise MissingArgumentError, "'#{flag}' expects an argument, none given" end end elsif option.callback option.callback.call(nil) end end end items.delete_if { |item| trash.include? item } end # @param [Array] args # @return [Array] def clean_options(args) options = [] short = args.first.to_s.sub(/^--?/, '') if short.size == 1 options.push short args.shift else options.push nil end long = args.first if !long.is_a?(TrueClass) && !long.is_a?(FalseClass) && long.to_s =~ /\A(--?)?[a-zA-Z0-9_-]+\z/ options.push args.shift.to_s.sub(/^--?/, '') else options.push nil end options.push args.first.respond_to?(:to_sym) ? args.shift : nil options.push args.shift ? true : false # force true/false options end end
require 'slop/option' require 'slop/options' require 'slop/parser' require 'slop/result' require 'slop/types' require 'slop/error' module Slop VERSION = '4.2.1' # Parse an array of options (defaults to ARGV). Accepts an # optional hash of configuration options and block. # # Example: # # opts = Slop.parse(["-host", "localhost"]) do |o| # o.string '-host', 'a hostname', default: '0.0.0.0' # end # opts.to_hash #=> { host: 'localhost' } # # Returns a Slop::Result. def self.parse(items = ARGV, **config, &block) Options.new(config, &block).parse(items) end # Example: # # Slop.option_defined?(:string) #=> true # Slop.option_defined?(:omg) #=> false # # Returns true if an option is defined. def self.option_defined?(name) const_defined?(string_to_option(name.to_s)) end # Example: # # Slop.string_to_option("string") #=> "StringOption" # Slop.string_to_option("some_thing") #=> "SomeThingOption" # # Returns a camel-cased class looking string with Option suffix. def self.string_to_option(s) s.gsub(/(?:^|_)([a-z])/) { $1.capitalize } + "Option" end # Example: # # Slop.string_to_option_class("string") #=> Slop::StringOption # Slop.string_to_option_class("foo") #=> uninitialized constant FooOption # # Returns the full qualified option class. Uses `#string_to_option`. def self.string_to_option_class(s) const_get(string_to_option(s)) end end Bump version to 4.3.0 require 'slop/option' require 'slop/options' require 'slop/parser' require 'slop/result' require 'slop/types' require 'slop/error' module Slop VERSION = '4.3.0' # Parse an array of options (defaults to ARGV). Accepts an # optional hash of configuration options and block. # # Example: # # opts = Slop.parse(["-host", "localhost"]) do |o| # o.string '-host', 'a hostname', default: '0.0.0.0' # end # opts.to_hash #=> { host: 'localhost' } # # Returns a Slop::Result. def self.parse(items = ARGV, **config, &block) Options.new(config, &block).parse(items) end # Example: # # Slop.option_defined?(:string) #=> true # Slop.option_defined?(:omg) #=> false # # Returns true if an option is defined. def self.option_defined?(name) const_defined?(string_to_option(name.to_s)) end # Example: # # Slop.string_to_option("string") #=> "StringOption" # Slop.string_to_option("some_thing") #=> "SomeThingOption" # # Returns a camel-cased class looking string with Option suffix. def self.string_to_option(s) s.gsub(/(?:^|_)([a-z])/) { $1.capitalize } + "Option" end # Example: # # Slop.string_to_option_class("string") #=> Slop::StringOption # Slop.string_to_option_class("foo") #=> uninitialized constant FooOption # # Returns the full qualified option class. Uses `#string_to_option`. def self.string_to_option_class(s) const_get(string_to_option(s)) end end
backend = WhitelabBackend.instance metadata_dir = Rails.root.join('config','metadata_'+backend.get_backend_type).to_s if !File.directory?(metadata_dir) Dir.mkdir metadata_dir end doc_file = metadata_dir+'/documents.yml' logger = Logger.new STDOUT logger.formatter = Logger::Formatter.new logger.info "Loading documents" if !File.exists?(doc_file) logger.info "Retrieving document list from backend '"+backend.get_backend_type+"'" docs = backend.get_document_list File.open(doc_file, 'w') { |f| YAML.dump({ "documents" => docs }, f) } end ::DOCUMENT_DATA = YAML.load_file(doc_file)["documents"] logger.info "Finished loading documents" if Dir[metadata_dir+'/*.yml'].length < 2 logger.info "Creating metadata coverage configuration file" logger.info "Loading document metadata" threads = [] i = DOCUMENT_DATA.length / 80 + 1 DOCUMENT_DATA.keys.in_groups_of(i) do |subset| threads << Thread.new do subset.each_with_index do |xmlid, d| doc_data = DOCUMENT_DATA[xmlid] if d > 0 && d % 2000 == 0 logger.info "Thread "+Thread.current.object_id.to_s+" processed "+d.to_s+" out of "+i.to_s+" docs" end if !doc_data.blank? doc_tmp_file = Rails.root.join('tmp','data').to_s+'/'+xmlid+'.js' if doc_data.has_key?("token_count") && !doc_data["token_count"].blank? && doc_data["token_count"] > 0 && !File.exists?(doc_tmp_file) doc_metadata = {} doc_metadata["metadata"] = backend.get_document_metadata(xmlid) doc_metadata["token_count"] = doc_data["token_count"] doc_metadata["corpus"] = doc_data["corpus"] doc_metadata["collection"] = doc_data["collection"] if !doc_metadata.has_key?("document_xmlid") doc_metadata["document_xmlid"] = xmlid end if !File.directory?(Rails.root.join('tmp','data').to_s) Dir.mkdir Rails.root.join('tmp','data').to_s end File.open(doc_tmp_file, "w+") do |f| f.puts(doc_metadata.to_json) end end end end end end threads.each(&:join) logger.info "Adding document ids to metadata values" metadata = {} metadata["Corpus"] = {} metadata["Corpus"]["title"] = {} metadata["Collection"] = {} metadata["Collection"]["title"] = {} if backend.get_backend_type.eql?('blacklab') metadata["Metadata"] = {} end files = Dir[Rails.root.join('tmp','data').to_s+'/*.js'] files.each_with_index do |file, f| if f > 0 && f % 100000 == 0 logger.info "Processed "+f.to_s+" out of "+files.length.to_s+" documents" end content = File.read(file) if content.length > 0 doc_data = JSON.parse(content) if !metadata["Corpus"]["title"].has_key?(doc_data["corpus"]) metadata["Corpus"]["title"][doc_data["corpus"]] = [] end metadata["Corpus"]["title"][doc_data["corpus"]] << doc_data["document_xmlid"] if !metadata["Collection"]["title"].has_key?(doc_data["collection"]) metadata["Collection"]["title"][doc_data["collection"]] = [] end metadata["Collection"]["title"][doc_data["collection"]] << doc_data["document_xmlid"] if backend.get_backend_type.eql?('blacklab') doc_data["metadata"].each do |key, value| if !metadata["Metadata"].has_key?(key) metadata["Metadata"][key] = {} end if !metadata["Metadata"][key].has_key?(value) metadata["Metadata"][key][value] = [] end metadata["Metadata"][key][value] << doc_data["document_xmlid"] end elsif backend.get_backend_type.eql?('neo4j') doc_data["metadata"].each do |group, keys| if !metadata.has_key?(group) metadata[group] = {} end keys.each do |key, values| if !metadata[group].has_key?(key) metadata[group][key] = {} end values.each do |value| if !metadata[group][key].has_key?(value) metadata[group][key][value] = [] end metadata[group][key][value] << doc_data["document_xmlid"] end end end end end File.delete(file) end # save all data to configuration files logger.info "Writing metadata coverage to configuration files" # File.open(coverage_config, 'w') { |f| YAML.dump({ "coverage" => metadata }, f) } threads = [] metadata.each do |group, keys| threads << Thread.new do keys.each do |key, values| key_file = metadata_dir+'/'+group+'.'+key+'.yml' if !File.exists?(key_file) File.open(key_file, 'w', external_encoding: 'ASCII-8BIT') { |f| YAML.dump({ "values" => metadata[group][key] }, f) } end end end end threads.each(&:join) end logger.info "Loading metadata" metadata = {} Dir[metadata_dir+'/*.yml'].each do |file| if !file.end_with?('documents.yml') base = file.sub(metadata_dir+'/','').sub('.yml','') group = base.split('.')[0] key = base.split('.')[1] if !metadata.has_key?(group) metadata[group] = {} end metadata[group][key] = YAML.load_file(file)["values"] end end ::DOCUMENT_METADATA = metadata logger.info "Finished loading metadata" Fix metadata coverage bug backend = WhitelabBackend.instance metadata_dir = Rails.root.join('config','metadata_'+backend.get_backend_type).to_s if !File.directory?(metadata_dir) Dir.mkdir metadata_dir end doc_file = metadata_dir+'/documents.yml' logger = Logger.new STDOUT logger.formatter = Logger::Formatter.new logger.info "Loading documents" if !File.exists?(doc_file) logger.info "Retrieving document list from backend '"+backend.get_backend_type+"'" docs = backend.get_document_list File.open(doc_file, 'w') { |f| YAML.dump({ "documents" => docs }, f) } end ::DOCUMENT_DATA = YAML.load_file(doc_file)["documents"] logger.info "Finished loading documents" if Dir[metadata_dir+'/*.yml'].length < 2 logger.info "Creating metadata coverage configuration file" logger.info "Loading document metadata" threads = [] i = DOCUMENT_DATA.length / 80 + 1 DOCUMENT_DATA.keys.in_groups_of(i) do |subset| threads << Thread.new do subset.each_with_index do |xmlid, d| doc_data = DOCUMENT_DATA[xmlid] if d > 0 && d % 2000 == 0 logger.info "Thread "+Thread.current.object_id.to_s+" processed "+d.to_s+" out of "+i.to_s+" docs" end if !doc_data.blank? doc_tmp_file = Rails.root.join('tmp','data').to_s+'/'+xmlid+'.js' if doc_data.has_key?("token_count") && !doc_data["token_count"].blank? && doc_data["token_count"] > 0 && !File.exists?(doc_tmp_file) doc_metadata = {} doc_metadata["metadata"] = backend.get_document_metadata(xmlid) doc_metadata["token_count"] = doc_data["token_count"] doc_metadata["corpus"] = doc_data["corpus"] doc_metadata["collection"] = doc_data["collection"] if !doc_metadata.has_key?("document_xmlid") doc_metadata["document_xmlid"] = xmlid end if !File.directory?(Rails.root.join('tmp','data').to_s) Dir.mkdir Rails.root.join('tmp','data').to_s end File.open(doc_tmp_file, "w+") do |f| f.puts(doc_metadata.to_json) end end end end end end threads.each(&:join) logger.info "Adding document ids to metadata values" metadata = {} metadata["Corpus"] = {} metadata["Corpus"]["title"] = {} metadata["Collection"] = {} metadata["Collection"]["title"] = {} if backend.get_backend_type.eql?('blacklab') metadata["Metadata"] = {} end files = Dir[Rails.root.join('tmp','data').to_s+'/*.js'] files.each_with_index do |file, f| if f > 0 && f % 100000 == 0 logger.info "Processed "+f.to_s+" out of "+files.length.to_s+" documents" end content = File.read(file) if content.length > 0 doc_data = JSON.parse(content) if !metadata["Corpus"]["title"].has_key?(doc_data["corpus"]) metadata["Corpus"]["title"][doc_data["corpus"]] = [] end metadata["Corpus"]["title"][doc_data["corpus"]] << doc_data["document_xmlid"] if !metadata["Collection"]["title"].has_key?(doc_data["collection"]) metadata["Collection"]["title"][doc_data["collection"]] = [] end metadata["Collection"]["title"][doc_data["collection"]] << doc_data["document_xmlid"] if backend.get_backend_type.eql?('blacklab') doc_data["metadata"]["Metadata"].each do |key, value| if !metadata["Metadata"].has_key?(key) metadata["Metadata"][key] = {} end if !metadata["Metadata"][key].has_key?(value[0]) metadata["Metadata"][key][value[0]] = [] end metadata["Metadata"][key][value[0]] << doc_data["document_xmlid"] end elsif backend.get_backend_type.eql?('neo4j') doc_data["metadata"].each do |group, keys| if !metadata.has_key?(group) metadata[group] = {} end keys.each do |key, values| if !metadata[group].has_key?(key) metadata[group][key] = {} end values.each do |value| if !metadata[group][key].has_key?(value) metadata[group][key][value] = [] end metadata[group][key][value] << doc_data["document_xmlid"] end end end end end File.delete(file) end # save all data to configuration files logger.info "Writing metadata coverage to configuration files" # File.open(coverage_config, 'w') { |f| YAML.dump({ "coverage" => metadata }, f) } threads = [] metadata.each do |group, keys| threads << Thread.new do keys.each do |key, values| key_file = metadata_dir+'/'+group+'.'+key+'.yml' if !File.exists?(key_file) File.open(key_file, 'w', external_encoding: 'ASCII-8BIT') { |f| YAML.dump({ "values" => metadata[group][key] }, f) } end end end end threads.each(&:join) end logger.info "Loading metadata" metadata = {} Dir[metadata_dir+'/*.yml'].each do |file| if !file.end_with?('documents.yml') base = file.sub(metadata_dir+'/','').sub('.yml','') group = base.split('.')[0] key = base.split('.')[1] if !metadata.has_key?(group) metadata[group] = {} end metadata[group][key] = YAML.load_file(file)["values"] end end ::DOCUMENT_METADATA = metadata logger.info "Finished loading metadata"
# frozen_string_literal: true SecureHeaders::Configuration.default do |config| config.cookies = { secure: true, httponly: true, samesite: { strict: true } } config.referrer_policy = 'origin-when-cross-origin' config.csp = SecureHeaders::OPT_OUT end :pill: Fix a bug that user cannot remote follow # frozen_string_literal: true SecureHeaders::Configuration.default do |config| config.cookies = { secure: true, httponly: true, samesite: { lax: true } } config.referrer_policy = 'origin-when-cross-origin' config.csp = SecureHeaders::OPT_OUT end
# Options: # # All are optional. Defaults are configured in the incoming Slack webhook. # # channel: Name of the channel to notify. # username: The name as shown in the message. # emoji: The avatar as shown in the message. # # Usage: # # slack.register 'sevenscale', 'b8d9b31...', :channel => 'Ops' # :username => 'Robot' # :emoji => ':godmode:' # namespace :slack do set(:previous_current_revision) { raise "Previous current revision was never fetched" } def register(domain, token, config = {}) require 'net/http' short_domain = domain[/^([^\.]+)/, 1] default_payload = {} default_payload['channel'] = config[:channel] if config[:channel] default_payload['username'] = config[:username] if config[:username] default_payload['icon_emoji'] = config[:emoji] if config[:emoji] speak = lambda do |message| payload = default_payload.merge('text' => message) uri = URI.parse("https://#{domain}.slack.com/services/hooks/incoming-webhook?token=#{token}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data(:payload => payload.to_json) http.request request end notify_error = lambda do if ex = $! message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end if ::Interrupt === ex message << " was canceled." else message << " failed with exception #{ex.class}: " if ex.message.to_s.length > 200 message << ex.message.to_s[0..200] << "..." else message << ex.message.to_s end end speak.call message end end namespace short_domain do before 'deploy', "slack:#{short_domain}:notify_start" before 'deploy:migrations', "slack:#{short_domain}:notify_start" after 'deploy', "slack:#{short_domain}:notify_finished" after 'deploy:migrations', "slack:#{short_domain}:notify_finished" task :notify_start do deployer = ENV['USER'] deployed = current_revision.to_s[0..7] deploying = real_revision.to_s[0..7] github_repo = repository[/github.com:(.*)\.git$/, 1] compare_url = "http://github.com/#{github_repo}/compare/#{deployed}...#{deploying}" message = "[CAP] %s is deploying (%s..%s) of %s" % [ ENV['USER'], deployed, deploying, fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " with `cap #{ARGV.join(' ')}` (#{compare_url})" speak.call message # Make sure we say something if there's an error at_exit &notify_error end task :notify_finished do debug_message = "sending message on #{short_domain} Slack" debug_message << " to #{room}" if room logger.debug debug_message message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " is done." speak.call message end end end task :save_previous_current_revision do set(:previous_current_revision, (capture("cat #{current_path}/REVISION").chomp rescue nil)) end end # Originally lifted from: # http://github.com/vigetlabs/viget_deployment/tree/master/recipes/campfire.rb # # Usage: # # campfire.register 'sevenscale', 'b8d9b31...', :room => 'crazypants', :ssl => true # namespace :campfire do set(:previous_current_revision) { raise "Previous current revision was never fetched" } # before 'deploy', 'campfire:save_previous_current_revision' # before 'deploy:rollback:revision', 'campfire:save_previous_current_revision' def register(domain, token, config = {}) begin require 'uri' require 'tinder' rescue LoadError return false # skip campfire stuff if tinder can't be required end short_domain = domain[/^([^\.]+)/, 1] speak = lambda do |message| campfire = Tinder::Campfire.new(domain, :ssl => config[:ssl], :token => token) room = campfire.find_room_by_name(config[:room]) rescue nil if room room.speak message end end notify_error = lambda do if ex = $! message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end if ::Interrupt === ex message << " was canceled." else message << " failed with exception #{ex.class}: " if ex.message.to_s.length > 200 message << ex.message.to_s[0..200] << "..." else message << ex.message.to_s end end speak.call message end end namespace short_domain do before 'deploy', "campfire:#{short_domain}:notify_start" before 'deploy:migrations', "campfire:#{short_domain}:notify_start" after 'deploy', "campfire:#{short_domain}:notify_finished" after 'deploy:migrations', "campfire:#{short_domain}:notify_finished" task :notify_start do deployer = ENV['USER'] deployed = current_revision.to_s[0..7] deploying = real_revision.to_s[0..7] github_repo = repository[/github.com:(.*)\.git$/, 1] compare_url = "http://github.com/#{github_repo}/compare/#{deployed}...#{deploying}" message = "[CAP] %s is deploying (%s..%s) of %s" % [ ENV['USER'], deployed, deploying, fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " with `cap #{ARGV.join(' ')}` (#{compare_url})" speak.call message # Make sure we say something if there's an error at_exit &notify_error end task :notify_finished do logger.debug "sending message to #{config[:room]} on #{short_domain} Campfire" message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " is done." speak.call message end end end task :save_previous_current_revision do set(:previous_current_revision, (capture("cat #{current_path}/REVISION").chomp rescue nil)) end end Fix nonexistent variable # Options: # # All are optional. Defaults are configured in the incoming Slack webhook. # # channel: Name of the channel to notify. # username: The name as shown in the message. # emoji: The avatar as shown in the message. # # Usage: # # slack.register 'sevenscale', 'b8d9b31...', :channel => 'Ops' # :username => 'Robot' # :emoji => ':godmode:' # namespace :slack do set(:previous_current_revision) { raise "Previous current revision was never fetched" } def register(domain, token, config = {}) require 'net/http' short_domain = domain[/^([^\.]+)/, 1] default_payload = {} default_payload['channel'] = config[:channel] if config[:channel] default_payload['username'] = config[:username] if config[:username] default_payload['icon_emoji'] = config[:emoji] if config[:emoji] speak = lambda do |message| payload = default_payload.merge('text' => message) uri = URI.parse("https://#{domain}.slack.com/services/hooks/incoming-webhook?token=#{token}") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) request.set_form_data(:payload => payload.to_json) http.request request end notify_error = lambda do if ex = $! message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end if ::Interrupt === ex message << " was canceled." else message << " failed with exception #{ex.class}: " if ex.message.to_s.length > 200 message << ex.message.to_s[0..200] << "..." else message << ex.message.to_s end end speak.call message end end namespace short_domain do before 'deploy', "slack:#{short_domain}:notify_start" before 'deploy:migrations', "slack:#{short_domain}:notify_start" after 'deploy', "slack:#{short_domain}:notify_finished" after 'deploy:migrations', "slack:#{short_domain}:notify_finished" task :notify_start do deployer = ENV['USER'] deployed = current_revision.to_s[0..7] deploying = real_revision.to_s[0..7] github_repo = repository[/github.com:(.*)\.git$/, 1] compare_url = "http://github.com/#{github_repo}/compare/#{deployed}...#{deploying}" message = "[CAP] %s is deploying (%s..%s) of %s" % [ ENV['USER'], deployed, deploying, fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " with `cap #{ARGV.join(' ')}` (#{compare_url})" speak.call message # Make sure we say something if there's an error at_exit &notify_error end task :notify_finished do debug_message = "sending message on #{short_domain} Slack" debug_message << " to #{config[:channel]}" if config[:channel] logger.debug debug_message message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " is done." speak.call message end end end task :save_previous_current_revision do set(:previous_current_revision, (capture("cat #{current_path}/REVISION").chomp rescue nil)) end end # Originally lifted from: # http://github.com/vigetlabs/viget_deployment/tree/master/recipes/campfire.rb # # Usage: # # campfire.register 'sevenscale', 'b8d9b31...', :room => 'crazypants', :ssl => true # namespace :campfire do set(:previous_current_revision) { raise "Previous current revision was never fetched" } # before 'deploy', 'campfire:save_previous_current_revision' # before 'deploy:rollback:revision', 'campfire:save_previous_current_revision' def register(domain, token, config = {}) begin require 'uri' require 'tinder' rescue LoadError return false # skip campfire stuff if tinder can't be required end short_domain = domain[/^([^\.]+)/, 1] speak = lambda do |message| campfire = Tinder::Campfire.new(domain, :ssl => config[:ssl], :token => token) room = campfire.find_room_by_name(config[:room]) rescue nil if room room.speak message end end notify_error = lambda do if ex = $! message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end if ::Interrupt === ex message << " was canceled." else message << " failed with exception #{ex.class}: " if ex.message.to_s.length > 200 message << ex.message.to_s[0..200] << "..." else message << ex.message.to_s end end speak.call message end end namespace short_domain do before 'deploy', "campfire:#{short_domain}:notify_start" before 'deploy:migrations', "campfire:#{short_domain}:notify_start" after 'deploy', "campfire:#{short_domain}:notify_finished" after 'deploy:migrations', "campfire:#{short_domain}:notify_finished" task :notify_start do deployer = ENV['USER'] deployed = current_revision.to_s[0..7] deploying = real_revision.to_s[0..7] github_repo = repository[/github.com:(.*)\.git$/, 1] compare_url = "http://github.com/#{github_repo}/compare/#{deployed}...#{deploying}" message = "[CAP] %s is deploying (%s..%s) of %s" % [ ENV['USER'], deployed, deploying, fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " with `cap #{ARGV.join(' ')}` (#{compare_url})" speak.call message # Make sure we say something if there's an error at_exit &notify_error end task :notify_finished do logger.debug "sending message to #{config[:room]} on #{short_domain} Campfire" message = "[CAP] %s's deploy of %s" % [ ENV['USER'], fetch(:application), ] if stage = fetch(:rails_env, nil) message << " to #{stage}" end message << " is done." speak.call message end end end task :save_previous_current_revision do set(:previous_current_revision, (capture("cat #{current_path}/REVISION").chomp rescue nil)) end end
require_relative 'suby/downloader' module Suby extend self DEFAULT_OPTIONS = { lang: 'en' } SUB_EXTENSIONS = %w[srt sub] TEMP_ARCHIVE_NAME = '__archive__' def download_subtitles(files, options = {}) options = DEFAULT_OPTIONS.merge options files.each { |file| next if SUB_EXTENSIONS.include? File.extname(file) next puts "Skipping: #{file}" if SUB_EXTENSIONS.any? { |ext| File.exist? File.basename(file, File.extname(file)) + ".#{ext}" } begin Downloader.new(file, options[:lang]).download rescue puts " The download of the subtitles failed for #{file}:" puts " #{$!.inspect}" end } end def extract_subs_from_archive(archive) case `file #{archive}` when /Zip archive data/ subs = `unzip -qql #{archive}`.scan(/\d{2}:\d{2} (.+?(?:#{SUB_EXTENSIONS.join '|'}))$/).map(&:first) raise "no subtitles in #{archive}" if subs.empty? subs_for_unzip = subs.map { |sub| sub.gsub(/(\[|\])/) { "\\#{$1}" } } system 'unzip', archive, *subs_for_unzip, 1 => :close puts "found subtitles: #{subs.join(', ')}" else raise "unknown archive type (#{archive})" end # Cleaning File.unlink archive subs end end show full error message require_relative 'suby/downloader' module Suby extend self DEFAULT_OPTIONS = { lang: 'en' } SUB_EXTENSIONS = %w[srt sub] TEMP_ARCHIVE_NAME = '__archive__' def download_subtitles(files, options = {}) options = DEFAULT_OPTIONS.merge options files.each { |file| next if SUB_EXTENSIONS.include? File.extname(file) next puts "Skipping: #{file}" if SUB_EXTENSIONS.any? { |ext| File.exist? File.basename(file, File.extname(file)) + ".#{ext}" } begin Downloader.new(file, options[:lang]).download rescue puts " The download of the subtitles failed for #{file}:" puts " #{$!.class}: #{$!.message}" puts $!.backtrace.map { |line| line.prepend ' '*4 } end } end def extract_subs_from_archive(archive) case `file #{archive}` when /Zip archive data/ subs = `unzip -qql #{archive}`.scan(/\d{2}:\d{2} (.+?(?:#{SUB_EXTENSIONS.join '|'}))$/).map(&:first) raise "no subtitles in #{archive}" if subs.empty? subs_for_unzip = subs.map { |sub| sub.gsub(/(\[|\])/) { "\\#{$1}" } } system 'unzip', archive, *subs_for_unzip, 1 => :close puts "found subtitles: #{subs.join(', ')}" else raise "unknown archive type (#{archive})" end # Cleaning File.unlink archive subs end end
susy_stylesheets_path = File.expand_path(File.join(File.dirname(__FILE__), '..', 'sass')) begin require 'compass' Compass::Frameworks.register('susy', :stylesheets_directory => susy_stylesheets_path) rescue LoadError # compass not found, register on the Sass path via the environment. if ENV.has_key?("SASSPATH") ENV["SASSPATH"] = ENV["SASSPATH"] + File::PATH_SEPARATOR + susy_stylesheets_path else ENV["SASSPATH"] = susy_stylesheets_path end end Fixed SASS_PATH environment variable Make it compatible with sass and sass-rails gems. After changing the environment variables from SASSPATH to SASS_PATH, Susy 2 worked flawlessly on Rails 4 and Sinatra applications, without the compass dependency. susy_stylesheets_path = File.expand_path(File.join(File.dirname(__FILE__), '..', 'sass')) begin require 'compass' Compass::Frameworks.register('susy', :stylesheets_directory => susy_stylesheets_path) rescue LoadError # compass not found, register on the Sass path via the environment. if ENV.has_key?("SASS_PATH") ENV["SASS_PATH"] = ENV["SASS_PATH"] + File::PATH_SEPARATOR + susy_stylesheets_path else ENV["SASS_PATH"] = susy_stylesheets_path end end
#!/usr/bin/env ruby require 'rubygems' require 'net/ssh' require 'net/sftp' # # These want to be an input parameters: # host = 'repo.teacloud.net' user = 'circle' password = 'circle' keypath = '../assets/circle.key' File.open(File.dirname(__FILE__) + '/' + keypath, 'r') do |file| rsa_key = [file.read] Net::SSH.start(host, user, password: 'circle') do |ssh| # TODO: Enable SSH when key will work on circle@repo.tecloud.net # Net::SSH.start( host, user, :key_data => rsa_key, :keys_only => true) do |ssh| ssh.sftp.connect do |sftp| # upload a file or directory to the remote host sftp.upload!('~/test.data', '/home/circle/repo/test.data') result = ssh.exec!('ls') UI.message(result) remote = '/home/' + user + '/repo/test.data' local = '/Users/sychram/test.data.from-remote' # download a file or directory from the remote host sftp.download!(remote, local) # grab data off the remote host directly to a buffer data = sftp.download!(remote) # open and write to a pseudo-IO for a remote file sftp.file.open(remote, 'w') do |f| UI.message("opened file from sftp") end # open and read from a pseudo-IO for a remote file sftp.file.open(remote, 'r') do |f| puts f.gets end directory = '/home/' + user + '/ruby-test' # safely make a directory begin sftp.mkdir directory rescue Net::SFTP::StatusException => e # verify if this returns 11. Your server may return # something different like 4. if e.code == 11 puts 'directory already exists. Carry on...' sftp.rmdir!('/home/' + user + '/ruby-test') else raise end end # list the entries in a directory sftp.dir.foreach('.') do |entry| puts entry.longname end end end end propery way of dealing with class properties, refactoring test class to become uploader #!/usr/bin/env ruby require 'rubygems' require 'net/ssh' require 'net/sftp' require 'fastlane' require 'fastlane_core' require_relative 'apprepo/options' module AppRepo class Test attr_accessor :options # # These want to be an input parameters: # attr_accessor :host attr_accessor :user attr_accessor :password attr_accessor :rsa_keypath attr_accessor :ipa_path attr_accessor :manifest_path attr_accessor :appcode def initialize Fastlane::UI.message('[AppRepo:Test] Initializing...') self.host = 'repo.teacloud.net' self.user = 'circle' self.password = 'circle' self.rsa_keypath = '../assets/circle.key' self.ipa_path = '../sampleapp.ipa' self.manifest_path = '../assets/manifest.json' self.appcode = 'APPREPO' #self.options = options #AppRepo::Test.new.run! #FastlaneCore::PrintTable.print_values(config: nil , hide_keys: [:app], mask_keys: ['app_review_information.demo_password'], title: "deliver #{AppRepo::VERSION} Summary") # options end # upload an ipa and manifest file or directory to the remote host def ssh_sftp_upload(ssh, ipa_path, manifest_path) ssh.sftp.connect do |sftp| begin sftp.mkdir remote_path rescue Net::SFTP::StatusException => e if e.code == 11 Fastlane::UI.message('Remote directory' + remote_path + ' already exists. OK...') else raise end end ipa_remote = remote_ipa_path(ipa_path) Fastlane::UI.message("Uploading IPA: "+ipa_remote) sftp.upload!(ipa_path, ipa_remote) sftp.upload!(manifest_path, remote_path + 'manifest.json') result = ssh.exec!('ls') Fastlane::UI.message(result) end end def load_rsa_key(rsa_keypath) File.open(File.dirname(__FILE__) + '/' + rsa_keypath, 'r') do |file| rsa_key = [file.read] return rsa_key end end def remote_ipa_path(ipa_path) path = remote_path + appcode + '/' + File.basename(ipa_path) Fastlane::UI.message("remote_ipa_path: " + path) return path end def remote_path path = '/home/' + user + '/repo/apps/' Fastlane::UI.message("remote_ipa: " + path) return path end # open and write to a pseudo-IO for a remote file #sftp.file.open(remote, 'w') do |f| # UI.message("opened file from sftp") #end # list the entries in a directory #sftp.dir.foreach('.') do |entry| # puts entry.longname #end def run # Login & Upload IPA with metadata using RSA key or username/password rsa_key = load_rsa_key(self.rsa_keypath) if rsa_key != nil Fastlane::UI.message("Logging in with RSA key " + rsa_keypath) Net::SSH.start( host, user, :key_data => rsa_key, :keys_only => true) do |ssh| ssh_sftp_upload(ssh, ipa_path, manifest_path) end else # Login with Fastlane::UI.message("Logging in with username " + username + " and password *****...") Net::SSH.start(host, user, password: password) do |ssh| ssh_sftp_upload(ssh, ipa_path, manifest_path) end end end # test Test.new.run end # class end # module
require_relative '../../spec_helper' require_relative 'fixtures/common' # TODO: WTF is this using a global? describe "YAML.dump" do after :each do rm_r $test_file end it "converts an object to YAML and write result to io when io provided" do File.open($test_file, 'w' ) do |io| YAML.dump( ['badger', 'elephant', 'tiger'], io ) end YAML.load_file($test_file).should == ['badger', 'elephant', 'tiger'] end it "returns a string containing dumped YAML when no io provided" do YAML.dump( :locked ).should match_yaml("--- :locked\n") end it "returns the same string that #to_yaml on objects" do ["a", "b", "c"].to_yaml.should == YAML.dump(["a", "b", "c"]) end it "dumps strings into YAML strings" do YAML.dump("str").should match_yaml("--- str\n") end it "dumps hashes into YAML key-values" do YAML.dump({ "a" => "b" }).should match_yaml("--- \na: b\n") end it "dumps Arrays into YAML collection" do YAML.dump(["a", "b", "c"]).should match_yaml("--- \n- a\n- b\n- c\n") end it "dumps an OpenStruct" do require "ostruct" os = OpenStruct.new("age" => 20, "name" => "John") os2 = YAML.load(YAML.dump(os)) os2.age.should == 20 os2.name.should == "John" end it "dumps a File without any state" do file = File.new(__FILE__) begin YAML.dump(file).should match_yaml("--- !ruby/object:File {}\n") ensure file.close end end end Adjust spec for ostruct 0.3.0 behavior ostruct 0.3.0 no longer marshals the "table" key into YAML and instead just marshals the actual key/value attributes it contains. This addresses the remaining failure in #6426. require_relative '../../spec_helper' require_relative 'fixtures/common' # TODO: WTF is this using a global? describe "YAML.dump" do after :each do rm_r $test_file end it "converts an object to YAML and write result to io when io provided" do File.open($test_file, 'w' ) do |io| YAML.dump( ['badger', 'elephant', 'tiger'], io ) end YAML.load_file($test_file).should == ['badger', 'elephant', 'tiger'] end it "returns a string containing dumped YAML when no io provided" do YAML.dump( :locked ).should match_yaml("--- :locked\n") end it "returns the same string that #to_yaml on objects" do ["a", "b", "c"].to_yaml.should == YAML.dump(["a", "b", "c"]) end it "dumps strings into YAML strings" do YAML.dump("str").should match_yaml("--- str\n") end it "dumps hashes into YAML key-values" do YAML.dump({ "a" => "b" }).should match_yaml("--- \na: b\n") end it "dumps Arrays into YAML collection" do YAML.dump(["a", "b", "c"]).should match_yaml("--- \n- a\n- b\n- c\n") end it "dumps an OpenStruct" do require "ostruct" os = OpenStruct.new("age" => 20, "name" => "John") yaml_dump = YAML.dump(os) if OpenStruct::VERSION.split('.').map(&:to_i).<=>([0,3,0]) >= 0 expected = "--- !ruby/object:OpenStruct\nage: 20\nname: John\n" else expected = "--- !ruby/object:OpenStruct\ntable:\n :age: 20\n :name: John\n" end yaml_dump.should match_yaml(expected) end it "dumps a File without any state" do file = File.new(__FILE__) begin YAML.dump(file).should match_yaml("--- !ruby/object:File {}\n") ensure file.close end end end
# -*- encoding : utf-8 -*- require_relative 'Persistence' require_relative '../LogBatalha' require_relative '../Usuario' class DAOLogBatalha include Persistence # Cadastra usuario na tabela usuarios # @param [LogBatalha] log_batalha def create log_batalha vencedor_username = log_batalha.vencedor.username turnos = log_batalha.turnos id = gerador_de_id CONNECTION.exec( "INSERT INTO batalhas (id,turnos, vencedor) values (#{id}, #{turnos}, '#{vencedor_username}')" ) end # Procura usuario na tabela usuarios # @param [Usuario] usuario # @return [LogBatalha[]] batalhas def read_batalhas_vencidas_por usuario username = usuario.username query_batalhas = CONNECTION.exec( "SELECT * FROM batalhas where vencedor = '#{username}'" ) batalhas = [] query_batalhas.each do |resultado_tabela_batalhas| jogadores = [] query_username_jogadores = CONNECTION.exec( "SELECT username FROM batalha_usuarios where batalha_id = #{resultado_tabela_batalhas['id']}" ) query_username_jogadores.each do |resultado_tabela_batalha_usuarios| query_password = CONNECTION.exec( "SELECT password FROM usuarios where username = '#{resultado_tabela_batalha_usuarios['username']}' " ) query_password do |resultado_tabela_usuarios| jogadores.push (Usuario.new resultado_tabela_batalha_usuarios['username'], resultado_tabela_usuarios['password']) end query_password.clear end batalha = LogBatalha.new batalha.jogadores = jogadores batalha.turnos = resultado_tabela_batalhas["turnos"].to_i batalha.vencedor = usuario batalhas.push batalha query_username_jogadores.clear end query_batalhas.clear return batalhas end private # @return [Fixnum] id def gerador_de_id id = 0 result = CONNECTION.exec( "SELECT max(id) FROM batalhas" ) result.each do |row| id = row['max'].to_i end result.clear return (id + 1) end end Agora insere em batalha_usuarios # -*- encoding : utf-8 -*- require_relative 'Persistence' require_relative '../LogBatalha' require_relative '../Usuario' class DAOLogBatalha include Persistence # Cadastra usuario na tabela usuarios # @param [LogBatalha] log_batalha def create log_batalha vencedor_username = log_batalha.vencedor.username turnos = log_batalha.turnos id = gerador_de_id jogadores = log_batalha.jogadores # Preenche tabela batalhas CONNECTION.exec( "INSERT INTO batalhas (id,turnos, vencedor) values (#{id}, #{turnos}, '#{vencedor_username}')" ) # Preenche tabela batalha_usuarios (dependência de id com batalhas) jogadores.each do |usuario| username = usuario.username CONNECTION.exec( "INSERT INTO batalha_usuarios (username, batalha_id) values ('#{username}', #{id})") end end # Procura usuario na tabela usuarios # @param [Usuario] usuario # @return [LogBatalha[]] batalhas def read_batalhas_vencidas_por usuario username = usuario.username # Busca todas batalhas em que o vencedor foi o usuario passado como parâmetro query_batalhas = CONNECTION.exec( "SELECT * FROM batalhas where vencedor = '#{username}'" ) batalhas = [] query_batalhas.each do |resultado_tabela_batalhas| jogadores = [] # Busca username (Usuario) na tabela batalha_usuarios com o id da batalha query_username_jogadores = CONNECTION.exec( "SELECT username FROM batalha_usuarios where batalha_id = #{resultado_tabela_batalhas['id']}" ) query_username_jogadores.each do |resultado_tabela_batalha_usuarios| # Busca password (Usuario) da tabela usuarios query_password = CONNECTION.exec( "SELECT password FROM usuarios where username = '#{resultado_tabela_batalha_usuarios['username']}' " ) query_password.each do |resultado_tabela_usuarios| jogadores.push (Usuario.new resultado_tabela_batalha_usuarios['username'], resultado_tabela_usuarios['password'],resultado_tabela_usuarios['password']) end query_password.clear end batalha = LogBatalha.new batalha.jogadores = jogadores batalha.turnos = resultado_tabela_batalhas["turnos"].to_i batalha.vencedor = usuario batalhas.push batalha query_username_jogadores.clear end query_batalhas.clear return batalhas end private # Gera um ID (Primary Key) válido # @return [Fixnum] id def gerador_de_id id = 0 result = CONNECTION.exec( "SELECT max(id) FROM batalhas" ) result.each do |row| id = row['max'].to_i end result.clear return (id + 1) end end
Add Ohai plugin that collects iptables rules present on a server # Encoding: utf-8 # A plugin to discover IPTables rules configured on a server Ohai.plugin(:Iptables) do provides 'iptables' collect_data(:linux) do iptables Mash.new # Creating a mash of present IPTables rules so = shell_out("sudo iptables -S") so.stdout.each_line.with_index do |line, i| iptables[i] = line.strip end end end
#-- # Copyright (C) 2010 Tero Hänninen <tero.j.hanninen@jyu.fi> # Copyright (C) 2008 Johan Sørensen <johan@johansorensen.com> # Copyright (C) 2009 Marius Mårnes Mathiesen <marius.mathiesen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ require 'rubygems' require 'stomp' require 'json' require 'yaml' print "=> Syncing Gitorious... " class Publisher def connect stomp_server, stomp_port = stomp_server_and_port @connection = Stomp::Connection.open(nil, nil, stomp_server, stomp_port, true) @connected = true end def stomp_server_and_port gitorious_yaml = YAML::load_file(File.join(File.dirname(__FILE__), "..", "..", "config", "gitorious.yml"))[ENV['RAILS_ENV']] server = gitorious_yaml['stomp_server_address'] || 'localhost' host = (gitorious_yaml['stomp_server_port'] || '61613').to_i return [server, host] end def post_message(message) connect unless @connected @connection.send '/queue/GitoriousPushEvent', message, {'persistent' => true} end end Ensure RAILS_ENV is defined correctly in production env in messaging.rb Signed-off-by: Tero Hänninen <489b9d99f2a19a229b28084593ca5b61b1080f65@jyu.fi> #-- # Copyright (C) 2010 Tero Hänninen <tero.j.hanninen@jyu.fi> # Copyright (C) 2008 Johan Sørensen <johan@johansorensen.com> # Copyright (C) 2009 Marius Mårnes Mathiesen <marius.mathiesen@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #++ require 'rubygems' require 'stomp' require 'json' require 'yaml' print "=> Syncing Gitorious... " RAILS_ENV = ENV['RAILS_ENV'] || "production" class Publisher def connect stomp_server, stomp_port = stomp_server_and_port @connection = Stomp::Connection.open(nil, nil, stomp_server, stomp_port, true) @connected = true end def stomp_server_and_port gitorious_yaml = YAML::load_file(File.join(File.dirname(__FILE__), "..", "..", "config", "gitorious.yml"))[RAILS_ENV] server = gitorious_yaml['stomp_server_address'] || 'localhost' host = (gitorious_yaml['stomp_server_port'] || '61613').to_i return [server, host] end def post_message(message) connect unless @connected @connection.send '/queue/GitoriousPushEvent', message, {'persistent' => true} end end
module Tidy class << self PATH = Rails.root.join('node_modules','htmltidy2','bin',Gem::Platform.local.os,'tidy') CONFIG = {force_output: true, quiet: true, show_errors: 0, show_warnings: false, show_info: false, enclose_text: true, drop_empty_elements: true, hide_comments: true, tidy_mark: false} def exec html IO.popen("#{PATH} #{flags}", 'r+') do |io| io.write(html) io.close_write io.read end end private def flags CONFIG.map { |k, v| "--#{k.to_s.gsub('_', '-')} #{v === true ? 'yes' : v === false ? 'no' : v}" }.join(' ') end end end Add arch to tidy path module Tidy class << self PLATFORM = Gem::Platform.local.os + (Gem::Platform.local.os != 'darwin' ? Gem::Platform.local.cpu[-2..-1] : '') PATH = Rails.root.join('node_modules','htmltidy2','bin',PLATFORM,'tidy') CONFIG = {force_output: true, quiet: true, show_errors: 0, show_warnings: false, show_info: false, enclose_text: true, drop_empty_elements: true, hide_comments: true, tidy_mark: false} def exec html IO.popen("#{PATH} #{flags}", 'r+') do |io| io.write(html) io.close_write io.read end end private def flags CONFIG.map { |k, v| "--#{k.to_s.gsub('_', '-')} #{v === true ? 'yes' : v === false ? 'no' : v}" }.join(' ') end end end
require 'yaml' require 'time' require 'erb' require 'rack' require 'digest' require 'open-uri' require 'rdiscount' require 'builder' $:.unshift File.dirname(__FILE__) require 'ext/ext' module Toto Paths = { :templates => "templates", :pages => "templates/pages", :articles => "articles" } def self.env ENV['RACK_ENV'] || 'production' end def self.env= env ENV['RACK_ENV'] = env end module Template def to_html page, config, &blk path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages]) if config[:to_html].respond_to? :call config[:to_html].call(path, page, binding) else self.parse(path, page, binding) end end def parse path, page, ctx ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx || binding) end def markdown text if (options = @config[:markdown]) Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html else text.strip end end def method_missing m, *args, &blk self.keys.include?(m) ? self[m] : super end def self.included obj obj.class_eval do define_method(obj.to_s.split('::').last.downcase) { self } end end end class Site def initialize config @config = config end def [] *args @config[*args] end def []= key, value @config.set key, value end def index type = :html case type when :html {:articles => self.articles.reverse.map do |article| Article.new article, @config end }.merge archives when :xml, :json return :articles => self.articles.map do |article| Article.new article, @config end else return {} end end def archives filter = "" entries = ! self.articles.empty?? self.articles.select do |a| filter !~ /^\d{4}/ || File.basename(a) =~ /^#{filter}/ end.reverse.map do |article| Article.new article, @config end : [] return :archives => Archives.new(entries, @config) end def article route Article.new("#{Paths[:articles]}/#{route.join('-')}.#{self[:ext]}", @config).load end def / self[:root] end def go route, type = :html route << self./ if route.empty? type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/') context = lambda do |data, page| Context.new(data, @config, path).render(page, type) end body, status = if Context.new.respond_to?(:"to_#{type}") if route.first =~ /\d{4}/ case route.size when 1..3 context[archives(route * '-'), :archives] when 4 context[article(route), :article] else http 400 end elsif respond_to?(path) context[send(path, type), path.to_sym] elsif (repo = @config[:github][:repos].grep(/#{path}/).first) && !@config[:github][:user].empty? context[Repo.new(repo, @config), :repo] else context[{}, path.to_sym] end else http 400 end rescue Errno::ENOENT => e return :body => http(404).first, :type => :html, :status => 404 else return :body => body || "", :type => type, :status => status || 200 end protected def http code return ["<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>", code] end def articles self.class.articles self[:ext] end def self.articles ext Dir["#{Paths[:articles]}/*.#{ext}"] end class Context include Template def initialize ctx = {}, config = {}, path = "/" @config, @context, @path = config, ctx, path @articles = Site.articles(@config[:ext]).reverse.map do |a| Article.new(a, @config) end ctx.each do |k, v| meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) } end end def title @config[:title] end def render page, type type == :html ? to_html(:layout, @config, &Proc.new { to_html page, @config }) : send(:"to_#{type}", :feed) end def to_xml page xml = Builder::XmlMarkup.new(:indent => 2) instance_eval File.read("#{Paths[:templates]}/#{page}.builder") end alias :to_atom to_xml def method_missing m, *args, &blk @context.respond_to?(m) ? @context.send(m) : super end end end class Repo < Hash include Template README = "http://github.com/%s/%s/raw/master/README.%s" def initialize name, config self[:name], @config = name, config end def readme markdown open(README % [@config[:github][:user], self[:name], @config[:github][:ext]]).read rescue Timeout::Error, OpenURI::HTTPError => e "This page isn't available." end alias :content readme end class Archives < Array include Template def initialize articles, config self.replace articles @config = config end def [] a a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super end def to_html super(:archives, @config) end alias :to_s to_html alias :archive archives end class Article < Hash include Template def initialize obj, config = {} @obj, @config = obj, config self.load if obj.is_a? Hash end def load data = if @obj.is_a? String meta, self[:body] = File.read(@obj).split(/\n\n/, 2) YAML.load(meta) elsif @obj.is_a? Hash @obj end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) } self.taint self.update data self[:date] = Time.parse(self[:date].gsub('/', '-')) rescue Time.now self end def [] key self.load unless self.tainted? super end def slug self[:slug] || self[:title].slugize end def summary length = nil config = @config[:summary] sum = if self[:body] =~ config[:delim] self[:body].split(config[:delim]).first else self[:body].match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s end markdown(sum.length == self[:body].length ? sum : sum.strip.sub(/\.\Z/, '&hellip;')) end def url "http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}" end alias :permalink url def body markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body] end def title() self[:title] || "an article" end def date() @config[:date].call(self[:date]) end def path() self[:date].strftime("/%Y/%m/%d/#{slug}/") end def author() self[:author] || @config[:author] end def to_html() self.load; super(:article, @config) end alias :to_s to_html end class Config < Hash Defaults = { :author => ENV['USER'], # blog author :title => Dir.pwd.split('/').last, # site title :root => "index", # site index :url => "http://127.0.0.1", :date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function :markdown => :smart, # use markdown :disqus => false, # disqus name :summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter :ext => 'txt', # extension for articles :cache => 28800, # cache duration (seconds) :github => {:user => "", :repos => [], :ext => 'md'}# Github username and list of repos } def initialize obj self.update Defaults self.update obj end def set key, val if val.is_a? Hash self[key].update val else self[key] = val end end end class Server attr_reader :config def initialize config = {}, &blk @config = config.is_a?(Config) ? config : Config.new(config) @config.instance_eval(&blk) if block_given? end def call env @request = Rack::Request.new env @response = Rack::Response.new return [400, {}, []] unless @request.get? path, mime = @request.path_info.split('.') route = (path || '/').split('/').reject {|i| i.empty? } response = Toto::Site.new(@config).go(route, *(mime ? mime : [])) @response.body = [response[:body]] @response['Content-Length'] = response[:body].length.to_s unless response[:body].empty? @response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}") # Set http cache headers @response['Cache-Control'] = if Toto.env == 'production' "public, max-age=#{@config[:cache]}" else "no-cache, must-revalidate" end @response['Etag'] = Digest::SHA1.hexdigest(response[:body]) @response.status = response[:status] @response.finish end end end use the default config to store the html renderer require 'yaml' require 'time' require 'erb' require 'rack' require 'digest' require 'open-uri' require 'rdiscount' require 'builder' $:.unshift File.dirname(__FILE__) require 'ext/ext' module Toto Paths = { :templates => "templates", :pages => "templates/pages", :articles => "articles" } def self.env ENV['RACK_ENV'] || 'production' end def self.env= env ENV['RACK_ENV'] = env end module Template def to_html page, config, &blk path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages]) config[:to_html].call(path, page, binding) end def markdown text if (options = @config[:markdown]) Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html else text.strip end end def method_missing m, *args, &blk self.keys.include?(m) ? self[m] : super end def self.included obj obj.class_eval do define_method(obj.to_s.split('::').last.downcase) { self } end end end class Site def initialize config @config = config end def [] *args @config[*args] end def []= key, value @config.set key, value end def index type = :html case type when :html {:articles => self.articles.reverse.map do |article| Article.new article, @config end }.merge archives when :xml, :json return :articles => self.articles.map do |article| Article.new article, @config end else return {} end end def archives filter = "" entries = ! self.articles.empty?? self.articles.select do |a| filter !~ /^\d{4}/ || File.basename(a) =~ /^#{filter}/ end.reverse.map do |article| Article.new article, @config end : [] return :archives => Archives.new(entries, @config) end def article route Article.new("#{Paths[:articles]}/#{route.join('-')}.#{self[:ext]}", @config).load end def / self[:root] end def go route, type = :html route << self./ if route.empty? type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/') context = lambda do |data, page| Context.new(data, @config, path).render(page, type) end body, status = if Context.new.respond_to?(:"to_#{type}") if route.first =~ /\d{4}/ case route.size when 1..3 context[archives(route * '-'), :archives] when 4 context[article(route), :article] else http 400 end elsif respond_to?(path) context[send(path, type), path.to_sym] elsif (repo = @config[:github][:repos].grep(/#{path}/).first) && !@config[:github][:user].empty? context[Repo.new(repo, @config), :repo] else context[{}, path.to_sym] end else http 400 end rescue Errno::ENOENT => e return :body => http(404).first, :type => :html, :status => 404 else return :body => body || "", :type => type, :status => status || 200 end protected def http code return ["<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>", code] end def articles self.class.articles self[:ext] end def self.articles ext Dir["#{Paths[:articles]}/*.#{ext}"] end class Context include Template def initialize ctx = {}, config = {}, path = "/" @config, @context, @path = config, ctx, path @articles = Site.articles(@config[:ext]).reverse.map do |a| Article.new(a, @config) end ctx.each do |k, v| meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) } end end def title @config[:title] end def render page, type type == :html ? to_html(:layout, @config, &Proc.new { to_html page, @config }) : send(:"to_#{type}", :feed) end def to_xml page xml = Builder::XmlMarkup.new(:indent => 2) instance_eval File.read("#{Paths[:templates]}/#{page}.builder") end alias :to_atom to_xml def method_missing m, *args, &blk @context.respond_to?(m) ? @context.send(m) : super end end end class Repo < Hash include Template README = "http://github.com/%s/%s/raw/master/README.%s" def initialize name, config self[:name], @config = name, config end def readme markdown open(README % [@config[:github][:user], self[:name], @config[:github][:ext]]).read rescue Timeout::Error, OpenURI::HTTPError => e "This page isn't available." end alias :content readme end class Archives < Array include Template def initialize articles, config self.replace articles @config = config end def [] a a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super end def to_html super(:archives, @config) end alias :to_s to_html alias :archive archives end class Article < Hash include Template def initialize obj, config = {} @obj, @config = obj, config self.load if obj.is_a? Hash end def load data = if @obj.is_a? String meta, self[:body] = File.read(@obj).split(/\n\n/, 2) YAML.load(meta) elsif @obj.is_a? Hash @obj end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) } self.taint self.update data self[:date] = Time.parse(self[:date].gsub('/', '-')) rescue Time.now self end def [] key self.load unless self.tainted? super end def slug self[:slug] || self[:title].slugize end def summary length = nil config = @config[:summary] sum = if self[:body] =~ config[:delim] self[:body].split(config[:delim]).first else self[:body].match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s end markdown(sum.length == self[:body].length ? sum : sum.strip.sub(/\.\Z/, '&hellip;')) end def url "http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}" end alias :permalink url def body markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body] end def title() self[:title] || "an article" end def date() @config[:date].call(self[:date]) end def path() self[:date].strftime("/%Y/%m/%d/#{slug}/") end def author() self[:author] || @config[:author] end def to_html() self.load; super(:article, @config) end alias :to_s to_html end class Config < Hash Defaults = { :author => ENV['USER'], # blog author :title => Dir.pwd.split('/').last, # site title :root => "index", # site index :url => "http://127.0.0.1", :date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function :markdown => :smart, # use markdown :disqus => false, # disqus name :summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter :ext => 'txt', # extension for articles :cache => 28800, # cache duration (seconds) :github => {:user => "", :repos => [], :ext => 'md'},# Github username and list of repos :to_html => lambda {|path, page, ctx| # returns an html, from a path & context ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx) } } def initialize obj self.update Defaults self.update obj end def set key, val if val.is_a? Hash self[key].update val else self[key] = val end end end class Server attr_reader :config def initialize config = {}, &blk @config = config.is_a?(Config) ? config : Config.new(config) @config.instance_eval(&blk) if block_given? end def call env @request = Rack::Request.new env @response = Rack::Response.new return [400, {}, []] unless @request.get? path, mime = @request.path_info.split('.') route = (path || '/').split('/').reject {|i| i.empty? } response = Toto::Site.new(@config).go(route, *(mime ? mime : [])) @response.body = [response[:body]] @response['Content-Length'] = response[:body].length.to_s unless response[:body].empty? @response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}") # Set http cache headers @response['Cache-Control'] = if Toto.env == 'production' "public, max-age=#{@config[:cache]}" else "no-cache, must-revalidate" end @response['Etag'] = Digest::SHA1.hexdigest(response[:body]) @response.status = response[:status] @response.finish end end end
require 'yaml' require 'date' require 'erb' require 'rack' require 'digest' require 'open-uri' require 'rdiscount' require 'builder' require 'pp' $:.unshift File.dirname(__FILE__) require 'ext/ext' module Toto Paths = { :templates => "templates", :pages => "templates/pages", :articles => "articles" } def self.env ENV['RACK_ENV'] || 'production' end def self.env= env ENV['RACK_ENV'] = env end module Template def to_html page, config, &blk path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages]) config[:to_html].call(path, page, binding) end def markdown text if (options = @config[:markdown]) Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html else text.strip end end def method_missing m, *args, &blk self.keys.include?(m) ? self[m] : super end def self.included obj obj.class_eval do define_method(obj.to_s.split('::').last.downcase) { self } end end end class Site def initialize config @config = config end def [] *args @config[*args] end def []= key, value @config.set key, value end def index type = :html articles = type == :html ? self.articles.reverse : self.articles {:articles => articles.map do |article| Article.new article, @config end}.merge archives end def archives filter = "" entries = ! self.articles.empty?? self.articles.select do |a| filter !~ /^\d{4}/ || File.basename(a) =~ /^#{filter}/ end.reverse.map do |article| Article.new article, @config end : [] return :archives => Archives.new(entries, @config) end def article route Article.new("#{Paths[:articles]}/#{route.join('-')}.#{self[:ext]}", @config).load end def / self[:root] end def go route, type = :html route << self./ if route.empty? type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/') context = lambda do |data, page| Context.new(data, @config, path).render(page, type) end body, status = if Context.new.respond_to?(:"to_#{type}") if route.first =~ /\d{4}/ case route.size when 1..3 context[archives(route * '-'), :archives] when 4 context[article(route), :article] else http 400 end elsif respond_to?(path) context[send(path, type), path.to_sym] elsif (repo = @config[:github][:repos].grep(/#{path}/).first) && !@config[:github][:user].empty? context[Repo.new(repo, @config), :repo] else context[{}, path.to_sym] end else http 400 end rescue Errno::ENOENT => e return :body => http(404).first, :type => :html, :status => 404 else return :body => body || "", :type => type, :status => status || 200 end protected def http code return [@config[:error_page].call(code), code] end def articles self.class.articles self[:ext] end def self.articles ext Dir["#{Paths[:articles]}/*.#{ext}"].sort_by {|entry| File.basename(entry) } end class Context include Template def initialize ctx = {}, config = {}, path = "/" @config, @context, @path = config, ctx, path @articles = Site.articles(@config[:ext]).reverse.map do |a| Article.new(a, @config) end ctx.each do |k, v| meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) } end end def title @config[:title] end def render page, type content = to_html page, @config type == :html ? to_html(:layout, @config, &Proc.new { content }) : send(:"to_#{type}", page) end def to_xml page xml = Builder::XmlMarkup.new(:indent => 2) pp page instance_eval File.read("#{Paths[:templates]}/#{page}.builder") end alias :to_atom to_xml def method_missing m, *args, &blk @context.respond_to?(m) ? @context.send(m, *args, &blk) : super end end end class Repo < Hash include Template README = "http://github.com/%s/%s/raw/master/README.%s" def initialize name, config self[:name], @config = name, config end def readme markdown open(README % [@config[:github][:user], self[:name], @config[:github][:ext]]).read rescue Timeout::Error, OpenURI::HTTPError => e "This page isn't available." end alias :content readme end class Archives < Array include Template def initialize articles, config self.replace articles @config = config end def [] a a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super end def to_html super(:archives, @config) end alias :to_s to_html alias :archive archives end class Article < Hash include Template def initialize obj, config = {} @obj, @config = obj, config self.load if obj.is_a? Hash end def load data = if @obj.is_a? String meta, self[:body] = File.read(@obj).split(/\n\n/, 2) # use the date from the filename, or else toto won't find the article @obj =~ /\/(\d{4}-\d{2}-\d{2})[^\/]*$/ ($1 ? {:date => $1} : {}).merge(YAML.load(meta)) elsif @obj.is_a? Hash @obj end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) } self.taint self.update data self[:date] = Date.parse(self[:date].gsub('/', '-')) rescue Date.today self end def [] key self.load unless self.tainted? super end def slug self[:slug] || self[:title].slugize end def summary length = nil config = @config[:summary] sum = if self[:body] =~ config[:delim] self[:body].split(config[:delim]).first else self[:body].match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s end markdown(sum.length == self[:body].length ? sum : sum.strip.sub(/\.\Z/, '&hellip;')) end def url "http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}" end alias :permalink url def body markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body] end def title() self[:title] || "an article" end def date() @config[:date].call(self[:date]) end def path() self[:date].strftime("/%Y/%m/%d/#{slug}/") end def author() self[:author] || @config[:author] end def to_html() self.load; super(:article, @config) end alias :to_s to_html end class Config < Hash Defaults = { :author => ENV['USER'], # blog author :title => Dir.pwd.split('/').last, # site title :root => "index", # site index :url => "http://127.0.0.1", :date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function :markdown => :smart, # use markdown :disqus => false, # disqus name :summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter :ext => 'txt', # extension for articles :cache => 28800, # cache duration (seconds) :github => {:user => "", :repos => [], :ext => 'md'}, # Github username and list of repos :to_html => lambda {|path, page, ctx| # returns an html, from a path & context ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx) }, :error_page => lambda {|code| # The HTML for your error page "<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>" } } def initialize obj self.update Defaults self.update obj end def set key, val = nil, &blk if val.is_a? Hash self[key].update val else self[key] = block_given?? blk : val end end end class Server attr_reader :config def initialize config = {}, &blk @config = config.is_a?(Config) ? config : Config.new(config) @config.instance_eval(&blk) if block_given? end def call env @request = Rack::Request.new env @response = Rack::Response.new return [400, {}, []] unless @request.get? path, mime = @request.path_info.split('.') route = (path || '/').split('/').reject {|i| i.empty? } response = Toto::Site.new(@config).go(route, *(mime ? mime : [])) @response.body = [response[:body]] @response['Content-Length'] = response[:body].length.to_s unless response[:body].empty? @response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}") # Set http cache headers @response['Cache-Control'] = if Toto.env == 'production' "public, max-age=#{@config[:cache]}" else "no-cache, must-revalidate" end @response['Etag'] = Digest::SHA1.hexdigest(response[:body]) @response.status = response[:status] @response.finish end end end remove pp for real require 'yaml' require 'date' require 'erb' require 'rack' require 'digest' require 'open-uri' require 'rdiscount' require 'builder' $:.unshift File.dirname(__FILE__) require 'ext/ext' module Toto Paths = { :templates => "templates", :pages => "templates/pages", :articles => "articles" } def self.env ENV['RACK_ENV'] || 'production' end def self.env= env ENV['RACK_ENV'] = env end module Template def to_html page, config, &blk path = ([:layout, :repo].include?(page) ? Paths[:templates] : Paths[:pages]) config[:to_html].call(path, page, binding) end def markdown text if (options = @config[:markdown]) Markdown.new(text.to_s.strip, *(options.eql?(true) ? [] : options)).to_html else text.strip end end def method_missing m, *args, &blk self.keys.include?(m) ? self[m] : super end def self.included obj obj.class_eval do define_method(obj.to_s.split('::').last.downcase) { self } end end end class Site def initialize config @config = config end def [] *args @config[*args] end def []= key, value @config.set key, value end def index type = :html articles = type == :html ? self.articles.reverse : self.articles {:articles => articles.map do |article| Article.new article, @config end}.merge archives end def archives filter = "" entries = ! self.articles.empty?? self.articles.select do |a| filter !~ /^\d{4}/ || File.basename(a) =~ /^#{filter}/ end.reverse.map do |article| Article.new article, @config end : [] return :archives => Archives.new(entries, @config) end def article route Article.new("#{Paths[:articles]}/#{route.join('-')}.#{self[:ext]}", @config).load end def / self[:root] end def go route, type = :html route << self./ if route.empty? type, path = type =~ /html|xml|json/ ? type.to_sym : :html, route.join('/') context = lambda do |data, page| Context.new(data, @config, path).render(page, type) end body, status = if Context.new.respond_to?(:"to_#{type}") if route.first =~ /\d{4}/ case route.size when 1..3 context[archives(route * '-'), :archives] when 4 context[article(route), :article] else http 400 end elsif respond_to?(path) context[send(path, type), path.to_sym] elsif (repo = @config[:github][:repos].grep(/#{path}/).first) && !@config[:github][:user].empty? context[Repo.new(repo, @config), :repo] else context[{}, path.to_sym] end else http 400 end rescue Errno::ENOENT => e return :body => http(404).first, :type => :html, :status => 404 else return :body => body || "", :type => type, :status => status || 200 end protected def http code return [@config[:error_page].call(code), code] end def articles self.class.articles self[:ext] end def self.articles ext Dir["#{Paths[:articles]}/*.#{ext}"].sort_by {|entry| File.basename(entry) } end class Context include Template def initialize ctx = {}, config = {}, path = "/" @config, @context, @path = config, ctx, path @articles = Site.articles(@config[:ext]).reverse.map do |a| Article.new(a, @config) end ctx.each do |k, v| meta_def(k) { ctx.instance_of?(Hash) ? v : ctx.send(k) } end end def title @config[:title] end def render page, type content = to_html page, @config type == :html ? to_html(:layout, @config, &Proc.new { content }) : send(:"to_#{type}", page) end def to_xml page xml = Builder::XmlMarkup.new(:indent => 2) instance_eval File.read("#{Paths[:templates]}/#{page}.builder") end alias :to_atom to_xml def method_missing m, *args, &blk @context.respond_to?(m) ? @context.send(m, *args, &blk) : super end end end class Repo < Hash include Template README = "http://github.com/%s/%s/raw/master/README.%s" def initialize name, config self[:name], @config = name, config end def readme markdown open(README % [@config[:github][:user], self[:name], @config[:github][:ext]]).read rescue Timeout::Error, OpenURI::HTTPError => e "This page isn't available." end alias :content readme end class Archives < Array include Template def initialize articles, config self.replace articles @config = config end def [] a a.is_a?(Range) ? self.class.new(self.slice(a) || [], @config) : super end def to_html super(:archives, @config) end alias :to_s to_html alias :archive archives end class Article < Hash include Template def initialize obj, config = {} @obj, @config = obj, config self.load if obj.is_a? Hash end def load data = if @obj.is_a? String meta, self[:body] = File.read(@obj).split(/\n\n/, 2) # use the date from the filename, or else toto won't find the article @obj =~ /\/(\d{4}-\d{2}-\d{2})[^\/]*$/ ($1 ? {:date => $1} : {}).merge(YAML.load(meta)) elsif @obj.is_a? Hash @obj end.inject({}) {|h, (k,v)| h.merge(k.to_sym => v) } self.taint self.update data self[:date] = Date.parse(self[:date].gsub('/', '-')) rescue Date.today self end def [] key self.load unless self.tainted? super end def slug self[:slug] || self[:title].slugize end def summary length = nil config = @config[:summary] sum = if self[:body] =~ config[:delim] self[:body].split(config[:delim]).first else self[:body].match(/(.{1,#{length || config[:length] || config[:max]}}.*?)(\n|\Z)/m).to_s end markdown(sum.length == self[:body].length ? sum : sum.strip.sub(/\.\Z/, '&hellip;')) end def url "http://#{(@config[:url].sub("http://", '') + self.path).squeeze('/')}" end alias :permalink url def body markdown self[:body].sub(@config[:summary][:delim], '') rescue markdown self[:body] end def title() self[:title] || "an article" end def date() @config[:date].call(self[:date]) end def path() self[:date].strftime("/%Y/%m/%d/#{slug}/") end def author() self[:author] || @config[:author] end def to_html() self.load; super(:article, @config) end alias :to_s to_html end class Config < Hash Defaults = { :author => ENV['USER'], # blog author :title => Dir.pwd.split('/').last, # site title :root => "index", # site index :url => "http://127.0.0.1", :date => lambda {|now| now.strftime("%d/%m/%Y") }, # date function :markdown => :smart, # use markdown :disqus => false, # disqus name :summary => {:max => 150, :delim => /~\n/}, # length of summary and delimiter :ext => 'txt', # extension for articles :cache => 28800, # cache duration (seconds) :github => {:user => "", :repos => [], :ext => 'md'}, # Github username and list of repos :to_html => lambda {|path, page, ctx| # returns an html, from a path & context ERB.new(File.read("#{path}/#{page}.rhtml")).result(ctx) }, :error_page => lambda {|code| # The HTML for your error page "<font style='font-size:300%'>toto, we're not in Kansas anymore (#{code})</font>" } } def initialize obj self.update Defaults self.update obj end def set key, val = nil, &blk if val.is_a? Hash self[key].update val else self[key] = block_given?? blk : val end end end class Server attr_reader :config def initialize config = {}, &blk @config = config.is_a?(Config) ? config : Config.new(config) @config.instance_eval(&blk) if block_given? end def call env @request = Rack::Request.new env @response = Rack::Response.new return [400, {}, []] unless @request.get? path, mime = @request.path_info.split('.') route = (path || '/').split('/').reject {|i| i.empty? } response = Toto::Site.new(@config).go(route, *(mime ? mime : [])) @response.body = [response[:body]] @response['Content-Length'] = response[:body].length.to_s unless response[:body].empty? @response['Content-Type'] = Rack::Mime.mime_type(".#{response[:type]}") # Set http cache headers @response['Cache-Control'] = if Toto.env == 'production' "public, max-age=#{@config[:cache]}" else "no-cache, must-revalidate" end @response['Etag'] = Digest::SHA1.hexdigest(response[:body]) @response.status = response[:status] @response.finish end end end
Add utf8 module to lib. # <\ __ # \\ .~~ ~~. # \\ /|~| | # \\ /======\ | # //\\ |>/_\_<_=' | # ~\ \ `-`__ \\__| _ # <<\ \ \ ___ \..' `--' / ~-. # <<\\' )_) .+++++ _ (___.--'| _ /~-. ~-. # \_\' / x||||||| `-._ _.' /~-. ~-. `. # | | |X++++++| \ / /~-. ~-. ~-./ # | `. .|||||||| [] /~-. ~-. ~-./ # | |' ++++++| ::: [] : `-. ~-. ~-.' # | `. ' ::: []:: _.-:-. ~-/ | # (_ /| _. [] |____~|`-' | # ||`-'| |_.-' | |\\/|DREDD| `. # `.___.-' `. ||`' \~~~/ >. l # | :: || `-' / /`---'\ # | : || ( [(_)[_](] # | || | [ ] # .' || | \.---./ # __|________||_______|=.|____|_ # |: o | o |~\|%/~ o |_ o||-----| # |:--'|`-'||X\/X|`-'| `-|`. .-| # `--------' ll `-------' | |o| # | | `. |_| # | :: `. | | # | :: | | .' # | |\ :: | .' | # | || : | |. | # `. .'| : | ||..' # | | `. : | |'// # | | | : .' `=' # | | | :: | # `. | | :: | # | | | :: | # |_____ | .-------. # / _ `./.-- ::: \ # | | `----' || | # | | | || # \ \.-------./ # |-------||.-------.| # /-.____.|| | I A M T H E L A W # | || / # `. `:. / # | | | # `, | | # | | / # `. | | # | | | # | | | # __/ | < > \ # / / / \ # / :.___.|.-----.| \ # LS `----// \\ ___\ # / `---------' \ # _/ / # /__ |________\ # module Utf8 # Public: Says to hell with procedure and forces UTF8 Encoding! # # Returns a UTF8 encoded version of the string. def force_encoding(string) return unless string string.force_encoding('UTF-8') unless string.valid_encoding? string.encode!( 'UTF-8', 'Windows-1252' ) end return string rescue EncodingError # Force it to UTF-8, throwing out invalid bits string.encode!( 'UTF-8', invalid: :replace, undef: :replace ) end module_function :force_encoding end
require_relative 'piece' class ChessBoard attr_reader :board def initialize(board = nil) @board = board || { 'a8'=> Rook.new('black'), 'b8'=> Knight.new('black'), 'c8'=> Bishop.new('black'), 'd8'=> King.new('black'), 'e8'=> Queen.new('black'), 'f8'=> Bishop.new('black'), 'g8'=> Knight.new('black'), 'h8'=> Rook.new('black'), 'a7'=> Pawn.new('black'), 'b7'=> Pawn.new('black'), 'c7'=> Pawn.new('black'), 'd7'=> Pawn.new('black'), 'e7'=> Pawn.new('black'), 'f7'=> Pawn.new('black'), 'g7'=> Pawn.new('black'), 'h7'=> Pawn.new('black'), 'a6'=> " ", 'b6'=> " ", 'c6'=> " ", 'd6'=> " ", 'e6'=> " ", 'f6'=> " ", 'g6'=> " ", 'h6'=> " ", 'a5'=> " ", 'b5'=> " ", 'c5'=> " ", 'd5'=> " ", 'e5'=> " ", 'f5'=> " ", 'g5'=> " ", 'h5'=> " ", 'a4'=> " ", 'b4'=> " ", 'c4'=> " ", 'd4'=> " ", 'e4'=> " ", 'f4'=> " ", 'g4'=> " ", 'h4'=> " ", 'a3'=> " ", 'b3'=> " ", 'c3'=> " ", 'd3'=> " ", 'e3'=> " ", 'f3'=> " ", 'g3'=> " ", 'h3'=> " ", 'a2'=> Pawn.new('white'), 'b2'=> Pawn.new('white'), 'c2'=> Pawn.new('white'), 'd2'=> Pawn.new('white'), 'e2'=> Pawn.new('white'), 'f2'=> Pawn.new('white'), 'g2'=> Pawn.new('white'), 'h2'=> Pawn.new('white'), 'a1'=> Rook.new('white'), 'b1'=> Knight.new('white'), 'c1'=> Bishop.new('white'), 'd1'=> King.new('white'), 'e1'=> Queen.new('white'), 'f1'=> Bishop.new('white'), 'g1'=> Knight.new('white'), 'h1'=> Rook.new('white') } end def move_piece(source, destination, player_color) #checks before moving if valid_piece?(source, player_color) @board[source] = @board[destination] @board[source] = " " end end def valid_piece?(piece_location, player_color) return @board[piece_location].color == player_color if @board[piece_location] != " " end def to_s @board.values.each_slice(8).each_with_index { |row, index| puts row.unshift(8 - index).join(" ") } puts " a b c d e f g h" end #private def retrieve_column(col_num) column = Array.new @board.keys.select { |col| col[0] == col_num[0] }.each do |position| column << @board[position] end column end def retrieve_row(row_num) row = Array.new @board.keys.select { |col| col[1] == col_num[1] }.each do |position| column << @board[position] end row end # def generic_retrieve() # row_col = Array.new # end end add methods to retrieve column or row based on input position require_relative 'piece' class ChessBoard attr_reader :board def initialize(board = nil) @board = board || { 'a8'=> Rook.new('black'), 'b8'=> Knight.new('black'), 'c8'=> Bishop.new('black'), 'd8'=> King.new('black'), 'e8'=> Queen.new('black'), 'f8'=> Bishop.new('black'), 'g8'=> Knight.new('black'), 'h8'=> Rook.new('black'), 'a7'=> Pawn.new('black'), 'b7'=> Pawn.new('black'), 'c7'=> Pawn.new('black'), 'd7'=> Pawn.new('black'), 'e7'=> Pawn.new('black'), 'f7'=> Pawn.new('black'), 'g7'=> Pawn.new('black'), 'h7'=> Pawn.new('black'), 'a6'=> " ", 'b6'=> " ", 'c6'=> " ", 'd6'=> " ", 'e6'=> " ", 'f6'=> " ", 'g6'=> " ", 'h6'=> " ", 'a5'=> " ", 'b5'=> " ", 'c5'=> " ", 'd5'=> " ", 'e5'=> " ", 'f5'=> " ", 'g5'=> " ", 'h5'=> " ", 'a4'=> " ", 'b4'=> " ", 'c4'=> " ", 'd4'=> " ", 'e4'=> " ", 'f4'=> " ", 'g4'=> " ", 'h4'=> " ", 'a3'=> " ", 'b3'=> " ", 'c3'=> " ", 'd3'=> " ", 'e3'=> " ", 'f3'=> " ", 'g3'=> " ", 'h3'=> " ", 'a2'=> Pawn.new('white'), 'b2'=> Pawn.new('white'), 'c2'=> Pawn.new('white'), 'd2'=> Pawn.new('white'), 'e2'=> Pawn.new('white'), 'f2'=> Pawn.new('white'), 'g2'=> Pawn.new('white'), 'h2'=> Pawn.new('white'), 'a1'=> Rook.new('white'), 'b1'=> Knight.new('white'), 'c1'=> Bishop.new('white'), 'd1'=> King.new('white'), 'e1'=> Queen.new('white'), 'f1'=> Bishop.new('white'), 'g1'=> Knight.new('white'), 'h1'=> Rook.new('white') } end def get_piece(source) @board[source].class end def move_piece(source, destination) @board[destination] = @board[source] @board[source] = " " end def valid_piece?(piece_location, player_color) return @board[piece_location].color == player_color if @board[piece_location] != " " end def to_s @board.values.each_slice(8).each_with_index { |row, index| puts row.unshift(8 - index).join(" ") } puts " a b c d e f g h" end #private def retrieve_column(col_num) column = Array.new @board.keys.select { |col| col[0] == col_num[0] }.each do |position| column << @board[position] end column.map { |piece| piece.color if piece.class != String } end def retrieve_row(row_num) row = Array.new @board.keys.select { |col| col[1] == row_num[1] }.each do |position| column << @board[position] end row.map { |piece| piece.color if piece.class != String } end def generic_retrieve() end end
require_relative 'piece' class ChessBoard attr_reader :board def initialize(board = nil) @board = board || { 'a8'=> Rook.new('black'), 'b8'=> Knight.new('black'), 'c8'=> Bishop.new('black'), 'd8'=> King.new('black'), 'e8'=> Queen.new('black'), 'f8'=> Bishop.new('black'), 'g8'=> Knight.new('black'), 'h8'=> Rook.new('black'), 'a7'=> Pawn.new('black'), 'b7'=> Pawn.new('black'), 'c7'=> Pawn.new('black'), 'd7'=> Pawn.new('black'), 'e7'=> Pawn.new('black'), 'f7'=> Pawn.new('black'), 'g7'=> Pawn.new('black'), 'h7'=> Pawn.new('black'), 'a6'=> " ", 'b6'=> " ", 'c6'=> " ", 'd6'=> " ", 'e6'=> " ", 'f6'=> " ", 'g6'=> " ", 'h6'=> " ", 'a5'=> " ", 'b5'=> " ", 'c5'=> " ", 'd5'=> " ", 'e5'=> " ", 'f5'=> " ", 'g5'=> " ", 'h5'=> " ", 'a4'=> " ", 'b4'=> " ", 'c4'=> " ", 'd4'=> " ", 'e4'=> " ", 'f4'=> " ", 'g4'=> " ", 'h4'=> " ", 'a3'=> " ", 'b3'=> " ", 'c3'=> " ", 'd3'=> " ", 'e3'=> " ", 'f3'=> " ", 'g3'=> " ", 'h3'=> " ", 'a2'=> Pawn.new('white'), 'b2'=> Pawn.new('white'), 'c2'=> Pawn.new('white'), 'd2'=> Pawn.new('white'), 'e2'=> Pawn.new('white'), 'f2'=> Pawn.new('white'), 'g2'=> Pawn.new('white'), 'h2'=> Pawn.new('white'), 'a1'=> Rook.new('white'), 'b1'=> Knight.new('white'), 'c1'=> Bishop.new('white'), 'd1'=> King.new('white'), 'e1'=> Queen.new('white'), 'f1'=> Bishop.new('white'), 'g1'=> Knight.new('white'), 'h1'=> Rook.new('white') } end def get_piece(source) @board[source].class end def move_piece(source, destination) @board[destination] = @board[source] @board[source] = " " end def valid_piece?(piece_location, player_color) return @board[piece_location].color == player_color if @board[piece_location] != " " end def to_s @board.values.each_slice(8).each_with_index { |row, index| puts row.unshift(8 - index).join(" ") } puts ' ' + ('a'..'h').to_a.join(' ') end #private def retrieve_column(col_num) column = Array.new @board.keys.select { |col| col[0] == col_num[0] }.each do |position| column << @board[position] end column.map { |piece| piece.color if piece.class != String } end def retrieve_row(row_num) row = Array.new @board.keys.select { |col| col[1] == row_num[1] }.each do |position| column << @board[position] end row.map { |piece| piece.color if piece.class != String } end def generic_retrieve() end end refactored board.rb, made generic method to retrieve column or row require_relative 'piece' class ChessBoard attr_reader :board def initialize(board = nil) @board = board || { 'a8'=> Rook.new('black'), 'b8'=> Knight.new('black'), 'c8'=> Bishop.new('black'), 'd8'=> King.new('black'), 'e8'=> Queen.new('black'), 'f8'=> Bishop.new('black'), 'g8'=> Knight.new('black'), 'h8'=> Rook.new('black'), 'a7'=> Pawn.new('black'), 'b7'=> Pawn.new('black'), 'c7'=> Pawn.new('black'), 'd7'=> Pawn.new('black'), 'e7'=> Pawn.new('black'), 'f7'=> Pawn.new('black'), 'g7'=> Pawn.new('black'), 'h7'=> Pawn.new('black'), 'a6'=> " ", 'b6'=> " ", 'c6'=> " ", 'd6'=> " ", 'e6'=> " ", 'f6'=> " ", 'g6'=> " ", 'h6'=> " ", 'a5'=> " ", 'b5'=> " ", 'c5'=> " ", 'd5'=> " ", 'e5'=> " ", 'f5'=> " ", 'g5'=> " ", 'h5'=> " ", 'a4'=> " ", 'b4'=> " ", 'c4'=> " ", 'd4'=> " ", 'e4'=> " ", 'f4'=> " ", 'g4'=> " ", 'h4'=> " ", 'a3'=> " ", 'b3'=> " ", 'c3'=> " ", 'd3'=> " ", 'e3'=> " ", 'f3'=> " ", 'g3'=> " ", 'h3'=> " ", 'a2'=> Pawn.new('white'), 'b2'=> Pawn.new('white'), 'c2'=> Pawn.new('white'), 'd2'=> Pawn.new('white'), 'e2'=> Pawn.new('white'), 'f2'=> Pawn.new('white'), 'g2'=> Pawn.new('white'), 'h2'=> Pawn.new('white'), 'a1'=> Rook.new('white'), 'b1'=> Knight.new('white'), 'c1'=> Bishop.new('white'), 'd1'=> King.new('white'), 'e1'=> Queen.new('white'), 'f1'=> Bishop.new('white'), 'g1'=> Knight.new('white'), 'h1'=> Rook.new('white') } end def get_piece(position) # return's the class of the piece at give position @board[position].class end def move_piece(source, destination) # move the piece from source to destination @board[destination] = @board[source] @board[source] = " " end def valid_piece?(piece_location, player_color) # checks if the player have chosen a valid piece to move return @board[piece_location].color == player_color if @board[piece_location] != " " end def to_s # prints board out @board.values.each_slice(8).each_with_index { |row, index| puts row.unshift(8 - index).join(" ") } puts ' ' + ('a'..'h').to_a.join(' ') end #private def generic_retrieve(position, row_or_col) # returns array of the color of the pieces in the row or col row_or_col == "col" ? pos = 0 : pos = 1 @board.select do |space, piece| space[pos] == position[pos] end.values.map { |piece| piece.color if piece.class != String } end end
require File.join(File.expand_path(File.dirname(__FILE__)), '../spec_helper.rb') #describe 'home page', :type => :request do describe 'dashboard' do it 'allows people to see the connect page' do visit '/' within_frame 'appFrame' do page.should have_content("Nobody Selected") end end it 'should allow people to access the develop interface' do visit '/' click_link 'DEVELOP' within_frame 'appFrame' do page.should have_content('Edit your viewer locally!') end end it 'should allow access to api explorer' do visit '/' click_link 'DEVELOP' click_link 'API Explorer' within_frame 'appFrame' do page.should have_content('Choose an endpoint:') end end it "should allow the user to view all of their apps" do visit '/' click_link 'see all' within_frame 'appFrame' do page.should have_content('Hello Links, by Singly, Inc.') page.execute_script("$('li[data-id=\"hellolinks\"]').click()") page.should have_content('This is example of how easy it is to load your links using HTML and jQuery') end end it "should allow account holders to change their settings" do visit '/' click_link 'Account Settings' page.should have_content('ACCOUNT SETTINGS') end it "should allow account holders to connect to services (by default)" do visit '/' click_link 'Account Settings' page.should have_content('ACCOUNT SETTINGS') page.should have_css('.iframeLink.blue[data-id="connections"]') end end Deleted obsolete test that somehow wasn't merged out. require File.join(File.expand_path(File.dirname(__FILE__)), '../spec_helper.rb') #describe 'home page', :type => :request do describe 'dashboard' do it 'should allow people to access the develop interface' do visit '/' click_link 'DEVELOP' within_frame 'appFrame' do page.should have_content('Edit your viewer locally!') end end it 'should allow access to api explorer' do visit '/' click_link 'DEVELOP' click_link 'API Explorer' within_frame 'appFrame' do page.should have_content('Choose an endpoint:') end end it "should allow the user to view all of their apps" do visit '/' click_link 'see all' within_frame 'appFrame' do page.should have_content('Hello Links, by Singly, Inc.') page.execute_script("$('li[data-id=\"hellolinks\"]').click()") page.should have_content('This is example of how easy it is to load your links using HTML and jQuery') end end it "should allow account holders to change their settings" do visit '/' click_link 'Account Settings' page.should have_content('ACCOUNT SETTINGS') end it "should allow account holders to connect to services (by default)" do visit '/' click_link 'Account Settings' page.should have_content('ACCOUNT SETTINGS') page.should have_css('.iframeLink.blue[data-id="connections"]') end end
require './enigma.rb' class Bombe attr_accessor :array # let's try the crib 'afeturh' -> 'feturhe', # which has a cycle e-2-t-3-u-4-r-5-h-6-e # we need 5 enigmas, spaced one apart from each other # (one apart due to the way I found that crib) def self.testConfig array = (1..5).map {Enigma.fromMostBasicSettings} array.each_with_index do |enigma, index| index.times {enigma.step!} end new_bombe = self.new new_bombe.array = array new_bombe end def test_position(orig_position) temp_position = orig_position (0..4).each do |i| temp_position = array[i].encipher_without_step(temp_position) end temp_position == orig_position #if false, current state non-self-consistent end def step_all! array.each {|e| e.step!} end def test_until_valid! iteration = 0 good = [] # actual bombe didn't step rotors like the enigma did, # but rather like an odometer would, so this isn't quite # correct. 17576.times do if test_position(4) good << iteration end iteration += 1 step_all! end good end #with stecker #let's call them 'banks' on the diagonal board (the capital letters in the diagram) #each bank knows its 'connected to other bank X via enigma Y' pairings and has # 26 true/false registers representing the possible stecker values. #bank with most conncted enigmas is the 'test bank' #pick a letter on the test bank, and for each connected enigma, encrypt it and set # the bank/register on the other end to true. if it wasn't already set, # recursively repeat this propagation. #now, in the test register, if there are: # 26 live registers: this rotor state is not self-consistent # 1 live register: this rotor state may be (not necessarily) correct # else, the above should be repeated but check one of the registers # that is now unset (this would have been a manual check) end More notes and OO class/interface outline. require './enigma.rb' class Bombe attr_accessor :array # let's try the crib 'afeturh' -> 'feturhe', # which has a cycle e-2-t-3-u-4-r-5-h-6-e # we need 5 enigmas, spaced one apart from each other # (one apart due to the way I found that crib) def self.testConfig array = (1..5).map {Enigma.fromMostBasicSettings} array.each_with_index do |enigma, index| index.times {enigma.step!} end new_bombe = self.new new_bombe.array = array new_bombe end def test_position(orig_position) temp_position = orig_position (0..4).each do |i| temp_position = array[i].encipher_without_step(temp_position) end temp_position == orig_position #if false, current state non-self-consistent end def step_all! array.each {|e| e.step!} end def test_until_valid! iteration = 0 good = [] # actual bombe didn't step rotors like the enigma did, # but rather like an odometer would, so this isn't quite # correct. 17576.times do if test_position(4) good << iteration end iteration += 1 step_all! end good end #with stecker #let's call them 'banks' on the diagonal board (the capital letters in the diagram) #each bank knows its 'connected to other bank X via enigma Y' pairings and has # 26 true/false registers representing the possible stecker values. #bank with most conncted enigmas is the 'test bank' #pick a letter on the test bank, and for each connected enigma, encrypt it and set # the bank/register on the other end AND the register in the other bank # that's steckered to this one. (eg. set the X-y register and the Y-x register.) # if it wasn't already set, recursively repeat this propagation. #now, in the test register, if there are: # 26 live registers: this rotor state is not self-consistent # 1 live register: this rotor state may be (not necessarily) correct # else, the above should be repeated but check one of the registers # that is now unset (this would have been a manual check) ### # #So let's input the menu as a bunch of triplets. Eg. [[a,j,5],...] would #mean A and J cipher to each other at relative position 5. #Internally, for each input triplet, we make a reference in bank A and #in bank J to the enigma with displacement 5 and to other bank. (so #the entry in bank A would be like [enigma5, J] and the entry in bank #J would be like [enigma5, A]. # #To begin, we find the bank with the most references, and set some #stecker-register within it to true ALONG WITH the register in the #associated bank according to the diagonal board. Now, send that letter #through the first enigma in that bank. We get a ciphered letter, which #is the register in the target bank that we want to set to true. If #it is already true, stop (and continue with remaining enigmas). Else, #repeat this procedure recursively from that bank/register. # #After we've sent the test letter through every enigma in the test bank, #and have propogated the result, we do the check on the number of live #registers in the test bank. class DiagonalBoard attr_accessor :banks def set_register_pair(b_num, r_num) banks[b_num].set_register(r_num) banks[r_num].set_register(b_num) end def test_hypothesis(b_num, r_num) set_register_pair(b_num, r_num) banks[b_num].num_of_live_wires < 26 end end class Bank attr_accessor :number, :plug_halves, :registers def set_register(r_num) unless registers[r_num] set_register_pair(number, r_num) #TODO: better OO here? plug_halves.each {|ph| ph.encipher_and_set_target_register(r_num)} end end def num_of_live_wires registers.select {|r| !!r}.count end end class PlugHalf attr_accessor :enigma, :target_bank def encipher_and_set_target_register(letter) target_bank.set_register( enigma.encipher_without_step(letter) ) end end end
Common rails update pattern # coding: utf-8 ################################################ # © Alexander Semyonov, 2013—2013, MIT # # Author: Alexander Semyonov <al@semyonov.us> # ################################################ dep 'database migrated', :env, :deploying, :template => 'task' do run { shell "bundle exec rake db:migrate RAILS_ENV=#{env}" } end dep 'rails update', :path do requires 'common:app bundled'.with(path) requires 'database migrated'.with(path) requires 'common:assets precompiled'.with(path) end
Didn't add Match class file for last commit class Match def host_name return @match_values[2] end def visitor_name return @match_values[3] end def host_score return @match_values[4] end def visitor_score return @match_values[5] end def is_visitor_winner return visitor_score > host_score end def is_host_winner return host_score > visitor_score end def initialize(match_line) @match_values = match_line.split(',') end def is_host(clubName) return host_name == clubName end def is_visitor(clubName) return visitor_name == clubName end end
# This module provides an interface to the vips image processing library # via ruby-ffi. # # Author:: John Cupitt (mailto:jcupitt@gmail.com) # License:: MIT require 'ffi' require 'logger' # This module uses FFI to make a simple layer over the glib and gobject # libraries. module GLib class << self attr_accessor :logger end @logger = Logger.new(STDOUT) @logger.level = Logger::WARN extend FFI::Library if FFI::Platform.windows? glib_libname = 'libglib-2.0-0.dll' else glib_libname = 'glib-2.0' end ffi_lib glib_libname attach_function :g_malloc, [:size_t], :pointer # save the FFI::Function that attach will return ... we can use it directly # as a param for callbacks G_FREE = attach_function :g_free, [:pointer], :void callback :g_log_func, [:string, :int, :string, :pointer], :void attach_function :g_log_set_handler, [:string, :int, :g_log_func, :pointer], :int attach_function :g_log_remove_handler, [:string, :int], :void # log flags LOG_FLAG_RECURSION = 1 << 0 LOG_FLAG_FATAL = 1 << 1 # GLib log levels LOG_LEVEL_ERROR = 1 << 2 # always fatal LOG_LEVEL_CRITICAL = 1 << 3 LOG_LEVEL_WARNING = 1 << 4 LOG_LEVEL_MESSAGE = 1 << 5 LOG_LEVEL_INFO = 1 << 6 LOG_LEVEL_DEBUG = 1 << 7 # map glib levels to Logger::Severity GLIB_TO_SEVERITY = { LOG_LEVEL_ERROR => Logger::ERROR, LOG_LEVEL_CRITICAL => Logger::FATAL, LOG_LEVEL_WARNING => Logger::WARN, LOG_LEVEL_MESSAGE => Logger::UNKNOWN, LOG_LEVEL_INFO => Logger::INFO, LOG_LEVEL_DEBUG => Logger::DEBUG } GLIB_TO_SEVERITY.default = Logger::UNKNOWN # nil being the default @glib_log_domain = nil @glib_log_handler_id = 0 # module-level, so it's not GCd away LOG_HANDLER = Proc.new do |domain, level, message, user_data| @logger.log(GLIB_TO_SEVERITY[level], message, domain) end def self.remove_log_handler if @glib_log_handler_id != 0 && @glib_log_domain g_log_remove_handler @glib_log_domain, @glib_log_handler_id @glib_log_handler_id = nil end end def self.set_log_domain domain GLib::remove_log_handler @glib_log_domain = domain # forward all glib logging output from this domain to a Ruby logger if @glib_log_domain # disable this feature for now # # libvips background worker threads can issue warnings, and # since the main thread is blocked waiting for libvips to come back # from an ffi call, you get a deadlock on the GIL # # to fix this, we need a way for g_log() calls from libvips workers # to be returned via the main thread # # @glib_log_handler_id = g_log_set_handler @glib_log_domain, # LOG_LEVEL_DEBUG | # LOG_LEVEL_INFO | # LOG_LEVEL_MESSAGE | # LOG_LEVEL_WARNING | # LOG_LEVEL_ERROR | # LOG_LEVEL_CRITICAL | # LOG_FLAG_FATAL | LOG_FLAG_RECURSION, # LOG_HANDLER, nil # we must remove any handlers on exit, since libvips may log stuff # on shutdown and we don't want LOG_HANDLER to be invoked # after Ruby has gone at_exit { GLib::remove_log_handler } end end end module GObject extend FFI::Library if FFI::Platform.windows? gobject_libname = 'libgobject-2.0-0.dll' else gobject_libname = 'gobject-2.0' end ffi_lib gobject_libname # we can't just use ulong, windows has different int sizing rules if FFI::Platform::ADDRESS_SIZE == 64 typedef :uint64, :GType else typedef :uint32, :GType end attach_function :g_type_init, [], :void attach_function :g_type_name, [:GType], :string attach_function :g_type_from_name, [:string], :GType attach_function :g_type_fundamental, [:GType], :GType # glib before 2.36 needed this, does nothing in current glib g_type_init # look up some common gtypes GBOOL_TYPE = g_type_from_name "gboolean" GINT_TYPE = g_type_from_name "gint" GUINT64_TYPE = g_type_from_name "guint64" GDOUBLE_TYPE = g_type_from_name "gdouble" GENUM_TYPE = g_type_from_name "GEnum" GFLAGS_TYPE = g_type_from_name "GFlags" GSTR_TYPE = g_type_from_name "gchararray" GOBJECT_TYPE = g_type_from_name "GObject" end require 'vips/gobject' require 'vips/gvalue' # This module provides a binding for the [libvips image processing # library](https://jcupitt.github.io/libvips/). # # # Example # # ```ruby # require 'vips' # # if ARGV.length < 2 # raise "usage: #{$PROGRAM_NAME}: input-file output-file" # end # # im = Vips::Image.new_from_file ARGV[0], access: :sequential # # im *= [1, 2, 1] # # mask = Vips::Image.new_from_array [ # [-1, -1, -1], # [-1, 16, -1], # [-1, -1, -1] # ], 8 # im = im.conv mask, precision: :integer # # im.write_to_file ARGV[1] # ``` # # This example loads a file, boosts the green channel (I'm not sure why), # sharpens the image, and saves it back to disc again. # # Reading this example line by line, we have: # # ```ruby # im = Vips::Image.new_from_file ARGV[0], access: :sequential # ``` # # {Image.new_from_file} can load any image file supported by vips. In this # example, we will be accessing pixels top-to-bottom as we sweep through the # image reading and writing, so `:sequential` access mode is best for us. The # default mode is `:random`: this allows for full random access to image pixels, # but is slower and needs more memory. See {Access} # for full details # on the various modes available. # # You can also load formatted images from # memory buffers, create images that wrap C-style memory arrays, or make images # from constants. # # The next line: # # ```ruby # im *= [1, 2, 1] # ``` # # Multiplying the image by an array constant uses one array element for each # image band. This line assumes that the input image has three bands and will # double the middle band. For RGB images, that's doubling green. # # Next we have: # # ```ruby # mask = Vips::Image.new_from_array [ # [-1, -1, -1], # [-1, 16, -1], # [-1, -1, -1] # ], 8 # im = im.conv mask, precision: :integer # ``` # # {Image.new_from_array} creates an image from an array constant. The 8 at # the end sets the scale: the amount to divide the image by after # integer convolution. # # See the libvips API docs for `vips_conv()` (the operation # invoked by {Image#conv}) for details on the convolution operator. By default, # it computes with a float mask, but `:integer` is fine for this case, and is # much faster. # # Finally: # # ```ruby # im.write_to_file ARGV[1] # ``` # # {Image#write_to_file} writes an image back to the filesystem. It can # write any format supported by vips: the file type is set from the filename # suffix. You can also write formatted images to memory buffers, or dump # image data to a raw memory array. # # # How it works # # The binding uses [ruby-ffi](https://github.com/ffi/ffi) to open the libvips # shared library. When you call a method on the image class, it uses libvips # introspection system (based on GObject) to search the # library for an operation of that name, transforms the arguments to a form # libvips can digest, and runs the operation. # # This means ruby-vips always presents the API implemented by the libvips shared # library. It should update itself as new features are added. # # # Automatic wrapping # # `ruby-vips` adds a {Image.method_missing} handler to {Image} and uses # it to look up vips operations. For example, the libvips operation `add`, which # appears in C as `vips_add()`, appears in Ruby as {Image#add}. # # The operation's list of required arguments is searched and the first input # image is set to the value of `self`. Operations which do not take an input # image, such as {Image.black}, appear as class methods. The remainder of # the arguments you supply in the function call are used to set the other # required input arguments. Any trailing keyword arguments are used to set # options on the operation. # # The result is the required output # argument if there is only one result, or an array of values if the operation # produces several results. If the operation has optional output objects, they # are returned as a final hash. # # For example, {Image#min}, the vips operation that searches an image for # the minimum value, has a large number of optional arguments. You can use it to # find the minimum value like this: # # ```ruby # min_value = image.min # ``` # # You can ask it to return the position of the minimum with `:x` and `:y`. # # ```ruby # min_value, opts = min x: true, y: true # x_pos = opts['x'] # y_pos = opts['y'] # ``` # # Now `x_pos` and `y_pos` will have the coordinates of the minimum value. # There's actually a convenience method for this, {Image#minpos}. # # You can also ask for the top *n* minimum, for example: # # ```ruby # min_value, opts = min size: 10, x_array: true, y_array: true # x_pos = opts['x_array'] # y_pos = opts['y_array'] # ``` # # Now `x_pos` and `y_pos` will be 10-element arrays. # # Because operations are member functions and return the result image, you can # chain them. For example, you can write: # # ```ruby # result_image = image.real.cos # ``` # # to calculate the cosine of the real part of a complex image. # There are also a full set # of arithmetic operator overloads, see below. # # libvips types are also automatically wrapped. The override looks at the type # of argument required by the operation and converts the value you supply, # when it can. For example, {Image#linear} takes a `VipsArrayDouble` as # an argument # for the set of constants to use for multiplication. You can supply this # value as an integer, a float, or some kind of compound object and it # will be converted for you. You can write: # # ```ruby # result_image = image.linear 1, 3 # result_image = image.linear 12.4, 13.9 # result_image = image.linear [1, 2, 3], [4, 5, 6] # result_image = image.linear 1, [4, 5, 6] # ``` # # And so on. A set of overloads are defined for {Image#linear}, see below. # # It does a couple of more ambitious conversions. It will automatically convert # to and from the various vips types, like `VipsBlob` and `VipsArrayImage`. For # example, you can read the ICC profile out of an image like this: # # ```ruby # profile = im.get_value "icc-profile-data" # ``` # # and profile will be a byte array. # # If an operation takes several input images, you can use a constant for all but # one of them and the wrapper will expand the constant to an image for you. For # example, {Image#ifthenelse} uses a condition image to pick pixels # between a then and an else image: # # ```ruby # result_image = condition_image.ifthenelse then_image, else_image # ``` # # You can use a constant instead of either the then or the else parts and it # will be expanded to an image for you. If you use a constant for both then and # else, it will be expanded to match the condition image. For example: # # ```ruby # result_image = condition_image.ifthenelse [0, 255, 0], [255, 0, 0] # ``` # # Will make an image where true pixels are green and false pixels are red. # # This is useful for {Image#bandjoin}, the thing to join two or more # images up bandwise. You can write: # # ```ruby # rgba = rgb.bandjoin 255 # ``` # # to append a constant 255 band to an image, perhaps to add an alpha channel. Of # course you can also write: # # ```ruby # result_image = image1.bandjoin image2 # result_image = image1.bandjoin [image2, image3] # result_image = Vips::Image.bandjoin [image1, image2, image3] # result_image = image1.bandjoin [image2, 255] # ``` # # and so on. # # # Logging # # Libvips uses g_log() to log warning, debug, info and (some) error messages. # # https://developer.gnome.org/glib/stable/glib-Message-Logging.html # # You can disable wanrings by defining the `VIPS_WARNING` environment variable. # You can enable info output by defining `VIPS_INFO`. # # # Exceptions # # The wrapper spots errors from vips operations and raises the {Vips::Error} # exception. You can catch it in the usual way. # # # Automatic YARD documentation # # The bulk of these API docs are generated automatically by # {Vips::generate_yard}. It examines # libvips and writes a summary of each operation and the arguments and options # that that operation expects. # # Use the [C API # docs](https://jcupitt.github.io/libvips/API/current) # for more detail. # # # Enums # # The libvips enums, such as `VipsBandFormat` appear in ruby-vips as Symbols # like `:uchar`. They are documented as a set of classes for convenience, see # the class list. # # # Draw operations # # Paint operations like {Image#draw_circle} and {Image#draw_line} # modify their input image. This # makes them hard to use with the rest of libvips: you need to be very careful # about the order in which operations execute or you can get nasty crashes. # # The wrapper spots operations of this type and makes a private copy of the # image in memory before calling the operation. This stops crashes, but it does # make it inefficient. If you draw 100 lines on an image, for example, you'll # copy the image 100 times. The wrapper does make sure that memory is recycled # where possible, so you won't have 100 copies in memory. # # If you want to avoid the copies, you'll need to call drawing operations # yourself. # # # Overloads # # The wrapper defines the usual set of arithmetic, boolean and relational # overloads on image. You can mix images, constants and lists of constants # (almost) freely. For example, you can write: # # ```ruby # result_image = ((image * [1, 2, 3]).abs < 128) | 4 # ``` # # # Expansions # # Some vips operators take an enum to select an action, for example # {Image#math} can be used to calculate sine of every pixel like this: # # ```ruby # result_image = image.math :sin # ``` # # This is annoying, so the wrapper expands all these enums into separate members # named after the enum. So you can write: # # ```ruby # result_image = image.sin # ``` # # # Convenience functions # # The wrapper defines a few extra useful utility functions: # {Image#get_value}, {Image#set_value}, {Image#bandsplit}, # {Image#maxpos}, {Image#minpos}, # {Image#median}. module Vips extend FFI::Library if FFI::Platform.windows? vips_libname = 'libvips-42.dll' else vips_libname = 'vips' end ffi_lib vips_libname LOG_DOMAIN = "VIPS" GLib::set_log_domain LOG_DOMAIN typedef :ulong, :GType attach_function :vips_error_buffer, [], :string attach_function :vips_error_clear, [], :void # The ruby-vips error class. class Error < RuntimeError # @param msg [String] The error message. If this is not supplied, grab # and clear the vips error buffer and use that. def initialize msg = nil if msg @details = msg elsif Vips::vips_error_buffer != "" @details = Vips::vips_error_buffer Vips::vips_error_clear else @details = nil end end # Pretty-print a {Vips::Error}. # # @return [String] The error message def to_s if @details != nil @details else super.to_s end end end attach_function :vips_init, [:string], :int if Vips::vips_init($0) != 0 throw Vips::get_error end # don't use at_exit to call vips_shutdown, it causes problems with fork, and # in any case libvips does this for us attach_function :vips_leak_set, [:int], :void attach_function :vips_vector_set_enabled, [:int], :void attach_function :vips_concurrency_set, [:int], :void # vips_foreign_get_suffixes was added in libvips 8.8 begin attach_function :vips_foreign_get_suffixes, [], :pointer rescue FFI::NotFoundError nil end # Turn libvips leak testing on and off. Handy for debugging ruby-vips, not # very useful for user code. def self.leak_set leak vips_leak_set (leak ? 1 : 0) end attach_function :vips_cache_set_max, [:int], :void attach_function :vips_cache_set_max_mem, [:int], :void attach_function :vips_cache_set_max_files, [:int], :void # Set the maximum number of operations that libvips should cache. Set 0 to # disable the operation cache. The default is 1000. def self.cache_set_max size vips_cache_set_max size end # Set the maximum amount of memory that libvips should use for the operation # cache. Set 0 to disable the operation cache. The default is 100mb. def self.cache_set_max_mem size vips_cache_set_max_mem size end # Set the maximum number of files libvips should keep open in the # operation cache. Set 0 to disable the operation cache. The default is # 100. def self.cache_set_max_files size vips_cache_set_max_files size end # Set the size of the libvips worker pool. This defaults to the number of # hardware threads on your computer. Set to 1 to disable threading. def self.concurrency_set n vips_concurrency_set n end # Enable or disable SIMD and the run-time compiler. This can give a nice # speed-up, but can also be unstable on some systems or with some versions # of the run-time compiler. def self.vector_set enabled vips_vector_set_enabled(enabled ? 1 : 0) end # Deprecated compatibility function. # # Don't use this, instead change GLib::logger.level. def self.set_debug debug if debug GLib::logger.level = Logger::DEBUG end end attach_function :version, :vips_version, [:int], :int attach_function :version_string, :vips_version_string, [], :string # True if this is at least libvips x.y def self.at_least_libvips?(x, y) major = version(0) minor = version(1) major > x || (major == x && minor >= y) end # Get a list of all supported file suffixes. # # @return [[String]] array of supported suffixes def self.get_suffixes # vips_foreign_get_suffixes() was added in libvips 8.8 return [] unless Vips.respond_to? :vips_foreign_get_suffixes array = Vips::vips_foreign_get_suffixes names = [] p = array until (q = p.read_pointer).null? suff = q.read_string GLib::g_free q names << suff unless names.include? suff p += FFI::Type::POINTER.size end GLib::g_free array names end LIBRARY_VERSION = Vips::version_string # libvips has this arbitrary number as a sanity-check upper bound on image # size. It's sometimes useful for know whan calculating image ratios. MAX_COORD = 10000000 end require 'vips/object' require 'vips/operation' require 'vips/image' require 'vips/interpolate' require 'vips/version' Fix typo # This module provides an interface to the vips image processing library # via ruby-ffi. # # Author:: John Cupitt (mailto:jcupitt@gmail.com) # License:: MIT require 'ffi' require 'logger' # This module uses FFI to make a simple layer over the glib and gobject # libraries. module GLib class << self attr_accessor :logger end @logger = Logger.new(STDOUT) @logger.level = Logger::WARN extend FFI::Library if FFI::Platform.windows? glib_libname = 'libglib-2.0-0.dll' else glib_libname = 'glib-2.0' end ffi_lib glib_libname attach_function :g_malloc, [:size_t], :pointer # save the FFI::Function that attach will return ... we can use it directly # as a param for callbacks G_FREE = attach_function :g_free, [:pointer], :void callback :g_log_func, [:string, :int, :string, :pointer], :void attach_function :g_log_set_handler, [:string, :int, :g_log_func, :pointer], :int attach_function :g_log_remove_handler, [:string, :int], :void # log flags LOG_FLAG_RECURSION = 1 << 0 LOG_FLAG_FATAL = 1 << 1 # GLib log levels LOG_LEVEL_ERROR = 1 << 2 # always fatal LOG_LEVEL_CRITICAL = 1 << 3 LOG_LEVEL_WARNING = 1 << 4 LOG_LEVEL_MESSAGE = 1 << 5 LOG_LEVEL_INFO = 1 << 6 LOG_LEVEL_DEBUG = 1 << 7 # map glib levels to Logger::Severity GLIB_TO_SEVERITY = { LOG_LEVEL_ERROR => Logger::ERROR, LOG_LEVEL_CRITICAL => Logger::FATAL, LOG_LEVEL_WARNING => Logger::WARN, LOG_LEVEL_MESSAGE => Logger::UNKNOWN, LOG_LEVEL_INFO => Logger::INFO, LOG_LEVEL_DEBUG => Logger::DEBUG } GLIB_TO_SEVERITY.default = Logger::UNKNOWN # nil being the default @glib_log_domain = nil @glib_log_handler_id = 0 # module-level, so it's not GCd away LOG_HANDLER = Proc.new do |domain, level, message, user_data| @logger.log(GLIB_TO_SEVERITY[level], message, domain) end def self.remove_log_handler if @glib_log_handler_id != 0 && @glib_log_domain g_log_remove_handler @glib_log_domain, @glib_log_handler_id @glib_log_handler_id = nil end end def self.set_log_domain domain GLib::remove_log_handler @glib_log_domain = domain # forward all glib logging output from this domain to a Ruby logger if @glib_log_domain # disable this feature for now # # libvips background worker threads can issue warnings, and # since the main thread is blocked waiting for libvips to come back # from an ffi call, you get a deadlock on the GIL # # to fix this, we need a way for g_log() calls from libvips workers # to be returned via the main thread # # @glib_log_handler_id = g_log_set_handler @glib_log_domain, # LOG_LEVEL_DEBUG | # LOG_LEVEL_INFO | # LOG_LEVEL_MESSAGE | # LOG_LEVEL_WARNING | # LOG_LEVEL_ERROR | # LOG_LEVEL_CRITICAL | # LOG_FLAG_FATAL | LOG_FLAG_RECURSION, # LOG_HANDLER, nil # we must remove any handlers on exit, since libvips may log stuff # on shutdown and we don't want LOG_HANDLER to be invoked # after Ruby has gone at_exit { GLib::remove_log_handler } end end end module GObject extend FFI::Library if FFI::Platform.windows? gobject_libname = 'libgobject-2.0-0.dll' else gobject_libname = 'gobject-2.0' end ffi_lib gobject_libname # we can't just use ulong, windows has different int sizing rules if FFI::Platform::ADDRESS_SIZE == 64 typedef :uint64, :GType else typedef :uint32, :GType end attach_function :g_type_init, [], :void attach_function :g_type_name, [:GType], :string attach_function :g_type_from_name, [:string], :GType attach_function :g_type_fundamental, [:GType], :GType # glib before 2.36 needed this, does nothing in current glib g_type_init # look up some common gtypes GBOOL_TYPE = g_type_from_name "gboolean" GINT_TYPE = g_type_from_name "gint" GUINT64_TYPE = g_type_from_name "guint64" GDOUBLE_TYPE = g_type_from_name "gdouble" GENUM_TYPE = g_type_from_name "GEnum" GFLAGS_TYPE = g_type_from_name "GFlags" GSTR_TYPE = g_type_from_name "gchararray" GOBJECT_TYPE = g_type_from_name "GObject" end require 'vips/gobject' require 'vips/gvalue' # This module provides a binding for the [libvips image processing # library](https://jcupitt.github.io/libvips/). # # # Example # # ```ruby # require 'vips' # # if ARGV.length < 2 # raise "usage: #{$PROGRAM_NAME}: input-file output-file" # end # # im = Vips::Image.new_from_file ARGV[0], access: :sequential # # im *= [1, 2, 1] # # mask = Vips::Image.new_from_array [ # [-1, -1, -1], # [-1, 16, -1], # [-1, -1, -1] # ], 8 # im = im.conv mask, precision: :integer # # im.write_to_file ARGV[1] # ``` # # This example loads a file, boosts the green channel (I'm not sure why), # sharpens the image, and saves it back to disc again. # # Reading this example line by line, we have: # # ```ruby # im = Vips::Image.new_from_file ARGV[0], access: :sequential # ``` # # {Image.new_from_file} can load any image file supported by vips. In this # example, we will be accessing pixels top-to-bottom as we sweep through the # image reading and writing, so `:sequential` access mode is best for us. The # default mode is `:random`: this allows for full random access to image pixels, # but is slower and needs more memory. See {Access} # for full details # on the various modes available. # # You can also load formatted images from # memory buffers, create images that wrap C-style memory arrays, or make images # from constants. # # The next line: # # ```ruby # im *= [1, 2, 1] # ``` # # Multiplying the image by an array constant uses one array element for each # image band. This line assumes that the input image has three bands and will # double the middle band. For RGB images, that's doubling green. # # Next we have: # # ```ruby # mask = Vips::Image.new_from_array [ # [-1, -1, -1], # [-1, 16, -1], # [-1, -1, -1] # ], 8 # im = im.conv mask, precision: :integer # ``` # # {Image.new_from_array} creates an image from an array constant. The 8 at # the end sets the scale: the amount to divide the image by after # integer convolution. # # See the libvips API docs for `vips_conv()` (the operation # invoked by {Image#conv}) for details on the convolution operator. By default, # it computes with a float mask, but `:integer` is fine for this case, and is # much faster. # # Finally: # # ```ruby # im.write_to_file ARGV[1] # ``` # # {Image#write_to_file} writes an image back to the filesystem. It can # write any format supported by vips: the file type is set from the filename # suffix. You can also write formatted images to memory buffers, or dump # image data to a raw memory array. # # # How it works # # The binding uses [ruby-ffi](https://github.com/ffi/ffi) to open the libvips # shared library. When you call a method on the image class, it uses libvips # introspection system (based on GObject) to search the # library for an operation of that name, transforms the arguments to a form # libvips can digest, and runs the operation. # # This means ruby-vips always presents the API implemented by the libvips shared # library. It should update itself as new features are added. # # # Automatic wrapping # # `ruby-vips` adds a {Image.method_missing} handler to {Image} and uses # it to look up vips operations. For example, the libvips operation `add`, which # appears in C as `vips_add()`, appears in Ruby as {Image#add}. # # The operation's list of required arguments is searched and the first input # image is set to the value of `self`. Operations which do not take an input # image, such as {Image.black}, appear as class methods. The remainder of # the arguments you supply in the function call are used to set the other # required input arguments. Any trailing keyword arguments are used to set # options on the operation. # # The result is the required output # argument if there is only one result, or an array of values if the operation # produces several results. If the operation has optional output objects, they # are returned as a final hash. # # For example, {Image#min}, the vips operation that searches an image for # the minimum value, has a large number of optional arguments. You can use it to # find the minimum value like this: # # ```ruby # min_value = image.min # ``` # # You can ask it to return the position of the minimum with `:x` and `:y`. # # ```ruby # min_value, opts = min x: true, y: true # x_pos = opts['x'] # y_pos = opts['y'] # ``` # # Now `x_pos` and `y_pos` will have the coordinates of the minimum value. # There's actually a convenience method for this, {Image#minpos}. # # You can also ask for the top *n* minimum, for example: # # ```ruby # min_value, opts = min size: 10, x_array: true, y_array: true # x_pos = opts['x_array'] # y_pos = opts['y_array'] # ``` # # Now `x_pos` and `y_pos` will be 10-element arrays. # # Because operations are member functions and return the result image, you can # chain them. For example, you can write: # # ```ruby # result_image = image.real.cos # ``` # # to calculate the cosine of the real part of a complex image. # There are also a full set # of arithmetic operator overloads, see below. # # libvips types are also automatically wrapped. The override looks at the type # of argument required by the operation and converts the value you supply, # when it can. For example, {Image#linear} takes a `VipsArrayDouble` as # an argument # for the set of constants to use for multiplication. You can supply this # value as an integer, a float, or some kind of compound object and it # will be converted for you. You can write: # # ```ruby # result_image = image.linear 1, 3 # result_image = image.linear 12.4, 13.9 # result_image = image.linear [1, 2, 3], [4, 5, 6] # result_image = image.linear 1, [4, 5, 6] # ``` # # And so on. A set of overloads are defined for {Image#linear}, see below. # # It does a couple of more ambitious conversions. It will automatically convert # to and from the various vips types, like `VipsBlob` and `VipsArrayImage`. For # example, you can read the ICC profile out of an image like this: # # ```ruby # profile = im.get_value "icc-profile-data" # ``` # # and profile will be a byte array. # # If an operation takes several input images, you can use a constant for all but # one of them and the wrapper will expand the constant to an image for you. For # example, {Image#ifthenelse} uses a condition image to pick pixels # between a then and an else image: # # ```ruby # result_image = condition_image.ifthenelse then_image, else_image # ``` # # You can use a constant instead of either the then or the else parts and it # will be expanded to an image for you. If you use a constant for both then and # else, it will be expanded to match the condition image. For example: # # ```ruby # result_image = condition_image.ifthenelse [0, 255, 0], [255, 0, 0] # ``` # # Will make an image where true pixels are green and false pixels are red. # # This is useful for {Image#bandjoin}, the thing to join two or more # images up bandwise. You can write: # # ```ruby # rgba = rgb.bandjoin 255 # ``` # # to append a constant 255 band to an image, perhaps to add an alpha channel. Of # course you can also write: # # ```ruby # result_image = image1.bandjoin image2 # result_image = image1.bandjoin [image2, image3] # result_image = Vips::Image.bandjoin [image1, image2, image3] # result_image = image1.bandjoin [image2, 255] # ``` # # and so on. # # # Logging # # Libvips uses g_log() to log warning, debug, info and (some) error messages. # # https://developer.gnome.org/glib/stable/glib-Message-Logging.html # # You can disable warnings by defining the `VIPS_WARNING` environment variable. # You can enable info output by defining `VIPS_INFO`. # # # Exceptions # # The wrapper spots errors from vips operations and raises the {Vips::Error} # exception. You can catch it in the usual way. # # # Automatic YARD documentation # # The bulk of these API docs are generated automatically by # {Vips::generate_yard}. It examines # libvips and writes a summary of each operation and the arguments and options # that that operation expects. # # Use the [C API # docs](https://jcupitt.github.io/libvips/API/current) # for more detail. # # # Enums # # The libvips enums, such as `VipsBandFormat` appear in ruby-vips as Symbols # like `:uchar`. They are documented as a set of classes for convenience, see # the class list. # # # Draw operations # # Paint operations like {Image#draw_circle} and {Image#draw_line} # modify their input image. This # makes them hard to use with the rest of libvips: you need to be very careful # about the order in which operations execute or you can get nasty crashes. # # The wrapper spots operations of this type and makes a private copy of the # image in memory before calling the operation. This stops crashes, but it does # make it inefficient. If you draw 100 lines on an image, for example, you'll # copy the image 100 times. The wrapper does make sure that memory is recycled # where possible, so you won't have 100 copies in memory. # # If you want to avoid the copies, you'll need to call drawing operations # yourself. # # # Overloads # # The wrapper defines the usual set of arithmetic, boolean and relational # overloads on image. You can mix images, constants and lists of constants # (almost) freely. For example, you can write: # # ```ruby # result_image = ((image * [1, 2, 3]).abs < 128) | 4 # ``` # # # Expansions # # Some vips operators take an enum to select an action, for example # {Image#math} can be used to calculate sine of every pixel like this: # # ```ruby # result_image = image.math :sin # ``` # # This is annoying, so the wrapper expands all these enums into separate members # named after the enum. So you can write: # # ```ruby # result_image = image.sin # ``` # # # Convenience functions # # The wrapper defines a few extra useful utility functions: # {Image#get_value}, {Image#set_value}, {Image#bandsplit}, # {Image#maxpos}, {Image#minpos}, # {Image#median}. module Vips extend FFI::Library if FFI::Platform.windows? vips_libname = 'libvips-42.dll' else vips_libname = 'vips' end ffi_lib vips_libname LOG_DOMAIN = "VIPS" GLib::set_log_domain LOG_DOMAIN typedef :ulong, :GType attach_function :vips_error_buffer, [], :string attach_function :vips_error_clear, [], :void # The ruby-vips error class. class Error < RuntimeError # @param msg [String] The error message. If this is not supplied, grab # and clear the vips error buffer and use that. def initialize msg = nil if msg @details = msg elsif Vips::vips_error_buffer != "" @details = Vips::vips_error_buffer Vips::vips_error_clear else @details = nil end end # Pretty-print a {Vips::Error}. # # @return [String] The error message def to_s if @details != nil @details else super.to_s end end end attach_function :vips_init, [:string], :int if Vips::vips_init($0) != 0 throw Vips::get_error end # don't use at_exit to call vips_shutdown, it causes problems with fork, and # in any case libvips does this for us attach_function :vips_leak_set, [:int], :void attach_function :vips_vector_set_enabled, [:int], :void attach_function :vips_concurrency_set, [:int], :void # vips_foreign_get_suffixes was added in libvips 8.8 begin attach_function :vips_foreign_get_suffixes, [], :pointer rescue FFI::NotFoundError nil end # Turn libvips leak testing on and off. Handy for debugging ruby-vips, not # very useful for user code. def self.leak_set leak vips_leak_set (leak ? 1 : 0) end attach_function :vips_cache_set_max, [:int], :void attach_function :vips_cache_set_max_mem, [:int], :void attach_function :vips_cache_set_max_files, [:int], :void # Set the maximum number of operations that libvips should cache. Set 0 to # disable the operation cache. The default is 1000. def self.cache_set_max size vips_cache_set_max size end # Set the maximum amount of memory that libvips should use for the operation # cache. Set 0 to disable the operation cache. The default is 100mb. def self.cache_set_max_mem size vips_cache_set_max_mem size end # Set the maximum number of files libvips should keep open in the # operation cache. Set 0 to disable the operation cache. The default is # 100. def self.cache_set_max_files size vips_cache_set_max_files size end # Set the size of the libvips worker pool. This defaults to the number of # hardware threads on your computer. Set to 1 to disable threading. def self.concurrency_set n vips_concurrency_set n end # Enable or disable SIMD and the run-time compiler. This can give a nice # speed-up, but can also be unstable on some systems or with some versions # of the run-time compiler. def self.vector_set enabled vips_vector_set_enabled(enabled ? 1 : 0) end # Deprecated compatibility function. # # Don't use this, instead change GLib::logger.level. def self.set_debug debug if debug GLib::logger.level = Logger::DEBUG end end attach_function :version, :vips_version, [:int], :int attach_function :version_string, :vips_version_string, [], :string # True if this is at least libvips x.y def self.at_least_libvips?(x, y) major = version(0) minor = version(1) major > x || (major == x && minor >= y) end # Get a list of all supported file suffixes. # # @return [[String]] array of supported suffixes def self.get_suffixes # vips_foreign_get_suffixes() was added in libvips 8.8 return [] unless Vips.respond_to? :vips_foreign_get_suffixes array = Vips::vips_foreign_get_suffixes names = [] p = array until (q = p.read_pointer).null? suff = q.read_string GLib::g_free q names << suff unless names.include? suff p += FFI::Type::POINTER.size end GLib::g_free array names end LIBRARY_VERSION = Vips::version_string # libvips has this arbitrary number as a sanity-check upper bound on image # size. It's sometimes useful for know whan calculating image ratios. MAX_COORD = 10000000 end require 'vips/object' require 'vips/operation' require 'vips/image' require 'vips/interpolate' require 'vips/version'
add font Font Noto Sans Old Italic class FontNotoSansOldItalic < Cask version 'latest' sha256 :no_check url 'https://www.google.com/get/noto/pkgs/NotoSansOldItalic-unhinted.zip' homepage 'http://www.google.com/get/noto' font 'NotoSansOldItalic-Regular.ttf' end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/puppet-parse/version', __FILE__) if ENV.key?('PUPPET_VERSION') puppetversion = "= #{ENV['PUPPET_VERSION']}" else puppetversion = ['>= 2.7', '< 3.0'] end Gem::Specification.new do |gem| gem.authors = ["Johan van den Dorpe"] gem.email = ["johan.vandendorpe@gmail.com"] gem.description = %q{Parse Puppet modules for classes, defines, parameters and documentation} gem.summary = %q{Parser for Puppet Modules. Returns Information about available classes and defines, their parameters, and documentation for those parameters.} gem.homepage = "" gem.files = `git ls-files`.split($\) gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) gem.name = "puppet-parse" gem.require_paths = ["lib"] gem.version = PuppetParse::VERSION gem.add_development_dependency "rspec" gem.add_development_dependency "rake" gem.add_runtime_dependency "rdoc" gem.add_runtime_dependency "puppet", puppetversion end set homepage [skip ci] # -*- encoding: utf-8 -*- require File.expand_path('../lib/puppet-parse/version', __FILE__) if ENV.key?('PUPPET_VERSION') puppetversion = "= #{ENV['PUPPET_VERSION']}" else puppetversion = ['>= 2.7', '< 3.0'] end Gem::Specification.new do |gem| gem.authors = ["Johan van den Dorpe"] gem.email = ["johan.vandendorpe@gmail.com"] gem.description = %q{Parse Puppet modules for classes, defines, parameters and documentation} gem.summary = %q{Parser for Puppet Modules. Returns Information about available classes and defines, their parameters, and documentation for those parameters.} gem.homepage = "https://github.com/johanek/puppet-parse" 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 = "puppet-parse" gem.require_paths = ["lib"] gem.version = PuppetParse::VERSION gem.add_development_dependency "rspec" gem.add_development_dependency "rake" gem.add_runtime_dependency "rdoc" gem.add_runtime_dependency "puppet", puppetversion end
Committing first version of Wait class. require 'timeout' # Executes a block until there's a result that's not nil or false. # # Wait.for { rand(2).zero? } # => Rescued exception while waiting: Wait::Error: result was false # => Attempt 1/5 failed, delaying for 0.5s # => Rescued exception while waiting: Wait::Error: result was false # => Attempt 2/5 failed, delaying for 1.0s # => true # # By default, all exceptions are rescued. # # Wait.for do # if rand(2).zero? # true # else # raise Exception # end # end # => Rescued exception while waiting: Exception: Exception # => Attempt 1/5 failed, delaying for 0.5s # => true # # The attempt counter is passed to the block if special conditionals are # needed. # # Wait.for(:attempts => 3) { |attempt| puts Time.now if attempt == 3 } # => Rescued exception while waiting: Wait::Error: result was nil # => Attempt 1/3 failed, delaying for 0.5s # => Rescued exception while waiting: Wait::Error: result was nil # => Attempt 2/3 failed, delaying for 1.0s # => Sun Apr 29 10:03:17 -0400 2012 # => Rescued exception while waiting: Wait::Error: result was nil # => Wait::Error: 3/3 attempts failed # # ==== Supported Options # [:attempts] # Number of times to attempt the block. Default is 5. # [:timeout] # Seconds the block is permitted to execute. Default is 15. # [:delay] # Initial (grows exponentially) number of seconds to wait in between # attempts. Default is 0.5. # [:exceptions] # Array of exceptions to rescue. Default is +Exception+ (all exceptions). # [:silent] # If +true+, silences output. Default is +false+. class Wait def self.for(options = {}) attempts = options[:attempts] || 5 timeout = options[:timeout] || 15 delay = options[:delay] || 0.5 exceptions = options[:rescue] || Exception silent = options[:silent] || false # Prevent accidentally causing an infinite loop. unless attempts.is_a?(Fixnum) && attempts > 0 raise ArgumentError, 'invalid number of attempts' end # Initialize the attempt counter. attempt = 0 begin attempt += 1 result = Timeout.timeout(timeout) { yield attempt } result ? result : raise(Wait::Error, "result was #{result.inspect}") rescue Wait::Error, *exceptions => exception unless silent puts "Rescued exception while waiting: #{exception.class.name}: #{exception.message}" puts exception.backtrace.join("\n") end if attempt == attempts raise Wait::Error, "#{attempt}/#{attempts} attempts failed" else puts "Attempt #{attempt}/#{attempts} failed, delaying for #{delay}s" unless silent sleep delay *= 2 retry end end end #for class Error < StandardError; end end #Wait
cask 'mongodb-compass-community' do version '1.14.6' sha256 '6b68e74518dab8c4c018cbd0637266b133db2b042f9e1c9a1c98498ab3c11e7e' url "https://downloads.mongodb.com/compass/mongodb-compass-community-#{version}-darwin-x64.dmg" name 'MongoDB Compass Community' homepage 'https://www.mongodb.com/products/compass' app 'MongoDB Compass Community.app' end Update mongodb-compass-community to 1.15.2 (#52122) cask 'mongodb-compass-community' do version '1.15.2' sha256 'cc916d7421f88080b4b90342326709a71c494e72d8549e4156886ed40bfd7d3e' url "https://downloads.mongodb.com/compass/mongodb-compass-community-#{version}-darwin-x64.dmg" name 'MongoDB Compass Community' homepage 'https://www.mongodb.com/products/compass' app 'MongoDB Compass Community.app' end
# This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20100721172138) do create_table "accesses", :force => true do |t| t.integer "accessor_id", :null => false t.string "accessor_type", :limit => 100, :default => "", :null => false t.integer "accessable_id", :null => false t.string "accessable_type", :limit => 100, :default => "", :null => false t.integer "permission_id", :null => false end add_index "accesses", ["accessable_id", "accessable_type"], :name => "index_accesses_on_accessable_id_and_accessable_type" add_index "accesses", ["accessor_id", "accessor_type"], :name => "index_accesses_on_accessor_id_and_accessor_type" create_table "account_groups", :force => true do |t| t.integer "account_id", :null => false t.integer "group_id", :null => false end add_index "account_groups", ["account_id", "group_id"], :name => "account_groups_index" create_table "accounts", :force => true do |t| t.string "login" t.string "email" t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token" t.datetime "remember_token_expires_at" t.string "name", :limit => 100, :default => "" end add_index "accounts", ["login"], :name => "index_accounts_on_login", :unique => true create_table "applications", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "short_name", :limit => 10, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false t.integer "project_id", :null => false end add_index "applications", ["project_id"], :name => "index_applications_on_project_id" add_index "applications", ["short_name"], :name => "index_applications_on_short_name", :unique => true create_table "clients", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "short_name", :limit => 10, :default => "", :null => false end add_index "clients", ["name"], :name => "index_clients_on_name", :unique => true add_index "clients", ["short_name"], :name => "index_clients_on_short_name", :unique => true create_table "deploy_processes", :force => true do |t| t.integer "deploy_id", :null => false t.integer "environment_id", :null => false t.datetime "created_at", :null => false end add_index "deploy_processes", ["deploy_id"], :name => "deploy_environment", :unique => true add_index "deploy_processes", ["environment_id"], :name => "unique_environment", :unique => true create_table "deploys", :force => true do |t| t.datetime "deployed_at", :null => false t.datetime "updated_at", :null => false t.boolean "is_running", :null => false t.boolean "is_success", :null => false t.integer "environment_id", :null => false t.string "log_file", :limit => 200, :default => "", :null => false t.datetime "completed_at" t.string "version", :limit => 200, :default => "" t.text "note" t.string "path" t.integer "deployed_by_id" end add_index "deploys", ["environment_id"], :name => "index_deploys_on_environment_id" add_index "deploys", ["log_file"], :name => "index_deploys_on_log_file", :unique => true create_table "environment_parameters", :force => true do |t| t.string "name", :limit => 200, :default => "", :null => false t.text "value", :null => false t.integer "environment_id", :null => false t.boolean "is_private", :default => false, :null => false end add_index "environment_parameters", ["environment_id"], :name => "index_environment_parameters_on_environment_id" create_table "environment_templates", :force => true do |t| t.string "name" t.string "include" t.integer "environment_id" end create_table "environments", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "deployment_mode", :limit => 100, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false t.boolean "is_production", :default => false, :null => false t.integer "app_id" end add_index "environments", ["name"], :name => "index_environments_on_name_and_id", :unique => true create_table "groups", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false end create_table "permissions", :force => true do |t| t.string "name", :limit => 20, :default => "", :null => false end create_table "projects", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "short_name", :limit => 10, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false t.integer "client_id", :null => false end add_index "projects", ["client_id"], :name => "index_projects_on_client_id" add_index "projects", ["name"], :name => "index_projects_on_name", :unique => true end updated schema # This file is auto-generated from the current state of the database. Instead of editing this file, # please use the migrations feature of Active Record to incrementally modify your database, and # then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your database schema. If you need # to create the application database on another system, you should be using db:schema:load, not running # all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. ActiveRecord::Schema.define(:version => 20100819192940) do create_table "accesses", :force => true do |t| t.integer "accessor_id", :null => false t.string "accessor_type", :limit => 100, :default => "", :null => false t.integer "accessable_id", :null => false t.string "accessable_type", :limit => 100, :default => "", :null => false t.integer "permission_id", :null => false end add_index "accesses", ["accessable_id", "accessable_type"], :name => "index_accesses_on_accessable_id_and_accessable_type" add_index "accesses", ["accessor_id", "accessor_type"], :name => "index_accesses_on_accessor_id_and_accessor_type" create_table "account_groups", :force => true do |t| t.integer "account_id", :null => false t.integer "group_id", :null => false end add_index "account_groups", ["account_id", "group_id"], :name => "account_groups_index" create_table "accounts", :force => true do |t| t.string "login" t.string "email" t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token" t.datetime "remember_token_expires_at" t.string "name", :limit => 100, :default => "" end add_index "accounts", ["login"], :name => "index_accounts_on_login", :unique => true create_table "applications", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "short_name", :limit => 10, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false t.integer "project_id", :null => false end add_index "applications", ["project_id"], :name => "index_applications_on_project_id" add_index "applications", ["short_name"], :name => "index_applications_on_short_name", :unique => true create_table "clients", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "short_name", :limit => 10, :default => "", :null => false end add_index "clients", ["name"], :name => "index_clients_on_name", :unique => true add_index "clients", ["short_name"], :name => "index_clients_on_short_name", :unique => true create_table "deploy_processes", :force => true do |t| t.integer "deploy_id", :null => false t.integer "environment_id", :null => false t.datetime "created_at", :null => false end add_index "deploy_processes", ["deploy_id"], :name => "deploy_environment", :unique => true add_index "deploy_processes", ["environment_id"], :name => "unique_environment", :unique => true create_table "deploys", :force => true do |t| t.datetime "deployed_at", :null => false t.datetime "updated_at", :null => false t.boolean "is_running", :null => false t.boolean "is_success", :null => false t.integer "environment_id", :null => false t.string "log_file", :limit => 200, :default => "", :null => false t.datetime "completed_at" t.string "version", :limit => 200, :default => "" t.text "note" t.string "path" t.integer "deployed_by_id" end add_index "deploys", ["environment_id"], :name => "index_deploys_on_environment_id" add_index "deploys", ["log_file"], :name => "index_deploys_on_log_file", :unique => true create_table "environment_parameters", :force => true do |t| t.string "name", :limit => 200, :default => "", :null => false t.text "value", :null => false t.integer "environment_id", :null => false t.boolean "is_private", :default => false, :null => false end add_index "environment_parameters", ["environment_id"], :name => "index_environment_parameters_on_environment_id" create_table "environment_templates", :force => true do |t| t.string "name" t.string "include" t.integer "environment_id" end create_table "environments", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "deployment_mode", :limit => 100, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false t.boolean "is_production", :default => false, :null => false t.integer "app_id" end add_index "environments", ["name"], :name => "index_environments_on_name_and_id", :unique => true create_table "groups", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false end create_table "permissions", :force => true do |t| t.string "name", :limit => 20, :default => "", :null => false end create_table "projects", :force => true do |t| t.string "name", :limit => 50, :default => "", :null => false t.string "short_name", :limit => 10, :default => "", :null => false t.string "desc", :limit => 200, :default => "", :null => false t.integer "client_id", :null => false end add_index "projects", ["client_id"], :name => "index_projects_on_client_id" end
cask 'virtualbox-extension-pack' do version '5.2.12,122591' sha256 '4c36d129f17dcab2bb37292022f1b1adfefa5f32a3161b0d5d40784bc8acf4d0' url "https://download.virtualbox.org/virtualbox/#{version.before_comma}/Oracle_VM_VirtualBox_Extension_Pack-#{version.before_comma}-#{version.after_comma}.vbox-extpack" appcast 'https://download.virtualbox.org/virtualbox/LATEST.TXT' name 'Oracle VirtualBox Extension Pack' homepage 'https://www.virtualbox.org/' depends_on cask: 'virtualbox' container type: :naked stage_only true postflight do system_command '/usr/local/bin/VBoxManage', args: [ 'extpack', 'install', '--replace', "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version.before_comma}-#{version.after_comma}.vbox-extpack" ], input: 'y', sudo: true end uninstall_postflight do next unless File.exist?('/usr/local/bin/VBoxManage') system_command '/usr/local/bin/VBoxManage', args: [ 'extpack', 'uninstall', 'Oracle VM VirtualBox Extension Pack' ], sudo: true end caveats do license 'https://www.virtualbox.org/wiki/VirtualBox_PUEL' end end Update virtualbox-extension-pack to 5.2.14,123301 (#49196) cask 'virtualbox-extension-pack' do version '5.2.14,123301' sha256 'd90c1b0c89de19010f7c7fe7a675ac744067baf29a9966b034e97b5b2053b37e' url "https://download.virtualbox.org/virtualbox/#{version.before_comma}/Oracle_VM_VirtualBox_Extension_Pack-#{version.before_comma}-#{version.after_comma}.vbox-extpack" appcast 'https://download.virtualbox.org/virtualbox/LATEST.TXT' name 'Oracle VirtualBox Extension Pack' homepage 'https://www.virtualbox.org/' depends_on cask: 'virtualbox' container type: :naked stage_only true postflight do system_command '/usr/local/bin/VBoxManage', args: [ 'extpack', 'install', '--replace', "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version.before_comma}-#{version.after_comma}.vbox-extpack" ], input: 'y', sudo: true end uninstall_postflight do next unless File.exist?('/usr/local/bin/VBoxManage') system_command '/usr/local/bin/VBoxManage', args: [ 'extpack', 'uninstall', 'Oracle VM VirtualBox Extension Pack' ], sudo: true end caveats do license 'https://www.virtualbox.org/wiki/VirtualBox_PUEL' end end
cask 'virtualbox-extension-pack' do version '5.0.16-105871' sha256 'c234e158c49f4f92c38e41918c117d756a81236ff1030a896e44faf88284ecc7' url "http://download.virtualbox.org/virtualbox/#{version.sub(%r{-.*}, '')}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" name 'Oracle VirtualBox Extension Pack' homepage 'https://www.virtualbox.org' license :closed depends_on cask: 'virtualbox' container type: :naked stage_only true postflight do system 'sudo', 'VBoxManage', 'extpack', 'install', '--replace', "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" end uninstall_postflight do system 'sudo', 'VBoxManage', 'extpack', 'uninstall', 'Oracle VM VirtualBox Extension Pack' end end updated virtualbox-extension-pack (5.0.18-106667) (#20645) cask 'virtualbox-extension-pack' do version '5.0.18-106667' sha256 '1ccc48d457d1ee568166066df025f6cf82b6dde1ddc993c9bea1fe7abbe255ef' url "http://download.virtualbox.org/virtualbox/#{version.sub(%r{-.*}, '')}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" name 'Oracle VirtualBox Extension Pack' homepage 'https://www.virtualbox.org' license :closed depends_on cask: 'virtualbox' container type: :naked stage_only true postflight do system 'sudo', 'VBoxManage', 'extpack', 'install', '--replace', "#{staged_path}/Oracle_VM_VirtualBox_Extension_Pack-#{version}.vbox-extpack" end uninstall_postflight do system 'sudo', 'VBoxManage', 'extpack', 'uninstall', 'Oracle VM VirtualBox Extension Pack' end end
$repos = [ 'TRAVIS_REPO_ANTWEB', 'TRAVIS_REPO_ECOENGINE', 'TRAVIS_REPO_ELASTIC', 'TRAVIS_REPO_GIT2R', 'TRAVIS_REPO_PALEOBIODB', 'TRAVIS_REPO_RALTMETRIC', 'TRAVIS_REPO_RBHL', 'TRAVIS_REPO_RBISON', 'TRAVIS_REPO_REBIRD', 'TRAVIS_REPO_RENTREZ', 'TRAVIS_REPO_RFIGSHARE', 'TRAVIS_REPO_RFISHBASE', 'TRAVIS_REPO_RFISHERIES', 'TRAVIS_REPO_RGBIF', 'TRAVIS_REPO_RINAT', 'TRAVIS_REPO_RNEXML', 'TRAVIS_REPO_RNOAA', 'TRAVIS_REPO_RPLOS', 'TRAVIS_REPO_RSNPS', 'TRAVIS_REPO_RWBCLIMATE', 'TRAVIS_REPO_SPOCC', 'TRAVIS_REPO_TAXIZE', 'TRAVIS_REPO_TESTDAT', 'TRAVIS_REPO_TREEBASE', 'TRAVIS_REPO_BOLD', 'TRAVIS_REPO_RNPN', 'TRAVIS_REPO_PLOTLY', 'TRAVIS_REPO_RCROSSREF', 'TRAVIS_REPO_RGLOBI', 'TRAVIS_REPO_RSELENIUM', 'TRAVIS_REPO_EML', 'TRAVIS_REPO_DVN', 'TRAVIS_REPO_RDATACITE', 'TRAVIS_REPO_GEONAMES', 'TRAVIS_REPO_NEOTOMA', 'TRAVIS_REPO_OTS', 'TRAVIS_REPO_FULLTEXT', 'TRAVIS_REPO_GISTR', 'TRAVIS_REPO_GENDER', 'TRAVIS_REPO_RORCID', 'TRAVIS_REPO_BMC', 'TRAVIS_REPO_ARXIV', 'TRAVIS_REPO_CKANR', 'TRAVIS_REPO_CLIFRO', 'TRAVIS_REPO_DASHBOARD', 'TRAVIS_REPO_DEPENDENCIES', 'TRAVIS_REPO_FLORAS', 'TRAVIS_REPO_MUSEMETA', 'TRAVIS_REPO_PANGAEAR', 'TRAVIS_REPO_PLEIADES', 'TRAVIS_REPO_RDPLA', 'TRAVIS_REPO_REOL', 'TRAVIS_REPO_RERDDAP', 'TRAVIS_REPO_REUROPEANA', 'TRAVIS_REPO_RMETADATA', 'TRAVIS_REPO_RNBN', 'TRAVIS_REPO_TRAITS', 'TRAVIS_REPO_USABOUNDARIES', 'TRAVIS_REPO_HATHI', 'TRAVIS_REPO_RIF', 'TRAVIS_REPO_RDOPA', 'TRAVIS_REPO_ETSEED', 'TRAVIS_REPO_RVERTNET', 'TRAVIS_REPO_WELLKNOWN', 'TRAVIS_REPO_HELMINTHR', 'TRAVIS_REPO_FINCH', 'TRAVIS_REPO_BINOMEN', 'TRAVIS_REPO_CHROMER', 'TRAVIS_REPO_IEEER', 'TRAVIS_REPO_CSL', 'TRAVIS_REPO_ELASTICDSL', 'TRAVIS_REPO_GEOJSONIO', 'TRAVIS_REPO_LAWN', 'TRAVIS_REPO_PROJ', 'TRAVIS_REPO_RCRYPTSY', 'TRAVIS_REPO_WEBCHEM', 'TRAVIS_REPO_JQR', 'TRAVIS_REPO_INTERNETARCHIVE', 'TRAVIS_REPO_RDRYAD', 'TRAVIS_REPO_ZENODO', 'TRAVIS_REPO_RRLITE', 'TRAVIS_REPO_REDISAPI', 'TRAVIS_REPO_OPENCONTEXT', 'TRAVIS_REPO_ROTL', 'TRAVIS_REPO_USABOUNDARIESDATA', 'TRAVIS_REPO_MAPR', 'TRAVIS_REPO_RUSDA', 'TRAVIS_REPO_RSTARS', 'TRAVIS_REPO_SOFA', 'TRAVIS_REPO_GENDERDATA', 'TRAVIS_REPO_RDAT', 'TRAVIS_REPO_FISHBASEAPI', 'TRAVIS_REPO_TEXTREUSE', 'TRAVIS_REPO_STPLANR', 'TRAVIS_REPO_BRRANCHING', 'TRAVIS_REPO_OAI', 'TRAVIS_REPO_SOLRIUM', 'TRAVIS_REPO_RGEOSPATIALQUALITY', 'TRAVIS_REPO_GEOOPS', 'TRAVIS_REPO_VCR', 'TRAVIS_REPO_GEOJSONLINT', 'TRAVIS_REPO_GEOJSON', 'TRAVIS_REPO_GDOC', 'TRAVIS_REPO_ATOMIZE', 'TRAVIS_REPO_CORED', 'TRAVIS_REPO_ASPACER', 'TRAVIS_REPO_APIPKGEN', 'TRAVIS_REPO_ENIGMA', 'TRAVIS_REPO_RSUNLIGHT', 'TRAVIS_REPO_RTIMES', 'TRAVIS_REPO_PYTAXIZE', 'TRAVIS_REPO_HTTSNAP', 'TRAVIS_REPO_ANALOGSEA', 'TRAVIS_REPO_CANADIANA', 'TRAVIS_REPO_HTTPING', 'TRAVIS_REPO_COWSAY', 'TRAVIS_REPO_DISCGOLF', 'TRAVIS_REPO_HTTPCODE', 'TRAVIS_REPO_SERRANO', 'TRAVIS_REPO_EXTRACTR', 'TRAVIS_REPO_TEXTMINER', 'TRAVIS_REPO_RPHYLOPIC', 'TRAVIS_REPO_OPENADDS', 'TRAVIS_REPO_HABANERO', 'TRAVIS_REPO_PYGBIF', 'TRAVIS_REPO_PYOBIS', 'TRAVIS_REPO_DAPPR', 'TRAVIS_REPO_INIR', 'TRAVIS_REPO_RJSONAPI', 'TRAVIS_REPO_REQUEST', 'TRAVIS_REPO_SPENV', 'TRAVIS_REPO_SPPLIT', 'TRAVIS_REPO_GEOAXE', 'TRAVIS_REPO_SCRUBR', 'TRAVIS_REPO_MREGIONS', 'TRAVIS_REPO_SPPLIST', 'TRAVIS_REPO_SPLISTER', 'TRAVIS_REPO_GETLANDSAT', 'TRAVIS_REPO_RREDLIST', 'TRAVIS_REPO_RWDPA', 'TRAVIS_REPO_ORIGINR', 'TRAVIS_REPO_DIRDF', 'TRAVIS_REPO_EECHIDNA', 'TRAVIS_REPO_HISTORYDATA', 'TRAVIS_REPO_HUNSPELL', 'TRAVIS_REPO_JSONVALIDATE', 'TRAVIS_REPO_OPENCAGE', 'TRAVIS_REPO_ROBOTSTXT', 'TRAVIS_REPO_ROPENAQ', 'TRAVIS_REPO_TAXA', 'TRAVIS_REPO_URLTEMPLATE', 'TRAVIS_REPO_CCAFS', 'TRAVIS_REPO_CMIP', 'TRAVIS_REPO_CONVERTR', 'TRAVIS_REPO_GUTENBERGR', 'TRAVIS_REPO_OSMPLOTR' ] added riem to pkg restarts $repos = [ 'TRAVIS_REPO_ANTWEB', 'TRAVIS_REPO_ECOENGINE', 'TRAVIS_REPO_ELASTIC', 'TRAVIS_REPO_GIT2R', 'TRAVIS_REPO_PALEOBIODB', 'TRAVIS_REPO_RALTMETRIC', 'TRAVIS_REPO_RBHL', 'TRAVIS_REPO_RBISON', 'TRAVIS_REPO_REBIRD', 'TRAVIS_REPO_RENTREZ', 'TRAVIS_REPO_RFIGSHARE', 'TRAVIS_REPO_RFISHBASE', 'TRAVIS_REPO_RFISHERIES', 'TRAVIS_REPO_RGBIF', 'TRAVIS_REPO_RINAT', 'TRAVIS_REPO_RNEXML', 'TRAVIS_REPO_RNOAA', 'TRAVIS_REPO_RPLOS', 'TRAVIS_REPO_RSNPS', 'TRAVIS_REPO_RWBCLIMATE', 'TRAVIS_REPO_SPOCC', 'TRAVIS_REPO_TAXIZE', 'TRAVIS_REPO_TESTDAT', 'TRAVIS_REPO_TREEBASE', 'TRAVIS_REPO_BOLD', 'TRAVIS_REPO_RNPN', 'TRAVIS_REPO_PLOTLY', 'TRAVIS_REPO_RCROSSREF', 'TRAVIS_REPO_RGLOBI', 'TRAVIS_REPO_RSELENIUM', 'TRAVIS_REPO_EML', 'TRAVIS_REPO_DVN', 'TRAVIS_REPO_RDATACITE', 'TRAVIS_REPO_GEONAMES', 'TRAVIS_REPO_NEOTOMA', 'TRAVIS_REPO_OTS', 'TRAVIS_REPO_FULLTEXT', 'TRAVIS_REPO_GISTR', 'TRAVIS_REPO_GENDER', 'TRAVIS_REPO_RORCID', 'TRAVIS_REPO_BMC', 'TRAVIS_REPO_ARXIV', 'TRAVIS_REPO_CKANR', 'TRAVIS_REPO_CLIFRO', 'TRAVIS_REPO_DASHBOARD', 'TRAVIS_REPO_DEPENDENCIES', 'TRAVIS_REPO_FLORAS', 'TRAVIS_REPO_MUSEMETA', 'TRAVIS_REPO_PANGAEAR', 'TRAVIS_REPO_PLEIADES', 'TRAVIS_REPO_RDPLA', 'TRAVIS_REPO_REOL', 'TRAVIS_REPO_RERDDAP', 'TRAVIS_REPO_REUROPEANA', 'TRAVIS_REPO_RMETADATA', 'TRAVIS_REPO_RNBN', 'TRAVIS_REPO_TRAITS', 'TRAVIS_REPO_USABOUNDARIES', 'TRAVIS_REPO_HATHI', 'TRAVIS_REPO_RIF', 'TRAVIS_REPO_RDOPA', 'TRAVIS_REPO_ETSEED', 'TRAVIS_REPO_RVERTNET', 'TRAVIS_REPO_WELLKNOWN', 'TRAVIS_REPO_HELMINTHR', 'TRAVIS_REPO_FINCH', 'TRAVIS_REPO_BINOMEN', 'TRAVIS_REPO_CHROMER', 'TRAVIS_REPO_IEEER', 'TRAVIS_REPO_CSL', 'TRAVIS_REPO_ELASTICDSL', 'TRAVIS_REPO_GEOJSONIO', 'TRAVIS_REPO_LAWN', 'TRAVIS_REPO_PROJ', 'TRAVIS_REPO_RCRYPTSY', 'TRAVIS_REPO_WEBCHEM', 'TRAVIS_REPO_JQR', 'TRAVIS_REPO_INTERNETARCHIVE', 'TRAVIS_REPO_RDRYAD', 'TRAVIS_REPO_ZENODO', 'TRAVIS_REPO_RRLITE', 'TRAVIS_REPO_REDISAPI', 'TRAVIS_REPO_OPENCONTEXT', 'TRAVIS_REPO_ROTL', 'TRAVIS_REPO_USABOUNDARIESDATA', 'TRAVIS_REPO_MAPR', 'TRAVIS_REPO_RUSDA', 'TRAVIS_REPO_RSTARS', 'TRAVIS_REPO_SOFA', 'TRAVIS_REPO_GENDERDATA', 'TRAVIS_REPO_RDAT', 'TRAVIS_REPO_FISHBASEAPI', 'TRAVIS_REPO_TEXTREUSE', 'TRAVIS_REPO_STPLANR', 'TRAVIS_REPO_BRRANCHING', 'TRAVIS_REPO_OAI', 'TRAVIS_REPO_SOLRIUM', 'TRAVIS_REPO_RGEOSPATIALQUALITY', 'TRAVIS_REPO_GEOOPS', 'TRAVIS_REPO_VCR', 'TRAVIS_REPO_GEOJSONLINT', 'TRAVIS_REPO_GEOJSON', 'TRAVIS_REPO_GDOC', 'TRAVIS_REPO_ATOMIZE', 'TRAVIS_REPO_CORED', 'TRAVIS_REPO_ASPACER', 'TRAVIS_REPO_APIPKGEN', 'TRAVIS_REPO_ENIGMA', 'TRAVIS_REPO_RSUNLIGHT', 'TRAVIS_REPO_RTIMES', 'TRAVIS_REPO_PYTAXIZE', 'TRAVIS_REPO_HTTSNAP', 'TRAVIS_REPO_ANALOGSEA', 'TRAVIS_REPO_CANADIANA', 'TRAVIS_REPO_HTTPING', 'TRAVIS_REPO_COWSAY', 'TRAVIS_REPO_DISCGOLF', 'TRAVIS_REPO_HTTPCODE', 'TRAVIS_REPO_SERRANO', 'TRAVIS_REPO_EXTRACTR', 'TRAVIS_REPO_TEXTMINER', 'TRAVIS_REPO_RPHYLOPIC', 'TRAVIS_REPO_OPENADDS', 'TRAVIS_REPO_HABANERO', 'TRAVIS_REPO_PYGBIF', 'TRAVIS_REPO_PYOBIS', 'TRAVIS_REPO_DAPPR', 'TRAVIS_REPO_INIR', 'TRAVIS_REPO_RJSONAPI', 'TRAVIS_REPO_REQUEST', 'TRAVIS_REPO_SPENV', 'TRAVIS_REPO_SPPLIT', 'TRAVIS_REPO_GEOAXE', 'TRAVIS_REPO_SCRUBR', 'TRAVIS_REPO_MREGIONS', 'TRAVIS_REPO_SPPLIST', 'TRAVIS_REPO_SPLISTER', 'TRAVIS_REPO_GETLANDSAT', 'TRAVIS_REPO_RREDLIST', 'TRAVIS_REPO_RWDPA', 'TRAVIS_REPO_ORIGINR', 'TRAVIS_REPO_DIRDF', 'TRAVIS_REPO_EECHIDNA', 'TRAVIS_REPO_HISTORYDATA', 'TRAVIS_REPO_HUNSPELL', 'TRAVIS_REPO_JSONVALIDATE', 'TRAVIS_REPO_OPENCAGE', 'TRAVIS_REPO_ROBOTSTXT', 'TRAVIS_REPO_ROPENAQ', 'TRAVIS_REPO_TAXA', 'TRAVIS_REPO_URLTEMPLATE', 'TRAVIS_REPO_CCAFS', 'TRAVIS_REPO_CMIP', 'TRAVIS_REPO_CONVERTR', 'TRAVIS_REPO_GUTENBERGR', 'TRAVIS_REPO_OSMPLOTR', 'TRAVIS_REPO_RIEM' ]
require 'naught' require 'pow' module Yeah include Naught.build { |c| c.black_hole }::Conversions VERSION = '0.2.2' end %i[numeric string].each { |r| require "patch/#{r}" } %i[ utility command vector v color surface rectangle entity basic_physics stage desktop_window game ].each { |r| require "yeah/#{r}" } naught conversions include minor cleanup require 'naught' require 'pow' module Yeah include Naught.build(&:black_hole)::Conversions VERSION = '0.2.2' end %i[numeric string].each { |r| require "patch/#{r}" } %i[ utility command vector v color surface rectangle entity basic_physics stage desktop_window game ].each { |r| require "yeah/#{r}" }
require 'fileutils' require 'erb' require 'net/http' require 'optparse' require 'vendor/gems/environment' Bundler.require_env require 'constants' # load application # Dir["#{APPLICATION_PATH}/*.rb"].each do |path| require path end # load support # Dir["#{APPLICATION_PATH}/support/*.rb"].each do |path| require path end # load everything in the lib directory # Dir["#{BASE_PATH}/lib/**/*.rb"].each do |path| require path unless path == File.expand_path(__FILE__) end require "#{APPLICATION_PATH}/support/file" change ymdp.rb # load application # Dir["lib/application_view/*.rb"].each do |path| require path end # load support # Dir["lib/application_view/support/*.rb"].each do |path| require path end # load everything in the lib directory # Dir["lib/**/*.rb"].each do |path| require path unless path == File.expand_path(__FILE__) end
require "yogi/version" require 'fileutils' require 'json' $file_names = [] $file_names = Dir.glob("app/**/*.rb") + Dir.glob("app/**/*.js") + Dir.glob("app/**/*.css") + Dir.glob("app/**/*.scss") + Dir.glob("app/**/*.erb") + Dir.glob("app/**/*.html") $file_sample = $file_names.sample(5) module Yogi $pre_counted_comma = 0 $pre_counted_semicolon = 0 $pre_counted_l = 0 $pre_counted_3 = 0 $pre_counted_s = 0 $pre_counted_bracket = 0 $pre_counted_px = 0 $pre_diff_comma = 0 $pre_diff_semicolon = 0 $pre_diff_l = 0 $pre_diff_3 = 0 $pre_diff_s = 0 $pre_diff_bracket = 0 $pre_diff_px = 0 class ErrorInside def count_em(text, substring) text.scan(/(?=#{substring})/).count end # creating backup directory def backup FileUtils.mkdir_p '.backupFiles' unless File.exists?('.backupFiles') # puts "created folder backupFiles" #copy backup to backup folder FileUtils.cp_r "./app", ".backupFiles/" # puts "copied files to backupFiles #{$file_names}" # #rename files in backupFiles folder # backup_file_path = "./backupFiles/" # Dir.foreach('./backupFiles') do |item| # next if item == '.' or item == '..' # File.rename(backup_file_path+item, backup_file_path+item +".bak") # end # end end def yogify $file_sample.each do |file_name| text = File.open(file_name, "r"){ |file| file.read }#File.read(file_name) # puts "editing #{$file_sample}" $pre_counted_comma = count_em(text,",") $pre_counted_semicolon = count_em(text,";") $pre_counted_l = count_em(text,"l") $pre_counted_3 = count_em(text,"3") $pre_counted_s = count_em(text,"s") $pre_counted_bracket = count_em(text,"}") $pre_counted_px = count_em(text,"px") pre_count_hash = { file_name => { :"pre_counted_comma" => $pre_counted_comma, :"pre_counted_semicolon" => $pre_counted_semicolon, :"pre_counted_l" => $pre_counted_l, :"pre_counted_3" => $pre_counted_3, :"pre_counted_s" => $pre_counted_s, :"pre_counted_bracket" => $pre_counted_bracket, :"pre_counted_px" => $pre_counted_px }} File.open('.ignoreme.json', "a") {|file| file.write pre_count_hash.to_json} # puts "commas : #{$pre_counted_comma}" # puts "semicolons : #{$pre_counted_semicolon}" # puts "l : #{$pre_counted_l}" # puts "3 : #{$pre_counted_3}" # puts "s : #{$pre_counted_s}" # puts "} : #{$pre_counted_bracket}" # puts "px : #{$pre_counted_px}" #counts total symbols to be effected # pre_total = pre_counted_comma + pre_counted_semicolon + pre_counted_l + pre_counted_3 + pre_counted_s + pre_counted_bracket + pre_counted_px # puts pre_total # To merely print the contents of the file, use: new_contents1 = text.gsub(";"){rand(2).zero? ? ";" : ","} new_contents2 = new_contents1.gsub(","){rand(2).zero? ? "," : ";"} new_contents3 = new_contents2.gsub("l"){rand(2).zero? ? "l" : "1"} new_contents4 = new_contents3.gsub("3"){rand(2).zero? ? "3" : "E"} new_contents5 = new_contents4.gsub("s"){rand(2).zero? ? "s" : "5"} new_contents6 = new_contents5.gsub("}"){rand(2).zero? ? "}" : "]"} new_contents7 = new_contents6.gsub("px"){rand(2).zero? ? "px" : "xp"} # puts new_contents6 # To write changes to the file, use: File.open(file_name, "w") {|file| file.puts new_contents7 } text = File.open(file_name, "r"){ |file| file.read }#File.read(file_name) # puts text #counts ocurences in the file after initial change post_counted_comma = count_em(text,",") post_counted_semicolon = count_em(text,";") post_counted_l = count_em(text,"l") post_counted_3 = count_em(text,"3") post_counted_s = count_em(text,"s") post_counted_bracket = count_em(text,"}") post_counted_px = count_em(text,"px") # puts "commas : #{post_counted_comma}" # puts "semicolons : #{post_counted_semicolon}" # puts "l : #{post_counted_l}" # puts "3 : #{post_counted_3}" # puts "s : #{post_counted_s}" # puts "} : #{post_counted_bracket}" # puts "px : #{post_counted_px}" #counts total symbols to be effected # post_total = post_counted_comma + post_counted_semicolon + post_counted_l + post_counted_3 + post_counted_s + post_counted_bracket + post_counted_px # puts post_total $pre_diff_comma = $pre_counted_comma - post_counted_comma $pre_diff_semicolon = $pre_counted_semicolon - post_counted_semicolon $pre_diff_l = $pre_counted_l - post_counted_l $pre_diff_3 = $pre_counted_3 - post_counted_3 $pre_diff_s = $pre_counted_s - post_counted_s $pre_diff_bracket = $pre_counted_bracket - post_counted_bracket $pre_diff_px = $pre_counted_px - post_counted_px # puts "commas : #{$pre_diff_comma}" # puts "semicolons : #{$pre_diff_semicolon}" # puts "l : #{$pre_diff_l}" # puts "3 : #{$pre_diff_3}" # puts "s : #{$pre_diff_s}" # puts "} : #{$pre_diff_bracket}" # puts "px : #{$pre_diff_px}" end counter_test = IO.readlines(".ignoreme.json")[0] puts "pre_counted_l schould be : #{counter_test}" end end class CheckErrors def count_em(text, substring) text.scan(/(?=#{substring})/).count end def checker puts $pre_diff_comma puts $pre_diff_semicolon puts $pre_diff_l puts $pre_diff_3 puts $pre_diff_s puts $pre_diff_bracket puts $pre_diff_px $file_sample.each do |file_name| text = File.open(file_name, "r"){ |file| file.read }#File.read(file_name) post_counted_comma = count_em(text,",") post_counted_semicolon = count_em(text,";") post_counted_l = count_em(text,"l") post_counted_3 = count_em(text,"3") post_counted_s = count_em(text,"s") post_counted_bracket = count_em(text,"}") post_counted_px = count_em(text,"px") # puts "commas : #{post_counted_comma}" # puts "semicolons : #{post_counted_semicolon}" # puts "l : #{post_counted_l}" # puts "3 : #{post_counted_3}" # puts "s : #{post_counted_s}" # puts "} : #{post_counted_bracket}" # puts "px : #{post_counted_px}" puts ($pre_counted_comma) puts ($pre_counted_semicolon) puts ($pre_counted_l) puts ($pre_counted_3) puts ($pre_counted_s) puts ($pre_counted_bracket) puts ($pre_counted_px) post_diff_comma = $pre_counted_comma - post_counted_comma post_diff_semicolon = $pre_counted_semicolon - post_counted_semicolon post_diff_l = $pre_counted_l - post_counted_l post_diff_3 = $pre_counted_3 - post_counted_3 post_diff_s = $pre_counted_s - post_counted_s post_diff_bracket = $pre_counted_bracket - post_counted_bracket post_diff_px = $pre_counted_px - post_counted_px if $pre_diff_comma == 0 comma_fix = 100 else comma_fix = (($pre_diff_comma - post_diff_comma)/$pre_diff_comma)*100 end puts " #{comma_fix}% of comma errors fixed" if $pre_diff_semicolon == 0 semicolon_fix = 100 else semicolon_fix = (($pre_diff_semicolon - post_diff_semicolon)/$pre_diff_semicolon)*100 end puts " #{semicolon_fix}% of comma errors fixed" if $pre_diff_l == 0 l_fix = 100 else l_fix = (($pre_diff_l - post_diff_l)/$pre_diff_l)*100 end puts " #{l_fix}% of comma errors fixed" if $pre_diff_3 == 0 three_fix = 100 else three_fix = (($pre_diff_3 - post_diff_3)/$pre_diff_3)*100 end puts " #{three_fix}% of comma errors fixed" if $pre_diff_s == 0 s_fix = 100 else s_fix = (($pre_diff_s - post_diff_s)/$pre_diff_s)*100 end puts " #{s_fix}% of comma errors fixed" if $pre_diff_bracket == 0 bracket_fix = 100 else bracket_fix = (($pre_diff_bracket - post_diff_bracket)/$pre_diff_bracket)*100 end puts " #{bracket_fix}% of comma errors fixed" if $pre_diff_px == 0 px_fix = 100 else px_fix = (($pre_diff_px - post_diff_px)/$pre_diff_px)*100 end puts " #{px_fix}% of comma errors fixed" end end end class ErrorOut def undo #undo changes originaly made. Dir.foreach('.backupFiles') do |item| next if item == '.' or item == '..' FileUtils.cp_r ".backupFiles/"+ item, "./" # puts item # FileUtils.cp_r file_names, "backupFiles/" end #removes folder backupFiles FileUtils.rm_r '.backupFiles' FileUtils.rm_r '.ignoreme.json' end end end readability of json require "yogi/version" require 'fileutils' require 'json' $file_names = [] $file_names = Dir.glob("app/**/*.rb") + Dir.glob("app/**/*.js") + Dir.glob("app/**/*.css") + Dir.glob("app/**/*.scss") + Dir.glob("app/**/*.erb") + Dir.glob("app/**/*.html") $file_sample = $file_names.sample(5) module Yogi $pre_counted_comma = 0 $pre_counted_semicolon = 0 $pre_counted_l = 0 $pre_counted_3 = 0 $pre_counted_s = 0 $pre_counted_bracket = 0 $pre_counted_px = 0 $pre_diff_comma = 0 $pre_diff_semicolon = 0 $pre_diff_l = 0 $pre_diff_3 = 0 $pre_diff_s = 0 $pre_diff_bracket = 0 $pre_diff_px = 0 class ErrorInside def count_em(text, substring) text.scan(/(?=#{substring})/).count end # creating backup directory def backup FileUtils.mkdir_p '.backupFiles' unless File.exists?('.backupFiles') # puts "created folder backupFiles" #copy backup to backup folder FileUtils.cp_r "./app", ".backupFiles/" # puts "copied files to backupFiles #{$file_names}" # #rename files in backupFiles folder # backup_file_path = "./backupFiles/" # Dir.foreach('./backupFiles') do |item| # next if item == '.' or item == '..' # File.rename(backup_file_path+item, backup_file_path+item +".bak") # end # end end def yogify $file_sample.each do |file_name| text = File.open(file_name, "r"){ |file| file.read }#File.read(file_name) # puts "editing #{$file_sample}" $pre_counted_comma = count_em(text,",") $pre_counted_semicolon = count_em(text,";") $pre_counted_l = count_em(text,"l") $pre_counted_3 = count_em(text,"3") $pre_counted_s = count_em(text,"s") $pre_counted_bracket = count_em(text,"}") $pre_counted_px = count_em(text,"px") # puts "commas : #{$pre_counted_comma}" # puts "semicolons : #{$pre_counted_semicolon}" # puts "l : #{$pre_counted_l}" # puts "3 : #{$pre_counted_3}" # puts "s : #{$pre_counted_s}" # puts "} : #{$pre_counted_bracket}" # puts "px : #{$pre_counted_px}" #counts total symbols to be effected # pre_total = pre_counted_comma + pre_counted_semicolon + pre_counted_l + pre_counted_3 + pre_counted_s + pre_counted_bracket + pre_counted_px # puts pre_total # To merely print the contents of the file, use: new_contents1 = text.gsub(";"){rand(2).zero? ? ";" : ","} new_contents2 = new_contents1.gsub(","){rand(2).zero? ? "," : ";"} new_contents3 = new_contents2.gsub("l"){rand(2).zero? ? "l" : "1"} new_contents4 = new_contents3.gsub("3"){rand(2).zero? ? "3" : "E"} new_contents5 = new_contents4.gsub("s"){rand(2).zero? ? "s" : "5"} new_contents6 = new_contents5.gsub("}"){rand(2).zero? ? "}" : "]"} new_contents7 = new_contents6.gsub("px"){rand(2).zero? ? "px" : "xp"} # puts new_contents6 # To write changes to the file, use: File.open(file_name, "w") {|file| file.puts new_contents7 } text = File.open(file_name, "r"){ |file| file.read }#File.read(file_name) # puts text #counts ocurences in the file after initial change post_counted_comma = count_em(text,",") post_counted_semicolon = count_em(text,";") post_counted_l = count_em(text,"l") post_counted_3 = count_em(text,"3") post_counted_s = count_em(text,"s") post_counted_bracket = count_em(text,"}") post_counted_px = count_em(text,"px") # puts "commas : #{post_counted_comma}" # puts "semicolons : #{post_counted_semicolon}" # puts "l : #{post_counted_l}" # puts "3 : #{post_counted_3}" # puts "s : #{post_counted_s}" # puts "} : #{post_counted_bracket}" # puts "px : #{post_counted_px}" #counts total symbols to be effected # post_total = post_counted_comma + post_counted_semicolon + post_counted_l + post_counted_3 + post_counted_s + post_counted_bracket + post_counted_px # puts post_total $pre_diff_comma = $pre_counted_comma - post_counted_comma $pre_diff_semicolon = $pre_counted_semicolon - post_counted_semicolon $pre_diff_l = $pre_counted_l - post_counted_l $pre_diff_3 = $pre_counted_3 - post_counted_3 $pre_diff_s = $pre_counted_s - post_counted_s $pre_diff_bracket = $pre_counted_bracket - post_counted_bracket $pre_diff_px = $pre_counted_px - post_counted_px pre_count_hash = { file_name => { :"pre_counted_comma" => $pre_counted_comma, :"pre_counted_semicolon" => $pre_counted_semicolon, :"pre_counted_l" => $pre_counted_l, :"pre_counted_3" => $pre_counted_3, :"pre_counted_s" => $pre_counted_s, :"pre_counted_bracket" => $pre_counted_bracket, :"pre_counted_px" => $pre_counted_px, :"pre_diff_comma" => $pre_diff_comma :"pre_diff_semicolon" => $pre_diff_semicolon :"pre_diff_l" => $pre_diff_l :"pre_diff_3" => $pre_diff_3 :"pre_diff_s" => $pre_diff_s :"pre_diff_bracket" => $pre_diff_bracket :"pre_diff_px" => $pre_diff_px }} File.open('.ignoreme.json', "a") {|file| file.write pre_count_hash.to_json} # puts "commas : #{$pre_diff_comma}" # puts "semicolons : #{$pre_diff_semicolon}" # puts "l : #{$pre_diff_l}" # puts "3 : #{$pre_diff_3}" # puts "s : #{$pre_diff_s}" # puts "} : #{$pre_diff_bracket}" # puts "px : #{$pre_diff_px}" counter_test = IO.readlines(".ignoreme.json")file_name.pre_counted_l puts "pre_counted_l schould be : #{counter_test}" end end end class CheckErrors def count_em(text, substring) text.scan(/(?=#{substring})/).count end def checker puts $pre_diff_comma puts $pre_diff_semicolon puts $pre_diff_l puts $pre_diff_3 puts $pre_diff_s puts $pre_diff_bracket puts $pre_diff_px $file_sample.each do |file_name| text = File.open(file_name, "r"){ |file| file.read }#File.read(file_name) post_counted_comma = count_em(text,",") post_counted_semicolon = count_em(text,";") post_counted_l = count_em(text,"l") post_counted_3 = count_em(text,"3") post_counted_s = count_em(text,"s") post_counted_bracket = count_em(text,"}") post_counted_px = count_em(text,"px") # puts "commas : #{post_counted_comma}" # puts "semicolons : #{post_counted_semicolon}" # puts "l : #{post_counted_l}" # puts "3 : #{post_counted_3}" # puts "s : #{post_counted_s}" # puts "} : #{post_counted_bracket}" # puts "px : #{post_counted_px}" puts ($pre_counted_comma) puts ($pre_counted_semicolon) puts ($pre_counted_l) puts ($pre_counted_3) puts ($pre_counted_s) puts ($pre_counted_bracket) puts ($pre_counted_px) post_diff_comma = $pre_counted_comma - post_counted_comma post_diff_semicolon = $pre_counted_semicolon - post_counted_semicolon post_diff_l = $pre_counted_l - post_counted_l post_diff_3 = $pre_counted_3 - post_counted_3 post_diff_s = $pre_counted_s - post_counted_s post_diff_bracket = $pre_counted_bracket - post_counted_bracket post_diff_px = $pre_counted_px - post_counted_px if $pre_diff_comma == 0 comma_fix = 100 else comma_fix = (($pre_diff_comma - post_diff_comma)/$pre_diff_comma)*100 end puts " #{comma_fix}% of comma errors fixed" if $pre_diff_semicolon == 0 semicolon_fix = 100 else semicolon_fix = (($pre_diff_semicolon - post_diff_semicolon)/$pre_diff_semicolon)*100 end puts " #{semicolon_fix}% of comma errors fixed" if $pre_diff_l == 0 l_fix = 100 else l_fix = (($pre_diff_l - post_diff_l)/$pre_diff_l)*100 end puts " #{l_fix}% of comma errors fixed" if $pre_diff_3 == 0 three_fix = 100 else three_fix = (($pre_diff_3 - post_diff_3)/$pre_diff_3)*100 end puts " #{three_fix}% of comma errors fixed" if $pre_diff_s == 0 s_fix = 100 else s_fix = (($pre_diff_s - post_diff_s)/$pre_diff_s)*100 end puts " #{s_fix}% of comma errors fixed" if $pre_diff_bracket == 0 bracket_fix = 100 else bracket_fix = (($pre_diff_bracket - post_diff_bracket)/$pre_diff_bracket)*100 end puts " #{bracket_fix}% of comma errors fixed" if $pre_diff_px == 0 px_fix = 100 else px_fix = (($pre_diff_px - post_diff_px)/$pre_diff_px)*100 end puts " #{px_fix}% of comma errors fixed" end end end class ErrorOut def undo #undo changes originaly made. Dir.foreach('.backupFiles') do |item| next if item == '.' or item == '..' FileUtils.cp_r ".backupFiles/"+ item, "./" # puts item # FileUtils.cp_r file_names, "backupFiles/" end #removes folder backupFiles FileUtils.rm_r '.backupFiles' FileUtils.rm_r '.ignoreme.json' end end end
require 'zewo/version' require 'thor' require 'json' require 'net/http' require 'uri' require 'fileutils' require 'pathname' require 'xcodeproj' require 'colorize' require 'thread' require 'thwait' def silent_cmd(cmd) system("#{cmd} > /dev/null 2>&1") end module Zewo class App < Thor class Repo attr_reader :name @name = nil attr_reader :data @data = nil @xcodeproj = nil def initialize(name, data = nil) @name = name @data = data end def framework_target target_name = name.gsub('-OSX', '').gsub('-', '_') if target_name == 'OS' target_name = 'OperatingSystem' end xcode_project.native_targets.find { |t| t.name == target_name } || xcode_project.new_target(:framework, target_name, :osx) end def test_target target_name = "#{framework_target.name}-Test" xcode_project.native_targets.find { |t| t.name == target_name } || xcode_project.new_target(:bundle, target_name, :osx) end def dir(ext = nil) r = name r = "#{r}/#{ext}" if ext r end def tests_dirname 'Tests' end def xcode_dirname 'XcodeDevelopment' end def xcode_project_path dir("#{xcode_dirname}/#{name}.xcodeproj") end def sources_dirname return 'Sources' if File.directory?(dir('Sources')) return 'Source' if File.directory?(dir('Source')) end def xcode_project return @xcodeproj if @xcodeproj return Xcodeproj::Project.open(xcode_project_path) if File.exist?(xcode_project_path) Xcodeproj::Project.new(xcode_project_path) end def add_files(direc, current_group, main_target) Dir.glob(direc) do |item| next if item == '.' || item == '.DS_Store' if File.directory?(item) new_folder = File.basename(item) created_group = current_group.new_group(new_folder) add_files("#{item}/*", created_group, main_target) else item = item.split('/')[1..-1].unshift('..') * '/' i = current_group.new_file(item) main_target.add_file_references([i]) if item.include? '.swift' end end end def build_dependencies puts "Configuring dependencies for #{name}".green dependency_repos = File.read(dir('Package.swift')).scan(/(?<=Zewo\/|SwiftX\/|VeniceX\/|paulofaria\/)(.*?)(?=\.git)/).map(&:first) group = xcode_project.new_group('Subprojects') dependency_repos.each do |repo_name| next if repo_name.end_with?('-OSX') repo = Repo.new(repo_name) project_reference = group.new_file(repo.xcode_project_path.to_s) project_reference.path = "../../#{project_reference.path}" framework_target.add_dependency(repo.framework_target) if framework_target end xcode_project.save end def configure_xcode_project @xcodeproj = nil silent_cmd("rm -rf #{dir(xcode_dirname)}") puts "Creating Xcode project #{name}".green framework_target.build_configurations.each do |configuration| framework_target.build_settings(configuration.name)['HEADER_SEARCH_PATHS'] = '/usr/local/include' framework_target.build_settings(configuration.name)['LIBRARY_SEARCH_PATHS'] = '/usr/local/lib' framework_target.build_settings(configuration.name)['ENABLE_TESTABILITY'] = 'YES' if File.exist?(dir('module.modulemap')) framework_target.build_settings(configuration.name)['MODULEMAP_FILE'] = '../module.modulemap' end end framework_target.frameworks_build_phase.clear xcode_project.new_file('../module.modulemap') if File.exist?(dir('module.modulemap')) if sources_dirname group = xcode_project.new_group(sources_dirname) add_files(dir("#{sources_dirname}/*"), group, framework_target) end test_target.resources_build_phase test_target.add_dependency(framework_target) test_target.build_configurations.each do |configuration| test_target.build_settings(configuration.name)['WRAPPER_EXTENSION'] = 'xctest' test_target.build_settings(configuration.name)['LD_RUNPATH_SEARCH_PATHS'] = '$(inherited) @executable_path/../../Frameworks @loader_path/../Frameworks' test_target.build_settings(configuration.name)['HEADER_SEARCH_PATHS'] = '/usr/local/include' test_target.build_settings(configuration.name)['LIBRARY_SEARCH_PATHS'] = '/usr/local/lib' end group = xcode_project.new_group(tests_dirname) add_files(dir("#{tests_dirname}/*"), group, test_target) xcode_project.save scheme = Xcodeproj::XCScheme.new scheme.configure_with_targets(framework_target, test_target) scheme.test_action.code_coverage_enabled = true scheme.save_as(xcode_project.path, framework_target.name, true) end end no_commands do def each_repo uri = URI.parse('https://api.github.com/orgs/Zewo/repos?per_page=200') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) blacklist = ['ZeroMQ'] response = http.request(request) if response.code == '200' result = JSON.parse(response.body).sort_by { |hsh| hsh['name'] } result.each do |doc| next if blacklist.include?(doc['name']) repo = Repo.new(doc['name'], doc) yield repo end else puts 'Error loading repositories'.red end end def each_repo_async threads = [] each_repo do |repo| threads << Thread.new do yield(repo) end end ThreadsWait.all_waits(*threads) end def each_code_repo each_repo do |repo| next unless File.exist?(repo.dir('Package.swift')) yield repo end end def each_code_repo_async threads = [] each_code_repo do |repo| threads << Thread.new do yield(repo) end end ThreadsWait.all_waits(*threads) end def verify_branches last_branch_name = nil each_repo do |repo| branch_name = `cd #{repo.dir}; git rev-parse --abbrev-ref HEAD`.delete("\n") if !last_branch_name.nil? && branch_name != last_branch_name puts "Branch mismatch. Branch of #{repo.name} does not match previous branch #{branch_name}".red return false end last_branch_name = branch_name end true end def prompt(question) printf "#{question} - y/N: " p = STDIN.gets.chomp p == 'y' end def uncommited_changes?(repo_name) !system("cd #{repo_name}; git diff --quiet HEAD") end def master_branch?(repo_name) `cd #{repo_name}; git rev-parse --abbrev-ref HEAD` end def each_osx_whitelisted_repo Zewo::OSX_CODE_REPO_WHITELIST.each do |repo_name| name = repo_name.split('/').last if name.end_with?('-OSX') name = name[0...-4] end repo_data = Hash[ 'name', name, 'organization', repo_name.split('/').first, 'clone_url', "https://github.com/#{repo_name}" ] yield Repo.new(repo_data['name'], repo_data) end end def each_osx_whitelisted_repo_async threads = [] each_osx_whitelisted_repo do |repo| threads << Thread.new do yield(repo) end end ThreadsWait.all_waits(*threads) end def checkout_modulemap_versions repos = ['CLibvenice', 'CURIParser', 'CHTTPParser'] repos.each do |repo| silent_cmd("cd #{repo} && git checkout 0.2.0") puts "Checked out #{repo} at 0.2.0".green end end end desc :status, 'Get status of all repos' def status each_code_repo do |repo| str = repo.name str = uncommited_changes?(repo.name) ? str.red : str.green tag = `cd #{repo.name}; git describe --abbrev=0 --tags` || 'No tag' str += " (#{tag})" puts str.delete("\n") end end desc :tag, 'Tags all code repositories with the given tag. Asks to confirm for each repository' def tag(tag) each_code_repo do |repo| should_tag = prompt("create tag #{tag} in #{repo.name}?") if should_tag silent_cmd("cd #{repo.name} && git tag #{tag}") puts repo.name.green end end end desc :checkout, 'Checks out all code repositories to the latest patch release for the given tag/branch' option :branch option :tag def checkout if !options[:branch] && !options[:tag] puts 'Need to specify either --tag or --branch'.red return end Dir['*/'].each do |folder_name| folder_name = folder_name[0...-1] matched = `cd #{repo.name} && git tag` .split("\n") .select { |t| t.start_with?(options[:tag]) } .last if options[:tag] matched = options[:branch] if options[:branch] if matched silent_cmd("cd #{folder_name} && git checkout #{matched}") puts "Checked out #{folder_name} at #{matched}".green else puts "No matching specifiers for #{folder_name}".red end end end desc :pull, 'git pull on all repos' def pull print "Updating all repositories...\n" each_code_repo_async do |repo| if uncommited_changes?(repo.name) print "Uncommitted changes in #{repo.name}. Not updating.".red + "\n" next end system("cd #{repo.name}; git pull") end puts 'Done!' end desc :make_projects, 'Makes Xcode projects for all modules' def make_projects each_code_repo(&:configure_xcode_project) each_code_repo(&:build_dependencies) end desc :init, 'Clones all Zewo repositories' def init use_ssh = prompt('Clone using SSH?') each_repo_async do |repo| print "Checking #{repo.name}..." + "\n" unless File.directory?(repo.name) print "Cloning #{repo.name}...".green + "\n" silent_cmd("git clone #{repo.data[use_ssh ? 'clone_url' : 'ssh_url']}") end end puts 'Done!' end desc :clone_osx_dev, 'Clones repositories for OSX development' def clone_osx_dev puts 'Cloning repositories...' each_osx_whitelisted_repo_async do |repo| unless File.directory?(repo.name) print "Cloning #{repo.data['organization']}/#{repo.name}...".green + "\n" silent_cmd("git clone #{repo.data['clone_url']}") cloned_name = repo.data['clone_url'].split('/').last if cloned_name.end_with?('-OSX') FileUtils.mv cloned_name, cloned_name[0...-4] end end end end desc :make_osx_dev_projects, 'Makes Xcode projects for OSX development repositories' def make_osx_dev_projects each_osx_whitelisted_repo(&:configure_xcode_project) each_osx_whitelisted_repo(&:build_dependencies) end desc :setup_osx_dev, 'Sets up OSX development environment (clone, checkout, create xcode projects)' option :version, :required => true def setup_osx_dev() clone_osx_dev() invoke 'checkout', [], :tag => options[:version] checkout_modulemap_versions() make_osx_dev_projects() end end OSX_CODE_REPO_WHITELIST = [ # Zewo stuff 'zewo/Base64', 'zewo/BasicAuthMiddleware', 'zewo/ContentNegotiationMiddleware', 'zewo/Data', 'zewo/Event', 'zewo/HTTP', 'zewo/HTTPJSON', 'zewo/HTTPParser', 'zewo/HTTPSerializer', 'zewo/InterchangeData', 'zewo/JSON', 'zewo/JSONMediaType', 'zewo/Log', 'zewo/LogMiddleware', 'zewo/MediaType', 'zewo/Mustache', 'zewo/MySQL', 'zewo/OS', 'zewo/OpenSSL', 'paulofaria/stream', #just for OpenSSL 'zewo/POSIXRegex', 'zewo/PathParameterMiddleware', 'zewo/PostgreSQL', 'zewo/RecoveryMiddleware', 'zewo/RegexRouteMatcher', 'zewo/Router', 'zewo/SQL', 'zewo/Sideburns', 'zewo/String', 'zewo/TrieRouteMatcher', 'zewo/URI', 'zewo/URLEncodedForm', 'zewo/URLEncodedFormMediaType', 'zewo/WebSocket', 'zewo/ZeroMQ', 'zewo/Zewo', # C stuff 'zewo/CHTTPParser', 'zewo/CLibpq-OSX', 'zewo/CMySQL-OSX', 'zewo/COpenSSL-OSX', 'zewo/CURIParser', 'zewo/CZeroMQ', # VeniceX stuff 'venicex/CLibvenice', 'venicex/Venice', 'venicex/IP', 'venicex/TCP', 'venicex/UDP', 'venicex/HTTPServer', 'venicex/HTTPClient', 'venicex/TCPSSL', 'venicex/HTTPSServer', 'venicex/HTTPSClient', 'venicex/File', 'venicex/HTTPFile', 'venicex/ChannelStream', # SwiftX stuff 'swiftx/S4', 'swiftx/C7' ] end Fix typos/bugs require 'zewo/version' require 'thor' require 'json' require 'net/http' require 'uri' require 'fileutils' require 'pathname' require 'xcodeproj' require 'colorize' require 'thread' require 'thwait' def silent_cmd(cmd) system("#{cmd} > /dev/null 2>&1") end module Zewo class App < Thor class Repo attr_reader :name @name = nil attr_reader :data @data = nil @xcodeproj = nil def initialize(name, data = nil) @name = name @data = data end def framework_target target_name = name.gsub('-OSX', '').gsub('-', '_') if target_name == 'OS' target_name = 'OperatingSystem' end xcode_project.native_targets.find { |t| t.name == target_name } || xcode_project.new_target(:framework, target_name, :osx) end def test_target target_name = "#{framework_target.name}-Test" xcode_project.native_targets.find { |t| t.name == target_name } || xcode_project.new_target(:bundle, target_name, :osx) end def dir(ext = nil) r = name r = "#{r}/#{ext}" if ext r end def tests_dirname 'Tests' end def xcode_dirname 'XcodeDevelopment' end def xcode_project_path dir("#{xcode_dirname}/#{name}.xcodeproj") end def sources_dirname return 'Sources' if File.directory?(dir('Sources')) return 'Source' if File.directory?(dir('Source')) end def xcode_project return @xcodeproj if @xcodeproj if File.exist?(xcode_project_path) @xcodeproj = Xcodeproj::Project.open(xcode_project_path) else @xcodeproj = Xcodeproj::Project.new(xcode_project_path) end @xcodeproj end def add_files(direc, current_group, main_target) Dir.glob(direc) do |item| next if item == '.' || item == '.DS_Store' if File.directory?(item) new_folder = File.basename(item) created_group = current_group.new_group(new_folder) add_files("#{item}/*", created_group, main_target) else item = item.split('/')[1..-1].unshift('..') * '/' i = current_group.new_file(item) main_target.add_file_references([i]) if item.include? '.swift' end end end def build_dependencies puts "Configuring dependencies for #{name}".green dependency_repos = File.read(dir('Package.swift')).scan(/(?<=Zewo\/|SwiftX\/|VeniceX\/|paulofaria\/)(.*?)(?=\.git)/).map(&:first) group = xcode_project.new_group('Subprojects') dependency_repos.each do |repo_name| next if repo_name.end_with?('-OSX') repo = Repo.new(repo_name) project_reference = group.new_file(repo.xcode_project_path.to_s) project_reference.path = "../../#{project_reference.path}" framework_target.add_dependency(repo.framework_target) if framework_target end xcode_project.save end def configure_xcode_project @xcodeproj = nil silent_cmd("rm -rf #{dir(xcode_dirname)}") puts "Creating Xcode project #{name}".green framework_target.build_configurations.each do |configuration| framework_target.build_settings(configuration.name)['HEADER_SEARCH_PATHS'] = '/usr/local/include' framework_target.build_settings(configuration.name)['LIBRARY_SEARCH_PATHS'] = '/usr/local/lib' framework_target.build_settings(configuration.name)['ENABLE_TESTABILITY'] = 'YES' if File.exist?(dir('module.modulemap')) framework_target.build_settings(configuration.name)['MODULEMAP_FILE'] = '../module.modulemap' end end framework_target.frameworks_build_phase.clear xcode_project.new_file('../module.modulemap') if File.exist?(dir('module.modulemap')) if sources_dirname group = xcode_project.new_group(sources_dirname) add_files(dir("#{sources_dirname}/*"), group, framework_target) end test_target.resources_build_phase test_target.add_dependency(framework_target) test_target.build_configurations.each do |configuration| test_target.build_settings(configuration.name)['WRAPPER_EXTENSION'] = 'xctest' test_target.build_settings(configuration.name)['LD_RUNPATH_SEARCH_PATHS'] = '$(inherited) @executable_path/../../Frameworks @loader_path/../Frameworks' test_target.build_settings(configuration.name)['HEADER_SEARCH_PATHS'] = '/usr/local/include' test_target.build_settings(configuration.name)['LIBRARY_SEARCH_PATHS'] = '/usr/local/lib' end group = xcode_project.new_group(tests_dirname) add_files(dir("#{tests_dirname}/*"), group, test_target) xcode_project.save scheme = Xcodeproj::XCScheme.new scheme.configure_with_targets(framework_target, test_target) scheme.test_action.code_coverage_enabled = true scheme.save_as(xcode_project.path, framework_target.name, true) end end no_commands do def each_repo uri = URI.parse('https://api.github.com/orgs/Zewo/repos?per_page=200') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) blacklist = ['ZeroMQ'] response = http.request(request) if response.code == '200' result = JSON.parse(response.body).sort_by { |hsh| hsh['name'] } result.each do |doc| next if blacklist.include?(doc['name']) repo = Repo.new(doc['name'], doc) yield repo end else puts 'Error loading repositories'.red end end def each_repo_async threads = [] each_repo do |repo| threads << Thread.new do yield(repo) end end ThreadsWait.all_waits(*threads) end def each_code_repo each_repo do |repo| next unless File.exist?(repo.dir('Package.swift')) yield repo end end def each_code_repo_async threads = [] each_code_repo do |repo| threads << Thread.new do yield(repo) end end ThreadsWait.all_waits(*threads) end def verify_branches last_branch_name = nil each_repo do |repo| branch_name = `cd #{repo.dir}; git rev-parse --abbrev-ref HEAD`.delete("\n") if !last_branch_name.nil? && branch_name != last_branch_name puts "Branch mismatch. Branch of #{repo.name} does not match previous branch #{branch_name}".red return false end last_branch_name = branch_name end true end def prompt(question) printf "#{question} - y/N: " p = STDIN.gets.chomp p == 'y' end def uncommited_changes?(repo_name) !system("cd #{repo_name}; git diff --quiet HEAD") end def master_branch?(repo_name) `cd #{repo_name}; git rev-parse --abbrev-ref HEAD` end def each_osx_whitelisted_repo Zewo::OSX_CODE_REPO_WHITELIST.each do |repo_name| name = repo_name.split('/').last if name.end_with?('-OSX') name = name[0...-4] end repo_data = Hash[ 'name', name, 'organization', repo_name.split('/').first, 'clone_url', "https://github.com/#{repo_name}" ] yield Repo.new(repo_data['name'], repo_data) end end def each_osx_whitelisted_repo_async threads = [] each_osx_whitelisted_repo do |repo| threads << Thread.new do yield(repo) end end ThreadsWait.all_waits(*threads) end def checkout_modulemap_versions repos = ['CLibvenice', 'CURIParser', 'CHTTPParser'] repos.each do |repo| silent_cmd("cd #{repo} && git checkout 0.2.0") puts "Checked out #{repo} at 0.2.0".green end end end desc :status, 'Get status of all repos' def status each_code_repo do |repo| str = repo.name str = uncommited_changes?(repo.name) ? str.red : str.green tag = `cd #{repo.name}; git describe --abbrev=0 --tags` || 'No tag' str += " (#{tag})" puts str.delete("\n") end end desc :tag, 'Tags all code repositories with the given tag. Asks to confirm for each repository' def tag(tag) each_code_repo do |repo| should_tag = prompt("create tag #{tag} in #{repo.name}?") if should_tag silent_cmd("cd #{repo.name} && git tag #{tag}") puts repo.name.green end end end desc :checkout, 'Checks out all code repositories to the latest patch release for the given tag/branch' option :branch option :tag def checkout if !options[:branch] && !options[:tag] puts 'Need to specify either --tag or --branch'.red return end Dir['*/'].each do |folder_name| folder_name = folder_name[0...-1] matched = `cd #{folder_name} && git tag` .split("\n") .select { |t| t.start_with?(options[:tag]) } .last if options[:tag] matched = options[:branch] if options[:branch] if matched silent_cmd("cd #{folder_name} && git checkout #{matched}") puts "Checked out #{folder_name} at #{matched}".green else puts "No matching specifiers for #{folder_name}".red end end end desc :pull, 'git pull on all repos' def pull print "Updating all repositories...\n" each_code_repo_async do |repo| if uncommited_changes?(repo.name) print "Uncommitted changes in #{repo.name}. Not updating.".red + "\n" next end system("cd #{repo.name}; git pull") end puts 'Done!' end desc :make_projects, 'Makes Xcode projects for all modules' def make_projects each_code_repo(&:configure_xcode_project) each_code_repo(&:build_dependencies) end desc :init, 'Clones all Zewo repositories' def init use_ssh = prompt('Clone using SSH?') each_repo_async do |repo| print "Checking #{repo.name}..." + "\n" unless File.directory?(repo.name) print "Cloning #{repo.name}...".green + "\n" silent_cmd("git clone #{repo.data[use_ssh ? 'clone_url' : 'ssh_url']}") end end puts 'Done!' end desc :clone_osx_dev, 'Clones repositories for OSX development' def clone_osx_dev puts 'Cloning repositories...' each_osx_whitelisted_repo_async do |repo| unless File.directory?(repo.name) print "Cloning #{repo.data['organization']}/#{repo.name}...".green + "\n" silent_cmd("git clone #{repo.data['clone_url']}") cloned_name = repo.data['clone_url'].split('/').last if cloned_name.end_with?('-OSX') FileUtils.mv cloned_name, cloned_name[0...-4] end end end end desc :make_osx_dev_projects, 'Makes Xcode projects for OSX development repositories' def make_osx_dev_projects each_osx_whitelisted_repo(&:configure_xcode_project) each_osx_whitelisted_repo(&:build_dependencies) end desc :setup_osx_dev, 'Sets up OSX development environment (clone, checkout, create xcode projects)' option :version, :required => true def setup_osx_dev() clone_osx_dev() invoke 'checkout', [], :tag => options[:version] checkout_modulemap_versions() make_osx_dev_projects() end end OSX_CODE_REPO_WHITELIST = [ # Zewo stuff 'zewo/Base64', 'zewo/BasicAuthMiddleware', 'zewo/ContentNegotiationMiddleware', 'zewo/Data', 'zewo/Event', 'zewo/HTTP', 'zewo/HTTPJSON', 'zewo/HTTPParser', 'zewo/HTTPSerializer', 'zewo/InterchangeData', 'zewo/JSON', 'zewo/JSONMediaType', 'zewo/Log', 'zewo/LogMiddleware', 'zewo/MediaType', 'zewo/Mustache', 'zewo/MySQL', 'zewo/OS', 'zewo/OpenSSL', 'paulofaria/stream', #just for OpenSSL 'zewo/POSIXRegex', 'zewo/PathParameterMiddleware', 'zewo/PostgreSQL', 'zewo/RecoveryMiddleware', 'zewo/RegexRouteMatcher', 'zewo/Router', 'zewo/SQL', 'zewo/Sideburns', 'zewo/String', 'zewo/TrieRouteMatcher', 'zewo/URI', 'zewo/URLEncodedForm', 'zewo/URLEncodedFormMediaType', 'zewo/WebSocket', 'zewo/ZeroMQ', 'zewo/Zewo', # C stuff 'zewo/CHTTPParser', 'zewo/CLibpq-OSX', 'zewo/CMySQL-OSX', 'zewo/COpenSSL-OSX', 'zewo/CURIParser', 'zewo/CZeroMQ', # VeniceX stuff 'venicex/CLibvenice', 'venicex/Venice', 'venicex/IP', 'venicex/TCP', 'venicex/UDP', 'venicex/HTTPServer', 'venicex/HTTPClient', 'venicex/TCPSSL', 'venicex/HTTPSServer', 'venicex/HTTPSClient', 'venicex/File', 'venicex/HTTPFile', 'venicex/ChannelStream', # SwiftX stuff 'swiftx/S4', 'swiftx/C7' ] end
module Zlib class Inflate def self.inflate(data) Compression::ZLib.new.inflate data end end class Deflate def self.deflate(data) Compression::ZLib.new.deflate data end end end Remove (now) generated lib/zlib.rb
# -*- encoding: utf-8 -*- require File.expand_path('../lib/pocket/version', __FILE__) Gem::Specification.new do |s| s.add_development_dependency('sinatra', '~> 1.3.3') s.add_development_dependency('multi_xml') s.add_runtime_dependency('faraday', ['>= 0.7', '< 0.9']) s.add_runtime_dependency('faraday_middleware', '~> 0.8') s.add_runtime_dependency('multi_json', '>= 1.0.3', '~> 1.0') s.add_runtime_dependency('hashie', '>= 0.4.0') s.authors = ["Turadg Aleahmad","Jason Ng PT"] s.description = %q{A Ruby wrapper for the Pocket API v3 (Add, Modify and Retrieve)} s.email = ['turadg@aleahmad.net',"me@jasonngpt.com"] s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.files = `git ls-files`.split("\n") s.homepage = 'https://github.com/turadg/pocket-ruby' s.name = 'pocket-ruby' s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') if s.respond_to? :required_rubygems_version= s.rubyforge_project = s.name s.summary = %q{Ruby wrapper for the Pocket API v3} s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.version = Pocket::VERSION end updated to use faraday >= 0.7 and faraday_middleware ~> 0.9 # -*- encoding: utf-8 -*- require File.expand_path('../lib/pocket/version', __FILE__) Gem::Specification.new do |s| s.add_development_dependency('sinatra', '~> 1.3.3') s.add_development_dependency('multi_xml') s.add_runtime_dependency('faraday', ['>= 0.7']) s.add_runtime_dependency('faraday_middleware', '~> 0.9') s.add_runtime_dependency('multi_json', '>= 1.0.3', '~> 1.0') s.add_runtime_dependency('hashie', '>= 0.4.0') s.authors = ["Turadg Aleahmad","Jason Ng PT"] s.description = %q{A Ruby wrapper for the Pocket API v3 (Add, Modify and Retrieve)} s.email = ['turadg@aleahmad.net',"me@jasonngpt.com"] s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.files = `git ls-files`.split("\n") s.homepage = 'https://github.com/turadg/pocket-ruby' s.name = 'pocket-ruby' s.platform = Gem::Platform::RUBY s.require_paths = ['lib'] s.required_rubygems_version = Gem::Requirement.new('>= 1.3.6') if s.respond_to? :required_rubygems_version= s.rubyforge_project = s.name s.summary = %q{Ruby wrapper for the Pocket API v3} s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.version = Pocket::VERSION end
module PoieticGen class User def initialize id @id = id end end end user: removed file.
require 'csv' headers = [ "Subscriber ID", "Member ID", "Relationship", "Policy ID", "First Name", "Middle Name", "Last Name", "DOB", "SSN", "Plan Name", "HIOS ID", "Carrier Name", "Premium Amount", "Premium Total", "Policy Employer Contribution", "Coverage Start", "Coverage End", "Employer FEIN", "Employer Name" ] congress_feins = %w() emp_ids = Employer.where(:fein => { "$in" => congress_feins }).map(&:id) pols = Policy.where({ :enrollees => {"$elemMatch" => { :rel_code => "self", :coverage_start => {"$gt" => Date.new(2014,12,31)} }}, :employer_id => { "$in" => emp_ids } }) Caches::MongoidCache.allocate(Plan) Caches::MongoidCache.allocate(Carrier) Caches::MongoidCache.allocate(Employer) def format_date(date) return "" if date.blank? date.strftime("%Y-%m-%d") end CSV.open("congressional_audit.csv", "w") do |csv| csv << headers pols.each do |pol| if !pol.canceled? sub = pol.subscriber end_date = Date.new(2015,12,31) if sub.coverage_start.year == 2015 and sub.coverage_end == nil sub.coverage_end = end_date end s_person = pol.subscriber.person s_am = s_person.authority_member s_id = s_person.authority_member.hbx_member_id plan = Caches::MongoidCache.lookup(Plan, pol.plan_id) { pol.plan } carrier = Caches::MongoidCache.lookup(Carrier, plan.carrier_id) { plan.carrier } emp = Caches::MongoidCache.lookup(Employer, pol.employer_id) { pol.employer } # pol.enrollees.each do |en| # if !en.canceled? # per = en.person # mem = per.authority_member csv << [ s_id, s_id, sub.rel_code, pol.eg_id, s_person.name_first, s_person.name_middle, s_person.name_last, s_am.dob, s_am.ssn, plan.name, plan.hios_plan_id, carrier.name, sub.pre_amt, pol.pre_amt_tot, pol.tot_emp_res_amt, format_date(sub.coverage_start), format_date(sub.coverage_end), emp.fein, emp.name ] # end # end end end end Update NFP Audit Report to add end date to 2016 Congressional policies to match NFP report require 'csv' headers = [ "Subscriber ID", "Member ID", "Relationship", "Policy ID", "First Name", "Middle Name", "Last Name", "DOB", "SSN", "Plan Name", "HIOS ID", "Carrier Name", "Premium Amount", "Premium Total", "Policy Employer Contribution", "Coverage Start", "Coverage End", "Employer FEIN", "Employer Name" ] congress_feins = %w() emp_ids = Employer.where(:fein => { "$in" => congress_feins }).map(&:id) pols = Policy.where({ :enrollees => {"$elemMatch" => { :rel_code => "self", :coverage_start => {"$gt" => Date.new(2014,12,31)} }}, :employer_id => { "$in" => emp_ids } }) Caches::MongoidCache.allocate(Plan) Caches::MongoidCache.allocate(Carrier) Caches::MongoidCache.allocate(Employer) def format_date(date) return "" if date.blank? date.strftime("%Y-%m-%d") end CSV.open("congressional_audit.csv", "w") do |csv| csv << headers pols.each do |pol| if !pol.canceled? sub = pol.subscriber end_date = Date.new(2015,12,31) if sub.coverage_start.year == 2015 and sub.coverage_end == nil sub.coverage_end = end_date elsif sub.coverage_start.year == 2016 and sub.coverage_end == nil sub.coverage_end = Date.new(2016,12,31) end s_person = pol.subscriber.person s_am = s_person.authority_member s_id = s_person.authority_member.hbx_member_id plan = Caches::MongoidCache.lookup(Plan, pol.plan_id) { pol.plan } carrier = Caches::MongoidCache.lookup(Carrier, plan.carrier_id) { plan.carrier } emp = Caches::MongoidCache.lookup(Employer, pol.employer_id) { pol.employer } # pol.enrollees.each do |en| # if !en.canceled? # per = en.person # mem = per.authority_member csv << [ s_id, s_id, sub.rel_code, pol.eg_id, s_person.name_first, s_person.name_middle, s_person.name_last, s_am.dob, s_am.ssn, plan.name, plan.hios_plan_id, carrier.name, sub.pre_amt, pol.pre_amt_tot, pol.tot_emp_res_amt, format_date(sub.coverage_start), format_date(sub.coverage_end), emp.fein, emp.name ] # end # end end end end
require 'sinatra' require 'json' require 'octokit' require 'open3' require 'fileutils' #You can write Visual-Basic in any language! set :bind, '0.0.0.0' set :environment, :production # XXX webrick has issues in recent versions accepting non-localhost transfers set :server, :thin set :port, 4567 $ACCESS_TOKEN = ENV['GITTOKEN'] fork = ENV['PX4FORK'] def do_work (command) Open3.popen2e(command) do |stdin, stdout_err, wait_thr| while line = stdout_err.gets puts "OUT> " + line end exit_status = wait_thr.value unless exit_status.success? abort "The command #{command} failed!" end end end def do_clone (srcdir, branch, html_url) puts "do_clone: " + branch system 'mkdir', '-p', srcdir Dir.chdir(srcdir) do #git clone <url> --branch <branch> --single-branch [<folder>] #result = `git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch ` #puts result do_work "git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch" Dir.chdir("Firmware") do #result = `git submodule init && git submodule update` #puts result do_work "git submodule init" do_work "git submodule update" end end end def do_master_merge (srcdir, base_repo, base_branch) puts "do_merge of #{base_repo}/#{base_branch}" Dir.chdir(srcdir + "/Firmware") do do_work "git remote add base_repo #{base_repo}.git" do_work "git fetch base_repo" do_work "git merge base_repo/#{base_branch} -m 'Merged #{base_repo}/#{base_branch} into test branch'" end end def do_build (srcdir) puts "Starting build" Dir.chdir(srcdir+"/Firmware") do =begin result = `git submodule init` puts "********************************** git submodule init *******************************************" puts result result = `git submodule update` puts "********************************** git submodule update *******************************************" puts result result = `git submodule status` puts "********************************** git submodule status *******************************************" puts result result = `make distclean` puts "********************************** make distclean *******************************************" puts result result = `make archives` puts "********************************** make archives *******************************************" puts result result = `make -j6 px4fmu-v2_default` puts "********************************** make -j6 px4fmu-v2_default *******************************************" puts result puts "\n\n**********make upload px4fmu-v2_default aufgerufen************" result = `make upload px4fmu-v2_test` #result = `Tools/px_uploader.py --port /dev/tty.usbmodem1 Images/px4fmu-v2_default.px4` puts "********************************** make upload px4fmu-v2_default *******************************************" puts result =end do_work 'BOARDS="px4fmu-v2 px4io-v2" make archives' do_work "make -j8 px4fmu-v2_test" end end def set_PR_Status (repo, sha, prstatus, description) puts "Access token: " + $ACCESS_TOKEN client = Octokit::Client.new(:access_token => $ACCESS_TOKEN) # XXX replace the URL below with the web server status details URL options = { "state" => prstatus, "target_url" => "http://px4.io/dev/unit_tests", "description" => description, "context" => "continuous-integration/hans-ci" }; puts "Setting commit status on repo: " + repo + " sha: " + sha + " to: " + prstatus + " description: " + description res = client.create_status(repo, sha, prstatus, options) puts res end def fork_hwtest (pr, srcdir, branch, url, full_repo_name, sha) #Starts the hardware test in a subshell pid = Process.fork if pid.nil? then lf = '.lockfile' # XXX put this into a function and check for a free worker # also requires to name directories after the free worker while File.file?(lf) # Keep waiting as long as the lock file exists sleep(1) end # This is the critical section - we might want to lock it # using a 2nd file, or something smarter and proper. # XXX for now, we just bet on timing - yay! FileUtils.touch(lf) # Clean up any mess left behind by a previous potential fail FileUtils.rm_rf(srcdir) # In child #exec "pwd" do_clone srcdir, branch, url if !pr.nil? do_master_merge srcdir, pr['base']['repo']['html_url'], pr['base']['ref'] end do_build srcdir system 'ruby hwtest.rb' puts "HW TEST RESULT:" + $?.exitstatus.to_s if ($?.exitstatus == 0) then set_PR_Status full_repo_name, sha, 'success', 'Hardware test on Pixhawk passed!' else set_PR_Status full_repo_name, sha, 'failed', 'Hardware test on Pixhawk FAILED!' end # Clean up by deleting the work directory FileUtils.rm_rf(srcdir) # We're done - delete lock file FileUtils.rm_rf(lf) # exec "ruby tstsub.rb" else # In parent puts "Worker PID: " + pid.to_s Process.detach(pid) end end # ---------- Routing ------------ get '/' do 'Hello unknown' end get '/payload' do "This URL is intended to be used with POST, not GET" end post '/payload' do body = JSON.parse(request.body.read) github_event = request.env['HTTP_X_GITHUB_EVENT'] case github_event when 'ping' "Hello" when 'pull_request' pr = body["pull_request"] number = body['number'] puts pr['state'] action = body['action'] if (['opened', 'reopened'].include?(action)) sha = pr['head']['sha'] srcdir = sha full_name = pr['base']['repo']['full_name'] ENV['srcdir'] = srcdir puts "Source directory: #{srcdir}" #Set environment vars for sub processes ENV['pushername'] = body['sender']['user'] ENV['pusheremail'] = "lorenz@px4.io" branch = pr['head']['ref'] url = pr['head']['repo']['html_url'] puts "Adding to queue: Pull request: #{number} " + branch + " from "+ url set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest pr, srcdir, branch, url, full_name, sha 'Pull request event queued for testing.' else puts 'Ignoring closing of pull request #' + String(number) end when 'push' branch = body['ref'] if !(body['head_commit'].nil?) && body['head_commit'] != 'null' sha = body['head_commit']['id'] srcdir = sha ENV['srcdir'] = srcdir puts "Source directory: #{$srcdir}" #Set environment vars for sub processes ENV['pushername'] = body ['pusher']['name'] ENV['pusheremail'] = body ['pusher']['email'] a = branch.split('/') branch = a[a.count-1] #last part is the bare branchname puts "Adding to queue: Branch: " + branch + " from "+ body['repository']['html_url'] full_name = body['repository']['full_name'] puts "Full name: " + full_name set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest nil, srcdir, branch, body['repository']['html_url'], full_name, sha 'Push event queued for testing.' end when 'status' puts "Ignoring GH status event" when 'fork' puts 'Ignoring GH fork repo event' when 'delete' puts 'Ignoring GH delete branch event' when 'issue_comment' puts 'Ignoring comments' else puts "Unhandled request:" puts "Envelope: " + JSON.pretty_generate(request.env) puts "JSON: " + JSON.pretty_generate(body) puts "Unknown Event: " + github_event end end Ignore non-useful events require 'sinatra' require 'json' require 'octokit' require 'open3' require 'fileutils' #You can write Visual-Basic in any language! set :bind, '0.0.0.0' set :environment, :production # XXX webrick has issues in recent versions accepting non-localhost transfers set :server, :thin set :port, 4567 $ACCESS_TOKEN = ENV['GITTOKEN'] fork = ENV['PX4FORK'] def do_work (command) Open3.popen2e(command) do |stdin, stdout_err, wait_thr| while line = stdout_err.gets puts "OUT> " + line end exit_status = wait_thr.value unless exit_status.success? abort "The command #{command} failed!" end end end def do_clone (srcdir, branch, html_url) puts "do_clone: " + branch system 'mkdir', '-p', srcdir Dir.chdir(srcdir) do #git clone <url> --branch <branch> --single-branch [<folder>] #result = `git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch ` #puts result do_work "git clone --depth 500 #{html_url}.git --branch #{branch} --single-branch" Dir.chdir("Firmware") do #result = `git submodule init && git submodule update` #puts result do_work "git submodule init" do_work "git submodule update" end end end def do_master_merge (srcdir, base_repo, base_branch) puts "do_merge of #{base_repo}/#{base_branch}" Dir.chdir(srcdir + "/Firmware") do do_work "git remote add base_repo #{base_repo}.git" do_work "git fetch base_repo" do_work "git merge base_repo/#{base_branch} -m 'Merged #{base_repo}/#{base_branch} into test branch'" end end def do_build (srcdir) puts "Starting build" Dir.chdir(srcdir+"/Firmware") do =begin result = `git submodule init` puts "********************************** git submodule init *******************************************" puts result result = `git submodule update` puts "********************************** git submodule update *******************************************" puts result result = `git submodule status` puts "********************************** git submodule status *******************************************" puts result result = `make distclean` puts "********************************** make distclean *******************************************" puts result result = `make archives` puts "********************************** make archives *******************************************" puts result result = `make -j6 px4fmu-v2_default` puts "********************************** make -j6 px4fmu-v2_default *******************************************" puts result puts "\n\n**********make upload px4fmu-v2_default aufgerufen************" result = `make upload px4fmu-v2_test` #result = `Tools/px_uploader.py --port /dev/tty.usbmodem1 Images/px4fmu-v2_default.px4` puts "********************************** make upload px4fmu-v2_default *******************************************" puts result =end do_work 'BOARDS="px4fmu-v2 px4io-v2" make archives' do_work "make -j8 px4fmu-v2_test" end end def set_PR_Status (repo, sha, prstatus, description) puts "Access token: " + $ACCESS_TOKEN client = Octokit::Client.new(:access_token => $ACCESS_TOKEN) # XXX replace the URL below with the web server status details URL options = { "state" => prstatus, "target_url" => "http://px4.io/dev/unit_tests", "description" => description, "context" => "continuous-integration/hans-ci" }; puts "Setting commit status on repo: " + repo + " sha: " + sha + " to: " + prstatus + " description: " + description res = client.create_status(repo, sha, prstatus, options) puts res end def fork_hwtest (pr, srcdir, branch, url, full_repo_name, sha) #Starts the hardware test in a subshell pid = Process.fork if pid.nil? then lf = '.lockfile' # XXX put this into a function and check for a free worker # also requires to name directories after the free worker while File.file?(lf) # Keep waiting as long as the lock file exists sleep(1) end # This is the critical section - we might want to lock it # using a 2nd file, or something smarter and proper. # XXX for now, we just bet on timing - yay! FileUtils.touch(lf) # Clean up any mess left behind by a previous potential fail FileUtils.rm_rf(srcdir) # In child #exec "pwd" do_clone srcdir, branch, url if !pr.nil? do_master_merge srcdir, pr['base']['repo']['html_url'], pr['base']['ref'] end do_build srcdir system 'ruby hwtest.rb' puts "HW TEST RESULT:" + $?.exitstatus.to_s if ($?.exitstatus == 0) then set_PR_Status full_repo_name, sha, 'success', 'Hardware test on Pixhawk passed!' else set_PR_Status full_repo_name, sha, 'failed', 'Hardware test on Pixhawk FAILED!' end # Clean up by deleting the work directory FileUtils.rm_rf(srcdir) # We're done - delete lock file FileUtils.rm_rf(lf) # exec "ruby tstsub.rb" else # In parent puts "Worker PID: " + pid.to_s Process.detach(pid) end end # ---------- Routing ------------ get '/' do 'Hello unknown' end get '/payload' do "This URL is intended to be used with POST, not GET" end post '/payload' do body = JSON.parse(request.body.read) github_event = request.env['HTTP_X_GITHUB_EVENT'] case github_event when 'ping' "Hello" when 'pull_request' pr = body["pull_request"] number = body['number'] puts pr['state'] action = body['action'] if (['opened', 'reopened'].include?(action)) sha = pr['head']['sha'] srcdir = sha full_name = pr['base']['repo']['full_name'] ENV['srcdir'] = srcdir puts "Source directory: #{srcdir}" #Set environment vars for sub processes ENV['pushername'] = body['sender']['user'] ENV['pusheremail'] = "lorenz@px4.io" branch = pr['head']['ref'] url = pr['head']['repo']['html_url'] puts "Adding to queue: Pull request: #{number} " + branch + " from "+ url set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest pr, srcdir, branch, url, full_name, sha 'Pull request event queued for testing.' else puts 'Ignoring closing of pull request #' + String(number) end when 'push' branch = body['ref'] if !(body['head_commit'].nil?) && body['head_commit'] != 'null' sha = body['head_commit']['id'] srcdir = sha ENV['srcdir'] = srcdir puts "Source directory: #{$srcdir}" #Set environment vars for sub processes ENV['pushername'] = body ['pusher']['name'] ENV['pusheremail'] = body ['pusher']['email'] a = branch.split('/') branch = a[a.count-1] #last part is the bare branchname puts "Adding to queue: Branch: " + branch + " from "+ body['repository']['html_url'] full_name = body['repository']['full_name'] puts "Full name: " + full_name set_PR_Status full_name, sha, 'pending', 'Running test on Pixhawk hardware..' fork_hwtest nil, srcdir, branch, body['repository']['html_url'], full_name, sha 'Push event queued for testing.' end when 'status' puts "Ignoring GH status event" when 'fork' puts 'Ignoring GH fork repo event' when 'delete' puts 'Ignoring GH delete branch event' when 'issue_comment' puts 'Ignoring comments' when 'issues' puts 'Ignoring issues' else puts "Unhandled request:" puts "Envelope: " + JSON.pretty_generate(request.env) puts "JSON: " + JSON.pretty_generate(body) puts "Unknown Event: " + github_event end end
#!/usr/bin/env ruby -w # encoding: UTF-8 需要 'Win32接口' module S鼠标 @获取鼠标位置 = Win32接口.新建("GetCursorPos", 'P', 'V', "user32") @设置鼠标位置 = Win32接口.新建("SetCursorPos", 'II', 'V', "user32") @鼠标事件 = Win32接口.新建("mouse_event", 'LLLLL', 'V', "user32") def self.位置 结果 = " " * 8 @获取鼠标位置.请求(结果) 结果.解包("LL") end def self.设置位置(x, y);@设置鼠标位置.请求(x, y) end def self.单击;按下左键;松开左键 end def self.双击;单击;单击 end def self.右键;按下右键;松开右键 end def self.按下左键;@鼠标事件.请求(2,0,0,0,0) end def self.松开左键;@鼠标事件.请求(4,0,0,0,0) end def self.按下右键;@鼠标事件.请求(0x0008,0,0,0,0) end def self.松开右键;@鼠标事件.请求(0x0010,0,0,0,0) end end 修改S鼠标方法 #!/usr/bin/env ruby -w # encoding: UTF-8 需要 'Win32接口' module S鼠标 @获取鼠标位置 = Win32接口.新建("GetCursorPos", 'P', 'V', "user32") @设置鼠标位置 = Win32接口.新建("SetCursorPos", 'II', 'V', "user32") @鼠标事件 = Win32接口.新建("mouse_event", 'LLLLL', 'V', "user32") def self.位置 结果 = " " * 8 @获取鼠标位置.请求(结果) 结果.解包("LL") end def self.移动至(x, y);@设置鼠标位置.请求(x, y) end def self.单击;按下左键;松开左键 end def self.双击;单击;单击 end def self.右键;按下右键;松开右键 end def self.按下左键;@鼠标事件.请求(2,0,0,0,0) end def self.松开左键;@鼠标事件.请求(4,0,0,0,0) end def self.按下右键;@鼠标事件.请求(0x0008,0,0,0,0) end def self.松开右键;@鼠标事件.请求(0x0010,0,0,0,0) end end
# -*- encoding : utf-8 -*- Teacup.handler UIButton, :image do |view, image| view.setImage(image, forState: :normal.uicontrolstate) end Teacup.handler UIButton, :backgroundImage do |view, image| view.setBackgroundImage(image, forState: :normal.uicontrolstate) end Removed unneeded Teacup handlers. These handlers are included in teacup now.
# depends on: module.rb class.rb class Object def to_marshal(ms, strip_ivars = false) out = ms.serialize_extended_object self out << Marshal::TYPE_OBJECT out << ms.serialize(self.class.name.to_sym) out << ms.serialize_instance_variables_suffix(self, true, strip_ivars) end end class Range def to_marshal(ms) super(ms, true) end end class NilClass def to_marshal(ms) Marshal::TYPE_NIL end end class TrueClass def to_marshal(ms) Marshal::TYPE_TRUE end end class FalseClass def to_marshal(ms) Marshal::TYPE_FALSE end end class Class def to_marshal(ms) raise TypeError, "can't dump anonymous class #{self}" if self.name == '' Marshal::TYPE_CLASS + ms.serialize_integer(name.length) + name end end class Module def to_marshal(ms) raise TypeError, "can't dump anonymous module #{self}" if self.name == '' Marshal::TYPE_MODULE + ms.serialize_integer(name.length) + name end end class Symbol def to_marshal(ms) if idx = ms.find_symlink(self) then Marshal::TYPE_SYMLINK + ms.serialize_integer(idx) else ms.add_symlink self str = to_s Marshal::TYPE_SYMBOL + ms.serialize_integer(str.length) + str end end end class String def to_marshal(ms) out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, String) out << Marshal::TYPE_STRING out << ms.serialize_integer(self.length) << self out << ms.serialize_instance_variables_suffix(self) end end class Fixnum def to_marshal(ms) Marshal::TYPE_FIXNUM + ms.serialize_integer(self) end end class Bignum def to_marshal(ms) str = Marshal::TYPE_BIGNUM + (self < 0 ? '-' : '+') cnt = 0 num = self.abs while num != 0 str << ms.to_byte(num) num >>= 8 cnt += 1 end if cnt % 2 == 1 str << "\0" cnt += 1 end str[0..1] + ms.serialize_integer(cnt / 2) + str[2..-1] end end class Regexp def to_marshal(ms) str = self.source out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, Regexp) out << Marshal::TYPE_REGEXP out << ms.serialize_integer(str.length) + str out << ms.to_byte(options & 0x7) out << ms.serialize_instance_variables_suffix(self) end end class Struct def to_marshal(ms) out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << Marshal::TYPE_STRUCT out << ms.serialize(self.class.name.to_sym) out << ms.serialize_integer(self.length) self.each_pair do |name, value| out << ms.serialize(name) out << ms.serialize(value) end out << ms.serialize_instance_variables_suffix(self) out end end class Array def to_marshal(ms) out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, Array) out << Marshal::TYPE_ARRAY out << ms.serialize_integer(self.length) unless empty? then each do |element| out << ms.serialize(element) end end out << ms.serialize_instance_variables_suffix(self) end end class Hash def to_marshal(ms) raise TypeError, "can't dump hash with default proc" if default_proc out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, Hash) out << (self.default ? Marshal::TYPE_HASH_DEF : Marshal::TYPE_HASH) out << ms.serialize_integer(length) unless empty? then each_pair do |(key, val)| out << ms.serialize(key) out << ms.serialize(val) end end out << (default ? ms.serialize(default) : '') out << ms.serialize_instance_variables_suffix(self) end end class Float def to_marshal(ms) str = if nan? then "nan" elsif zero? then (1.0 / self) < 0 ? '-0' : '0' elsif infinite? then self < 0 ? "-inf" : "inf" else "%.*g" % [17, self] + ms.serialize_float_thing(self) end Marshal::TYPE_FLOAT + ms.serialize_integer(str.length) + str end end module Marshal MAJOR_VERSION = 4 MINOR_VERSION = 8 VERSION_STRING = "\x04\x08" TYPE_NIL = '0' TYPE_TRUE = 'T' TYPE_FALSE = 'F' TYPE_FIXNUM = 'i' TYPE_EXTENDED = 'e' TYPE_UCLASS = 'C' TYPE_OBJECT = 'o' TYPE_DATA = 'd' # no specs TYPE_USERDEF = 'u' TYPE_USRMARSHAL = 'U' TYPE_FLOAT = 'f' TYPE_BIGNUM = 'l' TYPE_STRING = '"' TYPE_REGEXP = '/' TYPE_ARRAY = '[' TYPE_HASH = '{' TYPE_HASH_DEF = '}' TYPE_STRUCT = 'S' TYPE_MODULE_OLD = 'M' # no specs TYPE_CLASS = 'c' TYPE_MODULE = 'm' TYPE_SYMBOL = ':' TYPE_SYMLINK = ';' TYPE_IVAR = 'I' TYPE_LINK = '@' class State def initialize(stream, depth, proc) # shared @links = {} @symlinks = {} @symbols = [] @objects = [] # dumping @depth = depth # loading @stream = stream @consumed = 0 consume 2 if @stream @modules = nil @has_ivar = [] @proc = proc @call = true end def add_object(obj) return if obj.kind_of?(ImmediateValue) sz = @links.size @objects[sz] = obj @links[obj.object_id] = sz end def add_symlink(obj) sz = @symlinks.size @symbols[sz] = obj @symlinks[obj.object_id] = sz end def call(obj) @proc.call obj if @proc and @call end def construct(ivar_index = nil, call_proc = true) type = consume obj = case type when TYPE_NIL nil when TYPE_TRUE true when TYPE_FALSE false when TYPE_CLASS, TYPE_MODULE name = construct_symbol obj = Object.const_lookup name store_unique_object obj obj when TYPE_FIXNUM construct_integer when TYPE_BIGNUM construct_bignum when TYPE_FLOAT construct_float when TYPE_SYMBOL construct_symbol when TYPE_STRING construct_string when TYPE_REGEXP construct_regexp when TYPE_ARRAY construct_array when TYPE_HASH, TYPE_HASH_DEF construct_hash type when TYPE_STRUCT construct_struct when TYPE_OBJECT construct_object when TYPE_USERDEF construct_user_defined ivar_index when TYPE_USRMARSHAL construct_user_marshal when TYPE_LINK num = construct_integer obj = @objects[num] raise ArgumentError, "dump format error (unlinked)" if obj.nil? return obj when TYPE_SYMLINK num = construct_integer sym = @symbols[num] raise ArgumentError, "bad symbol" if sym.nil? return sym when TYPE_EXTENDED @modules ||= [] name = get_symbol @modules << Object.const_lookup(name) obj = construct nil, false extend_object obj obj when TYPE_UCLASS name = get_symbol @user_class = name construct nil, false when TYPE_IVAR ivar_index = @has_ivar.length @has_ivar.push true obj = construct ivar_index, false set_instance_variables obj if @has_ivar.pop obj else raise ArgumentError, "load error, unknown type #{type}" end call obj if call_proc obj end def construct_array obj = @user_class ? get_user_class.new : [] store_unique_object obj construct_integer.times do obj << construct end obj end def construct_bignum sign = consume == '-' ? -1 : 1 size = construct_integer * 2 result = 0 data = consume size (0...size).each do |exp| result += (data[exp] * 2**(exp*8)) end obj = result * sign store_unique_object obj end def construct_float s = get_byte_sequence if s == "nan" obj = 0.0 / 0.0 elsif s == "inf" obj = 1.0 / 0.0 elsif s == "-inf" obj = 1.0 / -0.0 else obj = s.to_f end store_unique_object obj obj end def construct_hash(type) obj = @user_class ? get_user_class.new : {} store_unique_object obj construct_integer.times do key = construct val = construct obj[key] = val end obj.default = construct if type == TYPE_HASH_DEF obj end def construct_integer n = consume[0] if (n > 0 and n < 5) or n > 251 size, signed = n > 251 ? [256 - n, 2**((256 - n)*8)] : [n, 0] result = 0 data = consume size (0...size).each do |exp| result += (data[exp] * 2**(exp*8)) end result - signed elsif n > 127 (n - 256) + 5 elsif n > 4 n - 5 else n end end def construct_object name = get_symbol klass = Object.const_lookup name obj = klass.allocate raise TypeError, 'dump format error' unless Object === obj store_unique_object obj set_instance_variables obj obj end def construct_regexp s = get_byte_sequence if @user_class obj = get_user_class.new s, consume[0] else obj = Regexp.new s, consume[0] end store_unique_object obj end def construct_string obj = get_byte_sequence obj = get_user_class.new obj if @user_class store_unique_object obj end def construct_struct symbols = [] values = [] name = get_symbol store_unique_object name klass = Object.const_lookup name members = klass.members obj = klass.allocate store_unique_object obj construct_integer.times do |i| slot = get_symbol unless members[i].intern == slot then raise TypeError, "struct %s is not compatible (%p for %p)" % [klass, slot, members[i]] end obj.instance_variable_set "@#{slot}", construct end obj end def construct_symbol obj = get_byte_sequence.to_sym store_unique_object obj obj end def construct_user_defined(ivar_index) name = get_symbol klass = Module.const_lookup name data = get_byte_sequence if ivar_index and @has_ivar[ivar_index] then set_instance_variables data @has_ivar[ivar_index] = false end obj = klass._load data store_unique_object obj obj end def construct_user_marshal name = get_symbol store_unique_object name klass = Module.const_lookup name obj = klass.allocate extend_object obj if @modules unless obj.respond_to? :marshal_load then raise TypeError, "instance of #{klass} needs to have method `marshal_load'" end store_unique_object obj data = construct obj.marshal_load data obj end def consume(bytes = 1) data = @stream[@consumed, bytes] @consumed += bytes data end def extend_object(obj) obj.extend(@modules.pop) until @modules.empty? end def find_link(obj) @links[obj.object_id] end def find_symlink(obj) @symlinks[obj.object_id] end def frexp(flt) ptr = MemoryPointer.new :int return Platform::Float.frexp(flt, ptr) ensure ptr.free if ptr end def get_byte_sequence size = construct_integer consume size end def get_module_names(obj) names = [] sup = obj.metaclass.superclass while sup and [Module, IncludedModule].include? sup.class do names << sup.name sup = sup.superclass end names end def get_user_class cls = Module.const_lookup @user_class @user_class = nil cls end def get_symbol type = consume case type when TYPE_SYMBOL then @call = false obj = construct_symbol @call = true obj when TYPE_SYMLINK then num = construct_integer @symbols[num] else raise ArgumentError, "expected TYPE_SYMBOL or TYPE_SYMLINK, got #{type.inspect}" end end def ldexp(flt, exp) Platform::Float.ldexp flt, exp end def modf(flt) ptr = MemoryPointer.new :double flt = Platform::Float.modf flt, ptr num = ptr.read_float return flt, num ensure ptr.free if ptr end def prepare_ivar(ivar) ivar.to_s =~ /\A@/ ? ivar : "@#{ivar}".to_sym end def serialize(obj) raise ArgumentError, "exceed depth limit" if @depth == 0 # How much depth we have left. @depth -= 1; if link = find_link(obj) str = TYPE_LINK + serialize_integer(link) else add_object obj if obj.respond_to? :_dump then str = serialize_user_defined obj elsif obj.respond_to? :marshal_dump then str = serialize_user_marshal obj else str = obj.to_marshal self end end @depth += 1 return str end def serialize_extended_object(obj) str = '' get_module_names(obj).each do |mod_name| str << TYPE_EXTENDED + serialize(mod_name.to_sym) end str end def serialize_float_thing(flt) str = '' (flt, ) = modf(ldexp(frexp(flt.abs), 37)); str << "\0" if flt > 0 while flt > 0 (flt, n) = modf(ldexp(flt, 32)) n = n.to_i str << to_byte(n >> 24) str << to_byte(n >> 16) str << to_byte(n >> 8) str << to_byte(n) end str.chomp!("\0") while str[-1] == 0 str end def serialize_instance_variables_prefix(obj) if obj.instance_variables.length > 0 TYPE_IVAR + '' else '' end end def serialize_instance_variables_suffix(obj, force = false, strip_ivars = false) if force or obj.instance_variables.length > 0 str = serialize_integer(obj.instance_variables.length) obj.instance_variables.each do |ivar| sym = ivar.to_sym val = obj.instance_variable_get(sym) unless strip_ivars then str << serialize(sym) else str << serialize(ivar[1..-1].to_sym) end str << serialize(val) end str else '' end end def serialize_integer(n) if n == 0 s = to_byte(n) elsif n > 0 and n < 123 s = to_byte(n + 5) elsif n < 0 and n > -124 s = to_byte(256 + (n - 5)) else s = "\0" cnt = 0 4.times do s << to_byte(n) n >>= 8 cnt += 1 break if n == 0 or n == -1 end s[0] = to_byte(n < 0 ? 256 - cnt : cnt) end s end def serialize_user_class(obj, cls) if obj.class != cls TYPE_UCLASS + serialize(obj.class.name.to_sym) else '' end end def serialize_user_defined(obj) str = obj._dump @depth raise TypeError, "_dump() must return string" if str.class != String out = serialize_instance_variables_prefix(str) out << TYPE_USERDEF + serialize(obj.class.name.to_sym) out << serialize_integer(str.length) + str out << serialize_instance_variables_suffix(str) end def serialize_user_marshal(obj) val = obj.marshal_dump add_object val out = TYPE_USRMARSHAL + serialize(obj.class.name.to_sym) out << val.to_marshal(self) end def set_instance_variables(obj) construct_integer.times do ivar = get_symbol value = construct obj.instance_variable_set prepare_ivar(ivar), value end end def store_unique_object(obj) if obj.kind_of? Symbol add_symlink obj else add_object obj end obj end def to_byte(n) [n].pack('C') end end def self.dump(obj, an_io=nil, limit=nil) if limit.nil? if an_io.kind_of? Fixnum limit = an_io an_io = nil else limit = -1 end end depth = Type.coerce_to limit, Fixnum, :to_int ms = State.new nil, depth, nil if an_io and !an_io.respond_to? :write raise TypeError, "output must respond to write" end str = VERSION_STRING + ms.serialize(obj) if an_io an_io.write(str) return an_io end return str end def self.load(obj, proc = nil) if obj.respond_to? :to_str data = obj.to_s elsif obj.respond_to? :read data = obj.read if data.empty? raise EOFError, "end of file reached" end elsif obj.respond_to? :getc # FIXME - don't read all of it upfront data = '' data << c while (c = obj.getc.chr) else raise TypeError, "instance of IO needed" end major = data[0] minor = data[1] if major != MAJOR_VERSION or minor > MINOR_VERSION then raise TypeError, "incompatible marshal file format (can't be read)\n\tformat version #{MAJOR_VERSION}.#{MINOR_VERSION} required; #{major}.#{minor} given" end ms = State.new data, nil, proc ms.construct end end marshal should allocate, not new # depends on: module.rb class.rb class Object def to_marshal(ms, strip_ivars = false) out = ms.serialize_extended_object self out << Marshal::TYPE_OBJECT out << ms.serialize(self.class.name.to_sym) out << ms.serialize_instance_variables_suffix(self, true, strip_ivars) end end class Range def to_marshal(ms) super(ms, true) end end class NilClass def to_marshal(ms) Marshal::TYPE_NIL end end class TrueClass def to_marshal(ms) Marshal::TYPE_TRUE end end class FalseClass def to_marshal(ms) Marshal::TYPE_FALSE end end class Class def to_marshal(ms) raise TypeError, "can't dump anonymous class #{self}" if self.name == '' Marshal::TYPE_CLASS + ms.serialize_integer(name.length) + name end end class Module def to_marshal(ms) raise TypeError, "can't dump anonymous module #{self}" if self.name == '' Marshal::TYPE_MODULE + ms.serialize_integer(name.length) + name end end class Symbol def to_marshal(ms) if idx = ms.find_symlink(self) then Marshal::TYPE_SYMLINK + ms.serialize_integer(idx) else ms.add_symlink self str = to_s Marshal::TYPE_SYMBOL + ms.serialize_integer(str.length) + str end end end class String def to_marshal(ms) out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, String) out << Marshal::TYPE_STRING out << ms.serialize_integer(self.length) << self out << ms.serialize_instance_variables_suffix(self) end end class Fixnum def to_marshal(ms) Marshal::TYPE_FIXNUM + ms.serialize_integer(self) end end class Bignum def to_marshal(ms) str = Marshal::TYPE_BIGNUM + (self < 0 ? '-' : '+') cnt = 0 num = self.abs while num != 0 str << ms.to_byte(num) num >>= 8 cnt += 1 end if cnt % 2 == 1 str << "\0" cnt += 1 end str[0..1] + ms.serialize_integer(cnt / 2) + str[2..-1] end end class Regexp def to_marshal(ms) str = self.source out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, Regexp) out << Marshal::TYPE_REGEXP out << ms.serialize_integer(str.length) + str out << ms.to_byte(options & 0x7) out << ms.serialize_instance_variables_suffix(self) end end class Struct def to_marshal(ms) out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << Marshal::TYPE_STRUCT out << ms.serialize(self.class.name.to_sym) out << ms.serialize_integer(self.length) self.each_pair do |name, value| out << ms.serialize(name) out << ms.serialize(value) end out << ms.serialize_instance_variables_suffix(self) out end end class Array def to_marshal(ms) out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, Array) out << Marshal::TYPE_ARRAY out << ms.serialize_integer(self.length) unless empty? then each do |element| out << ms.serialize(element) end end out << ms.serialize_instance_variables_suffix(self) end end class Hash def to_marshal(ms) raise TypeError, "can't dump hash with default proc" if default_proc out = ms.serialize_instance_variables_prefix(self) out << ms.serialize_extended_object(self) out << ms.serialize_user_class(self, Hash) out << (self.default ? Marshal::TYPE_HASH_DEF : Marshal::TYPE_HASH) out << ms.serialize_integer(length) unless empty? then each_pair do |(key, val)| out << ms.serialize(key) out << ms.serialize(val) end end out << (default ? ms.serialize(default) : '') out << ms.serialize_instance_variables_suffix(self) end end class Float def to_marshal(ms) str = if nan? then "nan" elsif zero? then (1.0 / self) < 0 ? '-0' : '0' elsif infinite? then self < 0 ? "-inf" : "inf" else "%.*g" % [17, self] + ms.serialize_float_thing(self) end Marshal::TYPE_FLOAT + ms.serialize_integer(str.length) + str end end module Marshal MAJOR_VERSION = 4 MINOR_VERSION = 8 VERSION_STRING = "\x04\x08" TYPE_NIL = '0' TYPE_TRUE = 'T' TYPE_FALSE = 'F' TYPE_FIXNUM = 'i' TYPE_EXTENDED = 'e' TYPE_UCLASS = 'C' TYPE_OBJECT = 'o' TYPE_DATA = 'd' # no specs TYPE_USERDEF = 'u' TYPE_USRMARSHAL = 'U' TYPE_FLOAT = 'f' TYPE_BIGNUM = 'l' TYPE_STRING = '"' TYPE_REGEXP = '/' TYPE_ARRAY = '[' TYPE_HASH = '{' TYPE_HASH_DEF = '}' TYPE_STRUCT = 'S' TYPE_MODULE_OLD = 'M' # no specs TYPE_CLASS = 'c' TYPE_MODULE = 'm' TYPE_SYMBOL = ':' TYPE_SYMLINK = ';' TYPE_IVAR = 'I' TYPE_LINK = '@' class State def initialize(stream, depth, proc) # shared @links = {} @symlinks = {} @symbols = [] @objects = [] # dumping @depth = depth # loading @stream = stream @consumed = 0 consume 2 if @stream @modules = nil @has_ivar = [] @proc = proc @call = true end def add_object(obj) return if obj.kind_of?(ImmediateValue) sz = @links.size @objects[sz] = obj @links[obj.object_id] = sz end def add_symlink(obj) sz = @symlinks.size @symbols[sz] = obj @symlinks[obj.object_id] = sz end def call(obj) @proc.call obj if @proc and @call end def construct(ivar_index = nil, call_proc = true) type = consume obj = case type when TYPE_NIL nil when TYPE_TRUE true when TYPE_FALSE false when TYPE_CLASS, TYPE_MODULE name = construct_symbol obj = Object.const_lookup name store_unique_object obj obj when TYPE_FIXNUM construct_integer when TYPE_BIGNUM construct_bignum when TYPE_FLOAT construct_float when TYPE_SYMBOL construct_symbol when TYPE_STRING construct_string when TYPE_REGEXP construct_regexp when TYPE_ARRAY construct_array when TYPE_HASH, TYPE_HASH_DEF construct_hash type when TYPE_STRUCT construct_struct when TYPE_OBJECT construct_object when TYPE_USERDEF construct_user_defined ivar_index when TYPE_USRMARSHAL construct_user_marshal when TYPE_LINK num = construct_integer obj = @objects[num] raise ArgumentError, "dump format error (unlinked)" if obj.nil? return obj when TYPE_SYMLINK num = construct_integer sym = @symbols[num] raise ArgumentError, "bad symbol" if sym.nil? return sym when TYPE_EXTENDED @modules ||= [] name = get_symbol @modules << Object.const_lookup(name) obj = construct nil, false extend_object obj obj when TYPE_UCLASS name = get_symbol @user_class = name construct nil, false when TYPE_IVAR ivar_index = @has_ivar.length @has_ivar.push true obj = construct ivar_index, false set_instance_variables obj if @has_ivar.pop obj else raise ArgumentError, "load error, unknown type #{type}" end call obj if call_proc obj end def construct_array obj = @user_class ? get_user_class.new : [] store_unique_object obj construct_integer.times do obj << construct end obj end def construct_bignum sign = consume == '-' ? -1 : 1 size = construct_integer * 2 result = 0 data = consume size (0...size).each do |exp| result += (data[exp] * 2**(exp*8)) end obj = result * sign store_unique_object obj end def construct_float s = get_byte_sequence if s == "nan" obj = 0.0 / 0.0 elsif s == "inf" obj = 1.0 / 0.0 elsif s == "-inf" obj = 1.0 / -0.0 else obj = s.to_f end store_unique_object obj obj end def construct_hash(type) obj = @user_class ? get_user_class.allocate : {} store_unique_object obj construct_integer.times do key = construct val = construct obj[key] = val end obj.default = construct if type == TYPE_HASH_DEF obj end def construct_integer n = consume[0] if (n > 0 and n < 5) or n > 251 size, signed = n > 251 ? [256 - n, 2**((256 - n)*8)] : [n, 0] result = 0 data = consume size (0...size).each do |exp| result += (data[exp] * 2**(exp*8)) end result - signed elsif n > 127 (n - 256) + 5 elsif n > 4 n - 5 else n end end def construct_object name = get_symbol klass = Object.const_lookup name obj = klass.allocate raise TypeError, 'dump format error' unless Object === obj store_unique_object obj set_instance_variables obj obj end def construct_regexp s = get_byte_sequence if @user_class obj = get_user_class.new s, consume[0] else obj = Regexp.new s, consume[0] end store_unique_object obj end def construct_string obj = get_byte_sequence obj = get_user_class.new obj if @user_class store_unique_object obj end def construct_struct symbols = [] values = [] name = get_symbol store_unique_object name klass = Object.const_lookup name members = klass.members obj = klass.allocate store_unique_object obj construct_integer.times do |i| slot = get_symbol unless members[i].intern == slot then raise TypeError, "struct %s is not compatible (%p for %p)" % [klass, slot, members[i]] end obj.instance_variable_set "@#{slot}", construct end obj end def construct_symbol obj = get_byte_sequence.to_sym store_unique_object obj obj end def construct_user_defined(ivar_index) name = get_symbol klass = Module.const_lookup name data = get_byte_sequence if ivar_index and @has_ivar[ivar_index] then set_instance_variables data @has_ivar[ivar_index] = false end obj = klass._load data store_unique_object obj obj end def construct_user_marshal name = get_symbol store_unique_object name klass = Module.const_lookup name obj = klass.allocate extend_object obj if @modules unless obj.respond_to? :marshal_load then raise TypeError, "instance of #{klass} needs to have method `marshal_load'" end store_unique_object obj data = construct obj.marshal_load data obj end def consume(bytes = 1) data = @stream[@consumed, bytes] @consumed += bytes data end def extend_object(obj) obj.extend(@modules.pop) until @modules.empty? end def find_link(obj) @links[obj.object_id] end def find_symlink(obj) @symlinks[obj.object_id] end def frexp(flt) ptr = MemoryPointer.new :int return Platform::Float.frexp(flt, ptr) ensure ptr.free if ptr end def get_byte_sequence size = construct_integer consume size end def get_module_names(obj) names = [] sup = obj.metaclass.superclass while sup and [Module, IncludedModule].include? sup.class do names << sup.name sup = sup.superclass end names end def get_user_class cls = Module.const_lookup @user_class @user_class = nil cls end def get_symbol type = consume case type when TYPE_SYMBOL then @call = false obj = construct_symbol @call = true obj when TYPE_SYMLINK then num = construct_integer @symbols[num] else raise ArgumentError, "expected TYPE_SYMBOL or TYPE_SYMLINK, got #{type.inspect}" end end def ldexp(flt, exp) Platform::Float.ldexp flt, exp end def modf(flt) ptr = MemoryPointer.new :double flt = Platform::Float.modf flt, ptr num = ptr.read_float return flt, num ensure ptr.free if ptr end def prepare_ivar(ivar) ivar.to_s =~ /\A@/ ? ivar : "@#{ivar}".to_sym end def serialize(obj) raise ArgumentError, "exceed depth limit" if @depth == 0 # How much depth we have left. @depth -= 1; if link = find_link(obj) str = TYPE_LINK + serialize_integer(link) else add_object obj if obj.respond_to? :_dump then str = serialize_user_defined obj elsif obj.respond_to? :marshal_dump then str = serialize_user_marshal obj else str = obj.to_marshal self end end @depth += 1 return str end def serialize_extended_object(obj) str = '' get_module_names(obj).each do |mod_name| str << TYPE_EXTENDED + serialize(mod_name.to_sym) end str end def serialize_float_thing(flt) str = '' (flt, ) = modf(ldexp(frexp(flt.abs), 37)); str << "\0" if flt > 0 while flt > 0 (flt, n) = modf(ldexp(flt, 32)) n = n.to_i str << to_byte(n >> 24) str << to_byte(n >> 16) str << to_byte(n >> 8) str << to_byte(n) end str.chomp!("\0") while str[-1] == 0 str end def serialize_instance_variables_prefix(obj) if obj.instance_variables.length > 0 TYPE_IVAR + '' else '' end end def serialize_instance_variables_suffix(obj, force = false, strip_ivars = false) if force or obj.instance_variables.length > 0 str = serialize_integer(obj.instance_variables.length) obj.instance_variables.each do |ivar| sym = ivar.to_sym val = obj.instance_variable_get(sym) unless strip_ivars then str << serialize(sym) else str << serialize(ivar[1..-1].to_sym) end str << serialize(val) end str else '' end end def serialize_integer(n) if n == 0 s = to_byte(n) elsif n > 0 and n < 123 s = to_byte(n + 5) elsif n < 0 and n > -124 s = to_byte(256 + (n - 5)) else s = "\0" cnt = 0 4.times do s << to_byte(n) n >>= 8 cnt += 1 break if n == 0 or n == -1 end s[0] = to_byte(n < 0 ? 256 - cnt : cnt) end s end def serialize_user_class(obj, cls) if obj.class != cls TYPE_UCLASS + serialize(obj.class.name.to_sym) else '' end end def serialize_user_defined(obj) str = obj._dump @depth raise TypeError, "_dump() must return string" if str.class != String out = serialize_instance_variables_prefix(str) out << TYPE_USERDEF + serialize(obj.class.name.to_sym) out << serialize_integer(str.length) + str out << serialize_instance_variables_suffix(str) end def serialize_user_marshal(obj) val = obj.marshal_dump add_object val out = TYPE_USRMARSHAL + serialize(obj.class.name.to_sym) out << val.to_marshal(self) end def set_instance_variables(obj) construct_integer.times do ivar = get_symbol value = construct obj.instance_variable_set prepare_ivar(ivar), value end end def store_unique_object(obj) if obj.kind_of? Symbol add_symlink obj else add_object obj end obj end def to_byte(n) [n].pack('C') end end def self.dump(obj, an_io=nil, limit=nil) if limit.nil? if an_io.kind_of? Fixnum limit = an_io an_io = nil else limit = -1 end end depth = Type.coerce_to limit, Fixnum, :to_int ms = State.new nil, depth, nil if an_io and !an_io.respond_to? :write raise TypeError, "output must respond to write" end str = VERSION_STRING + ms.serialize(obj) if an_io an_io.write(str) return an_io end return str end def self.load(obj, proc = nil) if obj.respond_to? :to_str data = obj.to_s elsif obj.respond_to? :read data = obj.read if data.empty? raise EOFError, "end of file reached" end elsif obj.respond_to? :getc # FIXME - don't read all of it upfront data = '' data << c while (c = obj.getc.chr) else raise TypeError, "instance of IO needed" end major = data[0] minor = data[1] if major != MAJOR_VERSION or minor > MINOR_VERSION then raise TypeError, "incompatible marshal file format (can't be read)\n\tformat version #{MAJOR_VERSION}.#{MINOR_VERSION} required; #{major}.#{minor} given" end ms = State.new data, nil, proc ms.construct end end
# depends on: class.rb comparable.rb class Numeric include Comparable # Numeric and sub-classes do not have ivars def __ivars__ ; nil ; end def +@ self end def -@ 0 - self end def +(other) b, a = math_coerce other a + b end def -(other) b, a = math_coerce other a - b end def *(other) b, a = math_coerce other a * b end def %(other) b, a = math_coerce other raise ZeroDivisionError, "divided by 0" unless b.__kind_of__(Float) or b != 0 a % b end #-- # see README-DEVELOPERS regarding safe math compiler plugin #++ def divide(other) b, a = math_coerce other raise ZeroDivisionError, "divided by 0" unless b.__kind_of__(Float) or b != 0 a / b end alias_method :/, :divide def **(other) b, a = math_coerce other a ** b end def divmod(other) b, a = math_coerce other if other == 0 raise FloatDomainError, "NaN" if other.__kind_of__ Float raise ZeroDivisionError, "divided by 0" end a.divmod b end def div(other) raise FloatDomainError, "NaN" if self == 0 && other.__kind_of__(Float) && other == 0 b, a = math_coerce other (a / b).floor end def quo(other) if other.__kind_of__ Integer self / Float(other) else b, a = math_coerce other a / b end end def <(other) b, a = math_coerce other, :compare_error a < b end def <=(other) b, a = math_coerce other, :compare_error a <= b end def >(other) b, a = math_coerce other, :compare_error a > b end def >=(other) b, a = math_coerce other, :compare_error a >= b end def ==(other) other == self end def <=>(other) begin b, a = math_coerce other, :compare_error return a <=> b rescue ArgumentError return nil end end def integer? false end def zero? self == 0 end def nonzero? zero? ? nil : self end def round self.to_f.round end def abs self < 0 ? -self : self end def floor int = self.to_i if self == int or self > 0 int else int - 1 end end def ceil int = self.to_i if self == int or self < 0 int else int + 1 end end def remainder(other) b, a = math_coerce other mod = a % b if mod != 0 && (a < 0 && b > 0 || a > 0 && b < 0) mod - b else mod end end #-- # We deviate from MRI behavior here because we ensure that Fixnum op Bignum # => Bignum (possibly normalized to Fixnum) # # Note these differences on MRI, where a is a Fixnum, b is a Bignum # # a.coerce b => [Float, Float] # b.coerce a => [Bignum, Bignum] #++ def coerce(other) Ruby.primitive :numeric_coerce [Float(other), Float(self)] end ## # This method mimics the semantics of MRI's do_coerce function # in numeric.c. Note these differences between it and #coerce: # # 1.2.coerce("2") => [2.0, 1.2] # 1.2 + "2" => TypeError: String can't be coerced into Float # # See also Integer#coerce def math_coerce(other, error=:coerce_error) begin values = other.coerce(self) rescue send error, other end unless values.__kind_of__(Array) && values.length == 2 raise TypeError, "coerce must return [x, y]" end return values[1], values[0] end private :math_coerce def coerce_error(other) raise TypeError, "#{other.class} can't be coerced into #{self.class}" end private :coerce_error def compare_error(other) raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" end private :compare_error def step(limit, step=1, &block) raise ArgumentError, "step cannot be 0" if step == 0 limit,step = step.coerce(limit) # FIXME: why is this not covered by the block parameter above? raise LocalJumpError, "no block given" unless block_given? idx,step = step.coerce(self) cmp = step > 0 ? :<= : :>= while (idx.send(cmp,limit)) yield(idx) idx += step end return self rescue TypeError => e raise ArgumentError, e.message end end Numeric#== returns only boolean values. # depends on: class.rb comparable.rb class Numeric include Comparable # Numeric and sub-classes do not have ivars def __ivars__ ; nil ; end def +@ self end def -@ 0 - self end def +(other) b, a = math_coerce other a + b end def -(other) b, a = math_coerce other a - b end def *(other) b, a = math_coerce other a * b end def %(other) b, a = math_coerce other raise ZeroDivisionError, "divided by 0" unless b.__kind_of__(Float) or b != 0 a % b end #-- # see README-DEVELOPERS regarding safe math compiler plugin #++ def divide(other) b, a = math_coerce other raise ZeroDivisionError, "divided by 0" unless b.__kind_of__(Float) or b != 0 a / b end alias_method :/, :divide def **(other) b, a = math_coerce other a ** b end def divmod(other) b, a = math_coerce other if other == 0 raise FloatDomainError, "NaN" if other.__kind_of__ Float raise ZeroDivisionError, "divided by 0" end a.divmod b end def div(other) raise FloatDomainError, "NaN" if self == 0 && other.__kind_of__(Float) && other == 0 b, a = math_coerce other (a / b).floor end def quo(other) if other.__kind_of__ Integer self / Float(other) else b, a = math_coerce other a / b end end def <(other) b, a = math_coerce other, :compare_error a < b end def <=(other) b, a = math_coerce other, :compare_error a <= b end def >(other) b, a = math_coerce other, :compare_error a > b end def >=(other) b, a = math_coerce other, :compare_error a >= b end def ==(other) !!(other == self) end def <=>(other) begin b, a = math_coerce other, :compare_error return a <=> b rescue ArgumentError return nil end end def integer? false end def zero? self == 0 end def nonzero? zero? ? nil : self end def round self.to_f.round end def abs self < 0 ? -self : self end def floor int = self.to_i if self == int or self > 0 int else int - 1 end end def ceil int = self.to_i if self == int or self < 0 int else int + 1 end end def remainder(other) b, a = math_coerce other mod = a % b if mod != 0 && (a < 0 && b > 0 || a > 0 && b < 0) mod - b else mod end end #-- # We deviate from MRI behavior here because we ensure that Fixnum op Bignum # => Bignum (possibly normalized to Fixnum) # # Note these differences on MRI, where a is a Fixnum, b is a Bignum # # a.coerce b => [Float, Float] # b.coerce a => [Bignum, Bignum] #++ def coerce(other) Ruby.primitive :numeric_coerce [Float(other), Float(self)] end ## # This method mimics the semantics of MRI's do_coerce function # in numeric.c. Note these differences between it and #coerce: # # 1.2.coerce("2") => [2.0, 1.2] # 1.2 + "2" => TypeError: String can't be coerced into Float # # See also Integer#coerce def math_coerce(other, error=:coerce_error) begin values = other.coerce(self) rescue send error, other end unless values.__kind_of__(Array) && values.length == 2 raise TypeError, "coerce must return [x, y]" end return values[1], values[0] end private :math_coerce def coerce_error(other) raise TypeError, "#{other.class} can't be coerced into #{self.class}" end private :coerce_error def compare_error(other) raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" end private :compare_error def step(limit, step=1, &block) raise ArgumentError, "step cannot be 0" if step == 0 limit,step = step.coerce(limit) # FIXME: why is this not covered by the block parameter above? raise LocalJumpError, "no block given" unless block_given? idx,step = step.coerce(self) cmp = step > 0 ? :<= : :>= while (idx.send(cmp,limit)) yield(idx) idx += step end return self rescue TypeError => e raise ArgumentError, e.message end end
# depends on: module.rb class.rb class Sprintf attr_accessor :fmt attr_accessor :args attr_accessor :flags RADIXES = {"b" => 2, "o" => 8, "d" => 10, "x" => 16} ALTERNATIVES = {"o" => "0", "b" => "0b", "B" => "0B", "x" => "0x", "X" => "0X"} PrecisionMax = 1048576 # Totally random value def initialize(fmt, *args) @tainted = fmt.tainted? @fmt, @args, @arg_position = fmt.to_str, args, 0 end def parse start = 0 ret = "" width = nil precision = nil @positional = false @relative = false @arg_position = 0 while (match = /%/.match_from(fmt, start)) @flags = {:space => nil, :position => nil, :alternative => nil, :plus => nil, :minus => nil, :zero => nil, :star => nil} @width = @precision = @type = nil ret << match.pre_match_from(start) start = match.begin(0) + 1 # Special case: %% prints out as "%" if [?\n, 0].include?(@fmt[start]) ret << "%" << @fmt[start] start += 1 next elsif [?%, nil].include?(@fmt[start]) ret << "%" start += 1 next elsif @fmt[start..(start + 2)] =~ /[1-9]\$/ && !@fmt[start + 2] ret << "%" start = @fmt.size break end # FLAG STATE while token = /\G( |[1-9]\$|#|\+|\-|0|\*)/.match_from(fmt, start) case token[0] # Special case: if we get two [1-9]\$, it means that we're outside of flag-land when /[1-9]\$/ raise ArgumentError, "value given twice - #{token[0]}" if flags[:position] @flags[:position] = token[0][0].chr.to_i start += 1 when " " @flags[:space] = true when "#" @flags[:alternative] = true when "+" @flags[:plus] = true when "-" @flags[:minus] = true when "0" @flags[:zero] = true when "*" raise ArgumentError, "width given twice" if flags[:star] if width_dollar_match = /\G[1-9]\$/.match_from(fmt, start + 1) @width = Slot.new('*' << width_dollar_match[0]) start += 2 end @flags[:star] = true end start += 1 end # WIDTH STATE if !flags[:star] && width_match = /\G([1-9]\$|\*|\d+)/.match_from(fmt, start) @width = Slot.new(width_match[0]) start += width_match[0].size end # PRECISION DETERMINATION STATE if /\G\./.match_from(fmt, start) start += 1 # PRECISION STATE if /\G\*/.match_from(fmt, start) if precision_dollar_match = /\G[1-9]\$/.match_from(fmt, start + 1) @precision = Slot.new('*' << precision_dollar_match[0]) start += 3 else @precision = Slot.new('*') start += 1 end elsif precision_match = /\G([1-9]\$|\d+)/.match_from(fmt, start) @precision = Slot.new(precision_match[0]) start += precision_match[0].size else @precision = Slot.new("0") end # check for positional value again, after the optional '.' if positional_match = /\G[1-9]\$/.match_from(fmt, start) raise ArgumentError, "value given twice - #{token[0]}" if flags[:position] @flags[:position] = positional_match[0][0].chr.to_i start += 2 end end # TYPE STATE unless type = /\G[bcdEefGgiopsuXx]/i.match_from(fmt, start) raise ArgumentError, "malformed format string - missing field type" else @type = type[0] start += 1 end # Next: Use the parsed values to format some stuff :) f = format ret << f if f end if $DEBUG == true && !@positional raise ArgumentError, "you need to use all the arguments" unless @arg_position == args.size end ret << @fmt[start..-1] if start < @fmt.size ret.taint if @tainted ret end def format # GET VALUE if flags[:position] val = Slot.new("#{flags[:position]}$") val = get_arg(val) end # GET WIDTH @width = Slot.new("*") if flags[:star] && !@width width = get_arg(@width) width = width.to_int if width.respond_to?(:to_int) if width && width < 0 width = width.abs flags[:minus] = true end # GET PRECISION precision = get_arg(@precision) precision = precision.to_int if precision.respond_to?(:to_int) unless flags[:position] val = Slot.new("*") val = get_arg(val) end case @type when "e", "E", "f", "g", "G" if @type.downcase == "g" && flags[:alternative] @old_type = "g" @type = "f" precision = 4 unless precision end val = Float(val) if val.finite? ret = val.send(:to_s_formatted, build_format_string(width, precision)) ret = plus_char + ret if val >= 0 && @old_type else ret = (val < 0 ? "-Inf" : "Inf") if val.infinite? ret = "NaN" if val.nan? ret = plus_char + ret if val > 0 flags[:zero] = flags[:space] = flags[:plus] = nil ret = pad(ret, width, precision) end when "u" val = get_number(val) if val < 0 unless val.kind_of?(Fixnum) raise ArgumentError, "invalid type (only Fixnum allowed)" end val = (2**32) + val if !flags[:zero] and !precision ret = "..#{pad(val, width, precision)}" else ret = pad(val, width, precision) end else ret = pad(val, width, precision) end when "d", "i" val = get_number(val) ret = pad(val, width, precision) when "c" val = val.to_int if val.respond_to?(:to_int) raise TypeError, "cannot convert #{val.class} into Integer" unless val.respond_to?(:chr) && val.respond_to?(:%) val = (val % 256).chr ret = pad(val, width, precision) when "s" flags[:zero] = flags[:space] = flags[:plus] = nil ret = pad(val, width, precision) ret.taint if val.tainted? when "p" flags[:zero] = flags[:space] = flags[:plus] = nil ret = pad(val.inspect, width, precision) when "o", "x", "X", "b", "B" val = get_number(val) unless flags[:space] || flags[:plus] ret = Number.new(val, RADIXES[@type.downcase]).rep ret = pad(ret, width, precision, (RADIXES[@type.downcase] - 1).to_s(RADIXES[@type.downcase])) ret = ALTERNATIVES[@type].to_s + ret if flags[:alternative] else flags[:plus] = nil if val < 0 ret = val.to_s(RADIXES[@type.downcase]) ret.gsub!(/^(\-?)/, "\1#{ALTERNATIVES[@type]}") if flags[:alternative] ret = pad(ret, width, precision) ret.gsub!(/ \-/, "-") end ret = ret.downcase if @type == "x" ret = ret.upcase if @type == "X" end ret end def get_number(val) unless val.respond_to?(:full_to_i) if val.respond_to?(:to_int) val = val.to_int elsif val.respond_to?(:to_i) val = val.to_i end end val = val.full_to_i if val.respond_to?(:full_to_i) val = 0 if val.nil? val end def build_format_string(width, precision) ret = "%#{make_flags}#{width}" ret << ".#{precision}" if precision ret << @type ret end def make_flags ret = "" ret << " " if flags[:space] ret << "#" if flags[:alternative] ret << "+" if flags[:plus] ret << "-" if flags[:minus] ret << "0" if flags[:zero] ret end def get_arg(slot) return nil unless slot if slot.position == :next raise ArgumentError, "unnumbered mixed with numbered" if @positional @relative = true raise ArgumentError, "you ran out of arguments" if @arg_position >= args.size ret = args[@arg_position] @arg_position += 1 elsif slot.pos raise ArgumentError, "unnumbered mixed with numbered" if @relative @positional = true ret = args[slot.position - 1] elsif slot.value raise ArgumentError, "unnumbered mixed with numbered" if @positional @relative = true ret = slot.value end raise ArgumentError, "you specified an argument position that did not exist: #{slot.str}" unless defined?(ret) ret end def pad(val, width, precision, pad_override = nil) direction = flags[:minus] ? :ljust : :rjust ret = val.to_s modded_width = width.to_i + (flags[:plus] ? 1 : 0) width = nil if modded_width <= val.to_s.size if precision || flags[:zero] ret.gsub!("..", "") end if precision if precision > PrecisionMax raise ArgumentError, "precision too big" end ret = plus_char + ret.send(direction, precision, pad_override || "0") flags[:zero] = flags[:plus] = flags[:space] = nil end if width ret = ret.send(direction, width, pad_char) ret[0] = plus_char unless plus_char.empty? else ret = plus_char + ret end ret end def pad_char flags[:zero] ? "0" : " " end def plus_char return "+" if flags[:plus] return " " if flags[:space] "" end class Slot # pos means it got a N$ position attr_reader :pos attr_reader :position attr_reader :value attr_reader :str def initialize(str) @pos = false @str = str if str.size == 3 && /\*\d\$/.match(str) @pos = true @position = str[1..1].to_i elsif str.size == 2 && str[1] == ?$ @pos = true @position = str[0..0].to_i elsif str == "*" @position = :next else @value = str.to_i end end end class Number def initialize(number, radix) @number = number @radix = radix @pad = (radix - 1).to_s(radix) end def rep return @number.to_s(@radix) if(@number >= 0) || @radix == 10 strlen = (@number.to_s(@radix)).size max = (@pad * strlen).to_i(@radix) ".." + (max + @number + 1).to_s(@radix) end end end Fix Sprintf %u for 64 bit platforms # depends on: module.rb class.rb class Sprintf attr_accessor :fmt attr_accessor :args attr_accessor :flags RADIXES = {"b" => 2, "o" => 8, "d" => 10, "x" => 16} ALTERNATIVES = {"o" => "0", "b" => "0b", "B" => "0B", "x" => "0x", "X" => "0X"} PrecisionMax = 1048576 # Totally random value def initialize(fmt, *args) @tainted = fmt.tainted? @fmt, @args, @arg_position = fmt.to_str, args, 0 end def parse start = 0 ret = "" width = nil precision = nil @positional = false @relative = false @arg_position = 0 while (match = /%/.match_from(fmt, start)) @flags = {:space => nil, :position => nil, :alternative => nil, :plus => nil, :minus => nil, :zero => nil, :star => nil} @width = @precision = @type = nil ret << match.pre_match_from(start) start = match.begin(0) + 1 # Special case: %% prints out as "%" if [?\n, 0].include?(@fmt[start]) ret << "%" << @fmt[start] start += 1 next elsif [?%, nil].include?(@fmt[start]) ret << "%" start += 1 next elsif @fmt[start..(start + 2)] =~ /[1-9]\$/ && !@fmt[start + 2] ret << "%" start = @fmt.size break end # FLAG STATE while token = /\G( |[1-9]\$|#|\+|\-|0|\*)/.match_from(fmt, start) case token[0] # Special case: if we get two [1-9]\$, it means that we're outside of flag-land when /[1-9]\$/ raise ArgumentError, "value given twice - #{token[0]}" if flags[:position] @flags[:position] = token[0][0].chr.to_i start += 1 when " " @flags[:space] = true when "#" @flags[:alternative] = true when "+" @flags[:plus] = true when "-" @flags[:minus] = true when "0" @flags[:zero] = true when "*" raise ArgumentError, "width given twice" if flags[:star] if width_dollar_match = /\G[1-9]\$/.match_from(fmt, start + 1) @width = Slot.new('*' << width_dollar_match[0]) start += 2 end @flags[:star] = true end start += 1 end # WIDTH STATE if !flags[:star] && width_match = /\G([1-9]\$|\*|\d+)/.match_from(fmt, start) @width = Slot.new(width_match[0]) start += width_match[0].size end # PRECISION DETERMINATION STATE if /\G\./.match_from(fmt, start) start += 1 # PRECISION STATE if /\G\*/.match_from(fmt, start) if precision_dollar_match = /\G[1-9]\$/.match_from(fmt, start + 1) @precision = Slot.new('*' << precision_dollar_match[0]) start += 3 else @precision = Slot.new('*') start += 1 end elsif precision_match = /\G([1-9]\$|\d+)/.match_from(fmt, start) @precision = Slot.new(precision_match[0]) start += precision_match[0].size else @precision = Slot.new("0") end # check for positional value again, after the optional '.' if positional_match = /\G[1-9]\$/.match_from(fmt, start) raise ArgumentError, "value given twice - #{token[0]}" if flags[:position] @flags[:position] = positional_match[0][0].chr.to_i start += 2 end end # TYPE STATE unless type = /\G[bcdEefGgiopsuXx]/i.match_from(fmt, start) raise ArgumentError, "malformed format string - missing field type" else @type = type[0] start += 1 end # Next: Use the parsed values to format some stuff :) f = format ret << f if f end if $DEBUG == true && !@positional raise ArgumentError, "you need to use all the arguments" unless @arg_position == args.size end ret << @fmt[start..-1] if start < @fmt.size ret.taint if @tainted ret end def format # GET VALUE if flags[:position] val = Slot.new("#{flags[:position]}$") val = get_arg(val) end # GET WIDTH @width = Slot.new("*") if flags[:star] && !@width width = get_arg(@width) width = width.to_int if width.respond_to?(:to_int) if width && width < 0 width = width.abs flags[:minus] = true end # GET PRECISION precision = get_arg(@precision) precision = precision.to_int if precision.respond_to?(:to_int) unless flags[:position] val = Slot.new("*") val = get_arg(val) end case @type when "e", "E", "f", "g", "G" if @type.downcase == "g" && flags[:alternative] @old_type = "g" @type = "f" precision = 4 unless precision end val = Float(val) if val.finite? ret = val.send(:to_s_formatted, build_format_string(width, precision)) ret = plus_char + ret if val >= 0 && @old_type else ret = (val < 0 ? "-Inf" : "Inf") if val.infinite? ret = "NaN" if val.nan? ret = plus_char + ret if val > 0 flags[:zero] = flags[:space] = flags[:plus] = nil ret = pad(ret, width, precision) end when "u" val = get_number(val) if val < 0 unless val.kind_of?(Fixnum) raise ArgumentError, "invalid type (only Fixnum allowed)" end val = (2**(2.size * 8)) + val if !flags[:zero] and !precision ret = "..#{pad(val, width, precision)}" else ret = pad(val, width, precision) end else ret = pad(val, width, precision) end when "d", "i" val = get_number(val) ret = pad(val, width, precision) when "c" val = val.to_int if val.respond_to?(:to_int) raise TypeError, "cannot convert #{val.class} into Integer" unless val.respond_to?(:chr) && val.respond_to?(:%) val = (val % 256).chr ret = pad(val, width, precision) when "s" flags[:zero] = flags[:space] = flags[:plus] = nil ret = pad(val, width, precision) ret.taint if val.tainted? when "p" flags[:zero] = flags[:space] = flags[:plus] = nil ret = pad(val.inspect, width, precision) when "o", "x", "X", "b", "B" val = get_number(val) unless flags[:space] || flags[:plus] ret = Number.new(val, RADIXES[@type.downcase]).rep ret = pad(ret, width, precision, (RADIXES[@type.downcase] - 1).to_s(RADIXES[@type.downcase])) ret = ALTERNATIVES[@type].to_s + ret if flags[:alternative] else flags[:plus] = nil if val < 0 ret = val.to_s(RADIXES[@type.downcase]) ret.gsub!(/^(\-?)/, "\1#{ALTERNATIVES[@type]}") if flags[:alternative] ret = pad(ret, width, precision) ret.gsub!(/ \-/, "-") end ret = ret.downcase if @type == "x" ret = ret.upcase if @type == "X" end ret end def get_number(val) unless val.respond_to?(:full_to_i) if val.respond_to?(:to_int) val = val.to_int elsif val.respond_to?(:to_i) val = val.to_i end end val = val.full_to_i if val.respond_to?(:full_to_i) val = 0 if val.nil? val end def build_format_string(width, precision) ret = "%#{make_flags}#{width}" ret << ".#{precision}" if precision ret << @type ret end def make_flags ret = "" ret << " " if flags[:space] ret << "#" if flags[:alternative] ret << "+" if flags[:plus] ret << "-" if flags[:minus] ret << "0" if flags[:zero] ret end def get_arg(slot) return nil unless slot if slot.position == :next raise ArgumentError, "unnumbered mixed with numbered" if @positional @relative = true raise ArgumentError, "you ran out of arguments" if @arg_position >= args.size ret = args[@arg_position] @arg_position += 1 elsif slot.pos raise ArgumentError, "unnumbered mixed with numbered" if @relative @positional = true ret = args[slot.position - 1] elsif slot.value raise ArgumentError, "unnumbered mixed with numbered" if @positional @relative = true ret = slot.value end raise ArgumentError, "you specified an argument position that did not exist: #{slot.str}" unless defined?(ret) ret end def pad(val, width, precision, pad_override = nil) direction = flags[:minus] ? :ljust : :rjust ret = val.to_s modded_width = width.to_i + (flags[:plus] ? 1 : 0) width = nil if modded_width <= val.to_s.size if precision || flags[:zero] ret.gsub!("..", "") end if precision if precision > PrecisionMax raise ArgumentError, "precision too big" end ret = plus_char + ret.send(direction, precision, pad_override || "0") flags[:zero] = flags[:plus] = flags[:space] = nil end if width ret = ret.send(direction, width, pad_char) ret[0] = plus_char unless plus_char.empty? else ret = plus_char + ret end ret end def pad_char flags[:zero] ? "0" : " " end def plus_char return "+" if flags[:plus] return " " if flags[:space] "" end class Slot # pos means it got a N$ position attr_reader :pos attr_reader :position attr_reader :value attr_reader :str def initialize(str) @pos = false @str = str if str.size == 3 && /\*\d\$/.match(str) @pos = true @position = str[1..1].to_i elsif str.size == 2 && str[1] == ?$ @pos = true @position = str[0..0].to_i elsif str == "*" @position = :next else @value = str.to_i end end end class Number def initialize(number, radix) @number = number @radix = radix @pad = (radix - 1).to_s(radix) end def rep return @number.to_s(@radix) if(@number >= 0) || @radix == 10 strlen = (@number.to_s(@radix)).size max = (@pad * strlen).to_i(@radix) ".." + (max + @number + 1).to_s(@radix) end end end
Pod::Spec.new do |s| s.name = "DBEnvironmentConfiguration" s.version = "0.1.0" s.summary = "Easily switch between development environments/ configurations" s.description = <<-DESC Easily switch between development environments/ configurations DESC s.homepage = "https://github.com/DavidBenko/DBEnvironmentConfiguration" s.license = 'MIT' s.author = { "David Benko" => "dbenko@prndl.us" } s.source = { :git => "https://github.com/DavidBenko/DBEnvironmentConfiguration.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/davidwbenko' s.platform = :ios s.requires_arc = true s.source_files = 'DBEnvironmentConfiguration/**/*.{h,m}' end Update DBEnvironmentConfiguration.podspec description apparently can't be equal to the summary - wtf Pod::Spec.new do |s| s.name = "DBEnvironmentConfiguration" s.version = "0.1.0" s.summary = "Easily switch between development environments/ configurations" s.description = <<-DESC Super-simple environment configuration for iOS apps. Switch between environments by changing one word. DESC s.homepage = "https://github.com/DavidBenko/DBEnvironmentConfiguration" s.license = 'MIT' s.author = { "David Benko" => "dbenko@prndl.us" } s.source = { :git => "https://github.com/DavidBenko/DBEnvironmentConfiguration.git", :tag => s.version.to_s } s.social_media_url = 'https://twitter.com/davidwbenko' s.platform = :ios s.requires_arc = true s.source_files = 'DBEnvironmentConfiguration/**/*.{h,m}' end
require 'spec_helper' describe FrontMatterParser do it 'has a version number' do expect(FrontMatterParser::VERSION).to_not be_nil end describe "#parse" do context "when the string has both front matter and content" do let(:string) { %Q( --- title: hello --- Content) } let(:parsed) { FrontMatterParser.parse(string) } it "parses the front matter as a hash" do expect(parsed.front_matter).to eq({'title' => 'hello'}) end it "parses the content as a string" do expect(parsed.content).to eq("Content") end end context "when the string only has front matter" do let(:string) { %Q( --- title: hello --- ) } let(:parsed) { FrontMatterParser.parse(string) } it "parses the front matter as a hash" do expect(parsed.front_matter).to eq({'title' => 'hello'}) end it "parses the content as an empty string" do expect(parsed.content).to eq('') end end context "when an empty front matter is supplied" do let(:string) { %Q(Hello) } let(:parsed) { FrontMatterParser.parse(string) } it "parses the front matter as an empty hash" do expect(parsed.front_matter).to eq({}) end it "parses the content as the whole string" do expect(parsed.content).to eq(string) end end context "when an empty string is supplied" do let(:parsed) { FrontMatterParser.parse('') } it "parses the front matter as an empty hash" do expect(parsed.front_matter).to eq({}) end it "parses the content as an empty string" do expect(parsed.content).to eq('') end end end end describe "the front matter" do it "can be indented" do string = %Q( --- title: hello --- Content) expect(FrontMatterParser.parse(string).front_matter).to eq({'title' => 'hello'}) end it "can have each line commented" do string = %Q( #--- #title: hello #--- Content) expect(FrontMatterParser.parse(string, '#').front_matter).to eq({'title' => 'hello'}) end it "can be indented after the comment delimiter" do string = %Q( # --- # title: hello # --- Content) expect(FrontMatterParser.parse(string, '#').front_matter).to eq({'title' => 'hello'}) end it "can be between a multiline comment" do string = %Q( <!-- --- title: hello --- --> Content) expect(FrontMatterParser.parse(string, nil, '<!--', '-->').front_matter).to eq({'title' => 'hello'}) end it "can have the multiline comment delimiters indented" do string = %Q( <!-- --- title: hello --- --> Content) expect(FrontMatterParser.parse(string, nil, '<!--', '-->').front_matter).to eq({'title' => 'hello'}) end it "can have empty lines between the multiline comment delimiters and the front matter" do string = %Q( <!-- --- title: hello --- --> Content) expect(FrontMatterParser.parse(string, nil, '<!--', '-->').front_matter).to eq({'title' => 'hello'}) end end put used parsed front matter sample in a variable require 'spec_helper' describe FrontMatterParser do let(:sample) { {'title' => 'hello'} } it 'has a version number' do expect(FrontMatterParser::VERSION).to_not be_nil end describe "#parse" do context "when the string has both front matter and content" do let(:string) { %Q( --- title: hello --- Content) } let(:parsed) { FrontMatterParser.parse(string) } it "parses the front matter as a hash" do expect(parsed.front_matter).to eq(sample) end it "parses the content as a string" do expect(parsed.content).to eq("Content") end end context "when the string only has front matter" do let(:string) { %Q( --- title: hello --- ) } let(:parsed) { FrontMatterParser.parse(string) } it "parses the front matter as a hash" do expect(parsed.front_matter).to eq(sample) end it "parses the content as an empty string" do expect(parsed.content).to eq('') end end context "when an empty front matter is supplied" do let(:string) { %Q(Hello) } let(:parsed) { FrontMatterParser.parse(string) } it "parses the front matter as an empty hash" do expect(parsed.front_matter).to eq({}) end it "parses the content as the whole string" do expect(parsed.content).to eq(string) end end context "when an empty string is supplied" do let(:parsed) { FrontMatterParser.parse('') } it "parses the front matter as an empty hash" do expect(parsed.front_matter).to eq({}) end it "parses the content as an empty string" do expect(parsed.content).to eq('') end end end end describe "the front matter" do let(:sample) { {'title' => 'hello'} } it "can be indented" do string = %Q( --- title: hello --- Content) expect(FrontMatterParser.parse(string).front_matter).to eq(sample) end it "can have each line commented" do string = %Q( #--- #title: hello #--- Content) expect(FrontMatterParser.parse(string, '#').front_matter).to eq(sample) end it "can be indented after the comment delimiter" do string = %Q( # --- # title: hello # --- Content) expect(FrontMatterParser.parse(string, '#').front_matter).to eq(sample) end it "can be between a multiline comment" do string = %Q( <!-- --- title: hello --- --> Content) expect(FrontMatterParser.parse(string, nil, '<!--', '-->').front_matter).to eq(sample) end it "can have the multiline comment delimiters indented" do string = %Q( <!-- --- title: hello --- --> Content) expect(FrontMatterParser.parse(string, nil, '<!--', '-->').front_matter).to eq(sample) end it "can have empty lines between the multiline comment delimiters and the front matter" do string = %Q( <!-- --- title: hello --- --> Content) expect(FrontMatterParser.parse(string, nil, '<!--', '-->').front_matter).to eq(sample) end end
Added specs for last name generator require 'hanitizer/generator' module Hanitizer RSpec.describe Generator::LastName do subject(:generator) { described_class.new } describe '#generate' do let(:row) { Hash.new } it 'generates a fake last name' do expect(Faker::Name).to receive(:last_name) generator.generate(row) end end end end
require 'spec_helper' module Librato describe Metrics do before(:all) { prep_integration_tests } describe "#annotate" do before(:all) { @annotator = Metrics::Annotator.new } before(:each) { delete_all_annotations } it "should create new annotation" do Metrics.annotate :deployment, "deployed v68" annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-60) annos["events"]["unassigned"].length.should == 1 annos["events"]["unassigned"][0]["title"].should == 'deployed v68' end it "should support sources" do Metrics.annotate :deployment, 'deployed v69', :source => 'box1' annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-60) annos["events"]["box1"].length.should == 1 first = annos["events"]["box1"][0] first['title'].should == 'deployed v69' end it "should support start and end times" do start_time = Time.now.to_i-120 end_time = Time.now.to_i-30 Metrics.annotate :deployment, 'deployed v70', :start_time => start_time, :end_time => end_time annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-180) annos["events"]["unassigned"].length.should == 1 first = annos["events"]["unassigned"][0] first['title'].should == 'deployed v70' first['start_time'].should == start_time first['end_time'].should == end_time end it "should support description" do Metrics.annotate :deployment, 'deployed v71', :description => 'deployed foobar!' annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-180) annos["events"]["unassigned"].length.should == 1 first = annos["events"]["unassigned"][0] first['title'].should == 'deployed v71' first['description'].should == 'deployed foobar!' end end describe "#delete_metrics" do before(:each) { delete_all_metrics } context 'by names' do context "with a single argument" do it "should delete named metric" do Metrics.submit :foo => 123 Metrics.metrics(:name => :foo).should_not be_empty Metrics.delete_metrics :foo Metrics.metrics(:name => :foo).should be_empty end end context "with multiple arguments" do it "should delete named metrics" do Metrics.submit :foo => 123, :bar => 345, :baz => 567 Metrics.delete_metrics :foo, :bar Metrics.metrics(:name => :foo).should be_empty Metrics.metrics(:name => :bar).should be_empty Metrics.metrics(:name => :baz).should_not be_empty end end context "with missing metric" do it "should run cleanly" do # the API currently returns success even if # the metric has already been deleted or is absent. Metrics.delete_metrics :missing end end context "with no arguments" do it "should not make request" do lambda { Metrics.delete_metrics }.should raise_error(Metrics::NoMetricsProvided) end end end context 'by pattern' do it "should filter properly" do Metrics.submit :foo => 1, :foobar => 2, :foobaz => 3, :bar => 4 Metrics.delete_metrics :names => 'fo*', :exclude => ['foobar'] %w{foo foobaz}.each do |name| lambda { Metrics.get_metric name }.should raise_error(Librato::Metrics::NotFound) end %w{foobar bar}.each do |name| Metrics.get_metric name # stil exist end end end end describe "#get_metric" do before(:all) do delete_all_metrics Metrics.submit :my_counter => {:type => :counter, :value => 0, :measure_time => Time.now.to_i-60} 1.upto(2).each do |i| measure_time = Time.now.to_i - (5+i) opts = {:measure_time => measure_time, :type => :counter} Metrics.submit :my_counter => opts.merge(:value => i) Metrics.submit :my_counter => opts.merge(:source => 'baz', :value => i+1) end end context "without arguments" do it "should get metric attributes" do metric = Metrics.get_metric :my_counter metric['name'].should == 'my_counter' metric['type'].should == 'counter' end end context "with a start_time" do it "should return entries since that time" do # 1 hr ago metric = Metrics.get_metric :my_counter, :start_time => Time.now-3600 data = metric['measurements'] data['unassigned'].length.should == 3 data['baz'].length.should == 2 end end context "with a count limit" do it "should return that number of entries per source" do metric = Metrics.get_metric :my_counter, :count => 2 data = metric['measurements'] data['unassigned'].length.should == 2 data['baz'].length.should == 2 end end context "with a source limit" do it "should only return that source" do metric = Metrics.get_metric :my_counter, :source => 'baz', :start_time => Time.now-3600 data = metric['measurements'] data['baz'].length.should == 2 data['unassigned'].should be_nil end end end describe "#metrics" do before(:all) do delete_all_metrics Metrics.submit :foo => 123, :bar => 345, :baz => 678, :foo_2 => 901 end context "without arguments" do it "should list all metrics" do metric_names = Metrics.metrics.map { |metric| metric['name'] } metric_names.sort.should == %w{foo bar baz foo_2}.sort end end context "with a name argument" do it "should list metrics that match" do metric_names = Metrics.metrics(:name => 'foo').map { |metric| metric['name'] } metric_names.sort.should == %w{foo foo_2}.sort end end end describe "#submit" do context "with a gauge" do before(:all) do delete_all_metrics Metrics.submit :foo => 123 end it "should create the metrics" do metric = Metrics.metrics[0] metric['name'].should == 'foo' metric['type'].should == 'gauge' end it "should store their data" do data = Metrics.get_measurements :foo, :count => 1 data.should_not be_empty data['unassigned'][0]['value'] == 123.0 end end context "with a counter" do before(:all) do delete_all_metrics Metrics.submit :bar => {:type => :counter, :source => 'baz', :value => 456} end it "should create the metrics" do metric = Metrics.metrics[0] metric['name'].should == 'bar' metric['type'].should == 'counter' end it "should store their data" do data = Metrics.get_measurements :bar, :count => 1 data.should_not be_empty data['baz'][0]['value'] == 456.0 end end it "should not retain errors" do delete_all_metrics Metrics.submit :foo => {:type => :counter, :value => 12} lambda { Metrics.submit :foo => 15 # submitting as gauge }.should raise_error lambda { Metrics.submit :foo => {:type => :counter, :value => 17} }.should_not raise_error end end describe "#update_metric[s]" do context 'with a single metric' do context "with an existing metric" do before do delete_all_metrics Metrics.submit :foo => 123 end it "should update the metric" do Metrics.update_metric :foo, :display_name => "Foo Metric", :period => 15, :attributes => { :display_max => 1000 } foo = Metrics.get_metric :foo foo['display_name'].should == 'Foo Metric' foo['period'].should == 15 foo['attributes']['display_max'].should == 1000 end end context "without an existing metric" do it "should create the metric if type specified" do delete_all_metrics Metrics.update_metric :foo, :display_name => "Foo Metric", :type => 'gauge', :period => 15, :attributes => { :display_max => 1000 } foo = Metrics.get_metric :foo foo['display_name'].should == 'Foo Metric' foo['period'].should == 15 foo['attributes']['display_max'].should == 1000 end it "should raise error if no type specified" do delete_all_metrics lambda { Metrics.update_metric :foo, :display_name => "Foo Metric", :period => 15, :attributes => { :display_max => 1000 } }.should raise_error end end end context 'with multiple metrics' do before do delete_all_metrics Metrics.submit 'my.1' => 1, 'my.2' => 2, 'my.3' => 3, 'my.4' => 4 end it "should support named list" do names = ['my.1', 'my.3'] Metrics.update_metrics :names => names, :period => 60 names.each do |name| metric = Metrics.get_metric name metric['period'].should == 60 end end it "should support patterns" do Metrics.update_metrics :names => 'my.*', :exclude => ['my.3'], :display_max => 100 %w{my.1 my.2 my.4}.each do |name| metric = Metrics.get_metric name metric['attributes']['display_max'].should == 100 end excluded = Metrics.get_metric 'my.3' excluded['attributes']['display_max'].should_not == 100 end end end describe "Sources API" do before do Metrics.update_source("sources_api_test", display_name: "Sources Api Test") end describe "#sources" do it "should work" do sources = Metrics.sources sources.should be_an(Array) test_source = sources.detect { |s| s["name"] == "sources_api_test" } test_source["display_name"].should == "Sources Api Test" end end describe "#get_source" do it "should work" do test_source = Metrics.get_source("sources_api_test") test_source["display_name"].should == "Sources Api Test" end end describe "#update_source" do it "should update an existing source" do Metrics.update_source("sources_api_test", display_name: "Updated Source Name") test_source = Metrics.get_source("sources_api_test") test_source["display_name"].should == "Updated Source Name" end it "should create new sources" do source_name = "sources_api_test_#{Time.now.to_f}" lambda { no_source = Metrics.get_source(source_name) }.should raise_error(Librato::Metrics::NotFound) Metrics.update_source(source_name, display_name: "New Source") test_source = Metrics.get_source(source_name) test_source.should_not be_nil test_source["display_name"].should == "New Source" end end end describe "Snapshots API" do it "should #create_snapshot" do subject = {instrument: {href: "http://api.librato.dev/v1/instruments/1"}} result = Metrics.create_snapshot(subject: subject) result["href"].should =~ /snapshots\/\d+$/ end it "should #get_snapshot" do subject = {instrument: {href: "http://api.librato.dev/v1/instruments/1"}} result = Metrics.create_snapshot(subject: subject) snapshot_id = result["href"][/(\d+)$/] result = Metrics.get_snapshot(snapshot_id) result["href"].should =~ /snapshots\/\d+$/ end end end end Manually create the instrument used to test the snapshot require 'spec_helper' module Librato describe Metrics do before(:all) { prep_integration_tests } describe "#annotate" do before(:all) { @annotator = Metrics::Annotator.new } before(:each) { delete_all_annotations } it "should create new annotation" do Metrics.annotate :deployment, "deployed v68" annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-60) annos["events"]["unassigned"].length.should == 1 annos["events"]["unassigned"][0]["title"].should == 'deployed v68' end it "should support sources" do Metrics.annotate :deployment, 'deployed v69', :source => 'box1' annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-60) annos["events"]["box1"].length.should == 1 first = annos["events"]["box1"][0] first['title'].should == 'deployed v69' end it "should support start and end times" do start_time = Time.now.to_i-120 end_time = Time.now.to_i-30 Metrics.annotate :deployment, 'deployed v70', :start_time => start_time, :end_time => end_time annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-180) annos["events"]["unassigned"].length.should == 1 first = annos["events"]["unassigned"][0] first['title'].should == 'deployed v70' first['start_time'].should == start_time first['end_time'].should == end_time end it "should support description" do Metrics.annotate :deployment, 'deployed v71', :description => 'deployed foobar!' annos = @annotator.fetch(:deployment, :start_time => Time.now.to_i-180) annos["events"]["unassigned"].length.should == 1 first = annos["events"]["unassigned"][0] first['title'].should == 'deployed v71' first['description'].should == 'deployed foobar!' end end describe "#delete_metrics" do before(:each) { delete_all_metrics } context 'by names' do context "with a single argument" do it "should delete named metric" do Metrics.submit :foo => 123 Metrics.metrics(:name => :foo).should_not be_empty Metrics.delete_metrics :foo Metrics.metrics(:name => :foo).should be_empty end end context "with multiple arguments" do it "should delete named metrics" do Metrics.submit :foo => 123, :bar => 345, :baz => 567 Metrics.delete_metrics :foo, :bar Metrics.metrics(:name => :foo).should be_empty Metrics.metrics(:name => :bar).should be_empty Metrics.metrics(:name => :baz).should_not be_empty end end context "with missing metric" do it "should run cleanly" do # the API currently returns success even if # the metric has already been deleted or is absent. Metrics.delete_metrics :missing end end context "with no arguments" do it "should not make request" do lambda { Metrics.delete_metrics }.should raise_error(Metrics::NoMetricsProvided) end end end context 'by pattern' do it "should filter properly" do Metrics.submit :foo => 1, :foobar => 2, :foobaz => 3, :bar => 4 Metrics.delete_metrics :names => 'fo*', :exclude => ['foobar'] %w{foo foobaz}.each do |name| lambda { Metrics.get_metric name }.should raise_error(Librato::Metrics::NotFound) end %w{foobar bar}.each do |name| Metrics.get_metric name # stil exist end end end end describe "#get_metric" do before(:all) do delete_all_metrics Metrics.submit :my_counter => {:type => :counter, :value => 0, :measure_time => Time.now.to_i-60} 1.upto(2).each do |i| measure_time = Time.now.to_i - (5+i) opts = {:measure_time => measure_time, :type => :counter} Metrics.submit :my_counter => opts.merge(:value => i) Metrics.submit :my_counter => opts.merge(:source => 'baz', :value => i+1) end end context "without arguments" do it "should get metric attributes" do metric = Metrics.get_metric :my_counter metric['name'].should == 'my_counter' metric['type'].should == 'counter' end end context "with a start_time" do it "should return entries since that time" do # 1 hr ago metric = Metrics.get_metric :my_counter, :start_time => Time.now-3600 data = metric['measurements'] data['unassigned'].length.should == 3 data['baz'].length.should == 2 end end context "with a count limit" do it "should return that number of entries per source" do metric = Metrics.get_metric :my_counter, :count => 2 data = metric['measurements'] data['unassigned'].length.should == 2 data['baz'].length.should == 2 end end context "with a source limit" do it "should only return that source" do metric = Metrics.get_metric :my_counter, :source => 'baz', :start_time => Time.now-3600 data = metric['measurements'] data['baz'].length.should == 2 data['unassigned'].should be_nil end end end describe "#metrics" do before(:all) do delete_all_metrics Metrics.submit :foo => 123, :bar => 345, :baz => 678, :foo_2 => 901 end context "without arguments" do it "should list all metrics" do metric_names = Metrics.metrics.map { |metric| metric['name'] } metric_names.sort.should == %w{foo bar baz foo_2}.sort end end context "with a name argument" do it "should list metrics that match" do metric_names = Metrics.metrics(:name => 'foo').map { |metric| metric['name'] } metric_names.sort.should == %w{foo foo_2}.sort end end end describe "#submit" do context "with a gauge" do before(:all) do delete_all_metrics Metrics.submit :foo => 123 end it "should create the metrics" do metric = Metrics.metrics[0] metric['name'].should == 'foo' metric['type'].should == 'gauge' end it "should store their data" do data = Metrics.get_measurements :foo, :count => 1 data.should_not be_empty data['unassigned'][0]['value'] == 123.0 end end context "with a counter" do before(:all) do delete_all_metrics Metrics.submit :bar => {:type => :counter, :source => 'baz', :value => 456} end it "should create the metrics" do metric = Metrics.metrics[0] metric['name'].should == 'bar' metric['type'].should == 'counter' end it "should store their data" do data = Metrics.get_measurements :bar, :count => 1 data.should_not be_empty data['baz'][0]['value'] == 456.0 end end it "should not retain errors" do delete_all_metrics Metrics.submit :foo => {:type => :counter, :value => 12} lambda { Metrics.submit :foo => 15 # submitting as gauge }.should raise_error lambda { Metrics.submit :foo => {:type => :counter, :value => 17} }.should_not raise_error end end describe "#update_metric[s]" do context 'with a single metric' do context "with an existing metric" do before do delete_all_metrics Metrics.submit :foo => 123 end it "should update the metric" do Metrics.update_metric :foo, :display_name => "Foo Metric", :period => 15, :attributes => { :display_max => 1000 } foo = Metrics.get_metric :foo foo['display_name'].should == 'Foo Metric' foo['period'].should == 15 foo['attributes']['display_max'].should == 1000 end end context "without an existing metric" do it "should create the metric if type specified" do delete_all_metrics Metrics.update_metric :foo, :display_name => "Foo Metric", :type => 'gauge', :period => 15, :attributes => { :display_max => 1000 } foo = Metrics.get_metric :foo foo['display_name'].should == 'Foo Metric' foo['period'].should == 15 foo['attributes']['display_max'].should == 1000 end it "should raise error if no type specified" do delete_all_metrics lambda { Metrics.update_metric :foo, :display_name => "Foo Metric", :period => 15, :attributes => { :display_max => 1000 } }.should raise_error end end end context 'with multiple metrics' do before do delete_all_metrics Metrics.submit 'my.1' => 1, 'my.2' => 2, 'my.3' => 3, 'my.4' => 4 end it "should support named list" do names = ['my.1', 'my.3'] Metrics.update_metrics :names => names, :period => 60 names.each do |name| metric = Metrics.get_metric name metric['period'].should == 60 end end it "should support patterns" do Metrics.update_metrics :names => 'my.*', :exclude => ['my.3'], :display_max => 100 %w{my.1 my.2 my.4}.each do |name| metric = Metrics.get_metric name metric['attributes']['display_max'].should == 100 end excluded = Metrics.get_metric 'my.3' excluded['attributes']['display_max'].should_not == 100 end end end describe "Sources API" do before do Metrics.update_source("sources_api_test", display_name: "Sources Api Test") end describe "#sources" do it "should work" do sources = Metrics.sources sources.should be_an(Array) test_source = sources.detect { |s| s["name"] == "sources_api_test" } test_source["display_name"].should == "Sources Api Test" end end describe "#get_source" do it "should work" do test_source = Metrics.get_source("sources_api_test") test_source["display_name"].should == "Sources Api Test" end end describe "#update_source" do it "should update an existing source" do Metrics.update_source("sources_api_test", display_name: "Updated Source Name") test_source = Metrics.get_source("sources_api_test") test_source["display_name"].should == "Updated Source Name" end it "should create new sources" do source_name = "sources_api_test_#{Time.now.to_f}" lambda { no_source = Metrics.get_source(source_name) }.should raise_error(Librato::Metrics::NotFound) Metrics.update_source(source_name, display_name: "New Source") test_source = Metrics.get_source(source_name) test_source.should_not be_nil test_source["display_name"].should == "New Source" end end end describe "Snapshots API" do let(:instrument_id) do instrument_options = {name: "Snapshot test subject"} conn = Metrics.connection resp = conn.post do |req| req.url conn.build_url("/v1/instruments") req.body = Librato::Metrics::SmartJSON.write(instrument_options) end instrument_id = Librato::Metrics::SmartJSON.read(resp.body)["id"] end let(:subject) do {instrument: {href: "http://api.librato.dev/v1/instruments/#{instrument_id}"}} end it "should #create_snapshot" do result = Metrics.create_snapshot(subject: subject) result["href"].should =~ /snapshots\/\d+$/ end it "should #get_snapshot" do result = Metrics.create_snapshot(subject: subject) snapshot_id = result["href"][/(\d+)$/] result = Metrics.get_snapshot(snapshot_id) result["href"].should =~ /snapshots\/\d+$/ end end end end
require "spec_helper" require "hamster/set" describe Hamster::Set do [:any?, :exist?, :exists?].each do |method| describe "##{method}" do context "when empty" do it "with a block returns false" do Hamster.set.send(method) {}.should == false end it "with no block returns false" do Hamster.set.send(method).should == false end end context "when not empty" do context "with a block" do let(:set) { Hamster.set("A", "B", "C", nil) } ["A", "B", "C", nil].each do |value| it "returns true if the block ever returns true (#{value.inspect})" do set.send(method) { |item| item == value }.should == true end end it "returns false if the block always returns false" do set.send(method) { |item| item == "D" }.should == false end it "propagates exceptions raised in the block" do -> { set.any? { |k,v| raise "help" } }.should raise_error(RuntimeError) end it "stops iterating as soon as the block returns true" do yielded = [] set.any? { |k,v| yielded << k; true } yielded.size.should == 1 end end context "with no block" do it "returns true if any value is truthy" do Hamster.set(nil, false, true, "A").send(method).should == true end it "returns false if all values are falsey" do Hamster.set(nil, false).send(method).should == false end end end end end end Removed extraneous line from Hash#any? spec require "spec_helper" require "hamster/set" describe Hamster::Set do [:any?, :exist?, :exists?].each do |method| describe "##{method}" do context "when empty" do it "with a block returns false" do Hamster.set.send(method) {}.should == false end it "with no block returns false" do Hamster.set.send(method).should == false end end context "when not empty" do context "with a block" do let(:set) { Hamster.set("A", "B", "C", nil) } ["A", "B", "C", nil].each do |value| it "returns true if the block ever returns true (#{value.inspect})" do set.send(method) { |item| item == value }.should == true end end it "returns false if the block always returns false" do set.send(method) { |item| item == "D" }.should == false end it "propagates exceptions raised in the block" do -> { set.any? { |k,v| raise "help" } }.should raise_error(RuntimeError) end it "stops iterating as soon as the block returns true" do yielded = [] set.any? { |k,v| yielded << k; true } yielded.size.should == 1 end end context "with no block" do it "returns true if any value is truthy" do Hamster.set(nil, false, true, "A").send(method).should == true end it "returns false if all values are falsey" do Hamster.set(nil, false).send(method).should == false end end end end end end
require 'spec_helper' describe LocaSMS::Numbers do subject { LocaSMS::Numbers.new } describe '.initialize' do subject do expect_any_instance_of(LocaSMS::Numbers) .to receive(:evaluate) .once .with([:numbers]) .and_return({ good: [1,3], bad: [2,4] }) LocaSMS::Numbers.new :numbers end it { expect(subject.good).to eq([1,3]) } it { expect(subject.bad).to eq([2,4]) } end describe '#normalize' do it do expect(subject.normalize('+55 (11) 8888-9999')).to( eq(%w(551188889999)) ) end it do expect(subject.normalize('55', ['11', '22'])).to( eq(%w(55 11 22)) ) end it do expect(subject.normalize(['55', 'ZZ', '22'])).to( eq(%w(55 ZZ 22)) ) end it do expect(subject.normalize('55,44,33', ['ZZ', '22,11'])).to( eq(%w(55 44 33 ZZ 22 11)) ) end it do expect(subject.normalize(55, [11, 22])).to( eq(%w(55 11 22)) ) end it { expect(subject.normalize('Z')).to eq(['Z']) } it { expect(subject.normalize(nil)).to eq([]) } end describe '#valid_number?' do it { expect(subject.valid_number?('+55 (11) 8888-9999')).to be_falsey } it { expect(subject.valid_number?('88889999')).to be_falsey } it { expect(subject.valid_number?('988889999')).to be_falsey } it { expect(subject.valid_number?('ABC')).to be_falsey } it { expect(subject.valid_number?('')).to be_falsey } it { expect(subject.valid_number?(nil)).to be_falsey } it { expect(subject.valid_number?('1188889999')).to be_truthy } it { expect(subject.valid_number?('11988889999')).to be_truthy } end describe '#evaluate' do it 'Should separate numbers in good and bad' do expect(subject).to receive(:normalize) .once .with([:numbers]) .and_return([:good, :bad]) expect(subject).to receive(:valid_number?) .once .with(:good) .and_return(true) expect(subject).to receive(:valid_number?) .once .with(:bad) .and_return(false) expect(subject.evaluate(:numbers)).to( eq({ good: [:good], bad: [:bad] }) ) end end describe '#bad?' do it do expect(subject).to receive(:bad).once.and_return([ ]) expect(subject.bad?).to be_falsey end it do expect(subject).to receive(:bad).once.and_return([1]) expect(subject.bad?).to be_truthy end end describe '#to_s' do it 'Should return and empty string' do expect(subject.to_s).to eq('') end it 'Should return all good numbers in a string comma separated' do expect(subject).to receive(:good) .once .and_return([1,2,3,4]) expect(subject.to_s).to eq('1,2,3,4') end end end houndci sugested changes require 'spec_helper' describe LocaSMS::Numbers do subject { LocaSMS::Numbers.new } describe '.initialize' do subject do expect_any_instance_of(LocaSMS::Numbers). to receive(:evaluate). once. with([:numbers]). and_return(good: [1,3], bad: [2,4]) LocaSMS::Numbers.new :numbers end it { expect(subject.good).to eq([1,3]) } it { expect(subject.bad).to eq([2,4]) } end describe '#normalize' do it do expect(subject.normalize('+55 (11) 8888-9999')).to( eq(%w(551188889999)) ) end it do expect(subject.normalize('55', ['11', '22'])).to( eq(%w(55 11 22)) ) end it do expect(subject.normalize(['55', 'ZZ', '22'])).to( eq(%w(55 ZZ 22)) ) end it do expect(subject.normalize('55,44,33', ['ZZ', '22,11'])).to( eq(%w(55 44 33 ZZ 22 11)) ) end it do expect(subject.normalize(55, [11, 22])).to( eq(%w(55 11 22)) ) end it { expect(subject.normalize('Z')).to eq(['Z']) } it { expect(subject.normalize(nil)).to eq([]) } end describe '#valid_number?' do it { expect(subject.valid_number?('+55 (11) 8888-9999')).to be_falsey } it { expect(subject.valid_number?('88889999')).to be_falsey } it { expect(subject.valid_number?('988889999')).to be_falsey } it { expect(subject.valid_number?('ABC')).to be_falsey } it { expect(subject.valid_number?('')).to be_falsey } it { expect(subject.valid_number?(nil)).to be_falsey } it { expect(subject.valid_number?('1188889999')).to be_truthy } it { expect(subject.valid_number?('11988889999')).to be_truthy } end describe '#evaluate' do it 'Should separate numbers in good and bad' do expect(subject).to receive(:normalize). once. with([:numbers]). and_return([:good, :bad]) expect(subject).to receive(:valid_number?). once. with(:good). and_return(true). expect(subject).to receive(:valid_number?) once. with(:bad). and_return(false) expect(subject.evaluate(:numbers)).to( eq(good: [:good], bad: [:bad]) ) end end describe '#bad?' do it do expect(subject).to receive(:bad).once.and_return([ ]) expect(subject.bad?).to be_falsey end it do expect(subject).to receive(:bad).once.and_return([1]) expect(subject.bad?).to be_truthy end end describe '#to_s' do it 'Should return and empty string' do expect(subject.to_s).to eq('') end it 'Should return all good numbers in a string comma separated' do expect(subject).to receive(:good). once. and_return([1,2,3,4]) expect(subject.to_s).to eq('1,2,3,4') end end end
# -*- encoding: utf-8 -*- require 'spec_helper' describe CheckedItem do fixtures :all it "should respond to available_for_checkout?" do checked_items(:checked_item_00001).available_for_checkout?.should_not be_true end end # == Schema Information # # Table name: checked_items # # id :integer not null, primary key # item_id :integer not null # basket_id :integer not null # due_date :datetime not null # created_at :datetime # updated_at :datetime # refs5672 modieid spec file of checked_item # -*- encoding: utf-8 -*- require 'spec_helper' describe CheckedItem do fixtures :all describe 'validates' do describe '' do #validates_associated :item, :basket, :on => :update it '' # TODO end describe '' do #validates_presence_of :item, :basket, :due_date, :on => :update it '' # TODO end describe '' do #validates_uniqueness_of :item_id, :scope => :basket_id end describe '' do #validate :available_for_checkout?, :on => :create end describe '' do #before_validation :set_due_date, :on => :create end end describe '#available_for_checkout?' do it '' # TODO: immediately # 以下のテストじゃ足らないので強化すること it "should respond to available_for_checkout?" do checked_items(:checked_item_00001).available_for_checkout?.should_not be_true end end describe '#item_checkout_type' do it '' # TODO end describe '#set_due_date' do it '' # TODO: immediately end describe '#in_transaction?' do it '' # TODO end describe '#destroy_reservation' do it '' # TODO: immediately end describe '#available_for_reserve_checkout?' do it '' # TODO: immediately end describe '#exchange_reserve_item' do it '' # TODO: immediately end end # == Schema Information # # Table name: checked_items # # id :integer not null, primary key # item_id :integer not null # basket_id :integer not null # due_date :datetime not null # created_at :datetime # updated_at :datetime #
# == Schema Information # # Table name: feed_versions # # id :integer not null, primary key # feed_id :integer # feed_type :string # file :string # earliest_calendar_date :date # latest_calendar_date :date # sha1 :string # md5 :string # tags :hstore # fetched_at :datetime # imported_at :datetime # created_at :datetime # updated_at :datetime # import_level :integer default(0) # url :string # file_raw :string # sha1_raw :string # md5_raw :string # # Indexes # # index_feed_versions_on_feed_type_and_feed_id (feed_type,feed_id) # describe FeedVersion do it 'computes file hashes' do feed_version = create(:feed_version_bart) expect(feed_version.sha1).to eq '2d340d595ec566ba54b0a6a25359f71d94268b5c' expect(feed_version.md5).to eq '1197a60bab8f685492aa9e50a732b466' end it 'reads earliest and latest dates from calendars.txt' do feed_version = create(:feed_version_bart) expect(feed_version.earliest_calendar_date).to eq Date.parse('2013-11-28') expect(feed_version.latest_calendar_date).to eq Date.parse('2017-01-01') end it 'reads feed_info.txt and puts into tags' do feed_version = create(:feed_version_bart) expect(feed_version.tags['feed_lang']).to eq 'en' expect(feed_version.tags['feed_version']).to eq '36' expect(feed_version.tags['feed_publisher_url']).to eq 'http://www.bart.gov' expect(feed_version.tags['feed_publisher_name']).to eq 'Bay Area Rapid Transit' end context 'imported_schedule_stop_pairs' do before(:each) do @feed_version = create(:feed_version) @ssp = create(:schedule_stop_pair, feed: @feed_version.feed, feed_version: @feed_version) end it '#delete_schedule_stop_pairs' do @feed_version.delete_schedule_stop_pairs! expect(ScheduleStopPair.exists?(@ssp.id)).to be false expect(@feed_version.imported_schedule_stop_pairs.count).to eq(0) end end it 'is active feed version' do feed = create(:feed) active_feed_version = create(:feed_version, feed: feed) inactive_feed_version = create(:feed_version, feed: feed) feed.update(active_feed_version: active_feed_version) expect(active_feed_version.is_active_feed_version).to eq true expect(inactive_feed_version.is_active_feed_version).to eq false end end Spec tidy up # == Schema Information # # Table name: feed_versions # # id :integer not null, primary key # feed_id :integer # feed_type :string # file :string # earliest_calendar_date :date # latest_calendar_date :date # sha1 :string # md5 :string # tags :hstore # fetched_at :datetime # imported_at :datetime # created_at :datetime # updated_at :datetime # import_level :integer default(0) # url :string # file_raw :string # sha1_raw :string # md5_raw :string # # Indexes # # index_feed_versions_on_feed_type_and_feed_id (feed_type,feed_id) # describe FeedVersion do context '#compute_and_set_hashes' do it 'computes file hashes' do feed_version = create(:feed_version_bart) expect(feed_version.sha1).to eq '2d340d595ec566ba54b0a6a25359f71d94268b5c' expect(feed_version.md5).to eq '1197a60bab8f685492aa9e50a732b466' end end context '#read_gtfs_calendar_dates' do it 'reads earliest and latest dates from calendars.txt' do feed_version = create(:feed_version_bart) expect(feed_version.earliest_calendar_date).to eq Date.parse('2013-11-28') expect(feed_version.latest_calendar_date).to eq Date.parse('2017-01-01') end end context '#read_gtfs_feed_info' do it 'reads feed_info.txt and puts into tags' do feed_version = create(:feed_version_bart) expect(feed_version.tags['feed_lang']).to eq 'en' expect(feed_version.tags['feed_version']).to eq '36' expect(feed_version.tags['feed_publisher_url']).to eq 'http://www.bart.gov' expect(feed_version.tags['feed_publisher_name']).to eq 'Bay Area Rapid Transit' end end context '#imported_schedule_stop_pairs' do before(:each) do @feed_version = create(:feed_version) @ssp = create(:schedule_stop_pair, feed: @feed_version.feed, feed_version: @feed_version) end it '#delete_schedule_stop_pairs' do @feed_version.delete_schedule_stop_pairs! expect(ScheduleStopPair.exists?(@ssp.id)).to be false expect(@feed_version.imported_schedule_stop_pairs.count).to eq(0) end end context '#is_active_feed_version' do it 'is active feed version' do feed = create(:feed) active_feed_version = create(:feed_version, feed: feed) inactive_feed_version = create(:feed_version, feed: feed) feed.update(active_feed_version: active_feed_version) expect(active_feed_version.is_active_feed_version).to eq true expect(inactive_feed_version.is_active_feed_version).to eq false end end end
require "rails_helper" RSpec.describe I18nContent, type: :model do let(:i18n_content) { build(:i18n_content) } it "is valid" do expect(i18n_content).to be_valid end it "is not valid if key is not unique" do new_content = create(:i18n_content) expect(i18n_content).not_to be_valid expect(i18n_content.errors.size).to eq(1) end context "Globalize" do it "translates key into multiple languages" do key = "devise_views.mailer.confirmation_instructions.welcome" welcome = build(:i18n_content, key: key, value_en: "Welcome", value_es: "Bienvenido") expect(welcome.value_en).to eq("Welcome") expect(welcome.value_es).to eq("Bienvenido") end it "responds to locales defined on model" do expect(i18n_content).to respond_to(:value_en) expect(i18n_content).to respond_to(:value_es) expect(i18n_content).not_to respond_to(:value_wl) end it "returns nil if translations are not available" do expect(i18n_content.value_en).to eq("Text in english") expect(i18n_content.value_es).to eq("Texto en español") expect(i18n_content.value_nl).to be(nil) expect(i18n_content.value_fr).to be(nil) end it "responds accordingly to the current locale" do expect(i18n_content.value).to eq("Text in english") I18n.with_locale(:es) { expect(i18n_content.value).to eq("Texto en español") } end end describe "#flat_hash" do it "uses one parameter" do expect(I18nContent.flat_hash(nil)).to eq({ nil => nil }) expect(I18nContent.flat_hash("string")).to eq({ nil => "string" }) expect(I18nContent.flat_hash({ w: "string" })).to eq({ "w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }})).to eq({ "w.p" => "string" }) end it "uses the first two parameters" do expect(I18nContent.flat_hash("string", "f")).to eq({ "f" => "string" }) expect(I18nContent.flat_hash(nil, "f")).to eq({ "f" => nil }) expect(I18nContent.flat_hash({ w: "string" }, "f")).to eq({ "f.w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }}, "f")).to eq({ "f.w.p" => "string" }) end it "uses the first and last parameters" do expect { I18nContent.flat_hash("string", nil, "not hash") }.to raise_error(NoMethodError) expect(I18nContent.flat_hash(nil, nil, { q: "other string" })).to eq({ q: "other string", nil => nil }) expect(I18nContent.flat_hash({ w: "string" }, nil, { q: "other string" })).to eq({ q: "other string", "w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }}, nil, { q: "other string" })).to eq({ q: "other string", "w.p" => "string" }) end it "uses all parameters" do expect { I18nContent.flat_hash("string", "f", "not hash") }.to raise_error NoMethodError expect(I18nContent.flat_hash(nil, "f", { q: "other string" })).to eq({ q: "other string", "f" => nil }) expect(I18nContent.flat_hash({ w: "string" }, "f", { q: "other string" })).to eq({ q: "other string", "f.w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }}, "f", { q: "other string" })).to eq({ q: "other string", "f.w.p" => "string" }) end end end Remove useless assignment in i18n content spec require "rails_helper" RSpec.describe I18nContent, type: :model do let(:i18n_content) { build(:i18n_content, key: "awe.so.me") } it "is valid" do expect(i18n_content).to be_valid end it "is not valid if key is not unique" do create(:i18n_content, key: "awe.so.me") expect(i18n_content).not_to be_valid expect(i18n_content.errors.size).to eq(1) end context "Globalize" do it "translates key into multiple languages" do key = "devise_views.mailer.confirmation_instructions.welcome" welcome = build(:i18n_content, key: key, value_en: "Welcome", value_es: "Bienvenido") expect(welcome.value_en).to eq("Welcome") expect(welcome.value_es).to eq("Bienvenido") end it "responds to locales defined on model" do expect(i18n_content).to respond_to(:value_en) expect(i18n_content).to respond_to(:value_es) expect(i18n_content).not_to respond_to(:value_wl) end it "returns nil if translations are not available" do expect(i18n_content.value_en).to eq("Text in english") expect(i18n_content.value_es).to eq("Texto en español") expect(i18n_content.value_nl).to be(nil) expect(i18n_content.value_fr).to be(nil) end it "responds accordingly to the current locale" do expect(i18n_content.value).to eq("Text in english") I18n.with_locale(:es) { expect(i18n_content.value).to eq("Texto en español") } end end describe "#flat_hash" do it "uses one parameter" do expect(I18nContent.flat_hash(nil)).to eq({ nil => nil }) expect(I18nContent.flat_hash("string")).to eq({ nil => "string" }) expect(I18nContent.flat_hash({ w: "string" })).to eq({ "w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }})).to eq({ "w.p" => "string" }) end it "uses the first two parameters" do expect(I18nContent.flat_hash("string", "f")).to eq({ "f" => "string" }) expect(I18nContent.flat_hash(nil, "f")).to eq({ "f" => nil }) expect(I18nContent.flat_hash({ w: "string" }, "f")).to eq({ "f.w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }}, "f")).to eq({ "f.w.p" => "string" }) end it "uses the first and last parameters" do expect { I18nContent.flat_hash("string", nil, "not hash") }.to raise_error(NoMethodError) expect(I18nContent.flat_hash(nil, nil, { q: "other string" })).to eq({ q: "other string", nil => nil }) expect(I18nContent.flat_hash({ w: "string" }, nil, { q: "other string" })).to eq({ q: "other string", "w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }}, nil, { q: "other string" })).to eq({ q: "other string", "w.p" => "string" }) end it "uses all parameters" do expect { I18nContent.flat_hash("string", "f", "not hash") }.to raise_error NoMethodError expect(I18nContent.flat_hash(nil, "f", { q: "other string" })).to eq({ q: "other string", "f" => nil }) expect(I18nContent.flat_hash({ w: "string" }, "f", { q: "other string" })).to eq({ q: "other string", "f.w" => "string" }) expect(I18nContent.flat_hash({ w: { p: "string" }}, "f", { q: "other string" })).to eq({ q: "other string", "f.w.p" => "string" }) end end end
# Copyright (c) 2010, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. require 'spec_helper' describe User do let(:user) { make_user } let(:aspect) { user.aspects.create(:name => 'heroes') } let(:user2) { make_user } let(:aspect2) { user2.aspects.create(:name => 'losers') } let(:user3) { make_user } let(:aspect3) { user3.aspects.create(:name => 'heroes') } before do friend_users(user, aspect, user2, aspect2) end it 'should stream only one message to the everyone aspect when a multi-aspected friend posts' do user.add_person_to_aspect(user2.person.id, user.aspect(:name => "villains").id) status = user2.post(:status_message, :message => "Users do things", :to => aspect2.id) xml = status.to_diaspora_xml Diaspora::WebSocket.should_receive(:queue_to_user).exactly(:once) user.receive xml, user2.person end it 'should be able to parse and store a status message from xml' do status_message = user2.post :status_message, :message => 'store this!', :to => aspect2.id xml = status_message.to_diaspora_xml user2.delete status_message.destroy lambda {user.receive xml , user2.person}.should change(Post,:count).by(1) end it 'should not create new aspects on message receive' do num_aspects = user.aspects.size (0..5).each{ |n| status_message = user2.post :status_message, :message => "store this #{n}!", :to => aspect2.id xml = status_message.to_diaspora_xml user.receive xml, user2.person } user.aspects.size.should == num_aspects end describe 'post refs' do before do @status_message = user2.post :status_message, :message => "hi", :to =>aspect2.id user.receive @status_message.to_diaspora_xml, user2.person user.reload end it "should add a received post to the aspect and visible_posts array" do user.raw_visible_posts.include?(@status_message).should be true aspect.reload aspect.posts.include?(@status_message).should be_true end it 'should be removed on unfriending' do user.unfriend(user2.person) user.reload user.raw_visible_posts.count.should == 0 end it 'should be remove a post if the noone links to it' do person = user2.person user2.delete lambda {user.unfriend(person)}.should change(Post, :count).by(-1) user.reload user.raw_visible_posts.count.should == 0 end it 'should keep track of user references for one person ' do @status_message.reload @status_message.user_refs.should == 1 user.unfriend(user2.person) @status_message.reload @status_message.user_refs.should == 0 end it 'should not override userrefs on receive by another person' do user3.activate_friend(user2.person, aspect3) user3.receive @status_message.to_diaspora_xml, user2.person @status_message.reload @status_message.user_refs.should == 2 user.unfriend(user2.person) @status_message.reload @status_message.user_refs.should == 1 end end describe 'comments' do before do friend_users(user, aspect, user3, aspect3) @post = user.post :status_message, :message => "hello", :to => aspect.id user2.receive @post.to_diaspora_xml, user.person user3.receive @post.to_diaspora_xml, user.person @comment = user3.comment('tada',:on => @post) @comment.post_creator_signature = @comment.sign_with_key(user.encryption_key) @xml = user.salmon(@comment).xml_for(user2.person) @comment.delete end it 'should correctly attach the user already on the pod' do local_person = user3.person user2.reload.raw_visible_posts.size.should == 1 post_in_db = user2.raw_visible_posts.first post_in_db.comments.should == [] user2.receive_salmon(@xml) post_in_db.reload post_in_db.comments.include?(@comment).should be true post_in_db.comments.first.person.should == local_person end it 'should correctly marshal a stranger for the downstream user' do remote_person = user3.person remote_person.delete user3.delete #stubs async webfinger Person.should_receive(:by_account_identifier).twice.and_return{ |handle| if handle == user.person.diaspora_handle; user.person.save user.person; else; remote_person.save; remote_person; end } user2.reload.raw_visible_posts.size.should == 1 post_in_db = user2.raw_visible_posts.first post_in_db.comments.should == [] user2.receive_salmon(@xml) post_in_db.reload post_in_db.comments.include?(@comment).should be true post_in_db.comments.first.person.should == remote_person end end describe 'salmon' do let(:post){user.post :status_message, :message => "hello", :to => aspect.id} let(:salmon){user.salmon( post )} it 'should receive a salmon for a post' do user2.receive_salmon( salmon.xml_for user2.person ) user2.visible_post_ids.include?(post.id).should be true end end end user.aspect is gone # Copyright (c) 2010, Diaspora Inc. This file is # licensed under the Affero General Public License version 3 or later. See # the COPYRIGHT file. require 'spec_helper' describe User do let(:user) { make_user } let(:aspect) { user.aspects.create(:name => 'heroes') } let(:user2) { make_user } let(:aspect2) { user2.aspects.create(:name => 'losers') } let(:user3) { make_user } let(:aspect3) { user3.aspects.create(:name => 'heroes') } before do friend_users(user, aspect, user2, aspect2) end it 'should stream only one message to the everyone aspect when a multi-aspected friend posts' do user.add_person_to_aspect(user2.person.id, user.aspects.create(:name => "villains").id) status = user2.post(:status_message, :message => "Users do things", :to => aspect2.id) xml = status.to_diaspora_xml Diaspora::WebSocket.should_receive(:queue_to_user).exactly(:once) user.receive xml, user2.person end it 'should be able to parse and store a status message from xml' do status_message = user2.post :status_message, :message => 'store this!', :to => aspect2.id xml = status_message.to_diaspora_xml user2.delete status_message.destroy lambda {user.receive xml , user2.person}.should change(Post,:count).by(1) end it 'should not create new aspects on message receive' do num_aspects = user.aspects.size (0..5).each{ |n| status_message = user2.post :status_message, :message => "store this #{n}!", :to => aspect2.id xml = status_message.to_diaspora_xml user.receive xml, user2.person } user.aspects.size.should == num_aspects end describe 'post refs' do before do @status_message = user2.post :status_message, :message => "hi", :to =>aspect2.id user.receive @status_message.to_diaspora_xml, user2.person user.reload end it "should add a received post to the aspect and visible_posts array" do user.raw_visible_posts.include?(@status_message).should be true aspect.reload aspect.posts.include?(@status_message).should be_true end it 'should be removed on unfriending' do user.unfriend(user2.person) user.reload user.raw_visible_posts.count.should == 0 end it 'should be remove a post if the noone links to it' do person = user2.person user2.delete lambda {user.unfriend(person)}.should change(Post, :count).by(-1) user.reload user.raw_visible_posts.count.should == 0 end it 'should keep track of user references for one person ' do @status_message.reload @status_message.user_refs.should == 1 user.unfriend(user2.person) @status_message.reload @status_message.user_refs.should == 0 end it 'should not override userrefs on receive by another person' do user3.activate_friend(user2.person, aspect3) user3.receive @status_message.to_diaspora_xml, user2.person @status_message.reload @status_message.user_refs.should == 2 user.unfriend(user2.person) @status_message.reload @status_message.user_refs.should == 1 end end describe 'comments' do before do friend_users(user, aspect, user3, aspect3) @post = user.post :status_message, :message => "hello", :to => aspect.id user2.receive @post.to_diaspora_xml, user.person user3.receive @post.to_diaspora_xml, user.person @comment = user3.comment('tada',:on => @post) @comment.post_creator_signature = @comment.sign_with_key(user.encryption_key) @xml = user.salmon(@comment).xml_for(user2.person) @comment.delete end it 'should correctly attach the user already on the pod' do local_person = user3.person user2.reload.raw_visible_posts.size.should == 1 post_in_db = user2.raw_visible_posts.first post_in_db.comments.should == [] user2.receive_salmon(@xml) post_in_db.reload post_in_db.comments.include?(@comment).should be true post_in_db.comments.first.person.should == local_person end it 'should correctly marshal a stranger for the downstream user' do remote_person = user3.person remote_person.delete user3.delete #stubs async webfinger Person.should_receive(:by_account_identifier).twice.and_return{ |handle| if handle == user.person.diaspora_handle; user.person.save user.person; else; remote_person.save; remote_person; end } user2.reload.raw_visible_posts.size.should == 1 post_in_db = user2.raw_visible_posts.first post_in_db.comments.should == [] user2.receive_salmon(@xml) post_in_db.reload post_in_db.comments.include?(@comment).should be true post_in_db.comments.first.person.should == remote_person end end describe 'salmon' do let(:post){user.post :status_message, :message => "hello", :to => aspect.id} let(:salmon){user.salmon( post )} it 'should receive a salmon for a post' do user2.receive_salmon( salmon.xml_for user2.person ) user2.visible_post_ids.include?(post.id).should be true end end end
require "spec_helper" describe Moped::IO::Connection do describe "#alive?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end after do connection.disconnect end context "when the socket is alive" do before do connection.connect end it "returns true" do expect(connection).to be_alive end end context "when the socket is not alive" do before do connection.connect connection.instance_variable_get(:@sock).close end it "returns false" do expect(connection).to_not be_alive end end context "when the socket is nil" do it "returns false" do expect(connection).to_not be_alive end end end pending "#connect" do context "when using ssl" do end context "when using tcp" do end context "when using unix" do end end describe "#connected?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end context "when the connection is connected" do before do connection.connect end after do connection.disconnect end it "returns true" do expect(connection).to be_connected end end context "when the connection is not connected" do it "returns false" do expect(connection).to_not be_connected end end end end Add specs around disconnect require "spec_helper" describe Moped::IO::Connection do describe "#alive?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end after do connection.disconnect end context "when the socket is alive" do before do connection.connect end it "returns true" do expect(connection).to be_alive end end context "when the socket is not alive" do before do connection.connect connection.instance_variable_get(:@sock).close end it "returns false" do expect(connection).to_not be_alive end end context "when the socket is nil" do it "returns false" do expect(connection).to_not be_alive end end end pending "#connect" do context "when using ssl" do end context "when using tcp" do end context "when using unix" do end end describe "#connected?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end context "when the connection is connected" do before do connection.connect end after do connection.disconnect end it "returns true" do expect(connection).to be_connected end end context "when the connection is not connected" do it "returns false" do expect(connection).to_not be_connected end end end describe "#disconnect" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end before do connection.connect connection.disconnect end it "disconnects the connection" do expect(connection).to_not be_connected end it "sets the socket to nil" do expect(connection.instance_variable_get(:@sock)).to be_nil end end end
require "spec_helper" describe Moped::IO::Connection do describe "#alive?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end after do connection.disconnect end context "when the socket is alive" do before do connection.connect end it "returns true" do expect(connection).to be_alive end end context "when the socket is not alive" do before do connection.connect connection.instance_variable_get(:@sock).close end it "returns false" do expect(connection).to_not be_alive end end context "when the socket is nil" do it "returns false" do expect(connection).to_not be_alive end end end end Add specs around connected require "spec_helper" describe Moped::IO::Connection do describe "#alive?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end after do connection.disconnect end context "when the socket is alive" do before do connection.connect end it "returns true" do expect(connection).to be_alive end end context "when the socket is not alive" do before do connection.connect connection.instance_variable_get(:@sock).close end it "returns false" do expect(connection).to_not be_alive end end context "when the socket is nil" do it "returns false" do expect(connection).to_not be_alive end end end pending "#connect" do context "when using ssl" do end context "when using tcp" do end context "when using unix" do end end describe "#connected?" do let(:connection) do described_class.new("127.0.0.1", 27017, 2) end context "when the connection is connected" do before do connection.connect end after do connection.disconnect end it "returns true" do expect(connection).to be_connected end end context "when the connection is not connected" do it "returns false" do expect(connection).to_not be_connected end end end end
require 'spec_helper' describe Mumukit::Auth::Permissions do let(:permissions) do Mumukit::Auth::Permissions.new( student: Mumukit::Auth::Scope.parse('foo/*:test/*'), owner: Mumukit::Auth::Scope.parse('test/*'), teacher: Mumukit::Auth::Scope.parse('foo/baz')) end let(:parsed_permissions) do Mumukit::Auth::Permissions.load(permissions.to_json) end it { expect(permissions).to json_like Mumukit::Auth::Permissions.parse(student: 'foo/*:test/*', owner: 'test/*', teacher: 'foo/baz') } it { expect(permissions).to json_like Mumukit::Auth::Permissions.parse('student' => 'foo/*:test/*', 'owner' => 'test/*', 'teacher' => 'foo/baz') } it { expect(permissions.teacher? 'foobar/baz').to be false } it { expect(permissions.teacher? 'foobar/_').to be false } it { expect(permissions.teacher? Mumukit::Auth::Slug.parse('foo/baz')).to be true } it { expect(permissions.teacher? Mumukit::Auth::Slug.parse('foobar/_')).to be false } it { expect(permissions.teacher? 'foo/baz').to be true } it { expect(permissions.teacher? 'foo/_').to be true } it { expect(permissions.owner? 'test/student').to be true } it { expect(permissions.owner? 'test/_').to be true } it { expect(permissions.writer? 'test/student').to be false } it { expect(permissions.writer? 'test/_').to be false } it { expect(permissions.student? 'foo/bar').to be true } it { expect(permissions.student? 'test/student').to be true } it { expect(permissions.student? 'foo/student').to be true } it { expect(permissions.student? 'baz/student').to be false } it { expect(permissions.student? 'baz/_').to be false } it { expect(parsed_permissions.student? 'foo/bar').to be true } it { expect(parsed_permissions.student? 'test/student').to be true } it { expect(parsed_permissions.student? 'foo/student').to be true } it { expect(parsed_permissions.student? 'baz/student').to be false } it { expect(parsed_permissions.student? 'baz/_').to be false } it { expect { parsed_permissions.protect! :student, 'baz/_' }.to raise_error(Mumukit::Auth::UnauthorizedAccessError) } it { expect { parsed_permissions.protect! :student, 'foo/student' }.not_to raise_error(Mumukit::Auth::UnauthorizedAccessError) } it { expect { parsed_permissions.protect! :writer, 'foo/student' }.not_to raise_error(NoMethodError) } it { expect { parsed_permissions.protect! :writer, 'foo/student' }.to raise_error(Mumukit::Auth::UnauthorizedAccessError) } context 'when no permissions' do let(:permissions) { Mumukit::Auth::Permissions.parse({}) } before { permissions.add_permission! :student, 'test/*' } it { expect(permissions.as_json).to json_like(student: 'test/*') } it { expect(permissions.has_permission? :student, 'test/baz').to be true } it { expect(permissions.has_role? :student).to be true } end context 'add_scope!' do let(:permissions) { Mumukit::Auth::Permissions.parse(student: 'foo/bar') } context 'when no permissions added' do before { permissions.add_permission!(:teacher, 'test/*') } it { expect(permissions.has_role? :teacher).to eq true } it { expect(permissions.teacher? 'test/*').to eq true } end context 'when no permissions added' do before { permissions.add_permission!(:student, 'test/*') } it { expect(permissions.has_role? :student).to eq true } it { expect(permissions.student? 'test/*').to eq true } end end context 'remove_scope!' do let(:permissions) { Mumukit::Auth::Permissions.parse(student: 'foo/bar:test/*:foo/baz') } context 'when permission is present' do before { permissions.remove_permission!(:student, 'test/*') } it { expect(permissions.student? 'test/*').to eq false } it { expect(permissions.student? 'foo/bar').to eq true } it { expect(permissions.student? 'foo/baz').to eq true } end context 'when scope is not present' do before { permissions.remove_permission!(:student, 'baz/*') } it { expect(permissions.student? 'test/*').to eq true } it { expect(permissions.student? 'foo/bar').to eq true } it { expect(permissions.student? 'foo/baz').to eq true } end context 'when role is not present' do before { permissions.remove_permission!(:teacher, 'baz/*') } it { expect(permissions.student? 'test/*').to eq true } it { expect(permissions.student? 'foo/bar').to eq true } it { expect(permissions.student? 'foo/baz').to eq true } end end end Fix deprecate warning require 'spec_helper' describe Mumukit::Auth::Permissions do let(:permissions) do Mumukit::Auth::Permissions.new( student: Mumukit::Auth::Scope.parse('foo/*:test/*'), owner: Mumukit::Auth::Scope.parse('test/*'), teacher: Mumukit::Auth::Scope.parse('foo/baz')) end let(:parsed_permissions) do Mumukit::Auth::Permissions.load(permissions.to_json) end it { expect(permissions).to json_like Mumukit::Auth::Permissions.parse(student: 'foo/*:test/*', owner: 'test/*', teacher: 'foo/baz') } it { expect(permissions).to json_like Mumukit::Auth::Permissions.parse('student' => 'foo/*:test/*', 'owner' => 'test/*', 'teacher' => 'foo/baz') } it { expect(permissions.teacher? 'foobar/baz').to be false } it { expect(permissions.teacher? 'foobar/_').to be false } it { expect(permissions.teacher? Mumukit::Auth::Slug.parse('foo/baz')).to be true } it { expect(permissions.teacher? Mumukit::Auth::Slug.parse('foobar/_')).to be false } it { expect(permissions.teacher? 'foo/baz').to be true } it { expect(permissions.teacher? 'foo/_').to be true } it { expect(permissions.owner? 'test/student').to be true } it { expect(permissions.owner? 'test/_').to be true } it { expect(permissions.writer? 'test/student').to be false } it { expect(permissions.writer? 'test/_').to be false } it { expect(permissions.student? 'foo/bar').to be true } it { expect(permissions.student? 'test/student').to be true } it { expect(permissions.student? 'foo/student').to be true } it { expect(permissions.student? 'baz/student').to be false } it { expect(permissions.student? 'baz/_').to be false } it { expect(parsed_permissions.student? 'foo/bar').to be true } it { expect(parsed_permissions.student? 'test/student').to be true } it { expect(parsed_permissions.student? 'foo/student').to be true } it { expect(parsed_permissions.student? 'baz/student').to be false } it { expect(parsed_permissions.student? 'baz/_').to be false } it { expect { parsed_permissions.protect! :student, 'baz/_' }.to raise_error(Mumukit::Auth::UnauthorizedAccessError) } it { expect { parsed_permissions.protect! :student, 'foo/student' }.not_to raise_error } it { expect { parsed_permissions.protect! :writer, 'foo/student' }.to raise_error(Mumukit::Auth::UnauthorizedAccessError) } context 'when no permissions' do let(:permissions) { Mumukit::Auth::Permissions.parse({}) } before { permissions.add_permission! :student, 'test/*' } it { expect(permissions.as_json).to json_like(student: 'test/*') } it { expect(permissions.has_permission? :student, 'test/baz').to be true } it { expect(permissions.has_role? :student).to be true } end context 'add_scope!' do let(:permissions) { Mumukit::Auth::Permissions.parse(student: 'foo/bar') } context 'when no permissions added' do before { permissions.add_permission!(:teacher, 'test/*') } it { expect(permissions.has_role? :teacher).to eq true } it { expect(permissions.teacher? 'test/*').to eq true } end context 'when no permissions added' do before { permissions.add_permission!(:student, 'test/*') } it { expect(permissions.has_role? :student).to eq true } it { expect(permissions.student? 'test/*').to eq true } end end context 'remove_scope!' do let(:permissions) { Mumukit::Auth::Permissions.parse(student: 'foo/bar:test/*:foo/baz') } context 'when permission is present' do before { permissions.remove_permission!(:student, 'test/*') } it { expect(permissions.student? 'test/*').to eq false } it { expect(permissions.student? 'foo/bar').to eq true } it { expect(permissions.student? 'foo/baz').to eq true } end context 'when scope is not present' do before { permissions.remove_permission!(:student, 'baz/*') } it { expect(permissions.student? 'test/*').to eq true } it { expect(permissions.student? 'foo/bar').to eq true } it { expect(permissions.student? 'foo/baz').to eq true } end context 'when role is not present' do before { permissions.remove_permission!(:teacher, 'baz/*') } it { expect(permissions.student? 'test/*').to eq true } it { expect(permissions.student? 'foo/bar').to eq true } it { expect(permissions.student? 'foo/baz').to eq true } end end end
require File.dirname(__FILE__) + '/../spec_helper' describe "Hash" do before(:each) do @a = {:a => "10", :b => "20", :c => "30"} end it "should preserve the contents of the original hash when safe_merge'ing" do a = {:a => "10", :b => "20"} b = {:b => "30", :c => "40"} a.safe_merge(b).should == {:a => "10", :b => "20", :c => "40"} end it "should preserve the contents of the original hash when safe_merge!'ing" do a = {:a => "10", :b => "20"} b = {:b => "30", :c => "40"} a.safe_merge!(b) a.should == {:a => "10", :b => "20", :c => "40"} end it "should be able to turn itself into an open struct" do @a.to_os.class.should == MyOpenStruct end it "should respond to to_hash" do @a.to_os.respond_to?(:to_hash).should == true end it "should be able to turn itself into an open struct with the method to_hash on the object" do @a.to_os.to_hash.should == @a end it "should not put quotes around integers" do {:a => 10, :b => "q"}.flush_out.should == ["a => 10", "b => 'q'"] end it "should be able to flush out into a string into an array" do @a.flush_out.should == ["a => '10'","b => '20'","c => '30'"] end it "should be able to flush out with pre and posts" do @a.flush_out("hi", "ho").should == ["hia => '10'ho","hib => '20'ho","hic => '30'ho"] end describe "select" do before(:each) do @selected_hash = @a.select {|k,v| k if k == :a} end it "should return a hash when selecting" do @selected_hash.class.should == Hash end it "should only have the key a (selected)" do @selected_hash.keys.should == [:a] end end describe "extract!" do before(:each) do @rejected_hash = @a.extract! {|k,v| k == :a } end it "should have a reject with the keys" do @rejected_hash.keys.should == [:a] end it "should return the old array with the other keys" do @a.keys.should == [:b, :c] end it "should not throw a fit with an empty hash" do lambda { {}.extract! }.should_not raise_error end end describe "append" do before(:each) do @hash = {:game => "token", :required => "for_play"} end it "should not destroy an option salready on the hash" do @hash.append(:required => "to_play")[:game].should == "token" end it "should change the entry to an array if it already exists" do @hash.append(:game => "coin")[:game].class.should == Array end it "should append the other hash's key to the end of the array" do @hash.append(:game => "coin")[:game][-1].should == "coin" end it "should change the hash with the append(bang) option" do @hash.append!(:game => "coin") @hash[:game][-1].should == "coin" end end end Fixing spec related to hash sorting require File.dirname(__FILE__) + '/../spec_helper' describe "Hash" do before(:each) do @a = {:a => "10", :b => "20", :c => "30"} end it "should preserve the contents of the original hash when safe_merge'ing" do a = {:a => "10", :b => "20"} b = {:b => "30", :c => "40"} a.safe_merge(b).should == {:a => "10", :b => "20", :c => "40"} end it "should preserve the contents of the original hash when safe_merge!'ing" do a = {:a => "10", :b => "20"} b = {:b => "30", :c => "40"} a.safe_merge!(b) a.should == {:a => "10", :b => "20", :c => "40"} end it "should be able to turn itself into an open struct" do @a.to_os.class.should == MyOpenStruct end it "should respond to to_hash" do @a.to_os.respond_to?(:to_hash).should == true end it "should be able to turn itself into an open struct with the method to_hash on the object" do @a.to_os.to_hash.should == @a end it "should not put quotes around integers" do {:a => 10, :b => "q"}.flush_out.sort.should == ["a => 10", "b => 'q'"] end it "should be able to flush out into a string into an array" do @a.flush_out.sort.should == ["a => '10'","b => '20'","c => '30'"] end it "should be able to flush out with pre and posts" do @a.flush_out("hi", "ho").sort.should == ["hia => '10'ho","hib => '20'ho","hic => '30'ho"] end describe "select" do before(:each) do @selected_hash = @a.select {|k,v| k if k == :a} end it "should return a hash when selecting" do @selected_hash.class.should == Hash end it "should only have the key a (selected)" do @selected_hash.keys.should == [:a] end end describe "extract!" do before(:each) do @rejected_hash = @a.extract! {|k,v| k == :a } end it "should have a reject with the keys" do @rejected_hash.keys.should == [:a] end it "should return the old array with the other keys" do @a.keys.should == [:b, :c] end it "should not throw a fit with an empty hash" do lambda { {}.extract! }.should_not raise_error end end describe "append" do before(:each) do @hash = {:game => "token", :required => "for_play"} end it "should not destroy an option salready on the hash" do @hash.append(:required => "to_play")[:game].should == "token" end it "should change the entry to an array if it already exists" do @hash.append(:game => "coin")[:game].class.should == Array end it "should append the other hash's key to the end of the array" do @hash.append(:game => "coin")[:game][-1].should == "coin" end it "should change the hash with the append(bang) option" do @hash.append!(:game => "coin") @hash[:game][-1].should == "coin" end end end
require 'spec_helper' describe QuickbooksEndpoint do def auth {'HTTP_X_AUGURY_TOKEN' => 'x123'} end def app described_class end context "windows" do context "persist" do end end context "online" do let(:message) { { "message" => "order:new", :payload => { "order" => Factories.order, "original" => Factories.original, "parameters" => Factories.parameters } } } context "persist" do it "should respond to POST 'persist'" do pending "make proper test" post '/persist', message.to_json, auth end end end end add spec for Sinatra 'perist' for online order:new require 'spec_helper' describe QuickbooksEndpoint do def auth {'HTTP_X_AUGURY_TOKEN' => 'x123'} end def app described_class end context "persist" do context "with order:new" do context "online" do let(:message) { { "message" => "order:new", :message_id => "abc", :payload => { "order" => Factories.order, "original" => Factories.original, "parameters" => Factories.parameters } } } it "should respond to POST 'persist'" do VCR.use_cassette('online/persist_new_order') do post '/persist', message.to_json, auth last_response.status.should eql 200 response = JSON.parse(last_response.body) response["message_id"].should eql "abc" response["notifications"].first["subject"].should eql "persisted order R181807170 in Quickbooks" response["notifications"].first["description"].should eql "Quickbooks SalesReceipt id = 36 and idDomain = QBO" end end end end end end
# vim:fileencoding=utf-8 describe RedisSessionStore do let :random_string do "#{rand}#{rand}#{rand}" end let :options do {} end subject(:store) { RedisSessionStore.new(nil, options) } let :default_options do store.instance_variable_get(:@default_options) end it 'assigns a :namespace to @default_options' do default_options[:namespace].should == 'rack:session' end describe 'when initializing with the redis sub-hash options' do let :options do { key: random_string, secret: random_string, redis: { host: 'hosty.local', port: 16_379, db: 2, key_prefix: 'myapp:session:', expire_after: 60 * 120 } } end it 'creates a redis instance' do store.instance_variable_get(:@redis).should_not be_nil end it 'assigns the :host option to @default_options' do default_options[:host].should == 'hosty.local' end it 'assigns the :port option to @default_options' do default_options[:port].should == 16_379 end it 'assigns the :db option to @default_options' do default_options[:db].should == 2 end it 'assigns the :key_prefix option to @default_options' do default_options[:key_prefix].should == 'myapp:session:' end it 'assigns the :expire_after option to @default_options' do default_options[:expire_after].should == 60 * 120 end end describe 'when initializing with top-level redis options' do let :options do { key: random_string, secret: random_string, host: 'hostersons.local', port: 26_379, db: 4, key_prefix: 'appydoo:session:', expire_after: 60 * 60 } end it 'creates a redis instance' do store.instance_variable_get(:@redis).should_not be_nil end it 'assigns the :host option to @default_options' do default_options[:host].should == 'hostersons.local' end it 'assigns the :port option to @default_options' do default_options[:port].should == 26_379 end it 'assigns the :db option to @default_options' do default_options[:db].should == 4 end it 'assigns the :key_prefix option to @default_options' do default_options[:key_prefix].should == 'appydoo:session:' end it 'assigns the :expire_after option to @default_options' do default_options[:expire_after].should == 60 * 60 end end end Spec example for set_session returning a session id # vim:fileencoding=utf-8 describe RedisSessionStore do let :random_string do "#{rand}#{rand}#{rand}" end let :options do {} end subject(:store) { RedisSessionStore.new(nil, options) } let :default_options do store.instance_variable_get(:@default_options) end it 'assigns a :namespace to @default_options' do default_options[:namespace].should == 'rack:session' end describe 'when initializing with the redis sub-hash options' do let :options do { key: random_string, secret: random_string, redis: { host: 'hosty.local', port: 16_379, db: 2, key_prefix: 'myapp:session:', expire_after: 60 * 120 } } end it 'creates a redis instance' do store.instance_variable_get(:@redis).should_not be_nil end it 'assigns the :host option to @default_options' do default_options[:host].should == 'hosty.local' end it 'assigns the :port option to @default_options' do default_options[:port].should == 16_379 end it 'assigns the :db option to @default_options' do default_options[:db].should == 2 end it 'assigns the :key_prefix option to @default_options' do default_options[:key_prefix].should == 'myapp:session:' end it 'assigns the :expire_after option to @default_options' do default_options[:expire_after].should == 60 * 120 end end describe 'when initializing with top-level redis options' do let :options do { key: random_string, secret: random_string, host: 'hostersons.local', port: 26_379, db: 4, key_prefix: 'appydoo:session:', expire_after: 60 * 60 } end it 'creates a redis instance' do store.instance_variable_get(:@redis).should_not be_nil end it 'assigns the :host option to @default_options' do default_options[:host].should == 'hostersons.local' end it 'assigns the :port option to @default_options' do default_options[:port].should == 26_379 end it 'assigns the :db option to @default_options' do default_options[:db].should == 4 end it 'assigns the :key_prefix option to @default_options' do default_options[:key_prefix].should == 'appydoo:session:' end it 'assigns the :expire_after option to @default_options' do default_options[:expire_after].should == 60 * 60 end end describe 'rack 1.45 compatibility' do # Rack 1.45 (which Rails 3.2.x depends on) uses the return value of set_session to set the cookie value # See https://github.com/rack/rack/blob/1.4.5/lib/rack/session/abstract/id.rb let(:env) { double('env') } let(:session_id) { 12_345 } let(:session_data) { double('session_data') } let(:options) { { expire_after: 123 } } context 'when successfully persisting the session' do it 'returns the session id' do store.send(:set_session, env, session_id, session_data, options).should eq(session_id) end end context 'when unsuccessfully persisting the session' do before do store.stub(:redis).and_raise(Errno::ECONNREFUSED) end it 'returns false' do store.send(:set_session, env, session_id, session_data, options).should eq(false) end end end end
require 'rails_helper' RSpec.describe "Developers", type: :request do describe "GET /developers" do it "works! (now write some real specs)" do get developers_path expect(response).to have_http_status(200) end end end added request specs for GET /developers require 'rails_helper' RSpec.describe "Developers", type: :request do describe "GET /developers" do before do get developers_path end it "returns 'OK' status code" do expect(response).to have_http_status(:ok) end context "with headers" do context "with pagination" do it "returns X-Pagination-Total" do expect(response.headers['X-Pagination-Total']).not_to be_blank end it "returns X-Pagination-Page" do expect(response.headers['X-Pagination-Page']).not_to be_blank end it "returns X-Pagination-Per-Page" do expect(response.headers['X-Pagination-Per-Page']).not_to be_blank end end it "returns X-Request-Id" do expect(response.headers['X-Request-Id']).not_to be_blank end it "returns X-Runtime" do expect(response.headers['X-Runtime']).not_to be_blank end it "returns Content-Type" do expect(response.headers['Content-Type']).not_to be_blank end end context "with response body" do context "when no developer is found" do it "returns an empty body" do expect(JSON.parse(response.body)).to be_empty end end context "when there are developers found" do let(:valid_params) { {name: "Mario Luan", age: 26 } } before do Developer.create! valid_params get developers_path end it "does not return an empty body" do expect(JSON.parse(response.body)).not_to be_empty end end end end end
require 'spec_helper' describe 'User' do subject { page } describe 'profile page' do let(:user) { Fabricate(:user) } let!(:article1) do Fabricate(:article, :author => user, :title => 'Hello', :content => 'World') end let!(:article2) do Fabricate(:article, :author => user, :title => 'Foo', :content => 'Bar') end before { visit user_path(user) } describe 'when a user has a name' do it { should have_selector('h1', :text => user.name) } it { should_not have_selector('h1', :text => user.email) } end describe 'when a user does not have a name' do let(:user) { Fabricate(:user, :name => ' ') } before do visit user_path(user) end it { should have_selector('h1', :text => user.email) } end describe 'articles' do it { should have_link(article1.title) } it { should have_link(article2.title) } it { should have_content(user.articles.count) } end end describe 'signup page' do before { visit new_user_registration_path } it { should have_selector('h1', :text => 'Sign up') } it { should have_selector('title', :text => full_title('Sign up')) } end describe 'signing up' do before { visit new_user_registration_path } describe 'with invalid information' do it 'should not create a user' do expect { click_button 'Sign up' }.not_to change(User, :count) end end describe 'with valid information' do before do fill_in 'Email', :with => 'user@example.com' fill_in 'Password', :with => 'foobar' fill_in 'Password confirmation', :with => 'foobar' end it 'should create a user' do expect { click_button 'Sign up' }.to change(User, :count).by(1) end describe 'after saving the user' do before { click_button 'Sign up' } let(:user) { User.find_by_email('user@example.com') } it { should have_selector('div.alert.alert-info', :text => 'Welcome!') } it { should have_link('Profile') } it { should have_link('Settings') } it { should have_link('Sign out') } it { should_not have_link('Sign up')} it { should_not have_link('Sign in') } end end end end Improve user integration tests require 'spec_helper' describe 'User' do subject { page } describe 'profile page' do before do @user = Fabricate(:user) visit user_path(@user) end describe 'when a user has a name' do it { should have_page_heading @user.name } it { should_not have_page_heading @user.email } end describe 'when a user does not have a name' do before do @user = Fabricate(:user, :name => ' ') visit user_path(@user) end it { should have_page_heading @user.email } end describe 'as an author' do before do @author = Fabricate(:author) @article = Fabricate(:article, :author => @author) visit user_path(@author) end it { should have_link @article.title } it { should have_content @author.articles.count } end end describe 'signup page' do before { visit new_user_registration_path } it { should have_page_title 'Sign up' } it { should have_page_heading 'Sign up' } end describe 'signing up' do before { visit new_user_registration_path } describe 'with invalid information' do it 'should not create a user' do expect { click_button 'Sign up' }.not_to change(User, :count) end end describe 'with valid information' do before do fill_in 'Email', :with => 'user@example.com' fill_in 'Password', :with => 'foobar' fill_in 'Password confirmation', :with => 'foobar' end it 'should create a user' do expect { click_button 'Sign up' }.to change(User, :count).by(1) end describe 'after saving the user' do before { click_button 'Sign up' } it { should have_notice_message 'Welcome!' } it { should have_link 'Profile' } it { should have_link 'Settings' } it { should have_link 'Sign out' } it { should_not have_link 'Sign up' } it { should_not have_link 'Sign in' } end end end end
require File.expand_path('../../../spec_helper', __FILE__) describe "IO.select" do before :each do @rd, @wr = IO.pipe end after :each do @rd.close unless @rd.closed? @wr.close unless @wr.closed? end it "blocks for duration of timeout if there are no objects ready for I/O" do timeout = 0.5 start = Time.now IO.select [@rd], nil, nil, timeout (Time.now - start).should be_close(timeout, 0.5) end it "returns immediately all objects that are ready for I/O when timeout is 0" do @wr.write("be ready") result = IO.select [@rd], [@wr], nil, 0 result.should == [[@rd], [@wr], []] end it "returns nil after timeout if there are no objects ready for I/O" do result = IO.select [@rd], nil, nil, 0 result.should == nil end it "returns supplied objects when they are ready for I/O" do Thread.new { sleep 0.5; @wr.write "be ready" } result = IO.select [@rd], nil, nil, nil result.should == [[@rd], [], []] end it "leaves out IO objects for which there is no I/O ready" do @wr.write "be ready" # Order matters here. We want to see that @wr doesn't expand the size # of the returned array, so it must be 1st. result = IO.select [@wr, @rd], nil, nil, nil result.should == [[@rd], [], []] end it "returns supplied objects correctly even when monitoring the same object in different arrays" do filename = tmp("IO_select_pipe_file") + $$.to_s io = File.open(filename, 'w+') result = IO.select [io], [io], nil, 0 result.should == [[io], [io], []] io.close rm_r filename end it "invokes to_io on supplied objects that are not IO" do # make some data available @wr.write("foobar") obj = mock("read_io") obj.should_receive(:to_io).at_least(1).and_return(@rd) IO.select([obj]).should == [[obj], [], []] obj = mock("write_io") obj.should_receive(:to_io).at_least(1).and_return(@wr) IO.select(nil, [obj]).should == [[], [obj], []] end it "raises TypeError if supplied objects are not IO" do lambda { IO.select([Object.new]) }.should raise_error(TypeError) lambda { IO.select(nil, [Object.new]) }.should raise_error(TypeError) obj = mock("io") obj.should_receive(:to_io).any_number_of_times.and_return(nil) lambda { IO.select([obj]) }.should raise_error(TypeError) lambda { IO.select(nil, [obj]) }.should raise_error(TypeError) end it "raises TypeError if the specified timeout value is not Numeric" do lambda { IO.select([@rd], nil, nil, Object.new) }.should raise_error(TypeError) end it "raises TypeError if the first three arguments are not Arrays" do lambda { IO.select(Object.new)}.should raise_error(TypeError) lambda { IO.select(nil, Object.new)}.should raise_error(TypeError) lambda { IO.select(nil, nil, Object.new)}.should raise_error(TypeError) end it "does not raise errors if the first three arguments are nil" do lambda { IO.select(nil, nil, nil, 0)}.should_not raise_error end it "does not accept negative timeouts" do lambda { IO.select(nil, nil, nil, -5)}.should raise_error(ArgumentError) end end Add more description to an IO.select spec require File.expand_path('../../../spec_helper', __FILE__) describe "IO.select" do before :each do @rd, @wr = IO.pipe end after :each do @rd.close unless @rd.closed? @wr.close unless @wr.closed? end it "blocks for duration of timeout if there are no objects ready for I/O" do timeout = 0.5 start = Time.now IO.select [@rd], nil, nil, timeout (Time.now - start).should be_close(timeout, 0.5) end it "returns immediately all objects that are ready for I/O when timeout is 0" do @wr.write("be ready") result = IO.select [@rd], [@wr], nil, 0 result.should == [[@rd], [@wr], []] end it "returns nil after timeout if there are no objects ready for I/O" do result = IO.select [@rd], nil, nil, 0 result.should == nil end it "returns supplied objects when they are ready for I/O" do Thread.new { sleep 0.5; @wr.write "be ready" } result = IO.select [@rd], nil, nil, nil result.should == [[@rd], [], []] end it "leaves out IO objects for which there is no I/O ready" do @wr.write "be ready" # Order matters here. We want to see that @wr doesn't expand the size # of the returned array, so it must be 1st. result = IO.select [@wr, @rd], nil, nil, nil result.should == [[@rd], [], []] end it "returns supplied objects correctly even when monitoring the same object in different arrays" do filename = tmp("IO_select_pipe_file") + $$.to_s io = File.open(filename, 'w+') result = IO.select [io], [io], nil, 0 result.should == [[io], [io], []] io.close rm_r filename end it "invokes to_io on supplied objects that are not IO and returns the supplied objects" do # make some data available @wr.write("foobar") obj = mock("read_io") obj.should_receive(:to_io).at_least(1).and_return(@rd) IO.select([obj]).should == [[obj], [], []] obj = mock("write_io") obj.should_receive(:to_io).at_least(1).and_return(@wr) IO.select(nil, [obj]).should == [[], [obj], []] end it "raises TypeError if supplied objects are not IO" do lambda { IO.select([Object.new]) }.should raise_error(TypeError) lambda { IO.select(nil, [Object.new]) }.should raise_error(TypeError) obj = mock("io") obj.should_receive(:to_io).any_number_of_times.and_return(nil) lambda { IO.select([obj]) }.should raise_error(TypeError) lambda { IO.select(nil, [obj]) }.should raise_error(TypeError) end it "raises TypeError if the specified timeout value is not Numeric" do lambda { IO.select([@rd], nil, nil, Object.new) }.should raise_error(TypeError) end it "raises TypeError if the first three arguments are not Arrays" do lambda { IO.select(Object.new)}.should raise_error(TypeError) lambda { IO.select(nil, Object.new)}.should raise_error(TypeError) lambda { IO.select(nil, nil, Object.new)}.should raise_error(TypeError) end it "does not raise errors if the first three arguments are nil" do lambda { IO.select(nil, nil, nil, 0)}.should_not raise_error end it "does not accept negative timeouts" do lambda { IO.select(nil, nil, nil, -5)}.should raise_error(ArgumentError) end end
require 'spec_helper' module Sphere describe Products do before do @prod = Sphere::Products.new "myProject", nil end describe '#list' do it 'no products' do Excon.stub( { :method => :get, :path => '/api/p/products' }, { :status => 200, :body => '{"total":0}' }) o, e = capture_outs { @prod.list({ :project => 'p' }, {}) } o.should match /^No products found in project with key 'p'.$/ end it 'just works' do Excon.stub( { :method => :get, :path => '/api/some-proj/products' }, { :status => 200, :body => '{"total":2}' }) expect { @prod.list({ :project => 'some-proj' }, {}) }.to_not raise_error end end describe '#create' do it 'just works' do Excon.stub( { :method => :post, :path => '/api/p/products' }, { :status => 200, :body => '{}' }) expect { @prod.create( ['{}'], { :project => 'p'} ) }.to_not raise_error end end describe 'json data' do it 'product' do rows = CSV.parse 'myProd,,' h2i = { 'name' => 0 } pt = { 'id' => 'abc', 'attributes' => [] } d = @prod.create_product_json_data rows[0], h2i, pt j = JSON.parse d.to_json j['name']['en'].should eq 'myProd' j['productType']['id'].should eq 'abc' end it 'variant' do rows = CSV.parse '123,a1Value,99,USD 999' h2i = { 'sku' => 0, 'a1' => 1, 'a2' => 2, 'a3' => 3 } pId = '123' pt = { 'attributes' => [{ 'name' => 'a1' }, { 'name' => 'a2', 'type' => 'number' }, {'name' => 'a3', 'type' => 'money' }] } d = @prod.variant_json_data rows[0], h2i, pt j = JSON.parse d.to_json j['sku'].should eq '123' j['attributes'].size.should eq 3 j['attributes'][0]['name'].should eq 'a1' j['attributes'][0]['value'].should eq 'a1Value' j['attributes'][1]['name'].should eq 'a2' j['attributes'][1]['value'].should eq 99 j['attributes'][2]['name'].should eq 'a3' j['attributes'][2]['value']['currencyCode'].should eq 'USD' j['attributes'][2]['value']['centAmount'].should eq 999 end it 'publish' do d = @prod.publish_product_json_command('abc', 42) j = JSON.parse d j['id'].should eq 'abc' j['version'].should eq 42 j['actions'].size.should eq 1 j['actions'][0]['action'].should eq 'publish' end it 'image import' do rows = CSV.parse 'bar,"http://sphere.io/foo.jpg"' h2i = { 'imageLabels' => 0, 'images' => 1 } d = @prod.import_image_json_data rows[0], h2i j = JSON.parse d.to_json j['images'].size.should eq 1 j['images'][0]['variantId'].should eq 1 j['images'][0]['url'].should eq 'http://sphere.io/foo.jpg' j['images'][0]['label'].should eq 'bar' j['images'][0]['filename'].should eq 'bar' end end describe '#validate_categories' do it 'category with name does not exist' do cat_impl = Sphere::Catalogs.new nil row = CSV.parse 'myCategory;myCat' h2i = { 'categories' => 0 } d = { :errors => [] } cat_ids = @prod.validate_categories row[0], 3, h2i, d, cat_impl cat_ids.size.should eq 0 d[:errors].size.should eq 2 d[:errors][0].should eq "[row 3] Category with name 'myCategory' does not exist." d[:errors][1].should eq "[row 3] Category with name 'myCat' does not exist." end it 'category name is not unique' do Excon.stub( { :method => :get, :path => '/api/proj/categories' }, { :status => 200, :body => '[{"subCategories":[{"subCategories":[{"subCategories":[],"id":"inner","name":{"en":"myCat"}}],"id":"middle","name":{"en":"myCat"}}],"id":"root","name":{"en":"rootCategory"}}]' }) cat_impl = Sphere::Catalogs.new 'proj' cat_impl.fetch_all cat_impl.fill_maps rows = CSV.parse 'myCat' h2i = { 'categories' => 0 } d = { :errors => [] } cat_ids = @prod.validate_categories rows[0], 4, h2i, d, cat_impl cat_ids.should eq '' d[:errors].size.should eq 1 d[:errors][0].should eq "[row 4] Category with name 'myCat' is not unique. Please use the category's id instead. One of middle, inner" rows = CSV.parse 'rootCategory>myCat;rootCategory>myCat>myCat;rootCategory;middle' d = { :errors => [] } cat_ids = @prod.validate_categories rows[0], 9, h2i, d, cat_impl d[:errors].size.should be 0 cat_ids.should eq 'middle;inner;root;middle' end end describe '#validate_categories' do before do @tax_impl = Sphere::Taxes.new 'proj' @h2i = { 'tax' => 0 } @d = { :errors => [] } end it 'no tax' do row = CSV.parse '' id = @prod.validate_tax_category row, 3, @h2i, @d, @tax_impl id.should eq nil @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 3] There is no tax defined." end it 'error cases' do row = CSV.parse 'myTax' t = @prod.get_val row, 'tax', @h2i id = @prod.validate_tax_category row[0], 7, @h2i, @d, @tax_impl id.should eq nil @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 7] Tax category with name 'myTax' does not exist." end it 'duplicate tax name' do Excon.stub( { :method => :get, :path => '/api/proj/tax-categories' }, { :status => 200, :body => '[{"id":"t1","name":"myTax"},{"id":"t2","name":"myTax"}]' }) @tax_impl.fetch_all @tax_impl.fill_maps row = CSV.parse 'myTax' t = @prod.get_val row, 'tax', @h2i id = @prod.validate_tax_category row[0], 1, @h2i, @d, @tax_impl id.should eq nil @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 1] Tax category with name 'myTax' is not unique. Please use the tax category's id instead. One of t1, t2" end end describe '#validate_prices' do before do @group_impl = Sphere::CustomerGroups.new 'proj' @h2i = { 'prices' => 0 } @d = { :errors => [] } end it 'no prices header' do row = CSV.parse 'foo,bar' prices = @prod.validate_prices row, 7, {}, @d, @group_impl prices.should eq nil @d[:errors].size.should be 0 end it 'no prices' do row = CSV.parse '' prices = @prod.validate_prices row, 3, @h2i, @d, @group_impl prices.should eq nil @d[:errors].size.should be 0 end it 'simple single price' do row = CSV.parse 'EUR 100' prices = @prod.validate_prices row[0], 6, @h2i, @d, @group_impl prices[:prices].size.should eq 1 prices[:prices][0][:value][:currencyCode].should eq 'EUR' prices[:prices][0][:value][:centAmount].should eq 100 @d[:errors].size.should be 0 end it 'price with unkown customer group' do row = CSV.parse 'EUR 100 B2B' prices = @prod.validate_prices row[0], 6, @h2i, @d, @group_impl @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 6] Customer group with name 'B2B' does not exist." end it 'invalid prices value' do row = CSV.parse 'EUR-100' prices = @prod.validate_prices row[0], 2, @h2i, @d, @group_impl @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 2] Invalid price value 'EUR-100' found." end it 'multiple prices' do row = CSV.parse 'YEN 1000;EUR 100;USD 3000' prices = @prod.validate_prices row[0], 2, @h2i, @d, @group_impl prices[:prices].size.should eq 3 prices[:prices][0][:value][:currencyCode].should eq 'YEN' prices[:prices][0][:value][:centAmount].should eq 1000 prices[:prices][1][:value][:currencyCode].should eq 'EUR' prices[:prices][1][:value][:centAmount].should eq 100 prices[:prices][2][:value][:currencyCode].should eq 'USD' prices[:prices][2][:value][:centAmount].should eq 3000 @d[:errors].size.should be 0 end end describe 'Product import with existing type but without existing products' do before do Excon.stub( { :method => :get, :path => '/api/myProject/products/types' }, { :status => 200, :body => '[{"id":"123","name":"pt","attributes":[]}]' }) Excon.stub( { :method => :get, :path => '/api/myProject/products' }, { :status => 200, :body => '{"count":0,"offset":0,"total":0,"results":[]}' }) Excon.stub( { :method => :get, :path => '/api/myProject/categories' }, { :status => 200, :body => '[]' }) Excon.stub( { :method => :get, :path => '/api/myProject/tax-categories' }, { :status => 200, :body => '[{"id":"t1","name":"T1"}]' }) Excon.stub( { :method => :get, :path => '/api/myProject/customer-groups' }, { :status => 200, :body => '[{"id":"cg1","name":"B2B"}]' }) $force = true @prod.fetch_all end it 'simple product' do Excon.stub( { :method => :post, :path => '/api/myProject/products', :body => '{"productType":{"id":"123","typeId":"product-type"},"taxCategory":{"id":"t1","typeId":"tax-category"},"name":{"en":"myProd"},"slug":{"en":"myprod"},"masterVariant":{"attributes":[]},"variants":[]}' }, { :status => 200, :body => '{"id":"abc","version":1}' }) Excon.stub( { :method => :put, :path => '/api/myProject/products/abc', :body => '{"id":"abc","version":1,"actions":[{"action":"publish"}]}' }, { :status => 200 }) r = <<-eos name,productType,tax,variantId, myProd,pt,t1 eos c = CSV.parse r d = @prod.validate_rows c d[:errors].size.should be 0 @prod.import_data d end it 'product with multiple languages' do Excon.stub( { :method => :post, :path => '/api/myProject/products', :body => '{"productType":{"id":"123","typeId":"product-type"},"taxCategory":{"id":"t1","typeId":"tax-category"},"name":{"de":"meinProd","en":"myProd"},"slug":{"de":"meinprod","en":"myprod"},"description":{"de":"tolles Produkt","en":"awesome product"},"masterVariant":{"attributes":[]},"variants":[]}' }, { :status => 200, :body => '{"id":"abc","version":1}' }) Excon.stub( { :method => :put, :path => '/api/myProject/products/abc', :body => '{"id":"abc","version":1,"actions":[{"action":"publish"}]}' }, { :status => 200 }) r = <<-eos name.de,name.en,description.de,description.en,productType,tax,variantId, meinProd,myProd,tolles Produkt,awesome product,pt,t1 eos c = CSV.parse r d = @prod.validate_rows c d[:errors].size.should be 0 @prod.import_data d end it 'product with variants and prices' do body = '{"productType":{"id":"123","typeId":"product-type"},"taxCategory":{"id":"t1","typeId":"tax-category"},"name":{"en":"my Prod"},"slug":{"en":"my-prod"}' body << ',"masterVariant":{"prices":[{"country":"DE","value":{"currencyCode":"EUR","centAmount":100}}],"attributes":[]}' body << ',"variants":[{"prices":[{"value":{"currencyCode":"USD","centAmount":9999}}],"attributes":[]},{"prices":[{"customerGroup":{"typeId":"customer-group","id":"cg1"},"value":{"currencyCode":"GBP","centAmount":123}}],"attributes":[]}]' body << '}' Excon.stub( { :method => :post, :path => '/api/myProject/products', :body => body }, { :status => 200, :body => '{"id":"abc","version":1}' }) Excon.stub( { :method => :put, :path => '/api/myProject/products/abc', :body => '{"id":"abc","version":1,"actions":[{"action":"publish"}]}' }, { :status => 200, :body => '{"id":"abc","version":2}' }) r = <<-eos action,id,name,productType,tax,variantId,prices ,,my Prod,pt,t1,1,DE-EUR 100 ,,,,,2,USD 9999 ,,,,,3,GBP 123 B2B eos c = CSV.parse r d = @prod.validate_rows c d[:errors].size.should be 0 @prod.import_data d end end describe '#validate_rows' do it 'Error when no column for name' do csv = CSV.parse("productType,\n1,") d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "Column with header 'name' missing." end it 'Duplicate header' do csv = CSV.parse("productType,name,attribX,attribX\n") d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "Duplicate header column named 'attribX'." end it 'Error when action is unknown' do csv = CSV.parse("action,name,productType,variantId\nFOO,myProd,,,") d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "[row 2] Unknown action 'FOO'." end it 'Error when delete action and no id given' do r = <<-eos action,id,name,productType,variantId delete,,myProd2,pt,1 eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be 1 d[:errors][0].should eq "[row 2] Delete not possible: missing product id." end it 'Error when delete action and there is no such product' do r = <<-eos action,id,productType,name,variantId, delete,abc,pt,myProd2,1, eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be 1 d[:errors][0].should eq "[row 2] Delete not possible: product with id 'abc' does not exist." end it 'Errors on creation preparation' do r = <<-eos action,id,name,productType,variantId create,,myProd,,1 create,,myProd,pt,1 eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "[row 2] Create not possible: missing product type." d[:errors][1].should eq "[row 3] Create not possible: product type with name/id 'pt' does not exist." end it 'Errors on deletion preparation' do r = <<-eos action,id,name,productType,variantId delete,,,, delete,123,,, eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "[row 2] Delete not possible: missing product id." d[:errors][1].should eq "[row 3] Delete not possible: product with id '123' does not exist." end end describe '#export_csv' do it 'simple product' do Excon.stub( { :method => :get, :path => '/api/myProject/products' }, { :status => 200, :body => '{"count":1,"offset":0,"total":1,"results":[{"id":"abc","productType":{"id":"pt"},"name":{"en":"myProd"},"masterVariant":{"attributes":[],"images":[]},"categories":[],"variants":[]}]}' }) @prod.fetch_all h,r = @prod.export_csv h.size.should be 7 h.to_csv.should eq "action,id,productType,name,categories,variantId,images\n" r.size.should be 1 r[0].size.should be 7 r[0].to_csv.should match /"",abc,pt,myProd,"","",/ end it 'product with attributes' do body = <<-eos {"offset":0, "count":1, "total":1, "results":[ { "masterVariant":{ "id":1, "sku":"sku_BMW_M7_2_door", "prices":[ { "value":{ "currencyCode":"EUR", "centAmount":1900000 } } ], "images":[ { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } } ], "attributes":[ { "name":"tags", "value":"white two door" }, { "name":"fuel", "value":"Petrol" } ] }, "id":"7bdc0808-b7b5-44fe-a9b5-d2ccde2cc81e", "version":5, "productType":{ "typeId":"product-type", "id":"2e7f452a-c428-42c1-90c5-9a90840b78b0" }, "name":{ "en":"BMW M7 2 door" }, "description":"Some\\nMulti\\nLine\\nText", "categories":[ { "typeId":"category", "id":"d44aa750-25dd-4857-b2b5-b7276f9e4aed" } ], "slug":"bmw-m7-2-door1363878603727", "variants":[ { "id":2, "sku":"sku_BMW_M7_2_door_variant1", "prices":[ { "value":{ "currencyCode":"EUR", "centAmount":2000000 } } ], "images":[ { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } } ], "attributes":[ { "name":"fuel", "value":"Diesel" }, { "name":"tags", "value":"M7 diesel variant" } ], "availability":{ "isOnStock":true } }, { "id":3, "sku":"sku_BMW_M7_2_door_variant2", "prices":[ { "value":{ "currencyCode":"EUR", "centAmount":2100000 } } ], "images":[ { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } } ], "attributes":[ { "name":"fuel", "value":"Diesel" }, { "name":"tags", "value":"M7 4 door variant" } ], "availability":{ "isOnStock":true } } ], "hasStagedChanges":false, "published":true } ], "facets":{}} eos Excon.stub( { :method => :get, :path => '/api/myProject/products' }, { :status => 200, :body => body }) @prod.fetch_all h,r = @prod.export_csv h.size.should be 12 h.to_csv.should eq "action,id,productType,name,description,slug,categories,variantId,sku,tags,fuel,images\n" r.size.should be 3 r[0].size.should be 12 r[0].to_csv.should match /"",[a-z0-9-]+,[a-z0-9-]+,BMW M7 2 door,"Some\nMulti\nLine\nText",bmw-m7-2-door1363878603727,[a-z0-9-]+,1,sku_BMW_M7_2_door,white two door,Petrol,http.*jpg;http.*jpg/ r[1].size.should be 12 r[1].to_csv.should match /"","","","","","","",2,sku_BMW_M7_2_door_variant1,M7 diesel variant,Diesel,http.*jpg;http.*jpg;http.*jpg;http.*jpg/ r[2].size.should be 12 r[2].to_csv.should match /"","","","","","","",3,sku_BMW_M7_2_door_variant2,M7 4 door variant,Diesel,http.*jpg;http.*jpg;http.*jpg;http.*jpg/ end end end end Fix test by passing global para argument. require 'spec_helper' module Sphere describe Products do before do @prod = Sphere::Products.new "myProject", { :para => 1 } end describe '#list' do it 'no products' do Excon.stub( { :method => :get, :path => '/api/p/products' }, { :status => 200, :body => '{"total":0}' }) o, e = capture_outs { @prod.list({ :project => 'p' }, {}) } o.should match /^No products found in project with key 'p'.$/ end it 'just works' do Excon.stub( { :method => :get, :path => '/api/some-proj/products' }, { :status => 200, :body => '{"total":2}' }) expect { @prod.list({ :project => 'some-proj' }, {}) }.to_not raise_error end end describe '#create' do it 'just works' do Excon.stub( { :method => :post, :path => '/api/p/products' }, { :status => 200, :body => '{}' }) expect { @prod.create( ['{}'], { :project => 'p'} ) }.to_not raise_error end end describe 'json data' do it 'product' do rows = CSV.parse 'myProd,,' h2i = { 'name' => 0 } pt = { 'id' => 'abc', 'attributes' => [] } d = @prod.create_product_json_data rows[0], h2i, pt j = JSON.parse d.to_json j['name']['en'].should eq 'myProd' j['productType']['id'].should eq 'abc' end it 'variant' do rows = CSV.parse '123,a1Value,99,USD 999' h2i = { 'sku' => 0, 'a1' => 1, 'a2' => 2, 'a3' => 3 } pId = '123' pt = { 'attributes' => [{ 'name' => 'a1' }, { 'name' => 'a2', 'type' => 'number' }, {'name' => 'a3', 'type' => 'money' }] } d = @prod.variant_json_data rows[0], h2i, pt j = JSON.parse d.to_json j['sku'].should eq '123' j['attributes'].size.should eq 3 j['attributes'][0]['name'].should eq 'a1' j['attributes'][0]['value'].should eq 'a1Value' j['attributes'][1]['name'].should eq 'a2' j['attributes'][1]['value'].should eq 99 j['attributes'][2]['name'].should eq 'a3' j['attributes'][2]['value']['currencyCode'].should eq 'USD' j['attributes'][2]['value']['centAmount'].should eq 999 end it 'publish' do d = @prod.publish_product_json_command('abc', 42) j = JSON.parse d j['id'].should eq 'abc' j['version'].should eq 42 j['actions'].size.should eq 1 j['actions'][0]['action'].should eq 'publish' end it 'image import' do rows = CSV.parse 'bar,"http://sphere.io/foo.jpg"' h2i = { 'imageLabels' => 0, 'images' => 1 } d = @prod.import_image_json_data rows[0], h2i j = JSON.parse d.to_json j['images'].size.should eq 1 j['images'][0]['variantId'].should eq 1 j['images'][0]['url'].should eq 'http://sphere.io/foo.jpg' j['images'][0]['label'].should eq 'bar' j['images'][0]['filename'].should eq 'bar' end end describe '#validate_categories' do it 'category with name does not exist' do cat_impl = Sphere::Catalogs.new nil row = CSV.parse 'myCategory;myCat' h2i = { 'categories' => 0 } d = { :errors => [] } cat_ids = @prod.validate_categories row[0], 3, h2i, d, cat_impl cat_ids.size.should eq 0 d[:errors].size.should eq 2 d[:errors][0].should eq "[row 3] Category with name 'myCategory' does not exist." d[:errors][1].should eq "[row 3] Category with name 'myCat' does not exist." end it 'category name is not unique' do Excon.stub( { :method => :get, :path => '/api/proj/categories' }, { :status => 200, :body => '[{"subCategories":[{"subCategories":[{"subCategories":[],"id":"inner","name":{"en":"myCat"}}],"id":"middle","name":{"en":"myCat"}}],"id":"root","name":{"en":"rootCategory"}}]' }) cat_impl = Sphere::Catalogs.new 'proj' cat_impl.fetch_all cat_impl.fill_maps rows = CSV.parse 'myCat' h2i = { 'categories' => 0 } d = { :errors => [] } cat_ids = @prod.validate_categories rows[0], 4, h2i, d, cat_impl cat_ids.should eq '' d[:errors].size.should eq 1 d[:errors][0].should eq "[row 4] Category with name 'myCat' is not unique. Please use the category's id instead. One of middle, inner" rows = CSV.parse 'rootCategory>myCat;rootCategory>myCat>myCat;rootCategory;middle' d = { :errors => [] } cat_ids = @prod.validate_categories rows[0], 9, h2i, d, cat_impl d[:errors].size.should be 0 cat_ids.should eq 'middle;inner;root;middle' end end describe '#validate_categories' do before do @tax_impl = Sphere::Taxes.new 'proj' @h2i = { 'tax' => 0 } @d = { :errors => [] } end it 'no tax' do row = CSV.parse '' id = @prod.validate_tax_category row, 3, @h2i, @d, @tax_impl id.should eq nil @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 3] There is no tax defined." end it 'error cases' do row = CSV.parse 'myTax' t = @prod.get_val row, 'tax', @h2i id = @prod.validate_tax_category row[0], 7, @h2i, @d, @tax_impl id.should eq nil @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 7] Tax category with name 'myTax' does not exist." end it 'duplicate tax name' do Excon.stub( { :method => :get, :path => '/api/proj/tax-categories' }, { :status => 200, :body => '[{"id":"t1","name":"myTax"},{"id":"t2","name":"myTax"}]' }) @tax_impl.fetch_all @tax_impl.fill_maps row = CSV.parse 'myTax' t = @prod.get_val row, 'tax', @h2i id = @prod.validate_tax_category row[0], 1, @h2i, @d, @tax_impl id.should eq nil @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 1] Tax category with name 'myTax' is not unique. Please use the tax category's id instead. One of t1, t2" end end describe '#validate_prices' do before do @group_impl = Sphere::CustomerGroups.new 'proj' @h2i = { 'prices' => 0 } @d = { :errors => [] } end it 'no prices header' do row = CSV.parse 'foo,bar' prices = @prod.validate_prices row, 7, {}, @d, @group_impl prices.should eq nil @d[:errors].size.should be 0 end it 'no prices' do row = CSV.parse '' prices = @prod.validate_prices row, 3, @h2i, @d, @group_impl prices.should eq nil @d[:errors].size.should be 0 end it 'simple single price' do row = CSV.parse 'EUR 100' prices = @prod.validate_prices row[0], 6, @h2i, @d, @group_impl prices[:prices].size.should eq 1 prices[:prices][0][:value][:currencyCode].should eq 'EUR' prices[:prices][0][:value][:centAmount].should eq 100 @d[:errors].size.should be 0 end it 'price with unkown customer group' do row = CSV.parse 'EUR 100 B2B' prices = @prod.validate_prices row[0], 6, @h2i, @d, @group_impl @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 6] Customer group with name 'B2B' does not exist." end it 'invalid prices value' do row = CSV.parse 'EUR-100' prices = @prod.validate_prices row[0], 2, @h2i, @d, @group_impl @d[:errors].size.should be 1 @d[:errors][0].should eq "[row 2] Invalid price value 'EUR-100' found." end it 'multiple prices' do row = CSV.parse 'YEN 1000;EUR 100;USD 3000' prices = @prod.validate_prices row[0], 2, @h2i, @d, @group_impl prices[:prices].size.should eq 3 prices[:prices][0][:value][:currencyCode].should eq 'YEN' prices[:prices][0][:value][:centAmount].should eq 1000 prices[:prices][1][:value][:currencyCode].should eq 'EUR' prices[:prices][1][:value][:centAmount].should eq 100 prices[:prices][2][:value][:currencyCode].should eq 'USD' prices[:prices][2][:value][:centAmount].should eq 3000 @d[:errors].size.should be 0 end end describe 'Product import with existing type but without existing products' do before do Excon.stub( { :method => :get, :path => '/api/myProject/products/types' }, { :status => 200, :body => '[{"id":"123","name":"pt","attributes":[]}]' }) Excon.stub( { :method => :get, :path => '/api/myProject/products' }, { :status => 200, :body => '{"count":0,"offset":0,"total":0,"results":[]}' }) Excon.stub( { :method => :get, :path => '/api/myProject/categories' }, { :status => 200, :body => '[]' }) Excon.stub( { :method => :get, :path => '/api/myProject/tax-categories' }, { :status => 200, :body => '[{"id":"t1","name":"T1"}]' }) Excon.stub( { :method => :get, :path => '/api/myProject/customer-groups' }, { :status => 200, :body => '[{"id":"cg1","name":"B2B"}]' }) $force = true @prod.fetch_all end it 'simple product' do Excon.stub( { :method => :post, :path => '/api/myProject/products', :body => '{"productType":{"id":"123","typeId":"product-type"},"taxCategory":{"id":"t1","typeId":"tax-category"},"name":{"en":"myProd"},"slug":{"en":"myprod"},"masterVariant":{"attributes":[]},"variants":[]}' }, { :status => 200, :body => '{"id":"abc","version":1}' }) Excon.stub( { :method => :put, :path => '/api/myProject/products/abc', :body => '{"id":"abc","version":1,"actions":[{"action":"publish"}]}' }, { :status => 200 }) r = <<-eos name,productType,tax,variantId, myProd,pt,t1 eos c = CSV.parse r d = @prod.validate_rows c d[:errors].size.should be 0 @prod.import_data d end it 'product with multiple languages' do Excon.stub( { :method => :post, :path => '/api/myProject/products', :body => '{"productType":{"id":"123","typeId":"product-type"},"taxCategory":{"id":"t1","typeId":"tax-category"},"name":{"de":"meinProd","en":"myProd"},"slug":{"de":"meinprod","en":"myprod"},"description":{"de":"tolles Produkt","en":"awesome product"},"masterVariant":{"attributes":[]},"variants":[]}' }, { :status => 200, :body => '{"id":"abc","version":1}' }) Excon.stub( { :method => :put, :path => '/api/myProject/products/abc', :body => '{"id":"abc","version":1,"actions":[{"action":"publish"}]}' }, { :status => 200 }) r = <<-eos name.de,name.en,description.de,description.en,productType,tax,variantId, meinProd,myProd,tolles Produkt,awesome product,pt,t1 eos c = CSV.parse r d = @prod.validate_rows c d[:errors].size.should be 0 @prod.import_data d end it 'product with variants and prices' do body = '{"productType":{"id":"123","typeId":"product-type"},"taxCategory":{"id":"t1","typeId":"tax-category"},"name":{"en":"my Prod"},"slug":{"en":"my-prod"}' body << ',"masterVariant":{"prices":[{"country":"DE","value":{"currencyCode":"EUR","centAmount":100}}],"attributes":[]}' body << ',"variants":[{"prices":[{"value":{"currencyCode":"USD","centAmount":9999}}],"attributes":[]},{"prices":[{"customerGroup":{"typeId":"customer-group","id":"cg1"},"value":{"currencyCode":"GBP","centAmount":123}}],"attributes":[]}]' body << '}' Excon.stub( { :method => :post, :path => '/api/myProject/products', :body => body }, { :status => 200, :body => '{"id":"abc","version":1}' }) Excon.stub( { :method => :put, :path => '/api/myProject/products/abc', :body => '{"id":"abc","version":1,"actions":[{"action":"publish"}]}' }, { :status => 200, :body => '{"id":"abc","version":2}' }) r = <<-eos action,id,name,productType,tax,variantId,prices ,,my Prod,pt,t1,1,DE-EUR 100 ,,,,,2,USD 9999 ,,,,,3,GBP 123 B2B eos c = CSV.parse r d = @prod.validate_rows c d[:errors].size.should be 0 @prod.import_data d end end describe '#validate_rows' do it 'Error when no column for name' do csv = CSV.parse("productType,\n1,") d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "Column with header 'name' missing." end it 'Duplicate header' do csv = CSV.parse("productType,name,attribX,attribX\n") d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "Duplicate header column named 'attribX'." end it 'Error when action is unknown' do csv = CSV.parse("action,name,productType,variantId\nFOO,myProd,,,") d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "[row 2] Unknown action 'FOO'." end it 'Error when delete action and no id given' do r = <<-eos action,id,name,productType,variantId delete,,myProd2,pt,1 eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be 1 d[:errors][0].should eq "[row 2] Delete not possible: missing product id." end it 'Error when delete action and there is no such product' do r = <<-eos action,id,productType,name,variantId, delete,abc,pt,myProd2,1, eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be 1 d[:errors][0].should eq "[row 2] Delete not possible: product with id 'abc' does not exist." end it 'Errors on creation preparation' do r = <<-eos action,id,name,productType,variantId create,,myProd,,1 create,,myProd,pt,1 eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "[row 2] Create not possible: missing product type." d[:errors][1].should eq "[row 3] Create not possible: product type with name/id 'pt' does not exist." end it 'Errors on deletion preparation' do r = <<-eos action,id,name,productType,variantId delete,,,, delete,123,,, eos csv = CSV.parse r d = @prod.validate_rows csv d[:errors].size.should be > 0 d[:errors][0].should eq "[row 2] Delete not possible: missing product id." d[:errors][1].should eq "[row 3] Delete not possible: product with id '123' does not exist." end end describe '#export_csv' do it 'simple product' do Excon.stub( { :method => :get, :path => '/api/myProject/products' }, { :status => 200, :body => '{"count":1,"offset":0,"total":1,"results":[{"id":"abc","productType":{"id":"pt"},"name":{"en":"myProd"},"masterVariant":{"attributes":[],"images":[]},"categories":[],"variants":[]}]}' }) @prod.fetch_all h,r = @prod.export_csv h.size.should be 7 h.to_csv.should eq "action,id,productType,name,categories,variantId,images\n" r.size.should be 1 r[0].size.should be 7 r[0].to_csv.should match /"",abc,pt,myProd,"","",/ end it 'product with attributes' do body = <<-eos {"offset":0, "count":1, "total":1, "results":[ { "masterVariant":{ "id":1, "sku":"sku_BMW_M7_2_door", "prices":[ { "value":{ "currencyCode":"EUR", "centAmount":1900000 } } ], "images":[ { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } } ], "attributes":[ { "name":"tags", "value":"white two door" }, { "name":"fuel", "value":"Petrol" } ] }, "id":"7bdc0808-b7b5-44fe-a9b5-d2ccde2cc81e", "version":5, "productType":{ "typeId":"product-type", "id":"2e7f452a-c428-42c1-90c5-9a90840b78b0" }, "name":{ "en":"BMW M7 2 door" }, "description":"Some\\nMulti\\nLine\\nText", "categories":[ { "typeId":"category", "id":"d44aa750-25dd-4857-b2b5-b7276f9e4aed" } ], "slug":"bmw-m7-2-door1363878603727", "variants":[ { "id":2, "sku":"sku_BMW_M7_2_door_variant1", "prices":[ { "value":{ "currencyCode":"EUR", "centAmount":2000000 } } ], "images":[ { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } } ], "attributes":[ { "name":"fuel", "value":"Diesel" }, { "name":"tags", "value":"M7 diesel variant" } ], "availability":{ "isOnStock":true } }, { "id":3, "sku":"sku_BMW_M7_2_door_variant2", "prices":[ { "value":{ "currencyCode":"EUR", "centAmount":2100000 } } ], "images":[ { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } }, { "url":"http://www.whitegadget.com/attachments/pc-wallpapers/76848d1316083027-bmw-bmw-picture.jpg", "label":"Sample image", "dimensions":{ "w":400, "h":300 } } ], "attributes":[ { "name":"fuel", "value":"Diesel" }, { "name":"tags", "value":"M7 4 door variant" } ], "availability":{ "isOnStock":true } } ], "hasStagedChanges":false, "published":true } ], "facets":{}} eos Excon.stub( { :method => :get, :path => '/api/myProject/products' }, { :status => 200, :body => body }) @prod.fetch_all h,r = @prod.export_csv h.size.should be 12 h.to_csv.should eq "action,id,productType,name,description,slug,categories,variantId,sku,tags,fuel,images\n" r.size.should be 3 r[0].size.should be 12 r[0].to_csv.should match /"",[a-z0-9-]+,[a-z0-9-]+,BMW M7 2 door,"Some\nMulti\nLine\nText",bmw-m7-2-door1363878603727,[a-z0-9-]+,1,sku_BMW_M7_2_door,white two door,Petrol,http.*jpg;http.*jpg/ r[1].size.should be 12 r[1].to_csv.should match /"","","","","","","",2,sku_BMW_M7_2_door_variant1,M7 diesel variant,Diesel,http.*jpg;http.*jpg;http.*jpg;http.*jpg/ r[2].size.should be 12 r[2].to_csv.should match /"","","","","","","",3,sku_BMW_M7_2_door_variant2,M7 4 door variant,Diesel,http.*jpg;http.*jpg;http.*jpg;http.*jpg/ end end end end