CombinedText stringlengths 4 3.42M |
|---|
module Gollum
class Page
include Pagination
Wiki.page_class = self
VALID_PAGE_RE = /^(.+)\.(md|mkdn?|mdown|markdown|textile|rdoc|org|creole|re?st(\.txt)?|asciidoc|pod)$/i
FORMAT_NAMES = { :markdown => "Markdown",
:textile => "Textile",
:rdoc => "RDoc",
:org => "Org-mode",
:creole => "Creole",
:rest => "reStructuredText",
:asciidoc => "AsciiDoc",
:pod => "Pod" }
# Checks if a filename has a valid extension understood by GitHub::Markup.
#
# filename - String filename, like "Home.md".
#
# Returns the matching String basename of the file without the extension.
def self.valid_filename?(filename)
filename && filename.to_s =~ VALID_PAGE_RE && $1
end
# Checks if a filename has a valid extension understood by GitHub::Markup.
# Also, checks if the filename has no "_" in the front (such as
# _Footer.md).
#
# filename - String filename, like "Home.md".
#
# Returns the matching String basename of the file without the extension.
def self.valid_page_name?(filename)
match = valid_filename?(filename)
filename =~ /^_/ ? false : match
end
# Public: Initialize a page.
#
# wiki - The Gollum::Wiki in question.
#
# Returns a newly initialized Gollum::Page.
def initialize(wiki)
@wiki = wiki
@blob = nil
end
# Public: The on-disk filename of the page including extension.
#
# Returns the String name.
def filename
@blob && @blob.name
end
# Public: The canonical page name without extension, and dashes converted
# to spaces.
#
# Returns the String name.
def name
filename.split('.')[0..-2].join('.').gsub('-', ' ')
end
# Public: If the first element of a formatted page is an <h1> tag it can
# be considered the title of the page and used in the display. If the
# first element is NOT an <h1> tag, the title will be constructed from the
# filename by stripping the extension and replacing any dashes with
# spaces.
#
# Returns the fully sanitized String title.
def title
doc = Nokogiri::HTML(%{<div id="gollum-root">} + self.formatted_data + %{</div>})
header =
case self.format
when :asciidoc
doc.css("div#gollum-root > div#header > h1:first-child")
when :org
doc.css("div#gollum-root > p.title:first-child")
when :pod
doc.css("div#gollum-root > a.dummyTopAnchor:first-child + h1")
when :rest
doc.css("div#gollum-root > div > div > h1:first-child")
else
doc.css("div#gollum-root > h1:first-child")
end
if !header.empty?
Sanitize.clean(header.to_html)
else
Sanitize.clean(name)
end
end
# Public: The path of the page within the repo.
#
# Returns the String path.
attr_reader :path
# Public: The raw contents of the page.
#
# Returns the String data.
def raw_data
@blob && @blob.data
end
# Public: The formatted contents of the page.
#
# Returns the String data.
def formatted_data
@blob && Gollum::Markup.new(self).render
end
# Public: The format of the page.
#
# Returns the Symbol format of the page. One of:
# [ :markdown | :textile | :rdoc | :org | :rest | :asciidoc | :pod |
# :roff ]
def format
case @blob.name
when /\.(md|mkdn?|mdown|markdown)$/i
:markdown
when /\.(textile)$/i
:textile
when /\.(rdoc)$/i
:rdoc
when /\.(org)$/i
:org
when /\.(creole)$/i
:creole
when /\.(re?st(\.txt)?)$/i
:rest
when /\.(asciidoc)$/i
:asciidoc
when /\.(pod)$/i
:pod
when /\.(\d)$/i
:roff
else
nil
end
end
# Public: The current version of the page.
#
# Returns the Grit::Commit.
attr_reader :version
# Public: All of the versions that have touched the Page.
#
# options - The options Hash:
# :page - The Integer page number (default: 1).
# :per_page - The Integer max count of items to return.
# :follow - Follow's a file across renames, but falls back
# to a slower Grit native call. (default: false)
#
# Returns an Array of Grit::Commit.
def versions(options = {})
if options[:follow]
options[:pretty] = 'raw'
options.delete :max_count
options.delete :skip
log = @wiki.repo.git.native "log", options, "master", "--", @path
Grit::Commit.list_from_string(@wiki.repo, log)
else
@wiki.repo.log('master', @path, log_pagination_options(options))
end
end
# Public: The footer Page.
#
# Returns the footer Page or nil if none exists.
def footer
return nil if page_match('_Footer', self.filename)
dirs = self.path.split('/')
dirs.pop
map = @wiki.tree_map_for(self.version.id)
while !dirs.empty?
if page = find_page_in_tree(map, '_Footer', dirs.join('/'))
return page
end
dirs.pop
end
find_page_in_tree(map, '_Footer', '')
end
#########################################################################
#
# Class Methods
#
#########################################################################
# Convert a human page name into a canonical page name.
#
# name - The String human page name.
#
# Examples
#
# Page.cname("Bilbo Baggins")
# # => 'Bilbo-Baggins'
#
# Returns the String canonical name.
def self.cname(name)
name.gsub(%r{[ /<>]}, '-')
end
# Convert a format Symbol into an extension String.
#
# format - The format Symbol.
#
# Returns the String extension (no leading period).
def self.format_to_ext(format)
case format
when :markdown then 'md'
when :textile then 'textile'
when :rdoc then 'rdoc'
when :org then 'org'
when :creole then 'creole'
when :rest then 'rest'
when :asciidoc then 'asciidoc'
when :pod then 'pod'
end
end
#########################################################################
#
# Internal Methods
#
#########################################################################
# The underlying wiki repo.
#
# Returns the Gollum::Wiki containing the page.
attr_reader :wiki
# Set the Grit::Commit version of the page.
#
# Returns nothing.
attr_writer :version
# Find a page in the given Gollum repo.
#
# name - The human or canonical String page name to find.
# version - The String version ID to find.
#
# Returns a Gollum::Page or nil if the page could not be found.
def find(name, version)
map = @wiki.tree_map_for(version)
if page = find_page_in_tree(map, name)
sha = @wiki.ref_map[version] || version
page.version = Grit::Commit.create(@wiki.repo, :id => sha)
page
end
rescue Grit::GitRuby::Repository::NoSuchShaFound
end
# Find a page in a given tree.
#
# map - The Array tree map from Wiki#tree_map.
# name - The canonical String page name.
# checked_dir - Optional String of the directory a matching page needs
# to be in. The string should
#
# Returns a Gollum::Page or nil if the page could not be found.
def find_page_in_tree(map, name, checked_dir = nil)
if checked_dir = BlobEntry.normalize_dir(checked_dir)
checked_dir.downcase!
end
map.each do |entry|
next unless checked_dir.nil? || entry.dir.downcase == checked_dir
next unless page_match(name, entry.name)
return entry.page(@wiki, @version)
end
return nil # nothing was found
end
# Populate the Page with information from the Blob.
#
# blob - The Grit::Blob that contains the info.
# path - The String directory path of the page file.
#
# Returns the populated Gollum::Page.
def populate(blob, path)
@blob = blob
@path = (path + '/' + blob.name)[1..-1]
self
end
# The full directory path for the given tree.
#
# treemap - The Hash treemap containing parentage information.
# tree - The Grit::Tree for which to compute the path.
#
# Returns the String path.
def tree_path(treemap, tree)
if ptree = treemap[tree]
tree_path(treemap, ptree) + '/' + tree.name
else
''
end
end
# Compare the canonicalized versions of the two names.
#
# name - The human or canonical String page name.
# filename - the String filename on disk (including extension).
#
# Returns a Boolean.
def page_match(name, filename)
if match = self.class.valid_filename?(filename)
Page.cname(name).downcase == Page.cname(match).downcase
else
false
end
end
end
end
dont bomb when trying to find a page with a blank name
module Gollum
class Page
include Pagination
Wiki.page_class = self
VALID_PAGE_RE = /^(.+)\.(md|mkdn?|mdown|markdown|textile|rdoc|org|creole|re?st(\.txt)?|asciidoc|pod)$/i
FORMAT_NAMES = { :markdown => "Markdown",
:textile => "Textile",
:rdoc => "RDoc",
:org => "Org-mode",
:creole => "Creole",
:rest => "reStructuredText",
:asciidoc => "AsciiDoc",
:pod => "Pod" }
# Checks if a filename has a valid extension understood by GitHub::Markup.
#
# filename - String filename, like "Home.md".
#
# Returns the matching String basename of the file without the extension.
def self.valid_filename?(filename)
filename && filename.to_s =~ VALID_PAGE_RE && $1
end
# Checks if a filename has a valid extension understood by GitHub::Markup.
# Also, checks if the filename has no "_" in the front (such as
# _Footer.md).
#
# filename - String filename, like "Home.md".
#
# Returns the matching String basename of the file without the extension.
def self.valid_page_name?(filename)
match = valid_filename?(filename)
filename =~ /^_/ ? false : match
end
# Public: Initialize a page.
#
# wiki - The Gollum::Wiki in question.
#
# Returns a newly initialized Gollum::Page.
def initialize(wiki)
@wiki = wiki
@blob = nil
end
# Public: The on-disk filename of the page including extension.
#
# Returns the String name.
def filename
@blob && @blob.name
end
# Public: The canonical page name without extension, and dashes converted
# to spaces.
#
# Returns the String name.
def name
filename.split('.')[0..-2].join('.').gsub('-', ' ')
end
# Public: If the first element of a formatted page is an <h1> tag it can
# be considered the title of the page and used in the display. If the
# first element is NOT an <h1> tag, the title will be constructed from the
# filename by stripping the extension and replacing any dashes with
# spaces.
#
# Returns the fully sanitized String title.
def title
doc = Nokogiri::HTML(%{<div id="gollum-root">} + self.formatted_data + %{</div>})
header =
case self.format
when :asciidoc
doc.css("div#gollum-root > div#header > h1:first-child")
when :org
doc.css("div#gollum-root > p.title:first-child")
when :pod
doc.css("div#gollum-root > a.dummyTopAnchor:first-child + h1")
when :rest
doc.css("div#gollum-root > div > div > h1:first-child")
else
doc.css("div#gollum-root > h1:first-child")
end
if !header.empty?
Sanitize.clean(header.to_html)
else
Sanitize.clean(name)
end
end
# Public: The path of the page within the repo.
#
# Returns the String path.
attr_reader :path
# Public: The raw contents of the page.
#
# Returns the String data.
def raw_data
@blob && @blob.data
end
# Public: The formatted contents of the page.
#
# Returns the String data.
def formatted_data
@blob && Gollum::Markup.new(self).render
end
# Public: The format of the page.
#
# Returns the Symbol format of the page. One of:
# [ :markdown | :textile | :rdoc | :org | :rest | :asciidoc | :pod |
# :roff ]
def format
case @blob.name
when /\.(md|mkdn?|mdown|markdown)$/i
:markdown
when /\.(textile)$/i
:textile
when /\.(rdoc)$/i
:rdoc
when /\.(org)$/i
:org
when /\.(creole)$/i
:creole
when /\.(re?st(\.txt)?)$/i
:rest
when /\.(asciidoc)$/i
:asciidoc
when /\.(pod)$/i
:pod
when /\.(\d)$/i
:roff
else
nil
end
end
# Public: The current version of the page.
#
# Returns the Grit::Commit.
attr_reader :version
# Public: All of the versions that have touched the Page.
#
# options - The options Hash:
# :page - The Integer page number (default: 1).
# :per_page - The Integer max count of items to return.
# :follow - Follow's a file across renames, but falls back
# to a slower Grit native call. (default: false)
#
# Returns an Array of Grit::Commit.
def versions(options = {})
if options[:follow]
options[:pretty] = 'raw'
options.delete :max_count
options.delete :skip
log = @wiki.repo.git.native "log", options, "master", "--", @path
Grit::Commit.list_from_string(@wiki.repo, log)
else
@wiki.repo.log('master', @path, log_pagination_options(options))
end
end
# Public: The footer Page.
#
# Returns the footer Page or nil if none exists.
def footer
return nil if page_match('_Footer', self.filename)
dirs = self.path.split('/')
dirs.pop
map = @wiki.tree_map_for(self.version.id)
while !dirs.empty?
if page = find_page_in_tree(map, '_Footer', dirs.join('/'))
return page
end
dirs.pop
end
find_page_in_tree(map, '_Footer', '')
end
#########################################################################
#
# Class Methods
#
#########################################################################
# Convert a human page name into a canonical page name.
#
# name - The String human page name.
#
# Examples
#
# Page.cname("Bilbo Baggins")
# # => 'Bilbo-Baggins'
#
# Returns the String canonical name.
def self.cname(name)
name.gsub(%r{[ /<>]}, '-')
end
# Convert a format Symbol into an extension String.
#
# format - The format Symbol.
#
# Returns the String extension (no leading period).
def self.format_to_ext(format)
case format
when :markdown then 'md'
when :textile then 'textile'
when :rdoc then 'rdoc'
when :org then 'org'
when :creole then 'creole'
when :rest then 'rest'
when :asciidoc then 'asciidoc'
when :pod then 'pod'
end
end
#########################################################################
#
# Internal Methods
#
#########################################################################
# The underlying wiki repo.
#
# Returns the Gollum::Wiki containing the page.
attr_reader :wiki
# Set the Grit::Commit version of the page.
#
# Returns nothing.
attr_writer :version
# Find a page in the given Gollum repo.
#
# name - The human or canonical String page name to find.
# version - The String version ID to find.
#
# Returns a Gollum::Page or nil if the page could not be found.
def find(name, version)
map = @wiki.tree_map_for(version)
if page = find_page_in_tree(map, name)
sha = @wiki.ref_map[version] || version
page.version = Grit::Commit.create(@wiki.repo, :id => sha)
page
end
rescue Grit::GitRuby::Repository::NoSuchShaFound
end
# Find a page in a given tree.
#
# map - The Array tree map from Wiki#tree_map.
# name - The canonical String page name.
# checked_dir - Optional String of the directory a matching page needs
# to be in. The string should
#
# Returns a Gollum::Page or nil if the page could not be found.
def find_page_in_tree(map, name, checked_dir = nil)
return nil if name.blank?
if checked_dir = BlobEntry.normalize_dir(checked_dir)
checked_dir.downcase!
end
map.each do |entry|
next if entry.name.blank?
next unless checked_dir.nil? || entry.dir.downcase == checked_dir
next unless page_match(name, entry.name)
return entry.page(@wiki, @version)
end
return nil # nothing was found
end
# Populate the Page with information from the Blob.
#
# blob - The Grit::Blob that contains the info.
# path - The String directory path of the page file.
#
# Returns the populated Gollum::Page.
def populate(blob, path)
@blob = blob
@path = (path + '/' + blob.name)[1..-1]
self
end
# The full directory path for the given tree.
#
# treemap - The Hash treemap containing parentage information.
# tree - The Grit::Tree for which to compute the path.
#
# Returns the String path.
def tree_path(treemap, tree)
if ptree = treemap[tree]
tree_path(treemap, ptree) + '/' + tree.name
else
''
end
end
# Compare the canonicalized versions of the two names.
#
# name - The human or canonical String page name.
# filename - the String filename on disk (including extension).
#
# Returns a Boolean.
def page_match(name, filename)
if match = self.class.valid_filename?(filename)
Page.cname(name).downcase == Page.cname(match).downcase
else
false
end
end
end
end |
railtie for easy rails integration ... hopefully
if defined?(Rails)
module GTA
class Railtie < Rails::Railtie
rake_tasks do
require File.dirname(__FILE__) + "/tasks.rb"
end
end
end
end |
require 'csv'
require 'fileutils'
require 'json'
require 'net/http'
require 'zipruby'
module GtfsParser
LOCAL_GTFS_DIR = File.expand_path('../../gtfs/', __FILE__)
STOP_NAME = 'Studio Arts Building'.freeze
CACHE_FILE = 'cached_departures.json'.freeze
GTFS_PROTOCOL = 'http://'.freeze
GTFS_HOST = 'pvta.com'.freeze
GTFS_PATH = '/g_trans/google_transit.zip'.freeze
log = File.expand_path('../../log', __FILE__)
def prepare!
zip_log_file!
get_new_files! unless files_up_to_date?
cache_departures!
end
# Returns a hash which you can query by route number and direction,
# and which stores the headsign of the next departure,
# the next scheduled departure,
# and the previous scheduled departure.
# Example:
# {['31', '0'] => ['Sunderland', '13:51:00', '14:06:00']}
def soonest_departures_within(minutes)
departure_times = {}
cached_departures.each do |(route_number, direction_id, headsign), times|
next_time = times.find { |time| time_within? minutes, time }
if next_time
last_time = times[times.index(next_time) - 1] unless next_time == times.first
times_in_same_route_direction = departure_times[[route_number, direction_id]]
unless times_in_same_route_direction && times_in_same_route_direction.last < next_time
departure_times[[route_number, direction_id]] = [headsign, last_time, next_time]
end
end
end
departure_times
end
private
# Stores departures in the cache file.
def cache_departures!
departures = find_departures
File.open CACHE_FILE, 'w' do |file|
file.puts departures.to_json
end
end
# Zip yesterday's log file into an archive directory, with filenames indicating the date
def zip_log_file!
# At 4am, so todays_date log file is yesterday's log file
zipfile = File.open "#{todays_date}.json"
Zip::Archive.open_buffer zipfile do |archive|
archive.each do |file|
file_path = File.join log, file.name
File.open file_path, 'w' do |f|
f << file.read
end
end
end
end
# Retrieves the cached departures.
def cached_departures
departures = JSON.parse(File.read(CACHE_FILE))
parsed_departures = {}
departures.each do |route_data, times|
parsed_departures[JSON.parse(route_data)] = times.map { |time| parse_time time }
end
parsed_departures
end
# Is the remote GTFS archive more recent than our cached files?
def files_up_to_date?
return false unless File.directory? LOCAL_GTFS_DIR
http = Net::HTTP.new GTFS_HOST
begin
response = http.head GTFS_PATH
rescue SocketError
true
else
mtime = DateTime.parse response['last-modified']
mtime < File.mtime(LOCAL_GTFS_DIR).to_datetime
end
end
# Find an array of the service IDs which are running today.
def find_service_ids_today
filename = [LOCAL_GTFS_DIR, 'calendar.txt'].join '/'
entries = []
weekday_columns = %w(sunday monday tuesday wednesday thursday friday saturday)
weekday = weekday_columns[todays_date.wday]
CSV.foreach filename, headers: true do |row|
service_id = row.fetch('service_id')
if service_id.include? 'UMTS'
if row.fetch(weekday) == '1' # that is to say, if the service type runs today
start_date = Date.parse row.fetch('start_date')
end_date = Date.parse row.fetch('end_date')
if (start_date..end_date).cover?(Date.today)
entries << service_id
end
end
end
end
entries
end
# Find the ID of the stop whose name is defined in STOP_NAME
def find_stop_id
filename = [LOCAL_GTFS_DIR, 'stops.txt'].join '/'
stop = {}
CSV.foreach filename, headers: true do |row|
if row.fetch('stop_name').include? STOP_NAME
stop = row
break
end
end
stop.fetch 'stop_id'
end
# Returns a hash which is keyed by trip ID,
# and which stores the trip's route ID, direction, and headsign
def find_trips_operating_today
service_ids = find_service_ids_today
filename = [LOCAL_GTFS_DIR, 'trips.txt'].join '/'
trips = {}
CSV.foreach filename, headers: true do |row|
if service_ids.include? row.fetch('service_id')
trips[row.fetch 'trip_id'] = [row.fetch('route_id'),
row.fetch('direction_id'),
row.fetch('trip_headsign')]
end
end
trips
end
# Given the trips operating day and the ID of the stop at STOP_NAME,
# find the departures at that route.
# This is a hash keyed by route ID, direction, and headsign,
# and which stores a sorted array of departure times.
def find_departures
filename = [LOCAL_GTFS_DIR, 'stop_times.txt'].join '/'
stop_id = find_stop_id
trips = find_trips_operating_today
# Track the indices so that for each row, we can always include the row after it.
rows, indices = [], []
CSV.foreach(filename, headers: true).with_index do |row, index|
rows << row and next if indices.map(&:succ).include? index # If the previous row has been saved
trip_id = row.fetch 'trip_id'
if trips.key? trip_id
if row.fetch('stop_id') == stop_id
rows << row
indices << index
end
end
end
departures = {}
# If the departure's trip ID does not match the trip ID of the next row,
# then it is the last stop in the trip, so it is not a departure.
# For example, the last stop of an inbound 45 trip will be at Studio Arts Building,
# but we do *not* want to report a departure with headsign UMass.
# Basically, trips always end with a headsign change.
rows.each_slice(2).map do |row, next_row| # Take the first of each pair if it matches
row if row.fetch('trip_id') == next_row.fetch('trip_id')
end.compact.each do |row|
trip_id = row.fetch 'trip_id'
route_data = trips[trip_id]
departures[route_data] ||= []
departures[route_data] << row.fetch('departure_time')
departures[route_data].sort!
end
departures
end
# Downloads the ZIP archive
def get_new_files!
FileUtils.rm_rf LOCAL_GTFS_DIR
FileUtils.mkdir_p LOCAL_GTFS_DIR
begin
zipfile = Net::HTTP.get URI(GTFS_PROTOCOL + GTFS_HOST + GTFS_PATH)
rescue SocketError
return # TODO: notify that there's some problem
end
Zip::Archive.open_buffer zipfile do |archive|
archive.each do |file|
file_path = File.join LOCAL_GTFS_DIR, file.name
File.open file_path, 'w' do |f|
f << file.read
end
end
end
end
# Parses a string time such as '16:30:00'
# into a Time object
def parse_time(time)
hour, minute = time.split(':').map(&:to_i)
date = Date.today
hour -= 24 and date += 1 if hour >= 24
Time.local date.year, date.month, date.day, hour, minute
end
# Checks to see whether a time object falls within n minutes
def time_within?(minutes, time)
compare_time = Time.now + (60 * minutes)
Time.now < time && time < compare_time
end
# Between midnight and 4am, return yesterday.
def todays_date
if Time.now.hour < 4
Date.today - 1
else Date.today
end
end
end
Changing constants to all caps
require 'csv'
require 'fileutils'
require 'json'
require 'net/http'
require 'zipruby'
module GtfsParser
LOCAL_GTFS_DIR = File.expand_path('../../gtfs/', __FILE__)
STOP_NAME = 'Studio Arts Building'.freeze
CACHE_FILE = 'cached_departures.json'.freeze
GTFS_PROTOCOL = 'http://'.freeze
GTFS_HOST = 'pvta.com'.freeze
GTFS_PATH = '/g_trans/google_transit.zip'.freeze
LOG = File.expand_path('../../log', __FILE__)
def prepare!
zip_log_file!
get_new_files! unless files_up_to_date?
cache_departures!
end
# Returns a hash which you can query by route number and direction,
# and which stores the headsign of the next departure,
# the next scheduled departure,
# and the previous scheduled departure.
# Example:
# {['31', '0'] => ['Sunderland', '13:51:00', '14:06:00']}
def soonest_departures_within(minutes)
departure_times = {}
cached_departures.each do |(route_number, direction_id, headsign), times|
next_time = times.find { |time| time_within? minutes, time }
if next_time
last_time = times[times.index(next_time) - 1] unless next_time == times.first
times_in_same_route_direction = departure_times[[route_number, direction_id]]
unless times_in_same_route_direction && times_in_same_route_direction.last < next_time
departure_times[[route_number, direction_id]] = [headsign, last_time, next_time]
end
end
end
departure_times
end
private
# Stores departures in the cache file.
def cache_departures!
departures = find_departures
File.open CACHE_FILE, 'w' do |file|
file.puts departures.to_json
end
end
# Zip yesterday's log file into an archive directory, with filenames indicating the date
def zip_log_file!
# At 4am, so todays_date log file is yesterday's log file
zipfile = File.open "#{todays_date}.json"
Zip::Archive.open_buffer zipfile do |archive|
archive.each do |file|
file_path = File.join LOG, file.name
File.open file_path, 'w' do |f|
f << file.read
end
end
end
end
# Retrieves the cached departures.
def cached_departures
departures = JSON.parse(File.read(CACHE_FILE))
parsed_departures = {}
departures.each do |route_data, times|
parsed_departures[JSON.parse(route_data)] = times.map { |time| parse_time time }
end
parsed_departures
end
# Is the remote GTFS archive more recent than our cached files?
def files_up_to_date?
return false unless File.directory? LOCAL_GTFS_DIR
http = Net::HTTP.new GTFS_HOST
begin
response = http.head GTFS_PATH
rescue SocketError
true
else
mtime = DateTime.parse response['last-modified']
mtime < File.mtime(LOCAL_GTFS_DIR).to_datetime
end
end
# Find an array of the service IDs which are running today.
def find_service_ids_today
filename = [LOCAL_GTFS_DIR, 'calendar.txt'].join '/'
entries = []
weekday_columns = %w(sunday monday tuesday wednesday thursday friday saturday)
weekday = weekday_columns[todays_date.wday]
CSV.foreach filename, headers: true do |row|
service_id = row.fetch('service_id')
if service_id.include? 'UMTS'
if row.fetch(weekday) == '1' # that is to say, if the service type runs today
start_date = Date.parse row.fetch('start_date')
end_date = Date.parse row.fetch('end_date')
if (start_date..end_date).cover?(Date.today)
entries << service_id
end
end
end
end
entries
end
# Find the ID of the stop whose name is defined in STOP_NAME
def find_stop_id
filename = [LOCAL_GTFS_DIR, 'stops.txt'].join '/'
stop = {}
CSV.foreach filename, headers: true do |row|
if row.fetch('stop_name').include? STOP_NAME
stop = row
break
end
end
stop.fetch 'stop_id'
end
# Returns a hash which is keyed by trip ID,
# and which stores the trip's route ID, direction, and headsign
def find_trips_operating_today
service_ids = find_service_ids_today
filename = [LOCAL_GTFS_DIR, 'trips.txt'].join '/'
trips = {}
CSV.foreach filename, headers: true do |row|
if service_ids.include? row.fetch('service_id')
trips[row.fetch 'trip_id'] = [row.fetch('route_id'),
row.fetch('direction_id'),
row.fetch('trip_headsign')]
end
end
trips
end
# Given the trips operating day and the ID of the stop at STOP_NAME,
# find the departures at that route.
# This is a hash keyed by route ID, direction, and headsign,
# and which stores a sorted array of departure times.
def find_departures
filename = [LOCAL_GTFS_DIR, 'stop_times.txt'].join '/'
stop_id = find_stop_id
trips = find_trips_operating_today
# Track the indices so that for each row, we can always include the row after it.
rows, indices = [], []
CSV.foreach(filename, headers: true).with_index do |row, index|
rows << row and next if indices.map(&:succ).include? index # If the previous row has been saved
trip_id = row.fetch 'trip_id'
if trips.key? trip_id
if row.fetch('stop_id') == stop_id
rows << row
indices << index
end
end
end
departures = {}
# If the departure's trip ID does not match the trip ID of the next row,
# then it is the last stop in the trip, so it is not a departure.
# For example, the last stop of an inbound 45 trip will be at Studio Arts Building,
# but we do *not* want to report a departure with headsign UMass.
# Basically, trips always end with a headsign change.
rows.each_slice(2).map do |row, next_row| # Take the first of each pair if it matches
row if row.fetch('trip_id') == next_row.fetch('trip_id')
end.compact.each do |row|
trip_id = row.fetch 'trip_id'
route_data = trips[trip_id]
departures[route_data] ||= []
departures[route_data] << row.fetch('departure_time')
departures[route_data].sort!
end
departures
end
# Downloads the ZIP archive
def get_new_files!
FileUtils.rm_rf LOCAL_GTFS_DIR
FileUtils.mkdir_p LOCAL_GTFS_DIR
begin
zipfile = Net::HTTP.get URI(GTFS_PROTOCOL + GTFS_HOST + GTFS_PATH)
rescue SocketError
return # TODO: notify that there's some problem
end
Zip::Archive.open_buffer zipfile do |archive|
archive.each do |file|
file_path = File.join LOCAL_GTFS_DIR, file.name
File.open file_path, 'w' do |f|
f << file.read
end
end
end
end
# Parses a string time such as '16:30:00'
# into a Time object
def parse_time(time)
hour, minute = time.split(':').map(&:to_i)
date = Date.today
hour -= 24 and date += 1 if hour >= 24
Time.local date.year, date.month, date.day, hour, minute
end
# Checks to see whether a time object falls within n minutes
def time_within?(minutes, time)
compare_time = Time.now + (60 * minutes)
Time.now < time && time < compare_time
end
# Between midnight and 4am, return yesterday.
def todays_date
if Time.now.hour < 4
Date.today - 1
else Date.today
end
end
end
|
require 'guard'
require 'guard/guard'
module Guard
class RSpec < Guard
autoload :Runner, 'guard/rspec/runner'
autoload :Inspector, 'guard/rspec/inspector'
attr_accessor :last_failed, :failed_paths
def initialize(watchers = [], options = {})
super
@options = {
:focus_on_failed => false,
:all_after_pass => true,
:all_on_start => true,
:keep_failed => true,
:spec_paths => ["spec"],
:run_all => {}
}.merge(options)
@last_failed = false
@failed_paths = []
@inspector = Inspector.new(@options)
@runner = Runner.new(@options)
end
# Call once when guard starts
def start
UI.info "Guard::RSpec is running"
run_all if @options[:all_on_start]
end
def run_all
passed = @runner.run(@inspector.spec_paths, @options[:run_all].merge(:message => 'Running all specs'))
unless @last_failed = !passed
@failed_paths = []
else
throw :task_has_failed
end
end
def reload
@failed_paths = []
end
def run_on_changes(paths)
if @last_failed && @options[:focus_on_failed]
path = './tmp/rspec_guard_result'
if File.exist?(path)
paths = File.open(path) { |file| file.read.split("\n") }
File.delete(path)
# some sane limit, stuff will explode if all tests fail ... cap at 10
paths = paths[0..10]
end
else
paths += failed_paths if @options[:keep_failed]
paths = @inspector.clean(paths)
end
if passed = @runner.run(paths)
remove_failed(paths)
# run all the specs if the run before this one failed
if last_failed && @options[:all_after_pass]
@last_failed = false
run_all
end
else
@last_failed = true
add_failed(paths)
throw :task_has_failed
end
end
private
def run(paths)
end
def remove_failed(paths)
@failed_paths -= paths if @options[:keep_failed]
end
def add_failed(paths)
@failed_paths += paths if @options[:keep_failed]
end
end
end
urgentish fix, should always clean paths
require 'guard'
require 'guard/guard'
module Guard
class RSpec < Guard
autoload :Runner, 'guard/rspec/runner'
autoload :Inspector, 'guard/rspec/inspector'
attr_accessor :last_failed, :failed_paths
def initialize(watchers = [], options = {})
super
@options = {
:focus_on_failed => false,
:all_after_pass => true,
:all_on_start => true,
:keep_failed => true,
:spec_paths => ["spec"],
:run_all => {}
}.merge(options)
@last_failed = false
@failed_paths = []
@inspector = Inspector.new(@options)
@runner = Runner.new(@options)
end
# Call once when guard starts
def start
UI.info "Guard::RSpec is running"
run_all if @options[:all_on_start]
end
def run_all
passed = @runner.run(@inspector.spec_paths, @options[:run_all].merge(:message => 'Running all specs'))
unless @last_failed = !passed
@failed_paths = []
else
throw :task_has_failed
end
end
def reload
@failed_paths = []
end
def run_on_changes(paths)
if @last_failed && @options[:focus_on_failed]
path = './tmp/rspec_guard_result'
if File.exist?(path)
paths = File.open(path) { |file| file.read.split("\n") }
File.delete(path)
# some sane limit, stuff will explode if all tests fail ... cap at 10
paths = paths[0..10]
end
else
paths += failed_paths if @options[:keep_failed]
end
paths = @inspector.clean(paths)
if passed = @runner.run(paths)
remove_failed(paths)
# run all the specs if the run before this one failed
if last_failed && @options[:all_after_pass]
@last_failed = false
run_all
end
else
@last_failed = true
add_failed(paths)
throw :task_has_failed
end
end
private
def run(paths)
end
def remove_failed(paths)
@failed_paths -= paths if @options[:keep_failed]
end
def add_failed(paths)
@failed_paths += paths if @options[:keep_failed]
end
end
end
|
#
# = test/unit/bio/io/test_ensembl.rb - Unit test for Bio::Ensembl.
#
# Copyright:: Copyright (C) 2006
# Mitsuteru C. Nakao <n@bioruby.org>
# License:: Ruby's
#
# $Id: test_ensembl.rb,v 1.2 2006/04/27 05:38:50 nakao Exp $
#
require 'pathname'
libpath = Pathname.new(File.join(File.dirname(__FILE__), ['..'] * 4, 'lib')).cleanpath.to_s
$:.unshift(libpath) unless $:.include?(libpath)
require 'test/unit'
require 'bio/io/ensembl'
class TestEnsembl < Test::Unit::TestCase
def test_server_name
assert_equal('http://www.ensembl.org', Bio::Ensembl::EBIServerURI)
end
def test_server_uri
assert_equal('http://www.ensembl.org', Bio::Ensembl.server_uri)
end
def test_set_server_uri
host = 'http://localhost'
Bio::Ensembl.server_uri(host)
assert_equal(host, Bio::Ensembl.server_uri)
end
end
class TestEnsemblBase < Test::Unit::TestCase
def test_exportview
end
end
class TestEnsemblBaseClient < Test::Unit::TestCase
def test_class
end
end
class TestEnsemblHuman < Test::Unit::TestCase
def test_organism
assert_equal("Homo_sapiens", Bio::Ensembl::Human::Organism)
end
end
class TestEnsemblMouse < Test::Unit::TestCase
def test_organism
assert_equal("Mus_musculus", Bio::Ensembl::Mouse::Organism)
end
end
* Added TestEnsembl_v14 class.
#
# = test/unit/bio/io/test_ensembl.rb - Unit test for Bio::Ensembl.
#
# Copyright:: Copyright (C) 2006, 2007
# Mitsuteru C. Nakao <n@bioruby.org>
# License:: Ruby's
#
# $Id: test_ensembl.rb,v 1.3 2007/03/28 12:01:00 nakao Exp $
#
require 'pathname'
libpath = Pathname.new(File.join(File.dirname(__FILE__), ['..'] * 4, 'lib')).cleanpath.to_s
$:.unshift(libpath) unless $:.include?(libpath)
require 'test/unit'
require 'bio/io/ensembl'
# tests for ensembl.rb,v 1.4
class TestEnsembl_v14 < Test::Unit::TestCase
def test_ensembl_url
assert_equal('http://www.ensembl.org', Bio::Ensembl::ENSEMBL_URL)
end
def test_server
obj = Bio::Ensembl.new('Homo_sapiens')
assert_equal('http://www.ensembl.org', obj.server)
end
def test_organism
organism = 'Homo_sapiens'
obj = Bio::Ensembl.new(organism)
assert_equal(organism, obj.organism)
end
def test_self_human
organism = 'Homo_sapiens'
obj = Bio::Ensembl.human
assert_equal(organism, obj.organism)
end
def test_self_mouse
organism = 'Mus_musculus'
obj = Bio::Ensembl.mouse
assert_equal(organism, obj.organism)
end
end
class TestEnsembl < Test::Unit::TestCase
def test_server_name
assert_equal('http://www.ensembl.org', Bio::Ensembl::EBIServerURI)
end
def test_server_uri
assert_equal('http://www.ensembl.org', Bio::Ensembl.server_uri)
end
def test_set_server_uri
host = 'http://localhost'
Bio::Ensembl.server_uri(host)
assert_equal(host, Bio::Ensembl.server_uri)
end
end
class TestEnsemblBase < Test::Unit::TestCase
def test_exportview
end
end
class TestEnsemblBaseClient < Test::Unit::TestCase
def test_class
end
end
class TestEnsemblHuman < Test::Unit::TestCase
def test_organism
assert_equal("Homo_sapiens", Bio::Ensembl::Human::Organism)
end
end
class TestEnsemblMouse < Test::Unit::TestCase
def test_organism
assert_equal("Mus_musculus", Bio::Ensembl::Mouse::Organism)
end
end
|
Regenerated gemspec for version 0.1.0
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{nc-freebase}
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Namit Chadha"]
s.date = %q{2010-10-08}
s.description = %q{}
s.email = %q{nc@appspark.us}
s.extra_rdoc_files = [
"LICENSE",
"README.markdown"
]
s.files = [
".bundle/config",
".document",
".gitignore",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE",
"README.markdown",
"Rakefile",
"VERSION",
"freebase.gemspec",
"freeman.gemspec",
"lib/freebase.rb",
"lib/freebase/base.rb",
"lib/freebase/response.rb",
"lib/freebase/result.rb",
"spec/freebase_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = %q{http://github.com/nc/freebase}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.summary = %q{quick freebase queries}
s.test_files = [
"spec/freebase_spec.rb",
"spec/spec_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<httparty>, [">= 0"])
s.add_runtime_dependency(%q<yajl-ruby>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 0"])
else
s.add_dependency(%q<httparty>, [">= 0"])
s.add_dependency(%q<yajl-ruby>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 0"])
end
else
s.add_dependency(%q<httparty>, [">= 0"])
s.add_dependency(%q<yajl-ruby>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 0"])
end
end
|
require "thor"
require "yaml"
require_relative "client"
module Hackpad
class Cli < Thor
class_option :configdir,
aliases: "-c",
default: File.join(ENV["HOME"], ".hackpad-cli/"),
desc: "Path to the hackpad-cli directory to use."
class_option :workspace,
aliases: "-w",
default: "default",
desc: "Name of the workspace to use."
class_option :plain,
aliases: "-p",
type: 'boolean',
default: false,
desc: "Add this if you don't want colors."
default_task :help
desc "search [term]", "Lists available pads matching [term]."
def search(term)
Hackpad::Client.new(options).search term
end
desc "list", "Lists available pads."
def list
Hackpad::Client.new(options).listall
end
desc "getinfo [pad_id]", "gets info for the pad <pad_id>."
def info(pad)
Hackpad::Client.new(options).getinfo pad
end
desc "show [pad_id] [format]", "shows pad <pad_id> in format [html,txt,md] (default txt)."
def show(pad,format='txt')
Hackpad::Client.new(options).show pad, format
end
desc "colors", "displays colorize color matrix."
option :hide
def colors
require 'colorize'
String.color_matrix ' xoxo '
end
end
end
hide colors task
require "thor"
require "yaml"
require_relative "client"
module Hackpad
class Cli < Thor
class_option :configdir,
aliases: "-c",
default: File.join(ENV["HOME"], ".hackpad-cli/"),
desc: "Path to the hackpad-cli directory to use."
class_option :workspace,
aliases: "-w",
default: "default",
desc: "Name of the workspace to use."
class_option :plain,
aliases: "-p",
type: 'boolean',
default: false,
desc: "Add this if you don't want colors."
default_task :help
desc "search [term]", "Lists available pads matching [term]."
def search(term)
Hackpad::Client.new(options).search term
end
desc "list", "Lists available pads."
def list
Hackpad::Client.new(options).listall
end
desc "getinfo [pad_id]", "gets info for the pad <pad_id>."
def info(pad)
Hackpad::Client.new(options).getinfo pad
end
desc "show [pad_id] [format]", "shows pad <pad_id> in format [html,txt,md] (default txt)."
def show(pad,format='txt')
Hackpad::Client.new(options).show pad, format
end
desc "colors", "displays colorize color matrix.", hide: true
def colors
require 'colorize'
String.color_matrix ' xoxo '
end
end
end
|
require "has_archive/version"
require "has_archive/railtie" if defined?(Rails)
require "has_archive/hook"
module HasArchive
def self.included(base)
base.send :extend, ClassMethods
base.send :include, InstanceMethods
eval <<-RUBY
class #{base}::Archive < #{base}
self.table_name = "#{base.to_s.underscore}_archives"
def restore
attrs = self.attributes
attrs.delete('archived_at')
restored = self.class.parent.new(attrs)
restored.save && self.destroy(for_real: true)
self
end
end
RUBY
end
module ClassMethods
def archived
union = self.unscoped.union(self::Archive.unscoped.select(self.attribute_names.map(&:to_sym)))
self.from(self.arel_table.create_table_alias(union, self.table_name.to_sym).to_sql)
end
end
module InstanceMethods
def archive
archive = self.class::Archive.new(self.attributes)
archive.archived_at = Time.now
archive.save(validate: false)
self.destroy(for_real: true)
end
def destroy(for_real: false)
if !for_real && Rails.configuration.has_archive.override_destroy
archive
else
super()
end
end
end
end
rescue exception when archive with conflicting id exists
require "has_archive/version"
require "has_archive/railtie" if defined?(Rails)
require "has_archive/hook"
module HasArchive
def self.included(base)
base.send :extend, ClassMethods
base.send :include, InstanceMethods
eval <<-RUBY
class #{base}::Archive < #{base}
self.table_name = "#{base.to_s.underscore}_archives"
def restore
attrs = self.attributes
attrs.delete('archived_at')
restored = self.class.parent.new(attrs)
restored.save && self.destroy(for_real: true)
self
end
end
RUBY
end
module ClassMethods
def archived
union = self.unscoped.union(self::Archive.unscoped.select(self.attribute_names.map(&:to_sym)))
self.from(self.arel_table.create_table_alias(union, self.table_name.to_sym).to_sql)
end
end
module InstanceMethods
def archive
archive = self.class::Archive.new(self.attributes)
archive.archived_at = Time.now
archive.save(validate: false)
self.destroy(for_real: true)
rescue ActiveRecord::RecordNotUnique => e
Rails.logger.warn "Rescued attempt to archive record with existing key: #{archive.id}."
false
end
def destroy(for_real: false)
if !for_real && Rails.configuration.has_archive.override_destroy
archive
else
super()
end
end
end
end
|
require 'net/ssh'
require 'highline/import'
require_relative "householder/version"
module Householder
def self.run(raw_argv)
box_url, _, remote_host, _, user, _, fqdn, _, ip_address, _, public_key_path = raw_argv
appliance_filename = File.basename(box_url)
appliance_file_ext = File.extname(appliance_filename)
appliance_name = File.basename(appliance_filename, appliance_file_ext)
new_appliance_filename = "#{appliance_name}_#{Time.now.to_i}.#{appliance_file_ext}"
puts ""
puts "Connecting via SSH..."
puts ""
pass = ask("Enter password for #{user}@#{remote_host}: ") { |q| q.echo = false }
Net::SSH.start(remote_host, user, password: pass ) do |ssh|
puts "Downloading VBox Appliance..."
puts ssh.exec!("curl -o #{new_appliance_filename} #{box_url}")
puts ""
puts "Importing VBox appliance..."
puts ""
puts ssh.exec!("VBoxManage import --options keepallmacs #{new_appliance_filename}")
vms = ssh.exec!('VBoxManage list vms')
vm_name = /\"(.*)\"/.match(vms.split("\n").last)[1]
puts ""
puts "Modifying VBox configuration:"
# Get VM Info
vm_info_raw = ssh.exec!(%Q(VBoxManage showvminfo "#{@vm_name}")).split("\n")
vm_info = {}
vm_info_raw.each do |l|
key, value = l.split(':', 2).map(&:strip)
vm_info[key] = value unless value.nil?
end
vm_info
vm_info.each do |key, value|
# Remove existing port forwarding rules on Network Adapter 1
if /NIC 1 Rule\(\d\)/.match(key)
rule_name = /^name = (.+?),/.match(value)
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --natpf1 delete "#{rule_name[1]}")) if !rule_name.nil? && rule_name.size > 1
# Remove network adapters 3 & 4 to avoid conflict with NAT and Bridged Adapter
elsif other_adapters = /^NIC (3|4)$/.match(key) && value != 'disabled'
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --nic#{other_adapters[1]} none))
end
end
puts "Creating NAT on Network Adapter 1 and adding port forwarding..."
host_port = 2222
guest_port = 22
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --nic1 nat --cableconnected1 on --natpf1 "guestssh,tcp,,#{host_port},,#{guest_port}"))
puts "Creating Bridged Adapter on Network Adapter 2..."
bridge_adapter_type = 'en1: Wi-Fi (AirPort)'
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --nic2 bridged --bridgeadapter2 "#{bridge_adapter_type}"))
puts ""
puts "Done creating your VBox (#{vm_name})."
puts ""
puts "Starting VM..."
puts ssh.exec!(%Q(VBoxManage startvm "#{vm_name}" --type headless))
end
end
end
WIP: Connect to guest VM and modify the network interfaces.
require 'net/ssh'
require 'highline/import'
require_relative "householder/version"
module Householder
HOST_IP = '127.0.0.1'
def self.run(raw_argv)
box_url, _, remote_host, _, user, _, fqdn, _, ip_address, _, public_key_path = raw_argv
appliance_filename = File.basename(box_url)
appliance_file_ext = File.extname(appliance_filename)
appliance_name = File.basename(appliance_filename, appliance_file_ext)
new_appliance_filename = "#{appliance_name}_#{Time.now.to_i}.#{appliance_file_ext}"
puts ""
puts "Connecting to #{remote_host} via SSH..."
pass = ask("Enter password for #{user}@#{remote_host}: ") { |q| q.echo = false }
Net::SSH.start(remote_host, user, password: pass ) do |ssh|
puts "Downloading VBox Appliance..."
puts ssh.exec!("curl -o #{new_appliance_filename} #{box_url}")
puts ""
puts "Importing VBox appliance..."
puts ""
puts ssh.exec!("VBoxManage import --options keepallmacs #{new_appliance_filename}")
vms = ssh.exec!('VBoxManage list vms')
vm_name = /\"(.*)\"/.match(vms.split("\n").last)[1]
puts ""
puts "Modifying VBox configuration:"
# Get VM Info
vm_info_raw = ssh.exec!(%Q(VBoxManage showvminfo "#{@vm_name}")).split("\n")
vm_info = {}
vm_info_raw.each do |l|
key, value = l.split(':', 2).map(&:strip)
vm_info[key] = value unless value.nil?
end
vm_info
vm_info.each do |key, value|
# Remove existing port forwarding rules on Network Adapter 1
if /NIC 1 Rule\(\d\)/.match(key)
rule_name = /^name = (.+?),/.match(value)
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --natpf1 delete "#{rule_name[1]}")) if !rule_name.nil? && rule_name.size > 1
# Remove network adapters 3 & 4 to avoid conflict with NAT and Bridged Adapter
elsif other_adapters = /^NIC (3|4)$/.match(key) && value != 'disabled'
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --nic#{other_adapters[1]} none))
end
end
puts "Creating NAT on Network Adapter 1 and adding port forwarding..."
host_port = 2233
guest_port = 22
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --nic1 nat --cableconnected1 on --natpf1 "guestssh,tcp,,#{host_port},,#{guest_port}"))
puts "Creating Bridged Adapter on Network Adapter 2 and adding port forwarding..."
# TODO: Need to detect if host is using wifi or cable (en1 or en0)
bridge_adapter_type = 'en1: Wi-Fi (AirPort)'
puts ssh.exec!(%Q(VBoxManage modifyvm "#{vm_name}" --nic2 bridged --cableconnected1 on --bridgeadapter2 "#{bridge_adapter_type}"))
puts ""
puts "Done creating your VBox (#{vm_name})."
puts ""
puts "Starting VM..."
puts ssh.exec!(%Q(VBoxManage startvm "#{vm_name}" --type headless))
puts ""
puts "Connecting to VM via SSH..."
static_network = "10.0.1"
static_host = "222"
static_address = "#{static_network}.#{static_host}"
interfaces = <<-CONFIG
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
auto br1
iface br1 inet static
address #{static_address}
netmask 255.255.255.0
network #{static_network}.0
broadcast #{static_network}.255
gateway #{static_network}.1
bridge_ports eth1
bridge_stp off
bridge_fd 0
bridge_maxwait 0
CONFIG
guest_user = ask("User for guest VM: ")
guest_pass = ask("Enter password for #{guest_user}@#{Householder::HOST_IP}: ") { |q| q.echo = false }
sleep 10
Net::SSH.start(Householder::HOST_IP, guest_user, password: guest_pass, port: host_port) do |guest_ssh|
guest_ssh.open_channel do |channel|
channel.request_pty do |channel , success|
raise "I can't get pty rquest" unless success
puts ""
puts "Creating backup for network interfaces config file..."
channel.exec('sudo cp /etc/network/interfaces /etc/network/interfaces-orig-backup')
channel.on_data do |ch , data|
if data.inspect.include?("[sudo]")
channel.send_data("#{guest_pass}\n")
sleep 0.1
end
ch.wait
end
end
end
guest_ssh.open_channel do |channel|
channel.request_pty do |channel , success|
raise "I can't get pty rquest" unless success
puts "Modifying VM's network interfaces..."
channel.exec(%Q(string="#{interfaces}" && printf "%b\n" "$string" | sudo tee /etc/network/interfaces))
channel.on_data do |ch , data|
if data.inspect.include?("[sudo]")
channel.send_data("#{guest_pass}\n")
sleep 0.1
end
ch.wait
end
end
end
guest_ssh.open_channel do |channel|
channel.request_pty do |channel , success|
raise "I can't get pty rquest" unless success
puts "Installing uml-utilties and bridge-utils..."
channel.exec(%Q(sudo apt-get install uml-utilities bridge-utils))
channel.on_data do |ch , data|
if data.inspect.include?("[sudo]")
channel.send_data("#{guest_pass}\n")
sleep 0.1
end
ch.wait
end
end
end
guest_ssh.open_channel do |channel|
channel.request_pty do |channel , success|
raise "I can't get pty rquest" unless success
puts "Restarting VM's network..."
channel.exec(%Q(sudo init 6))
channel.on_data do |ch , data|
if data.inspect.include?("[sudo]")
channel.send_data("#{guest_pass}\n")
sleep 0.1
end
ch.wait
end
end
end
guest_ssh.loop
end
end
end
end |
require 'sinatra/base'
require "haml"
require "slim"
module Hstatic
BASEDIR = File.join(File.dirname(__FILE__), '..', '..')
class App < Sinatra::Base
configure do
set :views, File.join(BASEDIR, 'views')
set :environment, :development
enable :logging
end
helpers do
def dynamic_size(size)
case
when size > 2**40
sprintf("%5.2f", size / 2**40) << ' GB'
when (size / 2**20) > 0.1
sprintf("%5.2f", size / 2**20) << ' MB'
else
sprintf("%5.2f", size / 2**10) << ' kB'
end
end
end
# Finally every Tilt supported template is rendered
helpers do
def render_file(path)
begin
if template = Tilt[path]
ext, _ = Tilt.mappings.find { |k, v| v.include? template }
method = self.method(ext)
basename = File.basename(path, File.extname(path)).to_sym
method.call(basename, { :views => File.dirname(path) })
else
raise Exception.new "Template engine not found for #{path}"
end
rescue Exception => e
send_file path
end
end
end
# Going around bootstrap
get '/.res/bootstrap.min.css' do
send_file(File.join(BASEDIR, 'res/bootstrap.min.css'))
end
get '/.res/style.css' do
send_file(File.join(BASEDIR, 'res/style.css'))
end
get '/.res/jquery-1.10.2.min.js' do
send_file(File.join(BASEDIR, 'res/jquery-1.10.2.min.js'))
end
get '/fonts/glyphicons-halflings-regular.woff' do
send_file(File.join(BASEDIR, 'res/glyphicons-halflings-regular.woff'))
end
get '/fonts/glyphicons-halflings-regular.ttf' do
send_file(File.join(BASEDIR, 'res/glyphicons-halflings-regular.ttf'))
end
get '/fonts/glyphicons-halflings-regular.svg' do
send_file(File.join(BASEDIR, 'res/glyphicons-halflings-regular.svg'))
end
# Catch all route
get '*' do
path = File.expand_path(File.join(Dir.pwd, unescape(request.path_info)))
if File.file? path
render_file path
elsif File.exists?(File.expand_path(File.join(path, 'index.html')))
redirect(File.join(request.path_info, 'index.html'))
elsif File.directory? path
# Building data
@folders = Array.new
@files = Array.new
@parent = File.dirname(request.path_info)
Dir.foreach(path) do |entry|
next if entry == "." || entry == ".."
url_base = File.join("/", request.path_info)
link = File.join(url_base, entry)
filename = File.expand_path(File.join(path, entry))
if File.directory? filename
@folders << { name: entry, href: link }
else
@files << { name: unescape(entry),
size: dynamic_size(File.size(filename)),
href: link }
end
end
# Render view
haml :index
else
[404, "File not found"]
end
end
end
end
app: add logging
require 'sinatra/base'
require "haml"
require "slim"
module Hstatic
BASEDIR = File.join(File.dirname(__FILE__), '..', '..')
class App < Sinatra::Base
configure do
set :views, File.join(BASEDIR, 'views')
set :environment, :development
enable :logging
end
helpers do
def dynamic_size(size)
case
when size > 2**40
sprintf("%5.2f", size / 2**40) << ' GB'
when (size / 2**20) > 0.1
sprintf("%5.2f", size / 2**20) << ' MB'
else
sprintf("%5.2f", size / 2**10) << ' kB'
end
end
end
# Finally every Tilt supported template is rendered
helpers do
def render_file(path)
begin
if template = Tilt[path]
ext, _ = Tilt.mappings.find { |k, v| v.include? template }
method = self.method(ext)
basename = File.basename(path, File.extname(path)).to_sym
method.call(basename, { :views => File.dirname(path) })
else
raise Exception.new "No template found for #{path}"
end
rescue Exception => e
logger.info e.message
send_file path
end
end
end
# Going around bootstrap
get '/.res/bootstrap.min.css' do
send_file(File.join(BASEDIR, 'res/bootstrap.min.css'))
end
get '/.res/style.css' do
send_file(File.join(BASEDIR, 'res/style.css'))
end
get '/.res/jquery-1.10.2.min.js' do
send_file(File.join(BASEDIR, 'res/jquery-1.10.2.min.js'))
end
get '/fonts/glyphicons-halflings-regular.woff' do
send_file(File.join(BASEDIR, 'res/glyphicons-halflings-regular.woff'))
end
get '/fonts/glyphicons-halflings-regular.ttf' do
send_file(File.join(BASEDIR, 'res/glyphicons-halflings-regular.ttf'))
end
get '/fonts/glyphicons-halflings-regular.svg' do
send_file(File.join(BASEDIR, 'res/glyphicons-halflings-regular.svg'))
end
# Catch all route
get '*' do
path = File.expand_path(File.join(Dir.pwd, unescape(request.path_info)))
if File.file? path
render_file path
elsif File.exists?(File.expand_path(File.join(path, 'index.html')))
redirect(File.join(request.path_info, 'index.html'))
elsif File.directory? path
# Building data
@folders = Array.new
@files = Array.new
@parent = File.dirname(request.path_info)
Dir.foreach(path) do |entry|
next if entry == "." || entry == ".."
url_base = File.join("/", request.path_info)
link = File.join(url_base, entry)
filename = File.expand_path(File.join(path, entry))
if File.directory? filename
@folders << { name: entry, href: link }
else
@files << { name: unescape(entry),
size: dynamic_size(File.size(filename)),
href: link }
end
end
# Render view
haml :index
else
[404, "File not found"]
end
end
end
end
|
Gem::Specification.new do |spec|
spec.name = 'lita-fortune'
spec.version = '0.0.6'
spec.authors = ['Chris Horton']
spec.email = ['hortoncd@gmail.com']
spec.description = %q{A Lita handler for fortune cookies.}
spec.summary = %q{A Lita handler for fortune cookies.}
spec.homepage = 'https://github.com/hortoncd/lita-fortune'
spec.license = 'Apache 2.0'
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'lita', '>= 2.0'
spec.add_runtime_dependency 'i18n', '~> 0.9'
spec.add_development_dependency 'bundler', '~> 1.15'
spec.add_development_dependency "rake", "~> 12.3"
spec.add_development_dependency "rspec", "~> 3.5"
spec.add_development_dependency "fakeredis", "~> 0.7.0"
end
bump version
Gem::Specification.new do |spec|
spec.name = 'lita-fortune'
spec.version = '0.0.7'
spec.authors = ['Chris Horton']
spec.email = ['hortoncd@gmail.com']
spec.description = %q{A Lita handler for fortune cookies.}
spec.summary = %q{A Lita handler for fortune cookies.}
spec.homepage = 'https://github.com/hortoncd/lita-fortune'
spec.license = 'Apache 2.0'
spec.metadata = { "lita_plugin_type" => "handler" }
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_runtime_dependency 'lita', '>= 2.0'
spec.add_runtime_dependency 'i18n', '~> 0.9'
spec.add_development_dependency 'bundler', '~> 1.15'
spec.add_development_dependency "rake", "~> 12.3"
spec.add_development_dependency "rspec", "~> 3.5"
spec.add_development_dependency "fakeredis", "~> 0.7.0"
end
|
from mac
puts "hello, world"
|
module Hub
Version = '0.1.3'
end
0.2.0
module Hub
Version = '0.2.0'
end
|
#
require File.dirname(__FILE__) + '/androidcommon.rb'
require 'pathname'
USE_STLPORT = true
USE_TRACES = false
ANDROID_API_LEVEL_TO_MARKET_VERSION = {}
ANDROID_MARKET_VERSION_TO_API_LEVEL = {}
{2 => "1.1", 3 => "1.5", 4 => "1.6", 5 => "2.0", 6 => "2.0.1", 7 => "2.1", 8 => "2.2"}.each do |k,v|
ANDROID_API_LEVEL_TO_MARKET_VERSION[k] = v
ANDROID_MARKET_VERSION_TO_API_LEVEL[v] = k
end
def get_market_version(apilevel)
ANDROID_API_LEVEL_TO_MARKET_VERSION[apilevel]
end
def get_api_level(version)
ANDROID_MARKET_VERSION_TO_API_LEVEL[version]
end
JAVA_PACKAGE_NAME = 'com.rhomobile.rhodes'
# Here is place were android platform should be specified.
# For complete list of android API levels and its mapping to
# market names (such as "Android-1.5" etc) see output of
# command "android list targets"
ANDROID_API_LEVEL = 4
ANDROID_PERMISSIONS = {
'audio' => ['RECORD_AUDIO', 'MODIFY_AUDIO_SETTINGS'],
'camera' => 'CAMERA',
'gps' => 'ACCESS_FINE_LOCATION',
'network_state' => 'ACCESS_NETWORK_STATE',
'phone' => ['CALL_PHONE', 'READ_PHONE_STATE'],
'pim' => ['READ_CONTACTS', 'WRITE_CONTACTS', 'GET_ACCOUNTS'],
'record_audio' => 'RECORD_AUDIO',
'vibrate' => 'VIBRATE',
'bluetooth' => ['BLUETOOTH_ADMIN', 'BLUETOOTH'],
'calendar' => ['READ_CALENDAR', 'WRITE_CALENDAR'],
'push' => proc do |manifest| add_push(manifest) end
}
def add_push(manifest)
element = REXML::Element.new('permission')
element.add_attribute('android:name', "#{$app_package_name}.permission.C2D_MESSAGE")
element.add_attribute('android:protectionLevel', 'signature')
manifest.add element
element = REXML::Element.new('uses-permission')
element.add_attribute('android:name', "#{$app_package_name}.permission.C2D_MESSAGE")
manifest.add element
element = REXML::Element.new('uses-permission')
element.add_attribute('android:name', "com.google.android.c2dm.permission.RECEIVE")
manifest.add element
receiver = REXML::Element.new('receiver')
receiver.add_attribute('android:name', "#{JAVA_PACKAGE_NAME}.PushReceiver")
receiver.add_attribute('android:permission', "com.google.android.c2dm.permission.SEND")
action = REXML::Element.new('action')
action.add_attribute('android:name', "com.google.android.c2dm.intent.RECEIVE")
category = REXML::Element.new('category')
category.add_attribute('android:name', $app_package_name)
ie = REXML::Element.new('intent-filter')
ie.add_element(action)
ie.add_element(category)
receiver.add_element(ie)
action = REXML::Element.new('action')
action.add_attribute('android:name', "com.google.android.c2dm.intent.REGISTRATION")
category = REXML::Element.new('category')
category.add_attribute('android:name', $app_package_name)
ie = REXML::Element.new('intent-filter')
ie.add_element(action)
ie.add_element(category)
receiver.add_element(ie)
manifest.elements.each('application') do |app|
app.add receiver
end
end
def set_app_name_android(newname)
puts "set_app_name"
$stdout.flush
rm_rf $appres
cp_r $rhores, $appres
iconappname = File.join($app_path, "icon", "icon.png")
iconresname = File.join($appres, "drawable", "icon.png")
rm_f iconresname
cp iconappname, iconresname
rhostrings = File.join($rhores, "values", "strings.xml")
appstrings = File.join($appres, "values", "strings.xml")
doc = REXML::Document.new(File.new(rhostrings))
doc.elements["resources/string[@name='app_name']"].text = newname
File.open(appstrings, "w") { |f| doc.write f }
version = {'major' => 0, 'minor' => 0, 'patch' => 0}
if $app_config["version"]
if $app_config["version"] =~ /^(\d+)$/
version["major"] = $1.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
version["patch"] = $3.to_i
end
end
version = version["major"]*10000 + version["minor"]*100 + version["patch"]
doc = REXML::Document.new(File.new($rhomanifest))
doc.root.attributes['package'] = $app_package_name
if version > 0
doc.root.attributes['android:versionCode'] = version.to_s
doc.root.attributes['android:versionName'] = $app_config["version"]
end
doc.elements.delete "manifest/application/uses-library[@android:name='com.google.android.maps']" unless $use_geomapping
caps_proc = []
caps = ['INTERNET', 'PERSISTENT_ACTIVITY', 'WAKE_LOCK']
$app_config["capabilities"].each do |cap|
cap = ANDROID_PERMISSIONS[cap]
next if cap.nil?
if cap.is_a? Proc
caps_proc << cap
next
end
cap = [cap] if cap.is_a? String
cap = [] unless cap.is_a? Array
caps += cap
end
caps.uniq!
manifest = doc.elements["manifest"]
manifest.elements.each('uses-sdk') { |e| manifest.delete e }
element = REXML::Element.new('uses-sdk')
element.add_attribute('android:minSdkVersion', ANDROID_API_LEVEL.to_s)
manifest.add element
# Remove category LAUNCHER from all activities if hidden_app is set
hidden_app = get_boolean($app_config['hidden_app'])
if hidden_app
manifest.elements.each('application') do |app|
app.elements.each('activity') do |activity|
activity.elements.each('intent-filter') do |intf|
intf.elements.each('category') do |c|
name = c.attribute('name', 'android')
next if name.nil?
intf.delete(c) if name.to_s == 'android.intent.category.LAUNCHER'
end
end
end
end
end
# Clear C2DM stuff
doc.elements.delete "manifest/application/receiver[@android:name='#{JAVA_PACKAGE_NAME}.PushReceiver']"
manifest.elements.each('permission') do |e|
name = e.attribute('name', 'android')
next if name.nil?
manifest.delete(e) if name.to_s =~ /\.C2D_MESSAGE$/
end
manifest.elements.each('uses-permission') { |e| manifest.delete e }
caps.sort.each do |cap|
element = REXML::Element.new('uses-permission')
element.add_attribute('android:name', "android.permission.#{cap}")
manifest.add element
end
caps_proc.each do |p|
p.call manifest
end
File.open($appmanifest, "w") { |f| doc.write f, 2 }
buf = File.new($rho_android_r,"r").read.gsub(/^\s*import com\.rhomobile\..*\.R;\s*$/,"\nimport #{$app_package_name}.R;\n")
File.open($app_android_r,"w") { |f| f.write(buf) }
end
def generate_rjava
Rake::Task["build:android:rjava"].execute
end
def get_boolean(arg)
arg == 'true' or arg == 'yes' or arg == 'enabled' or arg == 'enable' or arg == '1'
end
namespace "config" do
task :set_android_platform do
$current_platform = "android"
end
task :android => [:set_android_platform, "config:common"] do
$gapikey = $app_config["android"]["apikey"] unless $app_config["android"].nil?
$gapikey = $config["android"]["apikey"] if $gapikey.nil? and not $config["android"].nil?
$gapikey = '' unless $gapikey.is_a? String
$gapikey = nil if $gapikey.empty?
$use_geomapping = $app_config["android"]["mapping"] unless $app_config["android"].nil?
$use_geomapping = $config["android"]["mapping"] if $use_geomapping.nil? and not $config["android"].nil?
$use_geomapping = 'false' if $use_geomapping.nil?
$use_geomapping = get_boolean($use_geomapping.to_s)
$use_google_addon_api = false
$use_google_addon_api = true if $use_geomapping
$emuversion = $app_config["android"]["version"] unless $app_config["android"].nil?
$emuversion = $config["android"]["version"] if $emuversion.nil? and !$config["android"].nil?
# Here is switch between release/debug configuration used for
# building native libraries
if $app_config["debug"].nil?
$build_release = true
else
$build_release = !$app_config["debug"].to_i
end
$androidsdkpath = $config["env"]["paths"]["android"]
unless File.exists? $androidsdkpath
puts "Missing or invalid 'android' section in rhobuild.yml"
exit 1
end
$androidndkpath = $config["env"]["paths"]["android-ndk"]
unless File.exists? $androidndkpath
puts "Missing or invalid 'android-ndk' section in rhobuild.yml"
exit 1
end
errfmt = "WARNING!!! Path to Android %s contain spaces! It will not work because of the Google toolchain restrictions. Move it to another location and reconfigure rhodes."
if $androidsdkpath =~ /\s/
puts(errfmt % "SDK")
exit 1
end
if $androidndkpath =~ /\s/
puts(errfmt % "NDK")
exit 1
end
$java = $config["env"]["paths"]["java"]
$androidpath = Jake.get_absolute $config["build"]["androidpath"]
$bindir = File.join($app_path, "bin")
$rhobindir = File.join($androidpath, "bin")
$builddir = File.join($androidpath, "build")
$shareddir = File.join($androidpath, "..", "shared")
$srcdir = File.join($bindir, "RhoBundle")
$targetdir = File.join($bindir, "target")
$excludelib = ['**/builtinME.rb','**/ServeME.rb','**/TestServe.rb']
$tmpdir = File.join($bindir, "tmp")
$resourcedir = File.join($tmpdir, "resource")
$libs = File.join($androidpath, "Rhodes", "libs")
$appname = $app_config["name"]
$appname = "Rhodes" if $appname.nil?
$vendor = $app_config["vendor"]
$vendor = "rhomobile" if $vendor.nil?
$vendor = $vendor.gsub(/^[^A-Za-z]/, '_').gsub(/[^A-Za-z0-9]/, '_').gsub(/_+/, '_').downcase
$app_package_name = "com.#{$vendor}." + $appname.downcase.gsub(/[^A-Za-z_0-9]/, '')
$rhomanifest = File.join $androidpath, "Rhodes", "AndroidManifest.xml"
$appmanifest = File.join $tmpdir, "AndroidManifest.xml"
$rhores = File.join $androidpath, "Rhodes", "res"
$appres = File.join $tmpdir, "res"
$appincdir = File.join $tmpdir, "include"
$rho_android_r = File.join $androidpath, "Rhodes", "src", "com", "rhomobile", "rhodes", "AndroidR.java"
$app_android_r = File.join $tmpdir, "AndroidR.java"
$app_rjava_dir = File.join $tmpdir
$app_native_libs_java = File.join $tmpdir, "NativeLibraries.java"
$app_capabilities_java = File.join $tmpdir, "Capabilities.java"
$app_push_java = File.join $tmpdir, "Push.java"
if RUBY_PLATFORM =~ /(win|w)32$/
$emulator = #"cmd /c " +
File.join( $androidsdkpath, "tools", "emulator.exe" )
$bat_ext = ".bat"
$exe_ext = ".exe"
$path_separator = ";"
# Add PATH to cygwin1.dll
ENV['CYGWIN'] = 'nodosfilewarning'
if $path_cygwin_modified.nil?
ENV['PATH'] = Jake.get_absolute("res/build-tools") + ";" + ENV['PATH']
path_cygwin_modified = true
end
else
#XXX make these absolute
$emulator = File.join( $androidsdkpath, "tools", "emulator" )
$bat_ext = ""
$exe_ext = ""
$path_separator = ":"
# TODO: add ruby executable for Linux
end
puts "+++ Looking for platform..." if USE_TRACES
napilevel = ANDROID_API_LEVEL
Dir.glob(File.join($androidsdkpath, "platforms", "*")).each do |platform|
props = File.join(platform, "source.properties")
unless File.file? props
puts "+++ WARNING! No source.properties found in #{platform}"
next
end
apilevel = -1
marketversion = nil
File.open(props, "r") do |f|
while line = f.gets
apilevel = $1.to_i if line =~ /^\s*AndroidVersion\.ApiLevel\s*=\s*([0-9]+)\s*$/
marketversion = $1 if line =~ /^\s*Platform\.Version\s*=\s*([^\s]*)\s*$/
end
end
puts "+++ API LEVEL of #{platform}: #{apilevel}" if USE_TRACES
if apilevel > napilevel
napilevel = apilevel
$androidplatform = File.basename(platform)
$found_api_level = apilevel
end
end
if $androidplatform.nil?
ajar = File.join($androidsdkpath, 'platforms', 'android-' + ANDROID_API_LEVEL_TO_MARKET_VERSION[ANDROID_API_LEVEL], 'android.jar')
$androidplatform = 'android-' + ANDROID_API_LEVEL_TO_MARKET_VERSION[ANDROID_API_LEVEL] if File.file?(ajar)
end
if $androidplatform.nil?
puts "+++ No required platform (API level >= #{ANDROID_API_LEVEL}) found, can't proceed"
exit 1
else
puts "+++ Platform found: #{$androidplatform}" if USE_TRACES
end
$stdout.flush
$dx = File.join( $androidsdkpath, "platforms", $androidplatform, "tools", "dx" + $bat_ext )
$aapt = File.join( $androidsdkpath, "platforms", $androidplatform, "tools", "aapt" + $exe_ext )
$apkbuilder = File.join( $androidsdkpath, "tools", "apkbuilder" + $bat_ext )
$androidbin = File.join( $androidsdkpath, "tools", "android" + $bat_ext )
$adb = File.join( $androidsdkpath, "tools", "adb" + $exe_ext )
$zipalign = File.join( $androidsdkpath, "tools", "zipalign" + $exe_ext )
$androidjar = File.join($androidsdkpath, "platforms", $androidplatform, "android.jar")
$keytool = File.join( $java, "keytool" + $exe_ext )
$jarsigner = File.join( $java, "jarsigner" + $exe_ext )
$jarbin = File.join( $java, "jar" + $exe_ext )
$keystore = nil
$keystore = $app_config["android"]["production"]["certificate"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$keystore = $config["android"]["production"]["certificate"] if $keystore.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$keystore = File.expand_path(File.join(ENV['HOME'], ".rhomobile", "keystore")) if $keystore.nil?
$storepass = nil
$storepass = $app_config["android"]["production"]["password"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$storepass = $config["android"]["production"]["password"] if $storepass.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$storepass = "81719ef3a881469d96debda3112854eb" if $storepass.nil?
$keypass = $storepass
$storealias = nil
$storealias = $app_config["android"]["production"]["alias"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$storealias = $config["android"]["production"]["alias"] if $storealias.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$storealias = "rhomobile.keystore" if $storealias.nil?
$app_config["capabilities"] = [] if $app_config["capabilities"].nil?
$app_config["capabilities"] = [] unless $app_config["capabilities"].is_a? Array
if $app_config["android"] and $app_config["android"]["capabilities"]
$app_config["capabilities"] += $app_config["android"]["capabilities"]
$app_config["android"]["capabilities"] = nil
end
$app_config["capabilities"].map! { |cap| cap.is_a?(String) ? cap : nil }.delete_if { |cap| cap.nil? }
$use_google_addon_api = true unless $app_config["capabilities"].index("push").nil?
# Detect android targets
if $androidtargets.nil?
$androidtargets = {}
id = nil
`"#{$androidbin}" list targets`.split(/\n/).each do |line|
line.chomp!
if line =~ /^id:\s+([0-9]+)/
id = $1
end
if $use_google_addon_api
if line =~ /:Google APIs:([0-9]+)/
apilevel = $1
$androidtargets[apilevel.to_i] = id.to_i
end
else
if line =~ /^\s+API\s+level:\s+([0-9]+)$/ and not id.nil?
apilevel = $1
$androidtargets[apilevel.to_i] = id.to_i
end
end
end
end
# Detect Google API add-on path
if $use_google_addon_api
puts "+++ Looking for Google APIs add-on..." if USE_TRACES
napilevel = ANDROID_API_LEVEL
Dir.glob(File.join($androidsdkpath, 'add-ons', '*')).each do |dir|
props = File.join(dir, 'manifest.ini')
if !File.file? props
puts "+++ WARNING: no manifest.ini found in #{dir}"
next
end
apilevel = -1
File.open(props, 'r') do |f|
while line = f.gets
next unless line =~ /^api=([0-9]+)$/
apilevel = $1.to_i
break
end
end
puts "+++ API LEVEL of #{dir}: #{apilevel}" if USE_TRACES
if apilevel > napilevel
sgapijar = File.join(dir, 'libs', 'maps.jar')
if File.exists? sgapijar
napilevel = apilevel
$gapijar = sgapijar
$found_api_level = apilevel
end
end
end
if $gapijar.nil?
puts "+++ No Google APIs add-on found (which is required because appropriate capabilities enabled in build.yml)"
exit 1
else
puts "+++ Google APIs add-on found: #{$gapijar}" if USE_TRACES
end
end
$emuversion = get_market_version($found_api_level) if $emuversion.nil?
$emuversion = $emuversion.to_s
$avdname = "rhoAndroid" + $emuversion.gsub(/[^0-9]/, "")
$avdname += "ext" if $use_google_addon_api
$avdtarget = $androidtargets[get_api_level($emuversion)]
$appavdname = $app_config["android"]["emulator"]
setup_ndk($androidndkpath, ANDROID_API_LEVEL)
$stlport_includes = File.join $shareddir, "stlport", "stlport"
$native_libs = ["sqlite", "curl", "stlport", "ruby", "json", "rhocommon", "rhodb", "rholog", "rhosync", "rhomain"]
if $build_release
$confdir = "release"
else
$confdir = "debug"
end
$objdir = {}
$libname = {}
$native_libs.each do |x|
$objdir[x] = File.join($rhobindir, $confdir, $ndkgccver, "lib" + x)
$libname[x] = File.join($rhobindir, $confdir, $ndkgccver, "lib" + x + ".a")
end
$extensionsdir = $bindir + "/libs/" + $confdir + "/" + $ndkgccver + "/extensions"
#$app_config["extensions"] = [] if $app_config["extensions"].nil?
#$app_config["extensions"] = [] unless $app_config["extensions"].is_a? Array
#if $app_config["android"] and $app_config["android"]["extensions"]
# $app_config["extensions"] += $app_config["android"]["extensions"]
# $app_config["android"]["extensions"] = nil
#end
$push_sender = nil
$push_sender = $config["android"]["push"]["sender"] if !$config["android"].nil? and !$config["android"]["push"].nil?
$push_sender = $app_config["android"]["push"]["sender"] if !$app_config["android"].nil? and !$app_config["android"]["push"].nil?
$push_sender = "support@rhomobile.com" if $push_sender.nil?
mkdir_p $bindir if not File.exists? $bindir
mkdir_p $rhobindir if not File.exists? $rhobindir
mkdir_p $targetdir if not File.exists? $targetdir
mkdir_p $srcdir if not File.exists? $srcdir
mkdir_p $libs if not File.exists? $libs
end
end
namespace "build" do
namespace "android" do
# desc "Generate R.java file"
task :rjava => "config:android" do
manifest = $appmanifest
resource = $appres
assets = Jake.get_absolute(File.join($androidpath, "Rhodes", "assets"))
nativelibs = Jake.get_absolute(File.join($androidpath, "Rhodes", "libs"))
#rjava = Jake.get_absolute(File.join($androidpath, "Rhodes", "gen", "com", "rhomobile", "rhodes"))
args = ["package", "-f", "-M", manifest, "-S", resource, "-A", assets, "-I", $androidjar, "-J", $app_rjava_dir]
puts Jake.run($aapt, args)
unless $?.success?
puts "Error in AAPT"
exit 1
end
end
# desc "Build RhoBundle for android"
task :rhobundle => ["config:android","build:bundle:noxruby",:extensions,:librhodes] do
# Rake::Task["build:bundle:noxruby"].execute
assets = File.join(Jake.get_absolute($androidpath), "Rhodes", "assets")
rm_rf assets
mkdir_p assets
hash = nil
["apps", "db", "lib"].each do |d|
cp_r File.join($srcdir, d), assets, :preserve => true
# Calculate hash of directories
hash = get_dir_hash(File.join(assets, d), hash)
end
File.open(File.join(assets, "hash"), "w") { |f| f.write(hash.hexdigest) }
File.open(File.join(assets, "name"), "w") { |f| f.write($appname) }
psize = assets.size + 1
File.open(File.join(assets, 'rho.dat'), 'w') do |dat|
Dir.glob(File.join(assets, '**/*')).sort.each do |f|
relpath = f[psize..-1]
if File.directory?(f)
type = 'dir'
elsif File.file?(f)
type = 'file'
else
next
end
size = File.stat(f).size
tm = File.stat(f).mtime.to_i
dat.puts "#{relpath}\t#{type}\t#{size.to_s}\t#{tm.to_s}"
end
end
end
task :extensions => :genconfig do
ENV['RHO_PLATFORM'] = 'android'
ENV["ANDROID_NDK"] = $androidndkpath
ENV["ANDROID_API_LEVEL"] = ANDROID_API_LEVEL.to_s
ENV["TARGET_TEMP_DIR"] = $extensionsdir
ENV["RHO_ROOT"] = $startdir
ENV["BUILD_DIR"] ||= $startdir + "/platform/android/build"
ENV["RHO_INC"] = $appincdir
mkdir_p $extensionsdir unless File.directory? $extensionsdir
$app_config["extensions"].each do |ext|
$app_config["extpaths"].each do |p|
extpath = File.join(p, ext, 'ext')
if RUBY_PLATFORM =~ /(win|w)32$/
next unless File.exists? File.join(extpath, 'build.bat')
else
next unless File.executable? File.join(extpath, 'build')
end
ENV['TEMP_FILES_DIR'] = File.join(ENV["TARGET_TEMP_DIR"], ext)
if RUBY_PLATFORM =~ /(win|w)32$/
puts Jake.run('build.bat', [], extpath)
else
puts Jake.run('./build', [], extpath)
end
exit 1 unless $?.success?
end
end
end
task :libsqlite => "config:android" do
srcdir = File.join($shareddir, "sqlite")
objdir = $objdir["sqlite"]
libname = $libname["sqlite"]
cc_build 'libsqlite', objdir, ["-I#{srcdir}"] or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libcurl => "config:android" do
# Steps to get curl_config.h from fresh libcurl sources:
#export PATH=<ndkroot>/build/prebuilt/linux-x86/arm-eabi-4.2.1/bin:$PATH
#export CC=arm-eabi-gcc
#export CPP=arm-eabi-cpp
#export CFLAGS="--sysroot <ndkroot>/build/platforms/android-3/arch-arm -fPIC -mandroid -DANDROID -DOS_ANDROID"
#export CPPFLAGS="--sysroot <ndkroot>/build/platforms/android-3/arch-arm -fPIC -mandroid -DANDROID -DOS_ANDROID"
#./configure --without-ssl --without-ca-bundle --without-ca-path --without-libssh2 --without-libidn --disable-ldap --disable-ldaps --host=arm-eabi
srcdir = File.join $shareddir, "curl", "lib"
objdir = $objdir["curl"]
libname = $libname["curl"]
args = []
args << "-DHAVE_CONFIG_H"
args << "-I#{srcdir}/../include"
args << "-I#{srcdir}"
args << "-I#{$shareddir}"
cc_build 'libcurl', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libruby => "config:android" do
srcdir = File.join $shareddir, "ruby"
objdir = $objdir["ruby"]
libname = $libname["ruby"]
args = []
args << "-I#{srcdir}/include"
args << "-I#{srcdir}/linux"
args << "-I#{srcdir}/generated"
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-I#{srcdir}/../sqlite"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'libruby', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libjson => "config:android" do
srcdir = File.join $shareddir, "json"
objdir = $objdir["json"]
libname = $libname["json"]
args = []
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'libjson', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
unless USE_STLPORT
task :libstlport do
end
else
task :libstlport => "config:android" do
if USE_STLPORT
objdir = $objdir["stlport"]
libname = $libname["stlport"]
args = []
args << "-I#{$stlport_includes}"
args << "-DTARGET_OS=android"
args << "-DOSNAME=android"
args << "-DCOMPILER_NAME=gcc"
args << "-DBUILD_OSNAME=android"
args << "-D_REENTRANT"
args << "-D__NEW__"
args << "-ffunction-sections"
args << "-fdata-sections"
args << "-fno-rtti"
args << "-fno-exceptions"
cc_build 'libstlport', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
end
end
task :librholog => "config:android" do
srcdir = File.join $shareddir, "logging"
objdir = $objdir["rholog"]
libname = $libname["rholog"]
args = []
args << "-I#{srcdir}/.."
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librholog', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhomain => "config:android" do
srcdir = $shareddir
objdir = $objdir["rhomain"]
libname = $libname["rhomain"]
args = []
args << "-I#{srcdir}"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhomain', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhocommon => "config:android" do
objdir = $objdir["rhocommon"]
libname = $libname["rhocommon"]
args = []
args << "-I#{$shareddir}"
args << "-I#{$shareddir}/curl/include"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhocommon', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhodb => "config:android" do
srcdir = File.join $shareddir, "db"
objdir = $objdir["rhodb"]
libname = $libname["rhodb"]
args = []
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-I#{srcdir}/../sqlite"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhodb', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhosync => "config:android" do
srcdir = File.join $shareddir, "sync"
objdir = $objdir["rhosync"]
libname = $libname["rhosync"]
args = []
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-I#{srcdir}/../sqlite"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhosync', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libs => [:libsqlite, :libcurl, :libruby, :libjson, :libstlport, :librhodb, :librhocommon, :librhomain, :librhosync, :librholog]
task :genconfig => "config:android" do
mkdir_p $appincdir unless File.directory? $appincdir
# Generate genconfig.h
genconfig_h = File.join($appincdir, 'genconfig.h')
gapi_already_enabled = false
caps_already_enabled = {}
#ANDROID_PERMISSIONS.keys.each do |k|
# caps_already_enabled[k] = false
#end
if File.file? genconfig_h
File.open(genconfig_h, 'r') do |f|
while line = f.gets
if line =~ /^\s*#\s*define\s+RHO_GOOGLE_API_KEY\s+"[^"]*"\s*$/
gapi_already_enabled = true
else
ANDROID_PERMISSIONS.keys.each do |k|
if line =~ /^\s*#\s*define\s+RHO_CAP_#{k.upcase}_ENABLED\s+(.*)\s*$/
value = $1.strip
if value == 'true'
caps_already_enabled[k] = true
elsif value == 'false'
caps_already_enabled[k] = false
else
raise "Unknown value for the RHO_CAP_#{k.upcase}_ENABLED: #{value}"
end
end
end
end
end
end
end
regenerate = false
regenerate = true unless File.file? genconfig_h
regenerate = $use_geomapping != gapi_already_enabled unless regenerate
caps_enabled = {}
ANDROID_PERMISSIONS.keys.each do |k|
caps_enabled[k] = $app_config["capabilities"].index(k) != nil
regenerate = true if caps_already_enabled[k].nil? or caps_enabled[k] != caps_already_enabled[k]
end
if regenerate
puts "Need to regenerate genconfig.h"
$stdout.flush
File.open(genconfig_h, 'w') do |f|
f.puts "#ifndef RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F"
f.puts "#define RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F"
f.puts ""
f.puts "#define RHO_GOOGLE_API_KEY \"#{$gapikey}\"" if $use_geomapping and !$gapikey.nil?
caps_enabled.each do |k,v|
f.puts "#define RHO_CAP_#{k.upcase}_ENABLED #{v ? "true" : "false"}"
end
f.puts ""
f.puts "#endif /* RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F */"
end
else
puts "No need to regenerate genconfig.h"
$stdout.flush
end
# Generate rhocaps.inc
rhocaps_inc = File.join($appincdir, 'rhocaps.inc')
caps_already_defined = []
if File.exists? rhocaps_inc
File.open(rhocaps_inc, 'r') do |f|
while line = f.gets
next unless line =~ /^\s*RHO_DEFINE_CAP\s*\(\s*([A-Z_]*)\s*\)\s*\s*$/
caps_already_defined << $1.downcase
end
end
end
if caps_already_defined.sort.uniq != ANDROID_PERMISSIONS.keys.sort.uniq
puts "Need to regenerate rhocaps.inc"
$stdout.flush
File.open(rhocaps_inc, 'w') do |f|
ANDROID_PERMISSIONS.keys.sort.each do |k|
f.puts "RHO_DEFINE_CAP(#{k.upcase})"
end
end
else
puts "No need to regenerate rhocaps.inc"
$stdout.flush
end
# Generate Capabilities.java
File.open($app_capabilities_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class Capabilities {"
ANDROID_PERMISSIONS.keys.sort.each do |k|
f.puts " public static boolean #{k.upcase}_ENABLED = true;"
end
f.puts "}"
end
# Generate Push.java
File.open($app_push_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class Push {"
f.puts " public static final String SENDER = \"#{$push_sender}\";"
f.puts "};"
end
end
task :gen_java_ext => "config:android" do
File.open($app_native_libs_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class NativeLibraries {"
f.puts " public static void load() {"
f.puts " // Load native .so libraries"
Dir.glob($extensionsdir + "/lib*.so").reverse.each do |lib|
libname = File.basename(lib).gsub(/^lib/, '').gsub(/\.so$/, '')
f.puts " System.loadLibrary(\"#{libname}\");"
end
f.puts " // Load native implementation of rhodes"
f.puts " System.loadLibrary(\"rhodes\");"
f.puts " }"
f.puts "};"
end
end
task :gensources => [:genconfig, :gen_java_ext]
task :librhodes => [:libs, :gensources] do
srcdir = File.join $androidpath, "Rhodes", "jni", "src"
objdir = File.join $bindir, "libs", $confdir, $ndkgccver, "librhodes"
libname = File.join $bindir, "libs", $confdir, $ndkgccver, "librhodes.so"
args = []
args << "-I#{$appincdir}"
args << "-I#{srcdir}/../include"
args << "-I#{$shareddir}"
args << "-I#{$shareddir}/common"
args << "-I#{$shareddir}/sqlite"
args << "-I#{$shareddir}/curl/include"
args << "-I#{$shareddir}/ruby/include"
args << "-I#{$shareddir}/ruby/linux"
args << "-D__SGI_STL_INTERNAL_PAIR_H" if USE_STLPORT
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhodes', objdir, args or exit 1
deps = []
$libname.each do |k,v|
deps << v
end
args = []
args << "-L#{$rhobindir}/#{$confdir}/#{$ndkgccver}"
args << "-L#{$bindir}/libs/#{$confdir}/#{$ndkgccver}"
args << "-L#{$extensionsdir}"
rlibs = []
rlibs << "rhomain"
rlibs << "ruby"
rlibs << "rhosync"
rlibs << "rhodb"
rlibs << "rholog"
rlibs << "rhocommon"
rlibs << "json"
rlibs << "stlport" if USE_STLPORT
rlibs << "curl"
rlibs << "sqlite"
rlibs << "log"
rlibs << "dl"
rlibs << "z"
rlibs.map! { |x| "-l#{x}" }
elibs = []
extlibs = Dir.glob($extensionsdir + "/lib*.a") + Dir.glob($extensionsdir + "/lib*.so")
stub = []
extlibs.reverse.each do |f|
lparam = "-l" + File.basename(f).gsub(/^lib/,"").gsub(/\.(a|so)$/,"")
elibs << lparam
# Workaround for GNU ld: this way we have specified one lib multiple times
# command line so ld's dependency mechanism will find required functions
# independently of its position in command line
stub.each do |s|
args << s
end
stub << lparam
end
args += elibs
args += rlibs
args += elibs
args += rlibs
mkdir_p File.dirname(libname) unless File.directory? File.dirname(libname)
cc_link libname, Dir.glob(objdir + "/**/*.o"), args, deps or exit 1
destdir = File.join($androidpath, "Rhodes", "libs", "armeabi")
mkdir_p destdir unless File.exists? destdir
cp_r libname, destdir
cc_run($stripbin, [File.join(destdir, File.basename(libname))])
end
# desc "Build Rhodes for android"
task :rhodes => :rhobundle do
javac = $config["env"]["paths"]["java"] + "/javac" + $exe_ext
rm_rf $tmpdir + "/Rhodes"
mkdir_p $tmpdir + "/Rhodes"
set_app_name_android($appname)
generate_rjava
srclist = File.join($builddir, "RhodesSRC_build.files")
newsrclist = File.join($tmpdir, "RhodesSRC_build.files")
lines = []
File.open(srclist, "r") do |f|
while line = f.gets
line.chomp!
next if line =~ /\/AndroidR\.java\s*$/
next if !$use_geomapping and line =~ /\/mapview\//
lines << line
end
end
lines << File.join($app_rjava_dir, "R.java")
lines << $app_android_r
lines << $app_native_libs_java
lines << $app_capabilities_java
lines << $app_push_java
if File.exists? File.join($extensionsdir, "ext_build.files")
puts 'ext_build.files found ! Addditional files for compilation :'
File.open(File.join($extensionsdir, "ext_build.files")) do |f|
while line = f.gets
puts 'java file : ' + line
lines << line
end
end
else
puts 'ext_build.files not found - no additional java files for compilation'
end
File.open(newsrclist, "w") { |f| f.write lines.join("\n") }
srclist = newsrclist
args = []
args << "-g"
args << "-d"
args << $tmpdir + '/Rhodes'
args << "-source"
args << "1.6"
args << "-target"
args << "1.6"
args << "-nowarn"
args << "-encoding"
args << "latin1"
args << "-classpath"
classpath = $androidjar
classpath += $path_separator + $gapijar unless $gapijar.nil?
classpath += $path_separator + "#{$tmpdir}/Rhodes"
Dir.glob(File.join($extensionsdir, "*.jar")).each do |f|
classpath += $path_separator + f
end
args << classpath
args << "@#{srclist}"
puts Jake.run(javac, args)
unless $?.success?
puts "Error compiling java code"
exit 1
end
files = []
Dir.glob(File.join($extensionsdir, "*.jar")).each do |f|
puts Jake.run($jarbin, ["xf", f], File.join($tmpdir, "Rhodes"))
unless $?.success?
puts "Error running jar (xf)"
exit 1
end
end
Dir.glob(File.join($tmpdir, "Rhodes", "*")).each do |f|
relpath = Pathname.new(f).relative_path_from(Pathname.new(File.join($tmpdir, "Rhodes"))).to_s
files << relpath
end
unless files.empty?
args = ["cf", "../../Rhodes.jar"]
args += files
puts Jake.run($jarbin, args, File.join($tmpdir, "Rhodes"))
unless $?.success?
puts "Error running jar"
exit 1
end
end
end
#desc "build all"
task :all => [:rhobundle, :rhodes]
end
end
namespace "package" do
task :android => "build:android:all" do
puts "Running dx utility"
args = []
args << "--dex"
args << "--output=#{$bindir}/classes.dex"
args << "#{$bindir}/Rhodes.jar"
puts Jake.run($dx, args)
unless $?.success?
puts "Error running DX utility"
exit 1
end
manifest = $appmanifest
resource = $appres
assets = Jake.get_absolute $androidpath + "/Rhodes/assets"
resourcepkg = $bindir + "/rhodes.ap_"
puts "Packaging Assets and Jars"
set_app_name_android($appname)
args = ["package", "-f", "-M", manifest, "-S", resource, "-A", assets, "-I", $androidjar, "-F", resourcepkg]
puts Jake.run($aapt, args)
unless $?.success?
puts "Error running AAPT (1)"
exit 1
end
# Workaround: manually add files starting with '_' because aapt silently ignore such files when creating package
rm_rf File.join($tmpdir, "assets")
cp_r assets, $tmpdir
Dir.glob(File.join($tmpdir, "assets/**/*")).each do |f|
next unless File.basename(f) =~ /^_/
relpath = Pathname.new(f).relative_path_from(Pathname.new($tmpdir)).to_s
puts "Add #{relpath} to #{resourcepkg}..."
args = ["uf", resourcepkg, relpath]
puts Jake.run($jarbin, args, $tmpdir)
unless $?.success?
puts "Error running AAPT (2)"
exit 1
end
end
# Add native librhodes.so
rm_rf File.join($tmpdir, "lib")
mkdir_p File.join($tmpdir, "lib/armeabi")
cp_r File.join($bindir, "libs", $confdir, $ndkgccver, "librhodes.so"), File.join($tmpdir, "lib/armeabi")
# Add extensions .so libraries
Dir.glob($extensionsdir + "/lib*.so").each do |lib|
cp_r lib, File.join($tmpdir, "lib/armeabi")
end
args = ["uf", resourcepkg]
# Strip them all to decrease size
Dir.glob($tmpdir + "/lib/armeabi/lib*.so").each do |lib|
cc_run($stripbin, [lib])
args << "lib/armeabi/#{File.basename(lib)}"
end
puts Jake.run($jarbin, args, $tmpdir)
err = $?
rm_rf $tmpdir + "/lib"
unless err.success?
puts "Error running AAPT (3)"
exit 1
end
end
end
def get_app_log(appname, device, silent = false)
pkgname = "com.#{$vendor}." + appname.downcase.gsub(/[^A-Za-z_0-9]/, '')
path = File.join('/data/data', pkgname, 'rhodata', 'RhoLog.txt')
cc_run($adb, [device ? '-d' : '-e', 'pull', path, $app_path]) or return false
puts "RhoLog.txt stored to " + $app_path unless silent
return true
end
namespace "device" do
namespace "android" do
desc "Build debug self signed for device"
task :debug => "package:android" do
dexfile = $bindir + "/classes.dex"
simple_apkfile = $targetdir + "/" + $appname + "-tmp.apk"
final_apkfile = $targetdir + "/" + $appname + "-debug.apk"
resourcepkg = $bindir + "/rhodes.ap_"
puts "Building APK file"
Jake.run($apkbuilder, [simple_apkfile, "-z", resourcepkg, "-f", dexfile])
unless $?.success?
puts "Error building APK file"
exit 1
end
puts "Align Debug APK file"
args = []
args << "-f"
args << "-v"
args << "4"
args << '"' + simple_apkfile + '"'
args << '"' + final_apkfile + '"'
puts Jake.run($zipalign, args)
unless $?.success?
puts "Error running zipalign"
exit 1
end
#remove temporary files
rm_rf simple_apkfile
File.open(File.join(File.dirname(final_apkfile), "app_info.txt"), "w") do |f|
f.puts $app_package_name
end
end
task :install => :debug do
apkfile = $targetdir + "/" + $appname + "-debug.apk"
puts "Install APK file"
Jake.run($adb, ["-d", "install", "-r", apkfile])
unless $?.success?
puts "Error installing APK file"
exit 1
end
puts "Install complete"
end
desc "Build production signed for device"
task :production => "package:android" do
dexfile = $bindir + "/classes.dex"
simple_apkfile = $targetdir + "/" + $appname + "_tmp.apk"
final_apkfile = $targetdir + "/" + $appname + "_signed.apk"
signed_apkfile = $targetdir + "/" + $appname + "_tmp_signed.apk"
resourcepkg = $bindir + "/rhodes.ap_"
puts "Building APK file"
Jake.run($apkbuilder, [simple_apkfile, "-u", "-z", resourcepkg, "-f", dexfile])
unless $?.success?
puts "Error building APK file"
exit 1
end
if not File.exists? $keystore
puts "Generating private keystore..."
mkdir_p File.dirname($keystore) unless File.directory? File.dirname($keystore)
args = []
args << "-genkey"
args << "-alias"
args << $storealias
args << "-keyalg"
args << "RSA"
args << "-validity"
args << "20000"
args << "-keystore"
args << $keystore
args << "-storepass"
args << $storepass
args << "-keypass"
args << $keypass
puts Jake.run($keytool, args)
unless $?.success?
puts "Error generating keystore file"
exit 1
end
end
puts "Signing APK file"
args = []
args << "-verbose"
args << "-keystore"
args << $keystore
args << "-storepass"
args << $storepass
args << "-signedjar"
args << signed_apkfile
args << simple_apkfile
args << $storealias
puts Jake.run($jarsigner, args)
unless $?.success?
puts "Error running jarsigner"
exit 1
end
puts "Align APK file"
args = []
args << "-f"
args << "-v"
args << "4"
args << '"' + signed_apkfile + '"'
args << '"' + final_apkfile + '"'
puts Jake.run($zipalign, args)
unless $?.success?
puts "Error running zipalign"
exit 1
end
#remove temporary files
rm_rf simple_apkfile
rm_rf signed_apkfile
File.open(File.join(File.dirname(final_apkfile), "app_info.txt"), "w") do |f|
f.puts $app_package_name
end
end
task :getlog => "config:android" do
get_app_log($appname, true) or exit 1
end
end
end
namespace "emulator" do
namespace "android" do
task :getlog => "config:android" do
get_app_log($appname, false) or exit 1
end
end
end
def is_emulator_running
`#{$adb} devices`.split("\n")[1..-1].each do |line|
return true if line =~ /^emulator/
end
return false
end
def is_device_running
`#{$adb} devices`.split("\n")[1..-1].each do |line|
return true if line !~ /^emulator/
end
return false
end
def run_application (target_flag)
args = []
args << target_flag
args << "shell"
args << "am"
args << "start"
args << "-a"
args << "android.intent.action.MAIN"
args << "-n"
args << $app_package_name + "/#{JAVA_PACKAGE_NAME}.Rhodes"
Jake.run($adb, args)
end
def application_running(flag, pkgname)
pkg = pkgname.gsub(/\./, '\.')
`#{$adb} #{flag} shell ps`.split.each do |line|
return true if line =~ /#{pkg}/
end
false
end
namespace "run" do
namespace "android" do
task :spec => ["device:android:debug"] do
run_emulator
do_uninstall('-e')
log_name = $app_path + '/RhoLog.txt'
File.delete(log_name) if File.exist?(log_name)
# Failsafe to prevent eternal hangs
Thread.new {
sleep 1000
if RUBY_PLATFORM =~ /windows|cygwin|mingw/
# Windows
`taskkill /F /IM adb.exe`
`taskkill /F /IM emulator.exe`
else
`killall -9 adb`
`killall -9 emulator`
end
}
load_app_and_run
Jake.before_run_spec
start = Time.now
puts "waiting for log"
while !File.exist?(log_name)
get_app_log($appname, false, true)
sleep(1)
end
puts "start read log"
end_spec = false
while !end_spec do
get_app_log($appname, false, true)
io = File.new(log_name, "r")
io.each do |line|
#puts line
end_spec = !Jake.process_spec_output(line)
break if end_spec
end
io.close
break unless application_running('-e', $app_package_name)
sleep(5) unless end_spec
end
Jake.process_spec_results(start)
# stop app
if RUBY_PLATFORM =~ /windows|cygwin|mingw/
# Windows
`taskkill /F /IM adb.exe`
`taskkill /F /IM emulator.exe`
else
`killall -9 adb`
`killall -9 emulator`
end
$stdout.flush
end
task :phone_spec do
exit 1 if Jake.run_spec_app('android','phone_spec')
exit 0
end
task :framework_spec do
exit 1 if Jake.run_spec_app('android','framework_spec')
exit 0
end
task :emulator => "device:android:debug" do
run_emulator
load_app_and_run
end
def run_emulator
apkfile = Jake.get_absolute $targetdir + "/" + $appname + "-debug.apk"
Jake.run($adb, ['kill-server'])
#Jake.run($adb, ['start-server'])
#adb_start_server = $adb + ' start-server'
Thread.new { Jake.run($adb, ['start-server']) }
puts 'Sleep for 5 sec. waiting for "adb start-server"'
sleep 5
if $appavdname != nil
$avdname = $appavdname
end
createavd = "\"#{$androidbin}\" create avd --name #{$avdname} --target #{$avdtarget} --sdcard 32M --skin HVGA"
system(createavd) unless File.directory?( File.join(ENV['HOME'], ".android", "avd", "#{$avdname}.avd" ) )
if $use_google_addon_api
avdini = File.join(ENV['HOME'], '.android', 'avd', "#{$avdname}.ini")
avd_using_gapi = true if File.new(avdini).read =~ /:Google APIs:/
unless avd_using_gapi
puts "Can not use specified AVD (#{$avdname}) because of incompatibility with Google APIs. Delete it and try again."
exit 1
end
end
running = is_emulator_running
if !running
# Start the emulator, check on it every 5 seconds until it's running
Thread.new { system("\"#{$emulator}\" -avd #{$avdname}") }
puts "Waiting up to 180 seconds for emulator..."
startedWaiting = Time.now
adbRestarts = 1
while (Time.now - startedWaiting < 180 )
sleep 5
now = Time.now
emulatorState = ""
Jake.run2($adb,["-e", "get-state"],{:system => false, :hideerrors => :false}) do |line|
puts "RET: " + line
emulatorState += line
end
if emulatorState =~ /unknown/
printf("%.2fs: ",(now - startedWaiting))
if (now - startedWaiting) > (60 * adbRestarts)
# Restart the adb server every 60 seconds to prevent eternal waiting
puts "Appears hung, restarting adb server"
Jake.run($adb, ['kill-server'])
Thread.new { Jake.run($adb, ['start-server']) }
adbRestarts += 1
else
puts "Still waiting..."
end
else
puts "Success"
puts "Device is ready after " + (Time.now - startedWaiting).to_s + " seconds"
break
end
end
if !is_emulator_running
puts "Emulator still isn't up and running, giving up"
exit 1
end
else
puts "Emulator is up and running"
end
$stdout.flush
end
def load_app_and_run
puts "Loading package into emulator"
apkfile = Jake.get_absolute $targetdir + "/" + $appname + "-debug.apk"
count = 0
done = false
while count < 20
f = Jake.run2($adb, ["-e", "install", "-r", apkfile], {:nowait => true})
theoutput = ""
while c = f.getc
$stdout.putc c
$stdout.flush
theoutput << c
end
f.close
if theoutput.to_s.match(/Success/)
done = true
break
end
puts "Failed to load (possibly because emulator not done launching)- retrying"
$stdout.flush
sleep 1
count += 1
end
puts "Loading complete, starting application.." if done
run_application("-e") if done
end
desc "build and install on device"
task :device => "device:android:install" do
puts "Starting application..."
run_application("-d")
end
end
desc "build and launch emulator"
task :android => "run:android:emulator" do
end
end
namespace "uninstall" do
def do_uninstall(flag)
args = []
args << flag
args << "uninstall"
args << $app_package_name
Jake.run($adb, args)
unless $?.success?
puts "Error uninstalling application"
exit 1
end
puts "Application uninstalled successfully"
end
namespace "android" do
task :emulator => "config:android" do
unless is_emulator_running
puts "WARNING!!! Emulator is not up and running"
exit 1
end
do_uninstall('-e')
end
desc "uninstall from device"
task :device => "config:android" do
unless is_device_running
puts "WARNING!!! Device is not connected"
exit 1
end
do_uninstall('-d')
end
end
desc "uninstall from emulator"
task :android => "uninstall:android:emulator" do
end
end
namespace "clean" do
desc "Clean Android"
task :android => "clean:android:all"
namespace "android" do
task :assets => "config:android" do
Dir.glob($androidpath + "/Rhodes/assets/**/*") do |f|
rm f, :force => true unless f =~ /\/loading\.html$/
end
end
task :files => "config:android" do
rm_rf $targetdir
rm_rf $bindir
rm_rf $srcdir
rm_rf $libs
end
task :libsqlite => "config:android" do
cc_clean "sqlite"
end
task :libs => ["config:android"] do
$native_libs.each do |l|
cc_clean l
end
end
task :librhodes => "config:android" do
rm_rf $rhobindir + "/" + $confdir + "/" + $ndkgccver + "/librhodes"
rm_rf $bindir + "/libs/" + $confdir + "/" + $ndkgccver + "/librhodes.so"
end
# desc "clean android"
task :all => [:assets,:librhodes,:libs,:files]
end
end
check fro empty "android" section in build.yml
#
require File.dirname(__FILE__) + '/androidcommon.rb'
require 'pathname'
USE_STLPORT = true
USE_TRACES = false
ANDROID_API_LEVEL_TO_MARKET_VERSION = {}
ANDROID_MARKET_VERSION_TO_API_LEVEL = {}
{2 => "1.1", 3 => "1.5", 4 => "1.6", 5 => "2.0", 6 => "2.0.1", 7 => "2.1", 8 => "2.2"}.each do |k,v|
ANDROID_API_LEVEL_TO_MARKET_VERSION[k] = v
ANDROID_MARKET_VERSION_TO_API_LEVEL[v] = k
end
def get_market_version(apilevel)
ANDROID_API_LEVEL_TO_MARKET_VERSION[apilevel]
end
def get_api_level(version)
ANDROID_MARKET_VERSION_TO_API_LEVEL[version]
end
JAVA_PACKAGE_NAME = 'com.rhomobile.rhodes'
# Here is place were android platform should be specified.
# For complete list of android API levels and its mapping to
# market names (such as "Android-1.5" etc) see output of
# command "android list targets"
ANDROID_API_LEVEL = 4
ANDROID_PERMISSIONS = {
'audio' => ['RECORD_AUDIO', 'MODIFY_AUDIO_SETTINGS'],
'camera' => 'CAMERA',
'gps' => 'ACCESS_FINE_LOCATION',
'network_state' => 'ACCESS_NETWORK_STATE',
'phone' => ['CALL_PHONE', 'READ_PHONE_STATE'],
'pim' => ['READ_CONTACTS', 'WRITE_CONTACTS', 'GET_ACCOUNTS'],
'record_audio' => 'RECORD_AUDIO',
'vibrate' => 'VIBRATE',
'bluetooth' => ['BLUETOOTH_ADMIN', 'BLUETOOTH'],
'calendar' => ['READ_CALENDAR', 'WRITE_CALENDAR'],
'push' => proc do |manifest| add_push(manifest) end
}
def add_push(manifest)
element = REXML::Element.new('permission')
element.add_attribute('android:name', "#{$app_package_name}.permission.C2D_MESSAGE")
element.add_attribute('android:protectionLevel', 'signature')
manifest.add element
element = REXML::Element.new('uses-permission')
element.add_attribute('android:name', "#{$app_package_name}.permission.C2D_MESSAGE")
manifest.add element
element = REXML::Element.new('uses-permission')
element.add_attribute('android:name', "com.google.android.c2dm.permission.RECEIVE")
manifest.add element
receiver = REXML::Element.new('receiver')
receiver.add_attribute('android:name', "#{JAVA_PACKAGE_NAME}.PushReceiver")
receiver.add_attribute('android:permission', "com.google.android.c2dm.permission.SEND")
action = REXML::Element.new('action')
action.add_attribute('android:name', "com.google.android.c2dm.intent.RECEIVE")
category = REXML::Element.new('category')
category.add_attribute('android:name', $app_package_name)
ie = REXML::Element.new('intent-filter')
ie.add_element(action)
ie.add_element(category)
receiver.add_element(ie)
action = REXML::Element.new('action')
action.add_attribute('android:name', "com.google.android.c2dm.intent.REGISTRATION")
category = REXML::Element.new('category')
category.add_attribute('android:name', $app_package_name)
ie = REXML::Element.new('intent-filter')
ie.add_element(action)
ie.add_element(category)
receiver.add_element(ie)
manifest.elements.each('application') do |app|
app.add receiver
end
end
def set_app_name_android(newname)
puts "set_app_name"
$stdout.flush
rm_rf $appres
cp_r $rhores, $appres
iconappname = File.join($app_path, "icon", "icon.png")
iconresname = File.join($appres, "drawable", "icon.png")
rm_f iconresname
cp iconappname, iconresname
rhostrings = File.join($rhores, "values", "strings.xml")
appstrings = File.join($appres, "values", "strings.xml")
doc = REXML::Document.new(File.new(rhostrings))
doc.elements["resources/string[@name='app_name']"].text = newname
File.open(appstrings, "w") { |f| doc.write f }
version = {'major' => 0, 'minor' => 0, 'patch' => 0}
if $app_config["version"]
if $app_config["version"] =~ /^(\d+)$/
version["major"] = $1.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
elsif $app_config["version"] =~ /^(\d+)\.(\d+)\.(\d+)$/
version["major"] = $1.to_i
version["minor"] = $2.to_i
version["patch"] = $3.to_i
end
end
version = version["major"]*10000 + version["minor"]*100 + version["patch"]
doc = REXML::Document.new(File.new($rhomanifest))
doc.root.attributes['package'] = $app_package_name
if version > 0
doc.root.attributes['android:versionCode'] = version.to_s
doc.root.attributes['android:versionName'] = $app_config["version"]
end
doc.elements.delete "manifest/application/uses-library[@android:name='com.google.android.maps']" unless $use_geomapping
caps_proc = []
caps = ['INTERNET', 'PERSISTENT_ACTIVITY', 'WAKE_LOCK']
$app_config["capabilities"].each do |cap|
cap = ANDROID_PERMISSIONS[cap]
next if cap.nil?
if cap.is_a? Proc
caps_proc << cap
next
end
cap = [cap] if cap.is_a? String
cap = [] unless cap.is_a? Array
caps += cap
end
caps.uniq!
manifest = doc.elements["manifest"]
manifest.elements.each('uses-sdk') { |e| manifest.delete e }
element = REXML::Element.new('uses-sdk')
element.add_attribute('android:minSdkVersion', ANDROID_API_LEVEL.to_s)
manifest.add element
# Remove category LAUNCHER from all activities if hidden_app is set
hidden_app = get_boolean($app_config['hidden_app'])
if hidden_app
manifest.elements.each('application') do |app|
app.elements.each('activity') do |activity|
activity.elements.each('intent-filter') do |intf|
intf.elements.each('category') do |c|
name = c.attribute('name', 'android')
next if name.nil?
intf.delete(c) if name.to_s == 'android.intent.category.LAUNCHER'
end
end
end
end
end
# Clear C2DM stuff
doc.elements.delete "manifest/application/receiver[@android:name='#{JAVA_PACKAGE_NAME}.PushReceiver']"
manifest.elements.each('permission') do |e|
name = e.attribute('name', 'android')
next if name.nil?
manifest.delete(e) if name.to_s =~ /\.C2D_MESSAGE$/
end
manifest.elements.each('uses-permission') { |e| manifest.delete e }
caps.sort.each do |cap|
element = REXML::Element.new('uses-permission')
element.add_attribute('android:name', "android.permission.#{cap}")
manifest.add element
end
caps_proc.each do |p|
p.call manifest
end
File.open($appmanifest, "w") { |f| doc.write f, 2 }
buf = File.new($rho_android_r,"r").read.gsub(/^\s*import com\.rhomobile\..*\.R;\s*$/,"\nimport #{$app_package_name}.R;\n")
File.open($app_android_r,"w") { |f| f.write(buf) }
end
def generate_rjava
Rake::Task["build:android:rjava"].execute
end
def get_boolean(arg)
arg == 'true' or arg == 'yes' or arg == 'enabled' or arg == 'enable' or arg == '1'
end
namespace "config" do
task :set_android_platform do
$current_platform = "android"
end
task :android => [:set_android_platform, "config:common"] do
$gapikey = $app_config["android"]["apikey"] unless $app_config["android"].nil?
$gapikey = $config["android"]["apikey"] if $gapikey.nil? and not $config["android"].nil?
$gapikey = '' unless $gapikey.is_a? String
$gapikey = nil if $gapikey.empty?
$use_geomapping = $app_config["android"]["mapping"] unless $app_config["android"].nil?
$use_geomapping = $config["android"]["mapping"] if $use_geomapping.nil? and not $config["android"].nil?
$use_geomapping = 'false' if $use_geomapping.nil?
$use_geomapping = get_boolean($use_geomapping.to_s)
$use_google_addon_api = false
$use_google_addon_api = true if $use_geomapping
$emuversion = $app_config["android"]["version"] unless $app_config["android"].nil?
$emuversion = $config["android"]["version"] if $emuversion.nil? and !$config["android"].nil?
# Here is switch between release/debug configuration used for
# building native libraries
if $app_config["debug"].nil?
$build_release = true
else
$build_release = !$app_config["debug"].to_i
end
$androidsdkpath = $config["env"]["paths"]["android"]
unless File.exists? $androidsdkpath
puts "Missing or invalid 'android' section in rhobuild.yml"
exit 1
end
$androidndkpath = $config["env"]["paths"]["android-ndk"]
unless File.exists? $androidndkpath
puts "Missing or invalid 'android-ndk' section in rhobuild.yml"
exit 1
end
errfmt = "WARNING!!! Path to Android %s contain spaces! It will not work because of the Google toolchain restrictions. Move it to another location and reconfigure rhodes."
if $androidsdkpath =~ /\s/
puts(errfmt % "SDK")
exit 1
end
if $androidndkpath =~ /\s/
puts(errfmt % "NDK")
exit 1
end
$java = $config["env"]["paths"]["java"]
$androidpath = Jake.get_absolute $config["build"]["androidpath"]
$bindir = File.join($app_path, "bin")
$rhobindir = File.join($androidpath, "bin")
$builddir = File.join($androidpath, "build")
$shareddir = File.join($androidpath, "..", "shared")
$srcdir = File.join($bindir, "RhoBundle")
$targetdir = File.join($bindir, "target")
$excludelib = ['**/builtinME.rb','**/ServeME.rb','**/TestServe.rb']
$tmpdir = File.join($bindir, "tmp")
$resourcedir = File.join($tmpdir, "resource")
$libs = File.join($androidpath, "Rhodes", "libs")
$appname = $app_config["name"]
$appname = "Rhodes" if $appname.nil?
$vendor = $app_config["vendor"]
$vendor = "rhomobile" if $vendor.nil?
$vendor = $vendor.gsub(/^[^A-Za-z]/, '_').gsub(/[^A-Za-z0-9]/, '_').gsub(/_+/, '_').downcase
$app_package_name = "com.#{$vendor}." + $appname.downcase.gsub(/[^A-Za-z_0-9]/, '')
$rhomanifest = File.join $androidpath, "Rhodes", "AndroidManifest.xml"
$appmanifest = File.join $tmpdir, "AndroidManifest.xml"
$rhores = File.join $androidpath, "Rhodes", "res"
$appres = File.join $tmpdir, "res"
$appincdir = File.join $tmpdir, "include"
$rho_android_r = File.join $androidpath, "Rhodes", "src", "com", "rhomobile", "rhodes", "AndroidR.java"
$app_android_r = File.join $tmpdir, "AndroidR.java"
$app_rjava_dir = File.join $tmpdir
$app_native_libs_java = File.join $tmpdir, "NativeLibraries.java"
$app_capabilities_java = File.join $tmpdir, "Capabilities.java"
$app_push_java = File.join $tmpdir, "Push.java"
if RUBY_PLATFORM =~ /(win|w)32$/
$emulator = #"cmd /c " +
File.join( $androidsdkpath, "tools", "emulator.exe" )
$bat_ext = ".bat"
$exe_ext = ".exe"
$path_separator = ";"
# Add PATH to cygwin1.dll
ENV['CYGWIN'] = 'nodosfilewarning'
if $path_cygwin_modified.nil?
ENV['PATH'] = Jake.get_absolute("res/build-tools") + ";" + ENV['PATH']
path_cygwin_modified = true
end
else
#XXX make these absolute
$emulator = File.join( $androidsdkpath, "tools", "emulator" )
$bat_ext = ""
$exe_ext = ""
$path_separator = ":"
# TODO: add ruby executable for Linux
end
puts "+++ Looking for platform..." if USE_TRACES
napilevel = ANDROID_API_LEVEL
Dir.glob(File.join($androidsdkpath, "platforms", "*")).each do |platform|
props = File.join(platform, "source.properties")
unless File.file? props
puts "+++ WARNING! No source.properties found in #{platform}"
next
end
apilevel = -1
marketversion = nil
File.open(props, "r") do |f|
while line = f.gets
apilevel = $1.to_i if line =~ /^\s*AndroidVersion\.ApiLevel\s*=\s*([0-9]+)\s*$/
marketversion = $1 if line =~ /^\s*Platform\.Version\s*=\s*([^\s]*)\s*$/
end
end
puts "+++ API LEVEL of #{platform}: #{apilevel}" if USE_TRACES
if apilevel > napilevel
napilevel = apilevel
$androidplatform = File.basename(platform)
$found_api_level = apilevel
end
end
if $androidplatform.nil?
ajar = File.join($androidsdkpath, 'platforms', 'android-' + ANDROID_API_LEVEL_TO_MARKET_VERSION[ANDROID_API_LEVEL], 'android.jar')
$androidplatform = 'android-' + ANDROID_API_LEVEL_TO_MARKET_VERSION[ANDROID_API_LEVEL] if File.file?(ajar)
end
if $androidplatform.nil?
puts "+++ No required platform (API level >= #{ANDROID_API_LEVEL}) found, can't proceed"
exit 1
else
puts "+++ Platform found: #{$androidplatform}" if USE_TRACES
end
$stdout.flush
$dx = File.join( $androidsdkpath, "platforms", $androidplatform, "tools", "dx" + $bat_ext )
$aapt = File.join( $androidsdkpath, "platforms", $androidplatform, "tools", "aapt" + $exe_ext )
$apkbuilder = File.join( $androidsdkpath, "tools", "apkbuilder" + $bat_ext )
$androidbin = File.join( $androidsdkpath, "tools", "android" + $bat_ext )
$adb = File.join( $androidsdkpath, "tools", "adb" + $exe_ext )
$zipalign = File.join( $androidsdkpath, "tools", "zipalign" + $exe_ext )
$androidjar = File.join($androidsdkpath, "platforms", $androidplatform, "android.jar")
$keytool = File.join( $java, "keytool" + $exe_ext )
$jarsigner = File.join( $java, "jarsigner" + $exe_ext )
$jarbin = File.join( $java, "jar" + $exe_ext )
$keystore = nil
$keystore = $app_config["android"]["production"]["certificate"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$keystore = $config["android"]["production"]["certificate"] if $keystore.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$keystore = File.expand_path(File.join(ENV['HOME'], ".rhomobile", "keystore")) if $keystore.nil?
$storepass = nil
$storepass = $app_config["android"]["production"]["password"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$storepass = $config["android"]["production"]["password"] if $storepass.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$storepass = "81719ef3a881469d96debda3112854eb" if $storepass.nil?
$keypass = $storepass
$storealias = nil
$storealias = $app_config["android"]["production"]["alias"] if !$app_config["android"].nil? and !$app_config["android"]["production"].nil?
$storealias = $config["android"]["production"]["alias"] if $storealias.nil? and !$config["android"].nil? and !$config["android"]["production"].nil?
$storealias = "rhomobile.keystore" if $storealias.nil?
$app_config["capabilities"] = [] if $app_config["capabilities"].nil?
$app_config["capabilities"] = [] unless $app_config["capabilities"].is_a? Array
if $app_config["android"] and $app_config["android"]["capabilities"]
$app_config["capabilities"] += $app_config["android"]["capabilities"]
$app_config["android"]["capabilities"] = nil
end
$app_config["capabilities"].map! { |cap| cap.is_a?(String) ? cap : nil }.delete_if { |cap| cap.nil? }
$use_google_addon_api = true unless $app_config["capabilities"].index("push").nil?
# Detect android targets
if $androidtargets.nil?
$androidtargets = {}
id = nil
`"#{$androidbin}" list targets`.split(/\n/).each do |line|
line.chomp!
if line =~ /^id:\s+([0-9]+)/
id = $1
end
if $use_google_addon_api
if line =~ /:Google APIs:([0-9]+)/
apilevel = $1
$androidtargets[apilevel.to_i] = id.to_i
end
else
if line =~ /^\s+API\s+level:\s+([0-9]+)$/ and not id.nil?
apilevel = $1
$androidtargets[apilevel.to_i] = id.to_i
end
end
end
end
# Detect Google API add-on path
if $use_google_addon_api
puts "+++ Looking for Google APIs add-on..." if USE_TRACES
napilevel = ANDROID_API_LEVEL
Dir.glob(File.join($androidsdkpath, 'add-ons', '*')).each do |dir|
props = File.join(dir, 'manifest.ini')
if !File.file? props
puts "+++ WARNING: no manifest.ini found in #{dir}"
next
end
apilevel = -1
File.open(props, 'r') do |f|
while line = f.gets
next unless line =~ /^api=([0-9]+)$/
apilevel = $1.to_i
break
end
end
puts "+++ API LEVEL of #{dir}: #{apilevel}" if USE_TRACES
if apilevel > napilevel
sgapijar = File.join(dir, 'libs', 'maps.jar')
if File.exists? sgapijar
napilevel = apilevel
$gapijar = sgapijar
$found_api_level = apilevel
end
end
end
if $gapijar.nil?
puts "+++ No Google APIs add-on found (which is required because appropriate capabilities enabled in build.yml)"
exit 1
else
puts "+++ Google APIs add-on found: #{$gapijar}" if USE_TRACES
end
end
$emuversion = get_market_version($found_api_level) if $emuversion.nil?
$emuversion = $emuversion.to_s
$avdname = "rhoAndroid" + $emuversion.gsub(/[^0-9]/, "")
$avdname += "ext" if $use_google_addon_api
$avdtarget = $androidtargets[get_api_level($emuversion)]
$appavdname = nil
if $app_config["android"] != nil
$appavdname = $app_config["android"]["emulator"]
end
setup_ndk($androidndkpath, ANDROID_API_LEVEL)
$stlport_includes = File.join $shareddir, "stlport", "stlport"
$native_libs = ["sqlite", "curl", "stlport", "ruby", "json", "rhocommon", "rhodb", "rholog", "rhosync", "rhomain"]
if $build_release
$confdir = "release"
else
$confdir = "debug"
end
$objdir = {}
$libname = {}
$native_libs.each do |x|
$objdir[x] = File.join($rhobindir, $confdir, $ndkgccver, "lib" + x)
$libname[x] = File.join($rhobindir, $confdir, $ndkgccver, "lib" + x + ".a")
end
$extensionsdir = $bindir + "/libs/" + $confdir + "/" + $ndkgccver + "/extensions"
#$app_config["extensions"] = [] if $app_config["extensions"].nil?
#$app_config["extensions"] = [] unless $app_config["extensions"].is_a? Array
#if $app_config["android"] and $app_config["android"]["extensions"]
# $app_config["extensions"] += $app_config["android"]["extensions"]
# $app_config["android"]["extensions"] = nil
#end
$push_sender = nil
$push_sender = $config["android"]["push"]["sender"] if !$config["android"].nil? and !$config["android"]["push"].nil?
$push_sender = $app_config["android"]["push"]["sender"] if !$app_config["android"].nil? and !$app_config["android"]["push"].nil?
$push_sender = "support@rhomobile.com" if $push_sender.nil?
mkdir_p $bindir if not File.exists? $bindir
mkdir_p $rhobindir if not File.exists? $rhobindir
mkdir_p $targetdir if not File.exists? $targetdir
mkdir_p $srcdir if not File.exists? $srcdir
mkdir_p $libs if not File.exists? $libs
end
end
namespace "build" do
namespace "android" do
# desc "Generate R.java file"
task :rjava => "config:android" do
manifest = $appmanifest
resource = $appres
assets = Jake.get_absolute(File.join($androidpath, "Rhodes", "assets"))
nativelibs = Jake.get_absolute(File.join($androidpath, "Rhodes", "libs"))
#rjava = Jake.get_absolute(File.join($androidpath, "Rhodes", "gen", "com", "rhomobile", "rhodes"))
args = ["package", "-f", "-M", manifest, "-S", resource, "-A", assets, "-I", $androidjar, "-J", $app_rjava_dir]
puts Jake.run($aapt, args)
unless $?.success?
puts "Error in AAPT"
exit 1
end
end
# desc "Build RhoBundle for android"
task :rhobundle => ["config:android","build:bundle:noxruby",:extensions,:librhodes] do
# Rake::Task["build:bundle:noxruby"].execute
assets = File.join(Jake.get_absolute($androidpath), "Rhodes", "assets")
rm_rf assets
mkdir_p assets
hash = nil
["apps", "db", "lib"].each do |d|
cp_r File.join($srcdir, d), assets, :preserve => true
# Calculate hash of directories
hash = get_dir_hash(File.join(assets, d), hash)
end
File.open(File.join(assets, "hash"), "w") { |f| f.write(hash.hexdigest) }
File.open(File.join(assets, "name"), "w") { |f| f.write($appname) }
psize = assets.size + 1
File.open(File.join(assets, 'rho.dat'), 'w') do |dat|
Dir.glob(File.join(assets, '**/*')).sort.each do |f|
relpath = f[psize..-1]
if File.directory?(f)
type = 'dir'
elsif File.file?(f)
type = 'file'
else
next
end
size = File.stat(f).size
tm = File.stat(f).mtime.to_i
dat.puts "#{relpath}\t#{type}\t#{size.to_s}\t#{tm.to_s}"
end
end
end
task :extensions => :genconfig do
ENV['RHO_PLATFORM'] = 'android'
ENV["ANDROID_NDK"] = $androidndkpath
ENV["ANDROID_API_LEVEL"] = ANDROID_API_LEVEL.to_s
ENV["TARGET_TEMP_DIR"] = $extensionsdir
ENV["RHO_ROOT"] = $startdir
ENV["BUILD_DIR"] ||= $startdir + "/platform/android/build"
ENV["RHO_INC"] = $appincdir
mkdir_p $extensionsdir unless File.directory? $extensionsdir
$app_config["extensions"].each do |ext|
$app_config["extpaths"].each do |p|
extpath = File.join(p, ext, 'ext')
if RUBY_PLATFORM =~ /(win|w)32$/
next unless File.exists? File.join(extpath, 'build.bat')
else
next unless File.executable? File.join(extpath, 'build')
end
ENV['TEMP_FILES_DIR'] = File.join(ENV["TARGET_TEMP_DIR"], ext)
if RUBY_PLATFORM =~ /(win|w)32$/
puts Jake.run('build.bat', [], extpath)
else
puts Jake.run('./build', [], extpath)
end
exit 1 unless $?.success?
end
end
end
task :libsqlite => "config:android" do
srcdir = File.join($shareddir, "sqlite")
objdir = $objdir["sqlite"]
libname = $libname["sqlite"]
cc_build 'libsqlite', objdir, ["-I#{srcdir}"] or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libcurl => "config:android" do
# Steps to get curl_config.h from fresh libcurl sources:
#export PATH=<ndkroot>/build/prebuilt/linux-x86/arm-eabi-4.2.1/bin:$PATH
#export CC=arm-eabi-gcc
#export CPP=arm-eabi-cpp
#export CFLAGS="--sysroot <ndkroot>/build/platforms/android-3/arch-arm -fPIC -mandroid -DANDROID -DOS_ANDROID"
#export CPPFLAGS="--sysroot <ndkroot>/build/platforms/android-3/arch-arm -fPIC -mandroid -DANDROID -DOS_ANDROID"
#./configure --without-ssl --without-ca-bundle --without-ca-path --without-libssh2 --without-libidn --disable-ldap --disable-ldaps --host=arm-eabi
srcdir = File.join $shareddir, "curl", "lib"
objdir = $objdir["curl"]
libname = $libname["curl"]
args = []
args << "-DHAVE_CONFIG_H"
args << "-I#{srcdir}/../include"
args << "-I#{srcdir}"
args << "-I#{$shareddir}"
cc_build 'libcurl', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libruby => "config:android" do
srcdir = File.join $shareddir, "ruby"
objdir = $objdir["ruby"]
libname = $libname["ruby"]
args = []
args << "-I#{srcdir}/include"
args << "-I#{srcdir}/linux"
args << "-I#{srcdir}/generated"
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-I#{srcdir}/../sqlite"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'libruby', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libjson => "config:android" do
srcdir = File.join $shareddir, "json"
objdir = $objdir["json"]
libname = $libname["json"]
args = []
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'libjson', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
unless USE_STLPORT
task :libstlport do
end
else
task :libstlport => "config:android" do
if USE_STLPORT
objdir = $objdir["stlport"]
libname = $libname["stlport"]
args = []
args << "-I#{$stlport_includes}"
args << "-DTARGET_OS=android"
args << "-DOSNAME=android"
args << "-DCOMPILER_NAME=gcc"
args << "-DBUILD_OSNAME=android"
args << "-D_REENTRANT"
args << "-D__NEW__"
args << "-ffunction-sections"
args << "-fdata-sections"
args << "-fno-rtti"
args << "-fno-exceptions"
cc_build 'libstlport', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
end
end
task :librholog => "config:android" do
srcdir = File.join $shareddir, "logging"
objdir = $objdir["rholog"]
libname = $libname["rholog"]
args = []
args << "-I#{srcdir}/.."
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librholog', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhomain => "config:android" do
srcdir = $shareddir
objdir = $objdir["rhomain"]
libname = $libname["rhomain"]
args = []
args << "-I#{srcdir}"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhomain', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhocommon => "config:android" do
objdir = $objdir["rhocommon"]
libname = $libname["rhocommon"]
args = []
args << "-I#{$shareddir}"
args << "-I#{$shareddir}/curl/include"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhocommon', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhodb => "config:android" do
srcdir = File.join $shareddir, "db"
objdir = $objdir["rhodb"]
libname = $libname["rhodb"]
args = []
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-I#{srcdir}/../sqlite"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhodb', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :librhosync => "config:android" do
srcdir = File.join $shareddir, "sync"
objdir = $objdir["rhosync"]
libname = $libname["rhosync"]
args = []
args << "-I#{srcdir}"
args << "-I#{srcdir}/.."
args << "-I#{srcdir}/../sqlite"
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhosync', objdir, args or exit 1
cc_ar libname, Dir.glob(objdir + "/**/*.o") or exit 1
end
task :libs => [:libsqlite, :libcurl, :libruby, :libjson, :libstlport, :librhodb, :librhocommon, :librhomain, :librhosync, :librholog]
task :genconfig => "config:android" do
mkdir_p $appincdir unless File.directory? $appincdir
# Generate genconfig.h
genconfig_h = File.join($appincdir, 'genconfig.h')
gapi_already_enabled = false
caps_already_enabled = {}
#ANDROID_PERMISSIONS.keys.each do |k|
# caps_already_enabled[k] = false
#end
if File.file? genconfig_h
File.open(genconfig_h, 'r') do |f|
while line = f.gets
if line =~ /^\s*#\s*define\s+RHO_GOOGLE_API_KEY\s+"[^"]*"\s*$/
gapi_already_enabled = true
else
ANDROID_PERMISSIONS.keys.each do |k|
if line =~ /^\s*#\s*define\s+RHO_CAP_#{k.upcase}_ENABLED\s+(.*)\s*$/
value = $1.strip
if value == 'true'
caps_already_enabled[k] = true
elsif value == 'false'
caps_already_enabled[k] = false
else
raise "Unknown value for the RHO_CAP_#{k.upcase}_ENABLED: #{value}"
end
end
end
end
end
end
end
regenerate = false
regenerate = true unless File.file? genconfig_h
regenerate = $use_geomapping != gapi_already_enabled unless regenerate
caps_enabled = {}
ANDROID_PERMISSIONS.keys.each do |k|
caps_enabled[k] = $app_config["capabilities"].index(k) != nil
regenerate = true if caps_already_enabled[k].nil? or caps_enabled[k] != caps_already_enabled[k]
end
if regenerate
puts "Need to regenerate genconfig.h"
$stdout.flush
File.open(genconfig_h, 'w') do |f|
f.puts "#ifndef RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F"
f.puts "#define RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F"
f.puts ""
f.puts "#define RHO_GOOGLE_API_KEY \"#{$gapikey}\"" if $use_geomapping and !$gapikey.nil?
caps_enabled.each do |k,v|
f.puts "#define RHO_CAP_#{k.upcase}_ENABLED #{v ? "true" : "false"}"
end
f.puts ""
f.puts "#endif /* RHO_GENCONFIG_H_411BFA4742CF4F2AAA3F6B411ED7514F */"
end
else
puts "No need to regenerate genconfig.h"
$stdout.flush
end
# Generate rhocaps.inc
rhocaps_inc = File.join($appincdir, 'rhocaps.inc')
caps_already_defined = []
if File.exists? rhocaps_inc
File.open(rhocaps_inc, 'r') do |f|
while line = f.gets
next unless line =~ /^\s*RHO_DEFINE_CAP\s*\(\s*([A-Z_]*)\s*\)\s*\s*$/
caps_already_defined << $1.downcase
end
end
end
if caps_already_defined.sort.uniq != ANDROID_PERMISSIONS.keys.sort.uniq
puts "Need to regenerate rhocaps.inc"
$stdout.flush
File.open(rhocaps_inc, 'w') do |f|
ANDROID_PERMISSIONS.keys.sort.each do |k|
f.puts "RHO_DEFINE_CAP(#{k.upcase})"
end
end
else
puts "No need to regenerate rhocaps.inc"
$stdout.flush
end
# Generate Capabilities.java
File.open($app_capabilities_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class Capabilities {"
ANDROID_PERMISSIONS.keys.sort.each do |k|
f.puts " public static boolean #{k.upcase}_ENABLED = true;"
end
f.puts "}"
end
# Generate Push.java
File.open($app_push_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class Push {"
f.puts " public static final String SENDER = \"#{$push_sender}\";"
f.puts "};"
end
end
task :gen_java_ext => "config:android" do
File.open($app_native_libs_java, "w") do |f|
f.puts "package #{JAVA_PACKAGE_NAME};"
f.puts "public class NativeLibraries {"
f.puts " public static void load() {"
f.puts " // Load native .so libraries"
Dir.glob($extensionsdir + "/lib*.so").reverse.each do |lib|
libname = File.basename(lib).gsub(/^lib/, '').gsub(/\.so$/, '')
f.puts " System.loadLibrary(\"#{libname}\");"
end
f.puts " // Load native implementation of rhodes"
f.puts " System.loadLibrary(\"rhodes\");"
f.puts " }"
f.puts "};"
end
end
task :gensources => [:genconfig, :gen_java_ext]
task :librhodes => [:libs, :gensources] do
srcdir = File.join $androidpath, "Rhodes", "jni", "src"
objdir = File.join $bindir, "libs", $confdir, $ndkgccver, "librhodes"
libname = File.join $bindir, "libs", $confdir, $ndkgccver, "librhodes.so"
args = []
args << "-I#{$appincdir}"
args << "-I#{srcdir}/../include"
args << "-I#{$shareddir}"
args << "-I#{$shareddir}/common"
args << "-I#{$shareddir}/sqlite"
args << "-I#{$shareddir}/curl/include"
args << "-I#{$shareddir}/ruby/include"
args << "-I#{$shareddir}/ruby/linux"
args << "-D__SGI_STL_INTERNAL_PAIR_H" if USE_STLPORT
args << "-D__NEW__" if USE_STLPORT
args << "-I#{$stlport_includes}" if USE_STLPORT
cc_build 'librhodes', objdir, args or exit 1
deps = []
$libname.each do |k,v|
deps << v
end
args = []
args << "-L#{$rhobindir}/#{$confdir}/#{$ndkgccver}"
args << "-L#{$bindir}/libs/#{$confdir}/#{$ndkgccver}"
args << "-L#{$extensionsdir}"
rlibs = []
rlibs << "rhomain"
rlibs << "ruby"
rlibs << "rhosync"
rlibs << "rhodb"
rlibs << "rholog"
rlibs << "rhocommon"
rlibs << "json"
rlibs << "stlport" if USE_STLPORT
rlibs << "curl"
rlibs << "sqlite"
rlibs << "log"
rlibs << "dl"
rlibs << "z"
rlibs.map! { |x| "-l#{x}" }
elibs = []
extlibs = Dir.glob($extensionsdir + "/lib*.a") + Dir.glob($extensionsdir + "/lib*.so")
stub = []
extlibs.reverse.each do |f|
lparam = "-l" + File.basename(f).gsub(/^lib/,"").gsub(/\.(a|so)$/,"")
elibs << lparam
# Workaround for GNU ld: this way we have specified one lib multiple times
# command line so ld's dependency mechanism will find required functions
# independently of its position in command line
stub.each do |s|
args << s
end
stub << lparam
end
args += elibs
args += rlibs
args += elibs
args += rlibs
mkdir_p File.dirname(libname) unless File.directory? File.dirname(libname)
cc_link libname, Dir.glob(objdir + "/**/*.o"), args, deps or exit 1
destdir = File.join($androidpath, "Rhodes", "libs", "armeabi")
mkdir_p destdir unless File.exists? destdir
cp_r libname, destdir
cc_run($stripbin, [File.join(destdir, File.basename(libname))])
end
# desc "Build Rhodes for android"
task :rhodes => :rhobundle do
javac = $config["env"]["paths"]["java"] + "/javac" + $exe_ext
rm_rf $tmpdir + "/Rhodes"
mkdir_p $tmpdir + "/Rhodes"
set_app_name_android($appname)
generate_rjava
srclist = File.join($builddir, "RhodesSRC_build.files")
newsrclist = File.join($tmpdir, "RhodesSRC_build.files")
lines = []
File.open(srclist, "r") do |f|
while line = f.gets
line.chomp!
next if line =~ /\/AndroidR\.java\s*$/
next if !$use_geomapping and line =~ /\/mapview\//
lines << line
end
end
lines << File.join($app_rjava_dir, "R.java")
lines << $app_android_r
lines << $app_native_libs_java
lines << $app_capabilities_java
lines << $app_push_java
if File.exists? File.join($extensionsdir, "ext_build.files")
puts 'ext_build.files found ! Addditional files for compilation :'
File.open(File.join($extensionsdir, "ext_build.files")) do |f|
while line = f.gets
puts 'java file : ' + line
lines << line
end
end
else
puts 'ext_build.files not found - no additional java files for compilation'
end
File.open(newsrclist, "w") { |f| f.write lines.join("\n") }
srclist = newsrclist
args = []
args << "-g"
args << "-d"
args << $tmpdir + '/Rhodes'
args << "-source"
args << "1.6"
args << "-target"
args << "1.6"
args << "-nowarn"
args << "-encoding"
args << "latin1"
args << "-classpath"
classpath = $androidjar
classpath += $path_separator + $gapijar unless $gapijar.nil?
classpath += $path_separator + "#{$tmpdir}/Rhodes"
Dir.glob(File.join($extensionsdir, "*.jar")).each do |f|
classpath += $path_separator + f
end
args << classpath
args << "@#{srclist}"
puts Jake.run(javac, args)
unless $?.success?
puts "Error compiling java code"
exit 1
end
files = []
Dir.glob(File.join($extensionsdir, "*.jar")).each do |f|
puts Jake.run($jarbin, ["xf", f], File.join($tmpdir, "Rhodes"))
unless $?.success?
puts "Error running jar (xf)"
exit 1
end
end
Dir.glob(File.join($tmpdir, "Rhodes", "*")).each do |f|
relpath = Pathname.new(f).relative_path_from(Pathname.new(File.join($tmpdir, "Rhodes"))).to_s
files << relpath
end
unless files.empty?
args = ["cf", "../../Rhodes.jar"]
args += files
puts Jake.run($jarbin, args, File.join($tmpdir, "Rhodes"))
unless $?.success?
puts "Error running jar"
exit 1
end
end
end
#desc "build all"
task :all => [:rhobundle, :rhodes]
end
end
namespace "package" do
task :android => "build:android:all" do
puts "Running dx utility"
args = []
args << "--dex"
args << "--output=#{$bindir}/classes.dex"
args << "#{$bindir}/Rhodes.jar"
puts Jake.run($dx, args)
unless $?.success?
puts "Error running DX utility"
exit 1
end
manifest = $appmanifest
resource = $appres
assets = Jake.get_absolute $androidpath + "/Rhodes/assets"
resourcepkg = $bindir + "/rhodes.ap_"
puts "Packaging Assets and Jars"
set_app_name_android($appname)
args = ["package", "-f", "-M", manifest, "-S", resource, "-A", assets, "-I", $androidjar, "-F", resourcepkg]
puts Jake.run($aapt, args)
unless $?.success?
puts "Error running AAPT (1)"
exit 1
end
# Workaround: manually add files starting with '_' because aapt silently ignore such files when creating package
rm_rf File.join($tmpdir, "assets")
cp_r assets, $tmpdir
Dir.glob(File.join($tmpdir, "assets/**/*")).each do |f|
next unless File.basename(f) =~ /^_/
relpath = Pathname.new(f).relative_path_from(Pathname.new($tmpdir)).to_s
puts "Add #{relpath} to #{resourcepkg}..."
args = ["uf", resourcepkg, relpath]
puts Jake.run($jarbin, args, $tmpdir)
unless $?.success?
puts "Error running AAPT (2)"
exit 1
end
end
# Add native librhodes.so
rm_rf File.join($tmpdir, "lib")
mkdir_p File.join($tmpdir, "lib/armeabi")
cp_r File.join($bindir, "libs", $confdir, $ndkgccver, "librhodes.so"), File.join($tmpdir, "lib/armeabi")
# Add extensions .so libraries
Dir.glob($extensionsdir + "/lib*.so").each do |lib|
cp_r lib, File.join($tmpdir, "lib/armeabi")
end
args = ["uf", resourcepkg]
# Strip them all to decrease size
Dir.glob($tmpdir + "/lib/armeabi/lib*.so").each do |lib|
cc_run($stripbin, [lib])
args << "lib/armeabi/#{File.basename(lib)}"
end
puts Jake.run($jarbin, args, $tmpdir)
err = $?
rm_rf $tmpdir + "/lib"
unless err.success?
puts "Error running AAPT (3)"
exit 1
end
end
end
def get_app_log(appname, device, silent = false)
pkgname = "com.#{$vendor}." + appname.downcase.gsub(/[^A-Za-z_0-9]/, '')
path = File.join('/data/data', pkgname, 'rhodata', 'RhoLog.txt')
cc_run($adb, [device ? '-d' : '-e', 'pull', path, $app_path]) or return false
puts "RhoLog.txt stored to " + $app_path unless silent
return true
end
namespace "device" do
namespace "android" do
desc "Build debug self signed for device"
task :debug => "package:android" do
dexfile = $bindir + "/classes.dex"
simple_apkfile = $targetdir + "/" + $appname + "-tmp.apk"
final_apkfile = $targetdir + "/" + $appname + "-debug.apk"
resourcepkg = $bindir + "/rhodes.ap_"
puts "Building APK file"
Jake.run($apkbuilder, [simple_apkfile, "-z", resourcepkg, "-f", dexfile])
unless $?.success?
puts "Error building APK file"
exit 1
end
puts "Align Debug APK file"
args = []
args << "-f"
args << "-v"
args << "4"
args << '"' + simple_apkfile + '"'
args << '"' + final_apkfile + '"'
puts Jake.run($zipalign, args)
unless $?.success?
puts "Error running zipalign"
exit 1
end
#remove temporary files
rm_rf simple_apkfile
File.open(File.join(File.dirname(final_apkfile), "app_info.txt"), "w") do |f|
f.puts $app_package_name
end
end
task :install => :debug do
apkfile = $targetdir + "/" + $appname + "-debug.apk"
puts "Install APK file"
Jake.run($adb, ["-d", "install", "-r", apkfile])
unless $?.success?
puts "Error installing APK file"
exit 1
end
puts "Install complete"
end
desc "Build production signed for device"
task :production => "package:android" do
dexfile = $bindir + "/classes.dex"
simple_apkfile = $targetdir + "/" + $appname + "_tmp.apk"
final_apkfile = $targetdir + "/" + $appname + "_signed.apk"
signed_apkfile = $targetdir + "/" + $appname + "_tmp_signed.apk"
resourcepkg = $bindir + "/rhodes.ap_"
puts "Building APK file"
Jake.run($apkbuilder, [simple_apkfile, "-u", "-z", resourcepkg, "-f", dexfile])
unless $?.success?
puts "Error building APK file"
exit 1
end
if not File.exists? $keystore
puts "Generating private keystore..."
mkdir_p File.dirname($keystore) unless File.directory? File.dirname($keystore)
args = []
args << "-genkey"
args << "-alias"
args << $storealias
args << "-keyalg"
args << "RSA"
args << "-validity"
args << "20000"
args << "-keystore"
args << $keystore
args << "-storepass"
args << $storepass
args << "-keypass"
args << $keypass
puts Jake.run($keytool, args)
unless $?.success?
puts "Error generating keystore file"
exit 1
end
end
puts "Signing APK file"
args = []
args << "-verbose"
args << "-keystore"
args << $keystore
args << "-storepass"
args << $storepass
args << "-signedjar"
args << signed_apkfile
args << simple_apkfile
args << $storealias
puts Jake.run($jarsigner, args)
unless $?.success?
puts "Error running jarsigner"
exit 1
end
puts "Align APK file"
args = []
args << "-f"
args << "-v"
args << "4"
args << '"' + signed_apkfile + '"'
args << '"' + final_apkfile + '"'
puts Jake.run($zipalign, args)
unless $?.success?
puts "Error running zipalign"
exit 1
end
#remove temporary files
rm_rf simple_apkfile
rm_rf signed_apkfile
File.open(File.join(File.dirname(final_apkfile), "app_info.txt"), "w") do |f|
f.puts $app_package_name
end
end
task :getlog => "config:android" do
get_app_log($appname, true) or exit 1
end
end
end
namespace "emulator" do
namespace "android" do
task :getlog => "config:android" do
get_app_log($appname, false) or exit 1
end
end
end
def is_emulator_running
`#{$adb} devices`.split("\n")[1..-1].each do |line|
return true if line =~ /^emulator/
end
return false
end
def is_device_running
`#{$adb} devices`.split("\n")[1..-1].each do |line|
return true if line !~ /^emulator/
end
return false
end
def run_application (target_flag)
args = []
args << target_flag
args << "shell"
args << "am"
args << "start"
args << "-a"
args << "android.intent.action.MAIN"
args << "-n"
args << $app_package_name + "/#{JAVA_PACKAGE_NAME}.Rhodes"
Jake.run($adb, args)
end
def application_running(flag, pkgname)
pkg = pkgname.gsub(/\./, '\.')
`#{$adb} #{flag} shell ps`.split.each do |line|
return true if line =~ /#{pkg}/
end
false
end
namespace "run" do
namespace "android" do
task :spec => ["device:android:debug"] do
run_emulator
do_uninstall('-e')
log_name = $app_path + '/RhoLog.txt'
File.delete(log_name) if File.exist?(log_name)
# Failsafe to prevent eternal hangs
Thread.new {
sleep 1000
if RUBY_PLATFORM =~ /windows|cygwin|mingw/
# Windows
`taskkill /F /IM adb.exe`
`taskkill /F /IM emulator.exe`
else
`killall -9 adb`
`killall -9 emulator`
end
}
load_app_and_run
Jake.before_run_spec
start = Time.now
puts "waiting for log"
while !File.exist?(log_name)
get_app_log($appname, false, true)
sleep(1)
end
puts "start read log"
end_spec = false
while !end_spec do
get_app_log($appname, false, true)
io = File.new(log_name, "r")
io.each do |line|
#puts line
end_spec = !Jake.process_spec_output(line)
break if end_spec
end
io.close
break unless application_running('-e', $app_package_name)
sleep(5) unless end_spec
end
Jake.process_spec_results(start)
# stop app
if RUBY_PLATFORM =~ /windows|cygwin|mingw/
# Windows
`taskkill /F /IM adb.exe`
`taskkill /F /IM emulator.exe`
else
`killall -9 adb`
`killall -9 emulator`
end
$stdout.flush
end
task :phone_spec do
exit 1 if Jake.run_spec_app('android','phone_spec')
exit 0
end
task :framework_spec do
exit 1 if Jake.run_spec_app('android','framework_spec')
exit 0
end
task :emulator => "device:android:debug" do
run_emulator
load_app_and_run
end
def run_emulator
apkfile = Jake.get_absolute $targetdir + "/" + $appname + "-debug.apk"
Jake.run($adb, ['kill-server'])
#Jake.run($adb, ['start-server'])
#adb_start_server = $adb + ' start-server'
Thread.new { Jake.run($adb, ['start-server']) }
puts 'Sleep for 5 sec. waiting for "adb start-server"'
sleep 5
if $appavdname != nil
$avdname = $appavdname
end
createavd = "\"#{$androidbin}\" create avd --name #{$avdname} --target #{$avdtarget} --sdcard 32M --skin HVGA"
system(createavd) unless File.directory?( File.join(ENV['HOME'], ".android", "avd", "#{$avdname}.avd" ) )
if $use_google_addon_api
avdini = File.join(ENV['HOME'], '.android', 'avd', "#{$avdname}.ini")
avd_using_gapi = true if File.new(avdini).read =~ /:Google APIs:/
unless avd_using_gapi
puts "Can not use specified AVD (#{$avdname}) because of incompatibility with Google APIs. Delete it and try again."
exit 1
end
end
running = is_emulator_running
if !running
# Start the emulator, check on it every 5 seconds until it's running
Thread.new { system("\"#{$emulator}\" -avd #{$avdname}") }
puts "Waiting up to 180 seconds for emulator..."
startedWaiting = Time.now
adbRestarts = 1
while (Time.now - startedWaiting < 180 )
sleep 5
now = Time.now
emulatorState = ""
Jake.run2($adb,["-e", "get-state"],{:system => false, :hideerrors => :false}) do |line|
puts "RET: " + line
emulatorState += line
end
if emulatorState =~ /unknown/
printf("%.2fs: ",(now - startedWaiting))
if (now - startedWaiting) > (60 * adbRestarts)
# Restart the adb server every 60 seconds to prevent eternal waiting
puts "Appears hung, restarting adb server"
Jake.run($adb, ['kill-server'])
Thread.new { Jake.run($adb, ['start-server']) }
adbRestarts += 1
else
puts "Still waiting..."
end
else
puts "Success"
puts "Device is ready after " + (Time.now - startedWaiting).to_s + " seconds"
break
end
end
if !is_emulator_running
puts "Emulator still isn't up and running, giving up"
exit 1
end
else
puts "Emulator is up and running"
end
$stdout.flush
end
def load_app_and_run
puts "Loading package into emulator"
apkfile = Jake.get_absolute $targetdir + "/" + $appname + "-debug.apk"
count = 0
done = false
while count < 20
f = Jake.run2($adb, ["-e", "install", "-r", apkfile], {:nowait => true})
theoutput = ""
while c = f.getc
$stdout.putc c
$stdout.flush
theoutput << c
end
f.close
if theoutput.to_s.match(/Success/)
done = true
break
end
puts "Failed to load (possibly because emulator not done launching)- retrying"
$stdout.flush
sleep 1
count += 1
end
puts "Loading complete, starting application.." if done
run_application("-e") if done
end
desc "build and install on device"
task :device => "device:android:install" do
puts "Starting application..."
run_application("-d")
end
end
desc "build and launch emulator"
task :android => "run:android:emulator" do
end
end
namespace "uninstall" do
def do_uninstall(flag)
args = []
args << flag
args << "uninstall"
args << $app_package_name
Jake.run($adb, args)
unless $?.success?
puts "Error uninstalling application"
exit 1
end
puts "Application uninstalled successfully"
end
namespace "android" do
task :emulator => "config:android" do
unless is_emulator_running
puts "WARNING!!! Emulator is not up and running"
exit 1
end
do_uninstall('-e')
end
desc "uninstall from device"
task :device => "config:android" do
unless is_device_running
puts "WARNING!!! Device is not connected"
exit 1
end
do_uninstall('-d')
end
end
desc "uninstall from emulator"
task :android => "uninstall:android:emulator" do
end
end
namespace "clean" do
desc "Clean Android"
task :android => "clean:android:all"
namespace "android" do
task :assets => "config:android" do
Dir.glob($androidpath + "/Rhodes/assets/**/*") do |f|
rm f, :force => true unless f =~ /\/loading\.html$/
end
end
task :files => "config:android" do
rm_rf $targetdir
rm_rf $bindir
rm_rf $srcdir
rm_rf $libs
end
task :libsqlite => "config:android" do
cc_clean "sqlite"
end
task :libs => ["config:android"] do
$native_libs.each do |l|
cc_clean l
end
end
task :librhodes => "config:android" do
rm_rf $rhobindir + "/" + $confdir + "/" + $ndkgccver + "/librhodes"
rm_rf $bindir + "/libs/" + $confdir + "/" + $ndkgccver + "/librhodes.so"
end
# desc "clean android"
task :all => [:assets,:librhodes,:libs,:files]
end
end
|
class Abyss < Formula
desc "ABySS: genome sequence assembler for short reads"
homepage "http://www.bcgsc.ca/platform/bioinfo/software/abyss"
# doi "10.1101/gr.089532.108"
# tag "bioinformatics"
url "https://github.com/bcgsc/abyss/releases/download/1.9.0/abyss-1.9.0.tar.gz"
sha256 "1030fcea4bfae942789deefd3a4ffb30653143e02eb6a74c7e4087bb4bf18a14"
revision 2
bottle do
cellar :any
sha256 "231aa5e27f85f78b4ce75bba5bb1448b106f6650b1befc190fc3563ce4a18196" => :el_capitan
sha256 "68e20ab489764668d1f56041899849d19466824125133901e0e9d92c6dc01c55" => :yosemite
sha256 "aa5e6a5d3e4007f1b7d592a67612aa6b49a9f4536dbf07c068390de750400c8f" => :mavericks
end
head do
url "https://github.com/bcgsc/abyss.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "multimarkdown" => :build
end
option :cxx11
option "with-maxk=", "Set the maximum k-mer length to N [default is 96]"
option "without-test", "Skip build-time tests (not recommended)"
option "with-openmp", "Enable OpenMP multithreading"
deprecated_option "enable-maxk" => "with-maxk"
deprecated_option "without-check" => "without-test"
needs :openmp if build.with? "openmp"
# Only header files are used from these packages, so :build is appropriate
depends_on "boost" => :build
depends_on "google-sparsehash" => :build
depends_on "sqlite" unless OS.mac?
depends_on :mpi => [:cc, :recommended]
# strip breaks the ability to read compressed files.
skip_clean "bin"
def install
ENV.cxx11 if build.cxx11?
system "./autogen.sh" if build.head?
args = [
"--enable-maxk=#{ARGV.value("with-maxk") || 96}",
"--prefix=#{prefix}",
"--disable-dependency-tracking",
]
system "./configure", *args
system "make"
system "make", "check" if build.with? "test"
system "make", "install"
end
test do
system "#{bin}/ABYSS", "--version"
end
end
abyss: update 1.9.0_2 bottle for Linuxbrew.
class Abyss < Formula
desc "ABySS: genome sequence assembler for short reads"
homepage "http://www.bcgsc.ca/platform/bioinfo/software/abyss"
# doi "10.1101/gr.089532.108"
# tag "bioinformatics"
url "https://github.com/bcgsc/abyss/releases/download/1.9.0/abyss-1.9.0.tar.gz"
sha256 "1030fcea4bfae942789deefd3a4ffb30653143e02eb6a74c7e4087bb4bf18a14"
revision 2
bottle do
cellar :any
sha256 "231aa5e27f85f78b4ce75bba5bb1448b106f6650b1befc190fc3563ce4a18196" => :el_capitan
sha256 "68e20ab489764668d1f56041899849d19466824125133901e0e9d92c6dc01c55" => :yosemite
sha256 "aa5e6a5d3e4007f1b7d592a67612aa6b49a9f4536dbf07c068390de750400c8f" => :mavericks
sha256 "6a9574678706b7a78ebca7617f21d554d27041aa32427fe4370f03cbbe68f182" => :x86_64_linux
end
head do
url "https://github.com/bcgsc/abyss.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "multimarkdown" => :build
end
option :cxx11
option "with-maxk=", "Set the maximum k-mer length to N [default is 96]"
option "without-test", "Skip build-time tests (not recommended)"
option "with-openmp", "Enable OpenMP multithreading"
deprecated_option "enable-maxk" => "with-maxk"
deprecated_option "without-check" => "without-test"
needs :openmp if build.with? "openmp"
# Only header files are used from these packages, so :build is appropriate
depends_on "boost" => :build
depends_on "google-sparsehash" => :build
depends_on "sqlite" unless OS.mac?
depends_on :mpi => [:cc, :recommended]
# strip breaks the ability to read compressed files.
skip_clean "bin"
def install
ENV.cxx11 if build.cxx11?
system "./autogen.sh" if build.head?
args = [
"--enable-maxk=#{ARGV.value("with-maxk") || 96}",
"--prefix=#{prefix}",
"--disable-dependency-tracking",
]
system "./configure", *args
system "make"
system "make", "check" if build.with? "test"
system "make", "install"
end
test do
system "#{bin}/ABYSS", "--version"
end
end
|
module FbAppPlugin::DisplayHelper
protected
def link_to_product product, opts = {}
url_opts = opts.delete(:url_options) || {}
url_opts.merge! controller: :fb_app_plugin_page_tab, product_id: product.id
domain = FbAppPlugin.config[:app][:domain]
url_opts[:host] = domain if domain.present?
url = params.merge url_opts
link_to content_tag('span', product.name), url,
opts.merge(target: '')
end
def link_to name = nil, options = nil, html_options = nil, &block
html_options ||= {}
html_options[:target] ||= '_parent'
super
end
end
Keep protocol on links
module FbAppPlugin::DisplayHelper
protected
def link_to_product product, opts = {}
url_opts = opts.delete(:url_options) || {}
url_opts.merge! controller: :fb_app_plugin_page_tab, product_id: product.id
domain = FbAppPlugin.config[:app][:domain]
url_opts[:host] = domain if domain.present?
url_opts[:protocol] = '//'
url = params.merge url_opts
link_to content_tag('span', product.name), url,
opts.merge(target: '')
end
def link_to name = nil, options = nil, html_options = nil, &block
html_options ||= {}
options[:protocol] = '//'
html_options[:target] ||= '_parent'
super
end
end
|
require 'image_optim/bin_resolver'
require 'image_optim/config'
require 'image_optim/handler'
require 'image_optim/image_meta'
require 'image_optim/image_path'
require 'image_optim/worker'
require 'in_threads'
require 'shellwords'
class ImageOptim
# Nice level
attr_reader :nice
# Number of threads to run with
attr_reader :threads
# Verbose output?
attr_reader :verbose
# Initialize workers, specify options using worker underscored name:
#
# pass false to disable worker
#
# ImageOptim.new(:pngcrush => false)
#
# or hash with options to worker
#
# ImageOptim.new(:advpng => {:level => 3}, :optipng => {:level => 2})
#
# use :threads to set number of parallel optimizers to run (passing true or
# nil determines number of processors, false disables parallel processing)
#
# ImageOptim.new(:threads => 8)
#
# use :nice to specify optimizers nice level (true or nil makes it 10, false
# makes it 0)
#
# ImageOptim.new(:nice => 20)
def initialize(options = {})
config = Config.new(options)
@nice = config.nice
@threads = config.threads
@verbose = config.verbose
if verbose
$stderr << config
$stderr << "Nice level: #{nice}\n"
$stderr << "Using threads: #{threads}\n"
end
@bin_resolver = BinResolver.new(self)
@workers_by_format = {}
Worker.klasses.each do |klass|
next unless (worker_options = config.for_worker(klass))
worker = klass.new(self, worker_options)
worker.image_formats.each do |format|
@workers_by_format[format] ||= []
@workers_by_format[format] << worker
end
end
@workers_by_format.values.each(&:sort!)
config.assert_no_unused_options!
end
# Get workers for image
def workers_for_image(path)
@workers_by_format[ImagePath.convert(path).format]
end
# Optimize one file, return new path as OptimizedImagePath or nil if
# optimization failed
def optimize_image(original)
original = ImagePath.convert(original)
return unless (workers = workers_for_image(original))
handler = Handler.new(original)
workers.each do |worker|
handler.process do |src, dst|
worker.optimize(src, dst)
end
end
handler.cleanup
return unless handler.result
ImagePath::Optimized.new(handler.result, original)
end
# Optimize one file in place, return original as OptimizedImagePath or nil if
# optimization failed
def optimize_image!(original)
original = ImagePath.convert(original)
return unless (result = optimize_image(original))
result.replace(original)
ImagePath::Optimized.new(original, result.original_size)
end
# Optimize image data, return new data or nil if optimization failed
def optimize_image_data(original_data)
image_meta = ImageMeta.for_data(original_data)
return unless image_meta && image_meta.format
ImagePath.temp_file %W[image_optim .#{image_meta.format}] do |temp|
temp.binmode
temp.write(original_data)
temp.close
if (result = optimize_image(temp.path))
result.open('rb', &:read)
end
end
end
# Optimize multiple images
# if block given yields path and result for each image and returns array of
# yield results
# else return array of results
def optimize_images(paths, &block)
run_method_for(paths, :optimize_image, &block)
end
# Optimize multiple images in place
# if block given yields path and result for each image and returns array of
# yield results
# else return array of results
def optimize_images!(paths, &block)
run_method_for(paths, :optimize_image!, &block)
end
# Optimize multiple image datas
# if block given yields original and result for each image data and returns
# array of yield results
# else return array of results
def optimize_images_data(datas, &block)
run_method_for(datas, :optimize_image_data, &block)
end
# Optimization methods with default options
def self.method_missing(method, *args, &block)
if method_defined?(method) && method.to_s =~ /^optimize_image/
new.send(method, *args, &block)
else
super
end
end
# Version of image_optim gem spec loaded
def self.version
Gem.loaded_specs['image_optim'].version.to_s rescue 'DEV'
end
# Full version of image_optim
def self.full_version
"image_optim v#{version}"
end
# Are there workers for file at path?
def optimizable?(path)
!!workers_for_image(path)
end
# Check existance of binary, create symlink if ENV contains path for key
# XXX_BIN where XXX is upper case bin name
def resolve_bin!(bin)
@bin_resolver.resolve!(bin)
end
# Join resolve_dir, default path and vendor path for PATH environment variable
def env_path
@bin_resolver.env_path
end
private
# Run method for each path and yield each path and result if block given
def run_method_for(paths, method_name, &block)
apply_threading(paths).map do |path|
result = send(method_name, path)
if block
block.call(path, result)
else
result
end
end
end
# Apply threading if threading is allowed
def apply_threading(enum)
if threads > 1
enum.in_threads(threads)
else
enum
end
end
end
%w[
pngcrush pngout optipng advpng
jhead jpegoptim jpegtran
gifsicle
svgo
].each do |worker|
require "image_optim/worker/#{worker}"
end
require 'image_optim/railtie' if defined?(Rails)
extracted create_workers_by_format from ImageOptim#initialize
require 'image_optim/bin_resolver'
require 'image_optim/config'
require 'image_optim/handler'
require 'image_optim/image_meta'
require 'image_optim/image_path'
require 'image_optim/worker'
require 'in_threads'
require 'shellwords'
class ImageOptim
# Nice level
attr_reader :nice
# Number of threads to run with
attr_reader :threads
# Verbose output?
attr_reader :verbose
# Initialize workers, specify options using worker underscored name:
#
# pass false to disable worker
#
# ImageOptim.new(:pngcrush => false)
#
# or hash with options to worker
#
# ImageOptim.new(:advpng => {:level => 3}, :optipng => {:level => 2})
#
# use :threads to set number of parallel optimizers to run (passing true or
# nil determines number of processors, false disables parallel processing)
#
# ImageOptim.new(:threads => 8)
#
# use :nice to specify optimizers nice level (true or nil makes it 10, false
# makes it 0)
#
# ImageOptim.new(:nice => 20)
def initialize(options = {})
config = Config.new(options)
@nice = config.nice
@threads = config.threads
@verbose = config.verbose
if verbose
$stderr << config
$stderr << "Nice level: #{nice}\n"
$stderr << "Using threads: #{threads}\n"
end
@bin_resolver = BinResolver.new(self)
@workers_by_format = create_workers_by_format do |klass|
config.for_worker(klass)
end
config.assert_no_unused_options!
end
# Get workers for image
def workers_for_image(path)
@workers_by_format[ImagePath.convert(path).format]
end
# Optimize one file, return new path as OptimizedImagePath or nil if
# optimization failed
def optimize_image(original)
original = ImagePath.convert(original)
return unless (workers = workers_for_image(original))
handler = Handler.new(original)
workers.each do |worker|
handler.process do |src, dst|
worker.optimize(src, dst)
end
end
handler.cleanup
return unless handler.result
ImagePath::Optimized.new(handler.result, original)
end
# Optimize one file in place, return original as OptimizedImagePath or nil if
# optimization failed
def optimize_image!(original)
original = ImagePath.convert(original)
return unless (result = optimize_image(original))
result.replace(original)
ImagePath::Optimized.new(original, result.original_size)
end
# Optimize image data, return new data or nil if optimization failed
def optimize_image_data(original_data)
image_meta = ImageMeta.for_data(original_data)
return unless image_meta && image_meta.format
ImagePath.temp_file %W[image_optim .#{image_meta.format}] do |temp|
temp.binmode
temp.write(original_data)
temp.close
if (result = optimize_image(temp.path))
result.open('rb', &:read)
end
end
end
# Optimize multiple images
# if block given yields path and result for each image and returns array of
# yield results
# else return array of results
def optimize_images(paths, &block)
run_method_for(paths, :optimize_image, &block)
end
# Optimize multiple images in place
# if block given yields path and result for each image and returns array of
# yield results
# else return array of results
def optimize_images!(paths, &block)
run_method_for(paths, :optimize_image!, &block)
end
# Optimize multiple image datas
# if block given yields original and result for each image data and returns
# array of yield results
# else return array of results
def optimize_images_data(datas, &block)
run_method_for(datas, :optimize_image_data, &block)
end
# Optimization methods with default options
def self.method_missing(method, *args, &block)
if method_defined?(method) && method.to_s =~ /^optimize_image/
new.send(method, *args, &block)
else
super
end
end
# Version of image_optim gem spec loaded
def self.version
Gem.loaded_specs['image_optim'].version.to_s rescue 'DEV'
end
# Full version of image_optim
def self.full_version
"image_optim v#{version}"
end
# Are there workers for file at path?
def optimizable?(path)
!!workers_for_image(path)
end
# Check existance of binary, create symlink if ENV contains path for key
# XXX_BIN where XXX is upper case bin name
def resolve_bin!(bin)
@bin_resolver.resolve!(bin)
end
# Join resolve_dir, default path and vendor path for PATH environment variable
def env_path
@bin_resolver.env_path
end
private
# Create hash with format mapped to list of workers sorted by run order
def create_workers_by_format(&options_proc)
by_format = {}
Worker.klasses.each do |klass|
next unless (options = options_proc[klass])
worker = klass.new(self, options)
worker.image_formats.each do |format|
by_format[format] ||= []
by_format[format] << worker
end
end
by_format.each{ |_format, workers| workers.sort! }
end
# Run method for each path and yield each path and result if block given
def run_method_for(paths, method_name, &block)
apply_threading(paths).map do |path|
result = send(method_name, path)
if block
block.call(path, result)
else
result
end
end
end
# Apply threading if threading is allowed
def apply_threading(enum)
if threads > 1
enum.in_threads(threads)
else
enum
end
end
end
%w[
pngcrush pngout optipng advpng
jhead jpegoptim jpegtran
gifsicle
svgo
].each do |worker|
require "image_optim/worker/#{worker}"
end
require 'image_optim/railtie' if defined?(Rails)
|
require 'image_optim/bin_resolver'
require 'image_optim/config'
require 'image_optim/handler'
require 'image_optim/image_path'
require 'image_optim/worker'
require 'in_threads'
require 'shellwords'
class ImageOptim
# Nice level
attr_reader :nice
# Number of threads to run with
attr_reader :threads
# Verbose output?
def verbose?
@verbose
end
# Initialize workers, specify options using worker underscored name:
#
# pass false to disable worker
#
# ImageOptim.new(:pngcrush => false)
#
# or hash with options to worker
#
# ImageOptim.new(:advpng => {:level => 3}, :optipng => {:level => 2})
#
# use :threads to set number of parallel optimizers to run (passing true or nil determines number of processors, false disables parallel processing)
#
# ImageOptim.new(:threads => 8)
#
# use :nice to specify optimizers nice level (true or nil makes it 10, false makes it 0)
#
# ImageOptim.new(:nice => 20)
def initialize(options = {})
@bin_resolver = BinResolver.new
config = Config.new(options)
@nice = config.nice
@threads = config.threads
@verbose = config.verbose
@workers_by_format = {}
Worker.klasses.each do |klass|
if worker_options = config.for_worker(klass)
worker = klass.new(self, worker_options)
worker.image_formats.each do |format|
@workers_by_format[format] ||= []
@workers_by_format[format] << worker
end
end
end
@workers_by_format.values.each(&:sort!)
config.assert_no_unused_options!
puts config if verbose?
end
# Get workers for image
def workers_for_image(path)
@workers_by_format[ImagePath.convert(path).format]
end
# Optimize one file, return new path as OptimizedImagePath or nil if optimization failed
def optimize_image(original)
original = ImagePath.convert(original)
if workers = workers_for_image(original)
handler = Handler.new(original)
workers.each do |worker|
handler.process do |src, dst|
worker.optimize(src, dst)
end
end
if handler.result
ImagePath::Optimized.new(handler.result, original)
end
end
end
# Optimize one file in place, return original as OptimizedImagePath or nil if optimization failed
def optimize_image!(original)
original = ImagePath.convert(original)
if result = optimize_image(original)
result.replace(original)
ImagePath::Optimized.new(original, result.original_size)
end
end
# Optimize image data, return new data or nil if optimization failed
def optimize_image_data(original_data)
format = ImageSize.new(original_data).format
ImagePath.temp_file %W[image_optim .#{format}] do |temp|
temp.binmode
temp.write(original_data)
temp.close
if result = optimize_image(temp.path)
result.open('rb', &:read)
end
end
end
# Optimize multiple images
# if block given yields path and result for each image and returns array of yield results
# else return array of results
def optimize_images(paths, &block)
run_method_for(paths, :optimize_image, &block)
end
# Optimize multiple images in place
# if block given yields path and result for each image and returns array of yield results
# else return array of results
def optimize_images!(paths, &block)
run_method_for(paths, :optimize_image!, &block)
end
# Optimize multiple image datas
# if block given yields original and result for each image data and returns array of yield results
# else return array of results
def optimize_images_data(datas, &block)
run_method_for(datas, :optimize_image_data, &block)
end
# Optimization methods with default options
def self.method_missing(method, *args, &block)
if method_defined?(method) && method.to_s =~ /^optimize_image/
new.send(method, *args, &block)
else
super
end
end
# Version of image_optim gem spec loaded
def self.version
Gem.loaded_specs['image_optim'].version.to_s rescue 'DEV'
end
# Are there workers for file at path?
def optimizable?(path)
!!workers_for_image(path)
end
# Check existance of binary, create symlink if ENV contains path for key XXX_BIN where XXX is upper case bin name
def resolve_bin!(bin)
@bin_resolver.resolve!(bin)
end
# Join resolve_dir, default path and vendor path for PATH environment variable
def env_path
@bin_resolver.env_path
end
private
# Run method for each path and yield each path and result if block given
def run_method_for(paths, method_name, &block)
apply_threading(paths).map do |path|
result = send(method_name, path)
if block
block.call(path, result)
else
result
end
end
end
# Apply threading if threading is allowed
def apply_threading(enum)
if threads > 1
enum.in_threads(threads)
else
enum
end
end
end
%w[
pngcrush pngout optipng advpng
jhead jpegoptim jpegtran
gifsicle svgo
].each do |worker|
require "image_optim/worker/#{worker}"
end
require 'image_optim/railtie' if defined?(Rails)
put svgo require on separate line
require 'image_optim/bin_resolver'
require 'image_optim/config'
require 'image_optim/handler'
require 'image_optim/image_path'
require 'image_optim/worker'
require 'in_threads'
require 'shellwords'
class ImageOptim
# Nice level
attr_reader :nice
# Number of threads to run with
attr_reader :threads
# Verbose output?
def verbose?
@verbose
end
# Initialize workers, specify options using worker underscored name:
#
# pass false to disable worker
#
# ImageOptim.new(:pngcrush => false)
#
# or hash with options to worker
#
# ImageOptim.new(:advpng => {:level => 3}, :optipng => {:level => 2})
#
# use :threads to set number of parallel optimizers to run (passing true or nil determines number of processors, false disables parallel processing)
#
# ImageOptim.new(:threads => 8)
#
# use :nice to specify optimizers nice level (true or nil makes it 10, false makes it 0)
#
# ImageOptim.new(:nice => 20)
def initialize(options = {})
@bin_resolver = BinResolver.new
config = Config.new(options)
@nice = config.nice
@threads = config.threads
@verbose = config.verbose
@workers_by_format = {}
Worker.klasses.each do |klass|
if worker_options = config.for_worker(klass)
worker = klass.new(self, worker_options)
worker.image_formats.each do |format|
@workers_by_format[format] ||= []
@workers_by_format[format] << worker
end
end
end
@workers_by_format.values.each(&:sort!)
config.assert_no_unused_options!
puts config if verbose?
end
# Get workers for image
def workers_for_image(path)
@workers_by_format[ImagePath.convert(path).format]
end
# Optimize one file, return new path as OptimizedImagePath or nil if optimization failed
def optimize_image(original)
original = ImagePath.convert(original)
if workers = workers_for_image(original)
handler = Handler.new(original)
workers.each do |worker|
handler.process do |src, dst|
worker.optimize(src, dst)
end
end
if handler.result
ImagePath::Optimized.new(handler.result, original)
end
end
end
# Optimize one file in place, return original as OptimizedImagePath or nil if optimization failed
def optimize_image!(original)
original = ImagePath.convert(original)
if result = optimize_image(original)
result.replace(original)
ImagePath::Optimized.new(original, result.original_size)
end
end
# Optimize image data, return new data or nil if optimization failed
def optimize_image_data(original_data)
format = ImageSize.new(original_data).format
ImagePath.temp_file %W[image_optim .#{format}] do |temp|
temp.binmode
temp.write(original_data)
temp.close
if result = optimize_image(temp.path)
result.open('rb', &:read)
end
end
end
# Optimize multiple images
# if block given yields path and result for each image and returns array of yield results
# else return array of results
def optimize_images(paths, &block)
run_method_for(paths, :optimize_image, &block)
end
# Optimize multiple images in place
# if block given yields path and result for each image and returns array of yield results
# else return array of results
def optimize_images!(paths, &block)
run_method_for(paths, :optimize_image!, &block)
end
# Optimize multiple image datas
# if block given yields original and result for each image data and returns array of yield results
# else return array of results
def optimize_images_data(datas, &block)
run_method_for(datas, :optimize_image_data, &block)
end
# Optimization methods with default options
def self.method_missing(method, *args, &block)
if method_defined?(method) && method.to_s =~ /^optimize_image/
new.send(method, *args, &block)
else
super
end
end
# Version of image_optim gem spec loaded
def self.version
Gem.loaded_specs['image_optim'].version.to_s rescue 'DEV'
end
# Are there workers for file at path?
def optimizable?(path)
!!workers_for_image(path)
end
# Check existance of binary, create symlink if ENV contains path for key XXX_BIN where XXX is upper case bin name
def resolve_bin!(bin)
@bin_resolver.resolve!(bin)
end
# Join resolve_dir, default path and vendor path for PATH environment variable
def env_path
@bin_resolver.env_path
end
private
# Run method for each path and yield each path and result if block given
def run_method_for(paths, method_name, &block)
apply_threading(paths).map do |path|
result = send(method_name, path)
if block
block.call(path, result)
else
result
end
end
end
# Apply threading if threading is allowed
def apply_threading(enum)
if threads > 1
enum.in_threads(threads)
else
enum
end
end
end
%w[
pngcrush pngout optipng advpng
jhead jpegoptim jpegtran
gifsicle
svgo
].each do |worker|
require "image_optim/worker/#{worker}"
end
require 'image_optim/railtie' if defined?(Rails)
|
module IndexPager
def index
controller = self.controller_name.downcase
model_name=controller.classify
model_class=eval(model_name)
objects = eval("@"+controller)
objects.size
@hidden=0
params[:page] ||= Seek::Config.default_page(controller)
objects=model_class.paginate_after_fetch(objects, :page=>params[:page],
:latest_limit => Seek::Config.limit_latest
) unless objects.respond_to?("page_totals")
eval("@"+controller+"= objects")
respond_to do |format|
format.html
format.xml
end
end
def find_assets
controller = self.controller_name.downcase
model_class=controller.classify.constantize
if model_class.respond_to? :all_authorized_for
found = model_class.all_authorized_for "view",User.current_user
else
found = model_class.default_order
end
found = apply_filters(found)
eval("@" + controller + " = found")
end
end
add facet plugable configuration to index pager
module IndexPager
def index
controller = self.controller_name.downcase
unless Seek::Config.facet_enable_for_pages[controller]
model_name=controller.classify
model_class=eval(model_name)
objects = eval("@"+controller)
objects.size
@hidden=0
params[:page] ||= Seek::Config.default_page(controller)
objects=model_class.paginate_after_fetch(objects, :page=>params[:page],
:latest_limit => Seek::Config.limit_latest
) unless objects.respond_to?("page_totals")
eval("@"+controller+"= objects")
end
respond_to do |format|
format.html
format.xml
end
end
def find_assets
controller = self.controller_name.downcase
model_class=controller.classify.constantize
if model_class.respond_to? :all_authorized_for
found = model_class.all_authorized_for "view",User.current_user
else
found = model_class.default_order
end
found = apply_filters(found)
eval("@" + controller + " = found")
end
end |
require 'log4r'
require "vagrant/util/platform"
require File.expand_path("../base", __FILE__)
module VagrantPlugins
module ProviderVirtualBox
module Driver
# Driver for VirtualBox 5.0.x
class Version_5_0 < Base
def initialize(uuid)
super()
@logger = Log4r::Logger.new("vagrant::provider::virtualbox_5_0")
@uuid = uuid
end
def clear_forwarded_ports
args = []
read_forwarded_ports(@uuid).each do |nic, name, _, _|
args.concat(["--natpf#{nic}", "delete", name])
end
execute("modifyvm", @uuid, *args) if !args.empty?
end
def clear_shared_folders
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
if line =~ /^SharedFolderNameMachineMapping\d+="(.+?)"$/
execute("sharedfolder", "remove", @uuid, "--name", $1.to_s)
end
end
end
def create_dhcp_server(network, options)
execute("dhcpserver", "add", "--ifname", network,
"--ip", options[:dhcp_ip],
"--netmask", options[:netmask],
"--lowerip", options[:dhcp_lower],
"--upperip", options[:dhcp_upper],
"--enable")
end
def create_host_only_network(options)
# Create the interface
execute("hostonlyif", "create") =~ /^Interface '(.+?)' was successfully created$/
name = $1.to_s
# Configure it
execute("hostonlyif", "ipconfig", name,
"--ip", options[:adapter_ip],
"--netmask", options[:netmask])
# Return the details
return {
name: name,
ip: options[:adapter_ip],
netmask: options[:netmask],
dhcp: nil
}
end
def delete
execute("unregistervm", @uuid, "--delete")
end
def delete_unused_host_only_networks
networks = []
execute("list", "hostonlyifs", retryable: true).split("\n").each do |line|
networks << $1.to_s if line =~ /^Name:\s+(.+?)$/
end
execute("list", "vms", retryable: true).split("\n").each do |line|
if line =~ /^".+?"\s+\{(.+?)\}$/
info = execute("showvminfo", $1.to_s, "--machinereadable", retryable: true)
info.split("\n").each do |inner_line|
if inner_line =~ /^hostonlyadapter\d+="(.+?)"$/
networks.delete($1.to_s)
end
end
end
end
networks.each do |name|
# First try to remove any DHCP servers attached. We use `raw` because
# it is okay if this fails. It usually means that a DHCP server was
# never attached.
raw("dhcpserver", "remove", "--ifname", name)
# Delete the actual host only network interface.
execute("hostonlyif", "remove", name)
end
end
def discard_saved_state
execute("discardstate", @uuid)
end
def enable_adapters(adapters)
args = []
adapters.each do |adapter|
args.concat(["--nic#{adapter[:adapter]}", adapter[:type].to_s])
if adapter[:bridge]
args.concat(["--bridgeadapter#{adapter[:adapter]}",
adapter[:bridge], "--cableconnected#{adapter[:adapter]}", "on"])
end
if adapter[:hostonly]
args.concat(["--hostonlyadapter#{adapter[:adapter]}",
adapter[:hostonly], "--cableconnected#{adapter[:adapter]}", "on"])
end
if adapter[:intnet]
args.concat(["--intnet#{adapter[:adapter]}",
adapter[:intnet], "--cableconnected#{adapter[:adapter]}", "on"])
end
if adapter[:mac_address]
args.concat(["--macaddress#{adapter[:adapter]}",
adapter[:mac_address]])
end
if adapter[:nic_type]
args.concat(["--nictype#{adapter[:adapter]}", adapter[:nic_type].to_s])
end
end
execute("modifyvm", @uuid, *args)
end
def execute_command(command)
execute(*command)
end
def export(path)
execute("export", @uuid, "--output", path.to_s)
end
def forward_ports(ports)
args = []
ports.each do |options|
pf_builder = [options[:name],
options[:protocol] || "tcp",
options[:hostip] || "",
options[:hostport],
options[:guestip] || "",
options[:guestport]]
args.concat(["--natpf#{options[:adapter] || 1}",
pf_builder.join(",")])
end
execute("modifyvm", @uuid, *args) if !args.empty?
end
def halt
execute("controlvm", @uuid, "poweroff")
end
def import(ovf)
ovf = Vagrant::Util::Platform.cygwin_windows_path(ovf)
output = ""
total = ""
last = 0
# Dry-run the import to get the suggested name and path
@logger.debug("Doing dry-run import to determine parallel-safe name...")
output = execute("import", "-n", ovf)
result = /Suggested VM name "(.+?)"/.match(output)
if !result
raise Vagrant::Errors::VirtualBoxNoName, output: output
end
suggested_name = result[1].to_s
# Append millisecond plus a random to the path in case we're
# importing the same box elsewhere.
specified_name = "#{suggested_name}_#{(Time.now.to_f * 1000.0).to_i}_#{rand(100000)}"
@logger.debug("-- Parallel safe name: #{specified_name}")
# Build the specified name param list
name_params = [
"--vsys", "0",
"--vmname", specified_name,
]
# Extract the disks list and build the disk target params
disk_params = []
disks = output.scan(/(\d+): Hard disk image: source image=.+, target path=(.+),/)
disks.each do |unit_num, path|
disk_params << "--vsys"
disk_params << "0"
disk_params << "--unit"
disk_params << unit_num
disk_params << "--disk"
if Vagrant::Util::Platform.windows?
# we use the block form of sub here to ensure that if the specified_name happens to end with a number (which is fairly likely) then
# we won't end up having the character sequence of a \ followed by a number be interpreted as a back reference. For example, if
# specified_name were "abc123", then "\\abc123\\".reverse would be "\\321cba\\", and the \3 would be treated as a back reference by the sub
disk_params << path.reverse.sub("\\#{suggested_name}\\".reverse) { "\\#{specified_name}\\".reverse }.reverse # Replace only last occurrence
else
disk_params << path.reverse.sub("/#{suggested_name}/".reverse, "/#{specified_name}/".reverse).reverse # Replace only last occurrence
end
end
execute("import", ovf , *name_params, *disk_params) do |type, data|
if type == :stdout
# Keep track of the stdout so that we can get the VM name
output << data
elsif type == :stderr
# Append the data so we can see the full view
total << data.gsub("\r", "")
# Break up the lines. We can't get the progress until we see an "OK"
lines = total.split("\n")
if lines.include?("OK.")
# The progress of the import will be in the last line. Do a greedy
# regular expression to find what we're looking for.
match = /.+(\d{2})%/.match(lines.last)
if match
current = match[1].to_i
if current > last
last = current
yield current if block_given?
end
end
end
end
end
output = execute("list", "vms", retryable: true)
match = /^"#{Regexp.escape(specified_name)}" \{(.+?)\}$/.match(output)
return match[1].to_s if match
nil
end
def max_network_adapters
36
end
def read_forwarded_ports(uuid=nil, active_only=false)
uuid ||= @uuid
@logger.debug("read_forward_ports: uuid=#{uuid} active_only=#{active_only}")
results = []
current_nic = nil
info = execute("showvminfo", uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
# This is how we find the nic that a FP is attached to,
# since this comes first.
current_nic = $1.to_i if line =~ /^nic(\d+)=".+?"$/
# If we care about active VMs only, then we check the state
# to verify the VM is running.
if active_only && line =~ /^VMState="(.+?)"$/ && $1.to_s != "running"
return []
end
# Parse out the forwarded port information
if line =~ /^Forwarding.+?="(.+?),.+?,.*?,(.+?),.*?,(.+?)"$/
result = [current_nic, $1.to_s, $2.to_i, $3.to_i]
@logger.debug(" - #{result.inspect}")
results << result
end
end
results
end
def read_bridged_interfaces
execute("list", "bridgedifs").split("\n\n").collect do |block|
info = {}
block.split("\n").each do |line|
if line =~ /^Name:\s+(.+?)$/
info[:name] = $1.to_s
elsif line =~ /^IPAddress:\s+(.+?)$/
info[:ip] = $1.to_s
elsif line =~ /^NetworkMask:\s+(.+?)$/
info[:netmask] = $1.to_s
elsif line =~ /^Status:\s+(.+?)$/
info[:status] = $1.to_s
end
end
# Return the info to build up the results
info
end
end
def read_dhcp_servers
execute("list", "dhcpservers", retryable: true).split("\n\n").collect do |block|
info = {}
block.split("\n").each do |line|
if network = line[/^NetworkName:\s+HostInterfaceNetworking-(.+?)$/, 1]
info[:network] = network
info[:network_name] = "HostInterfaceNetworking-#{network}"
elsif ip = line[/^IP:\s+(.+?)$/, 1]
info[:ip] = ip
elsif netmask = line[/^NetworkMask:\s+(.+?)$/, 1]
info[:netmask] = netmask
elsif lower = line[/^lowerIPAddress:\s+(.+?)$/, 1]
info[:lower] = lower
elsif upper = line[/^upperIPAddress:\s+(.+?)$/, 1]
info[:upper] = upper
end
end
info
end
end
def read_guest_additions_version
output = execute("guestproperty", "get", @uuid, "/VirtualBox/GuestAdd/Version",
retryable: true)
if output =~ /^Value: (.+?)$/
# Split the version by _ since some distro versions modify it
# to look like this: 4.1.2_ubuntu, and the distro part isn't
# too important.
value = $1.to_s
return value.split("_").first
end
# If we can't get the guest additions version by guest property, try
# to get it from the VM info itself.
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
return $1.to_s if line =~ /^GuestAdditionsVersion="(.+?)"$/
end
return nil
end
def read_guest_ip(adapter_number)
ip = read_guest_property("/VirtualBox/GuestInfo/Net/#{adapter_number}/V4/IP")
if !valid_ip_address?(ip)
raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound,
guest_property: "/VirtualBox/GuestInfo/Net/#{adapter_number}/V4/IP"
end
return ip
end
def read_guest_property(property)
output = execute("guestproperty", "get", @uuid, property)
if output =~ /^Value: (.+?)$/
$1.to_s
else
raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: property
end
end
def read_host_only_interfaces
execute("list", "hostonlyifs", retryable: true).split("\n\n").collect do |block|
info = {}
block.split("\n").each do |line|
if line =~ /^Name:\s+(.+?)$/
info[:name] = $1.to_s
elsif line =~ /^IPAddress:\s+(.+?)$/
info[:ip] = $1.to_s
elsif line =~ /^NetworkMask:\s+(.+?)$/
info[:netmask] = $1.to_s
elsif line =~ /^Status:\s+(.+?)$/
info[:status] = $1.to_s
end
end
info
end
end
def read_mac_address
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
return $1.to_s if line =~ /^macaddress1="(.+?)"$/
end
nil
end
def read_mac_addresses
macs = {}
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
if matcher = /^macaddress(\d+)="(.+?)"$/.match(line)
adapter = matcher[1].to_i
mac = matcher[2].to_s
macs[adapter] = mac
end
end
macs
end
def read_machine_folder
execute("list", "systemproperties", retryable: true).split("\n").each do |line|
if line =~ /^Default machine folder:\s+(.+?)$/i
return $1.to_s
end
end
nil
end
def read_network_interfaces
nics = {}
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
if line =~ /^nic(\d+)="(.+?)"$/
adapter = $1.to_i
type = $2.to_sym
nics[adapter] ||= {}
nics[adapter][:type] = type
elsif line =~ /^hostonlyadapter(\d+)="(.+?)"$/
adapter = $1.to_i
network = $2.to_s
nics[adapter] ||= {}
nics[adapter][:hostonly] = network
elsif line =~ /^bridgeadapter(\d+)="(.+?)"$/
adapter = $1.to_i
network = $2.to_s
nics[adapter] ||= {}
nics[adapter][:bridge] = network
end
end
nics
end
def read_state
output = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
if output =~ /^name="<inaccessible>"$/
return :inaccessible
elsif output =~ /^VMState="(.+?)"$/
return $1.to_sym
end
nil
end
def read_used_ports
ports = []
execute("list", "vms", retryable: true).split("\n").each do |line|
if line =~ /^".+?" \{(.+?)\}$/
uuid = $1.to_s
# Ignore our own used ports
next if uuid == @uuid
read_forwarded_ports(uuid, true).each do |_, _, hostport, _|
ports << hostport
end
end
end
ports
end
def read_vms
results = {}
execute("list", "vms", retryable: true).split("\n").each do |line|
if line =~ /^"(.+?)" \{(.+?)\}$/
results[$1.to_s] = $2.to_s
end
end
results
end
def remove_dhcp_server(network_name)
execute("dhcpserver", "remove", "--netname", network_name)
end
def set_mac_address(mac)
execute("modifyvm", @uuid, "--macaddress1", mac)
end
def set_name(name)
execute("modifyvm", @uuid, "--name", name, retryable: true)
rescue Vagrant::Errors::VBoxManageError => e
raise if !e.extra_data[:stderr].include?("VERR_ALREADY_EXISTS")
# We got VERR_ALREADY_EXISTS. This means that we're renaming to
# a VM name that already exists. Raise a custom error.
raise Vagrant::Errors::VirtualBoxNameExists,
stderr: e.extra_data[:stderr]
end
def share_folders(folders)
folders.each do |folder|
args = ["--name",
folder[:name],
"--hostpath",
folder[:hostpath]]
args << "--transient" if folder.key?(:transient) && folder[:transient]
# Enable symlinks on the shared folder
execute("setextradata", @uuid, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{folder[:name]}", "1")
# Add the shared folder
execute("sharedfolder", "add", @uuid, *args)
end
end
def ssh_port(expected_port)
@logger.debug("Searching for SSH port: #{expected_port.inspect}")
# Look for the forwarded port only by comparing the guest port
read_forwarded_ports.each do |_, _, hostport, guestport|
return hostport if guestport == expected_port
end
nil
end
def resume
@logger.debug("Resuming paused VM...")
execute("controlvm", @uuid, "resume")
end
def start(mode)
command = ["startvm", @uuid, "--type", mode.to_s]
r = raw(*command)
if r.exit_code == 0 || r.stdout =~ /VM ".+?" has been successfully started/
# Some systems return an exit code 1 for some reason. For that
# we depend on the output.
return true
end
# If we reached this point then it didn't work out.
raise Vagrant::Errors::VBoxManageError,
command: command.inspect,
stderr: r.stderr
end
def suspend
execute("controlvm", @uuid, "savestate")
end
def unshare_folders(names)
names.each do |name|
begin
execute(
"sharedfolder", "remove", @uuid,
"--name", name,
"--transient")
execute(
"setextradata", @uuid,
"VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{name}")
rescue Vagrant::Errors::VBoxManageError => e
if e.extra_data[:stderr].include?("VBOX_E_FILE_ERROR")
# The folder doesn't exist. ignore.
else
raise
end
end
end
end
def verify!
# This command sometimes fails if kernel drivers aren't properly loaded
# so we just run the command and verify that it succeeded.
execute("list", "hostonlyifs", retryable: true)
end
def verify_image(path)
r = raw("import", path.to_s, "--dry-run")
return r.exit_code == 0
end
def vm_exists?(uuid)
5.times do |i|
result = raw("showvminfo", uuid)
return true if result.exit_code == 0
# GH-2479: Sometimes this happens. In this case, retry. If
# we don't see this text, the VM really probably doesn't exist.
return false if !result.stderr.include?("CO_E_SERVER_EXEC_FAILURE")
# Sleep a bit though to give VirtualBox time to fix itself
sleep 2
end
# If we reach this point, it means that we consistently got the
# failure, do a standard vboxmanage now. This will raise an
# exception if it fails again.
execute("showvminfo", uuid)
return true
end
protected
def valid_ip_address?(ip)
# Filter out invalid IP addresses
# GH-4658 VirtualBox can report an IP address of 0.0.0.0 for FreeBSD guests.
if ip == "0.0.0.0"
return false
else
return true
end
end
end
end
end
end
Port changes from pull request #5495 to the vb_5 module to fix #4815 here, too.
require 'log4r'
require "vagrant/util/platform"
require File.expand_path("../base", __FILE__)
module VagrantPlugins
module ProviderVirtualBox
module Driver
# Driver for VirtualBox 5.0.x
class Version_5_0 < Base
def initialize(uuid)
super()
@logger = Log4r::Logger.new("vagrant::provider::virtualbox_5_0")
@uuid = uuid
end
def clear_forwarded_ports
args = []
read_forwarded_ports(@uuid).each do |nic, name, _, _|
args.concat(["--natpf#{nic}", "delete", name])
end
execute("modifyvm", @uuid, *args) if !args.empty?
end
def clear_shared_folders
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
if line =~ /^SharedFolderNameMachineMapping\d+="(.+?)"$/
execute("sharedfolder", "remove", @uuid, "--name", $1.to_s)
end
end
end
def create_dhcp_server(network, options)
execute("dhcpserver", "add", "--ifname", network,
"--ip", options[:dhcp_ip],
"--netmask", options[:netmask],
"--lowerip", options[:dhcp_lower],
"--upperip", options[:dhcp_upper],
"--enable")
end
def create_host_only_network(options)
# Create the interface
execute("hostonlyif", "create") =~ /^Interface '(.+?)' was successfully created$/
name = $1.to_s
# Configure it
execute("hostonlyif", "ipconfig", name,
"--ip", options[:adapter_ip],
"--netmask", options[:netmask])
# Return the details
return {
name: name,
ip: options[:adapter_ip],
netmask: options[:netmask],
dhcp: nil
}
end
def delete
execute("unregistervm", @uuid, "--delete")
end
def delete_unused_host_only_networks
networks = []
execute("list", "hostonlyifs", retryable: true).split("\n").each do |line|
networks << $1.to_s if line =~ /^Name:\s+(.+?)$/
end
execute("list", "vms", retryable: true).split("\n").each do |line|
if line =~ /^".+?"\s+\{(.+?)\}$/
info = execute("showvminfo", $1.to_s, "--machinereadable", retryable: true)
info.split("\n").each do |inner_line|
if inner_line =~ /^hostonlyadapter\d+="(.+?)"$/
networks.delete($1.to_s)
end
end
end
end
networks.each do |name|
# First try to remove any DHCP servers attached. We use `raw` because
# it is okay if this fails. It usually means that a DHCP server was
# never attached.
raw("dhcpserver", "remove", "--ifname", name)
# Delete the actual host only network interface.
execute("hostonlyif", "remove", name)
end
end
def discard_saved_state
execute("discardstate", @uuid)
end
def enable_adapters(adapters)
args = []
adapters.each do |adapter|
args.concat(["--nic#{adapter[:adapter]}", adapter[:type].to_s])
if adapter[:bridge]
args.concat(["--bridgeadapter#{adapter[:adapter]}",
adapter[:bridge], "--cableconnected#{adapter[:adapter]}", "on"])
end
if adapter[:hostonly]
args.concat(["--hostonlyadapter#{adapter[:adapter]}",
adapter[:hostonly], "--cableconnected#{adapter[:adapter]}", "on"])
end
if adapter[:intnet]
args.concat(["--intnet#{adapter[:adapter]}",
adapter[:intnet], "--cableconnected#{adapter[:adapter]}", "on"])
end
if adapter[:mac_address]
args.concat(["--macaddress#{adapter[:adapter]}",
adapter[:mac_address]])
end
if adapter[:nic_type]
args.concat(["--nictype#{adapter[:adapter]}", adapter[:nic_type].to_s])
end
end
execute("modifyvm", @uuid, *args)
end
def execute_command(command)
execute(*command)
end
def export(path)
execute("export", @uuid, "--output", path.to_s)
end
def forward_ports(ports)
args = []
ports.each do |options|
pf_builder = [options[:name],
options[:protocol] || "tcp",
options[:hostip] || "",
options[:hostport],
options[:guestip] || "",
options[:guestport]]
args.concat(["--natpf#{options[:adapter] || 1}",
pf_builder.join(",")])
end
execute("modifyvm", @uuid, *args) if !args.empty?
end
def halt
execute("controlvm", @uuid, "poweroff")
end
def import(ovf)
ovf = Vagrant::Util::Platform.cygwin_windows_path(ovf)
output = ""
total = ""
last = 0
# Dry-run the import to get the suggested name and path
@logger.debug("Doing dry-run import to determine parallel-safe name...")
output = execute("import", "-n", ovf)
result = /Suggested VM name "(.+?)"/.match(output)
if !result
raise Vagrant::Errors::VirtualBoxNoName, output: output
end
suggested_name = result[1].to_s
# Append millisecond plus a random to the path in case we're
# importing the same box elsewhere.
specified_name = "#{suggested_name}_#{(Time.now.to_f * 1000.0).to_i}_#{rand(100000)}"
@logger.debug("-- Parallel safe name: #{specified_name}")
# Build the specified name param list
name_params = [
"--vsys", "0",
"--vmname", specified_name,
]
# Extract the disks list and build the disk target params
disk_params = []
disks = output.scan(/(\d+): Hard disk image: source image=.+, target path=(.+),/)
disks.each do |unit_num, path|
disk_params << "--vsys"
disk_params << "0"
disk_params << "--unit"
disk_params << unit_num
disk_params << "--disk"
if Vagrant::Util::Platform.windows?
# we use the block form of sub here to ensure that if the specified_name happens to end with a number (which is fairly likely) then
# we won't end up having the character sequence of a \ followed by a number be interpreted as a back reference. For example, if
# specified_name were "abc123", then "\\abc123\\".reverse would be "\\321cba\\", and the \3 would be treated as a back reference by the sub
disk_params << path.reverse.sub("\\#{suggested_name}\\".reverse) { "\\#{specified_name}\\".reverse }.reverse # Replace only last occurrence
else
disk_params << path.reverse.sub("/#{suggested_name}/".reverse, "/#{specified_name}/".reverse).reverse # Replace only last occurrence
end
end
execute("import", ovf , *name_params, *disk_params) do |type, data|
if type == :stdout
# Keep track of the stdout so that we can get the VM name
output << data
elsif type == :stderr
# Append the data so we can see the full view
total << data.gsub("\r", "")
# Break up the lines. We can't get the progress until we see an "OK"
lines = total.split("\n")
if lines.include?("OK.")
# The progress of the import will be in the last line. Do a greedy
# regular expression to find what we're looking for.
match = /.+(\d{2})%/.match(lines.last)
if match
current = match[1].to_i
if current > last
last = current
yield current if block_given?
end
end
end
end
end
output = execute("list", "vms", retryable: true)
match = /^"#{Regexp.escape(specified_name)}" \{(.+?)\}$/.match(output)
return match[1].to_s if match
nil
end
def max_network_adapters
36
end
def read_forwarded_ports(uuid=nil, active_only=false)
uuid ||= @uuid
@logger.debug("read_forward_ports: uuid=#{uuid} active_only=#{active_only}")
results = []
current_nic = nil
info = execute("showvminfo", uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
# This is how we find the nic that a FP is attached to,
# since this comes first.
current_nic = $1.to_i if line =~ /^nic(\d+)=".+?"$/
# If we care about active VMs only, then we check the state
# to verify the VM is running.
if active_only && line =~ /^VMState="(.+?)"$/ && $1.to_s != "running"
return []
end
# Parse out the forwarded port information
if line =~ /^Forwarding.+?="(.+?),.+?,.*?,(.+?),.*?,(.+?)"$/
result = [current_nic, $1.to_s, $2.to_i, $3.to_i]
@logger.debug(" - #{result.inspect}")
results << result
end
end
results
end
def read_bridged_interfaces
execute("list", "bridgedifs").split("\n\n").collect do |block|
info = {}
block.split("\n").each do |line|
if line =~ /^Name:\s+(.+?)$/
info[:name] = $1.to_s
elsif line =~ /^IPAddress:\s+(.+?)$/
info[:ip] = $1.to_s
elsif line =~ /^NetworkMask:\s+(.+?)$/
info[:netmask] = $1.to_s
elsif line =~ /^Status:\s+(.+?)$/
info[:status] = $1.to_s
end
end
# Return the info to build up the results
info
end
end
def read_dhcp_servers
execute("list", "dhcpservers", retryable: true).split("\n\n").collect do |block|
info = {}
block.split("\n").each do |line|
if network = line[/^NetworkName:\s+HostInterfaceNetworking-(.+?)$/, 1]
info[:network] = network
info[:network_name] = "HostInterfaceNetworking-#{network}"
elsif ip = line[/^IP:\s+(.+?)$/, 1]
info[:ip] = ip
elsif netmask = line[/^NetworkMask:\s+(.+?)$/, 1]
info[:netmask] = netmask
elsif lower = line[/^lowerIPAddress:\s+(.+?)$/, 1]
info[:lower] = lower
elsif upper = line[/^upperIPAddress:\s+(.+?)$/, 1]
info[:upper] = upper
end
end
info
end
end
def read_guest_additions_version
output = execute("guestproperty", "get", @uuid, "/VirtualBox/GuestAdd/Version",
retryable: true)
if output =~ /^Value: (.+?)$/
# Split the version by _ since some distro versions modify it
# to look like this: 4.1.2_ubuntu, and the distro part isn't
# too important.
value = $1.to_s
return value.split("_").first
end
# If we can't get the guest additions version by guest property, try
# to get it from the VM info itself.
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
return $1.to_s if line =~ /^GuestAdditionsVersion="(.+?)"$/
end
return nil
end
def read_guest_ip(adapter_number)
ip = read_guest_property("/VirtualBox/GuestInfo/Net/#{adapter_number}/V4/IP")
if !valid_ip_address?(ip)
raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound,
guest_property: "/VirtualBox/GuestInfo/Net/#{adapter_number}/V4/IP"
end
return ip
end
def read_guest_property(property)
output = execute("guestproperty", "get", @uuid, property)
if output =~ /^Value: (.+?)$/
$1.to_s
else
raise Vagrant::Errors::VirtualBoxGuestPropertyNotFound, guest_property: property
end
end
def read_host_only_interfaces
execute("list", "hostonlyifs", retryable: true).split("\n\n").collect do |block|
info = {}
block.split("\n").each do |line|
if line =~ /^Name:\s+(.+?)$/
info[:name] = $1.to_s
elsif line =~ /^IPAddress:\s+(.+?)$/
info[:ip] = $1.to_s
elsif line =~ /^NetworkMask:\s+(.+?)$/
info[:netmask] = $1.to_s
elsif line =~ /^Status:\s+(.+?)$/
info[:status] = $1.to_s
end
end
info
end
end
def read_mac_address
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
return $1.to_s if line =~ /^macaddress1="(.+?)"$/
end
nil
end
def read_mac_addresses
macs = {}
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
if matcher = /^macaddress(\d+)="(.+?)"$/.match(line)
adapter = matcher[1].to_i
mac = matcher[2].to_s
macs[adapter] = mac
end
end
macs
end
def read_machine_folder
execute("list", "systemproperties", retryable: true).split("\n").each do |line|
if line =~ /^Default machine folder:\s+(.+?)$/i
return $1.to_s
end
end
nil
end
def read_network_interfaces
nics = {}
info = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
info.split("\n").each do |line|
if line =~ /^nic(\d+)="(.+?)"$/
adapter = $1.to_i
type = $2.to_sym
nics[adapter] ||= {}
nics[adapter][:type] = type
elsif line =~ /^hostonlyadapter(\d+)="(.+?)"$/
adapter = $1.to_i
network = $2.to_s
nics[adapter] ||= {}
nics[adapter][:hostonly] = network
elsif line =~ /^bridgeadapter(\d+)="(.+?)"$/
adapter = $1.to_i
network = $2.to_s
nics[adapter] ||= {}
nics[adapter][:bridge] = network
end
end
nics
end
def read_state
output = execute("showvminfo", @uuid, "--machinereadable", retryable: true)
if output =~ /^name="<inaccessible>"$/
return :inaccessible
elsif output =~ /^VMState="(.+?)"$/
return $1.to_sym
end
nil
end
def read_used_ports
ports = []
execute("list", "vms", retryable: true).split("\n").each do |line|
if line =~ /^".+?" \{(.+?)\}$/
uuid = $1.to_s
# Ignore our own used ports
next if uuid == @uuid
read_forwarded_ports(uuid, true).each do |_, _, hostport, _|
ports << hostport
end
end
end
ports
end
def read_vms
results = {}
execute("list", "vms", retryable: true).split("\n").each do |line|
if line =~ /^"(.+?)" \{(.+?)\}$/
results[$1.to_s] = $2.to_s
end
end
results
end
def remove_dhcp_server(network_name)
execute("dhcpserver", "remove", "--netname", network_name)
end
def set_mac_address(mac)
execute("modifyvm", @uuid, "--macaddress1", mac)
end
def set_name(name)
execute("modifyvm", @uuid, "--name", name, retryable: true)
rescue Vagrant::Errors::VBoxManageError => e
raise if !e.extra_data[:stderr].include?("VERR_ALREADY_EXISTS")
# We got VERR_ALREADY_EXISTS. This means that we're renaming to
# a VM name that already exists. Raise a custom error.
raise Vagrant::Errors::VirtualBoxNameExists,
stderr: e.extra_data[:stderr]
end
def share_folders(folders)
folders.each do |folder|
hostpath = folder[:hostpath]
if Vagrant::Util::Platform.windows?
hostpath = Vagrant::Util::Platform.windows_unc_path(hostpath)
end
args = ["--name",
folder[:name],
"--hostpath",
hostpath]
args << "--transient" if folder.key?(:transient) && folder[:transient]
# Enable symlinks on the shared folder
execute("setextradata", @uuid, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{folder[:name]}", "1")
# Add the shared folder
execute("sharedfolder", "add", @uuid, *args)
end
end
def ssh_port(expected_port)
@logger.debug("Searching for SSH port: #{expected_port.inspect}")
# Look for the forwarded port only by comparing the guest port
read_forwarded_ports.each do |_, _, hostport, guestport|
return hostport if guestport == expected_port
end
nil
end
def resume
@logger.debug("Resuming paused VM...")
execute("controlvm", @uuid, "resume")
end
def start(mode)
command = ["startvm", @uuid, "--type", mode.to_s]
r = raw(*command)
if r.exit_code == 0 || r.stdout =~ /VM ".+?" has been successfully started/
# Some systems return an exit code 1 for some reason. For that
# we depend on the output.
return true
end
# If we reached this point then it didn't work out.
raise Vagrant::Errors::VBoxManageError,
command: command.inspect,
stderr: r.stderr
end
def suspend
execute("controlvm", @uuid, "savestate")
end
def unshare_folders(names)
names.each do |name|
begin
execute(
"sharedfolder", "remove", @uuid,
"--name", name,
"--transient")
execute(
"setextradata", @uuid,
"VBoxInternal2/SharedFoldersEnableSymlinksCreate/#{name}")
rescue Vagrant::Errors::VBoxManageError => e
if e.extra_data[:stderr].include?("VBOX_E_FILE_ERROR")
# The folder doesn't exist. ignore.
else
raise
end
end
end
end
def verify!
# This command sometimes fails if kernel drivers aren't properly loaded
# so we just run the command and verify that it succeeded.
execute("list", "hostonlyifs", retryable: true)
end
def verify_image(path)
r = raw("import", path.to_s, "--dry-run")
return r.exit_code == 0
end
def vm_exists?(uuid)
5.times do |i|
result = raw("showvminfo", uuid)
return true if result.exit_code == 0
# GH-2479: Sometimes this happens. In this case, retry. If
# we don't see this text, the VM really probably doesn't exist.
return false if !result.stderr.include?("CO_E_SERVER_EXEC_FAILURE")
# Sleep a bit though to give VirtualBox time to fix itself
sleep 2
end
# If we reach this point, it means that we consistently got the
# failure, do a standard vboxmanage now. This will raise an
# exception if it fails again.
execute("showvminfo", uuid)
return true
end
protected
def valid_ip_address?(ip)
# Filter out invalid IP addresses
# GH-4658 VirtualBox can report an IP address of 0.0.0.0 for FreeBSD guests.
if ip == "0.0.0.0"
return false
else
return true
end
end
end
end
end
end
|
module Irrc
module Runner
def run(threads)
done = []
loop do
# NOTE: trick to avoid dead lock
if last_thread? && @queue.empty?
terminate
(threads - 1).times { @queue.push nil }
return done
end
query = @queue.pop
# NOTE: trick to avoid dead lock
if query.nil?
terminate
return done
end
connect unless established?
begin
logger.info "Processing: #{query.object}"
query = process(query)
query.success
query.children.each {|q| @queue << q }
rescue
logger.error "#{$!.message} when processing #{query.object} for #{query.root.object}"
query.fail
end
done << query if query.root?
end
end
private
def cache(object, sources, &block)
@cache["#{object}:#{sources}"] ||= yield
end
def execute(command)
return if command.nil? || command == ''
logger.debug "Executing: #{command}"
connection.cmd(command).tap {|result| logger.debug "Returned: #{result}" }
end
def last_thread?
Thread.list.reject(&:stop?).size == 1
end
def terminate
logger.info "No more queries"
close
end
end
end
Detail logs for debugging (with cosmetic changes on logs)
module Irrc
module Runner
def run(threads)
done = []
loop do
# NOTE: trick to avoid dead lock
if last_thread? && @queue.empty?
terminate
logger.debug "Queue #{threads - 1} guard objects"
(threads - 1).times { @queue.push nil }
return done
end
query = @queue.pop
# NOTE: trick to avoid dead lock
if query.nil?
terminate
return done
end
connect unless established?
begin
logger.info "Processing #{query.object}"
query = process(query)
query.success
logger.debug "Queue new #{query.children.size} queries"
query.children.each {|q| @queue << q }
rescue
logger.error "#{$!.message} when processing #{query.object} for #{query.root.object}"
query.fail
end
done << query if query.root?
end
end
private
def cache(object, sources, &block)
@cache["#{object}:#{sources}"] ||= yield
end
def execute(command)
return if command.nil? || command == ''
logger.debug %(Executing "#{command}")
connection.cmd(command).tap {|result| logger.debug %(Got "#{result}") }
end
def last_thread?
Thread.list.reject(&:stop?).size == 1
end
def terminate
logger.info "No more queries"
close
end
end
end
|
module Janky
# Web API taylored for Hubot's needs. Supports setting up and disabling
# repositories, querying the status of branch or a repository and triggering
# builds.
#
# The client side implementation is at
# <https://github.com/github/hubot-scripts/blob/master/src/scripts/janky.coffee>
class Hubot < Sinatra::Base
register Helpers
# Setup a new repository.
post "/setup" do
nwo = params["nwo"]
name = params["name"]
tmpl = params["template"]
repo = Repository.setup(nwo, name, tmpl)
if repo
url = "#{settings.base_url}#{repo.name}"
[201, "Setup #{repo.name} at #{repo.uri} with #{repo.job_config_path.basename} | #{url}"]
else
[400, "Couldn't access #{nwo}. Check the permissions."]
end
end
# Activate/deactivate auto-build for the given repository.
post "/toggle/:repo_name" do |repo_name|
repo = find_repo(repo_name)
status = repo.toggle_auto_build ? "enabled" : "disabled"
[200, "#{repo.name} is now #{status}"]
end
# Build a repository's branch.
post %r{\/([-_\.0-9a-zA-Z]+)\/([-_\.a-zA-z0-9\/]+)} do |repo_name, branch_name|
repo = find_repo(repo_name)
branch = repo.branch_for(branch_name)
room_id = (params["room_id"] rescue nil)
user = params["user"]
build = branch.head_build_for(room_id, user)
build ||= repo.build_sha(branch_name, user, room_id)
if build
build.run
[201, "Going ham on #{build.repo_name}/#{build.branch_name}"]
else
[404, "Unknown branch #{branch_name.inspect}. Push again"]
end
end
# Get a list of available rooms.
get "/rooms" do
Yajl.dump(ChatService.room_names)
end
# Update a repository's notification room.
put "/:repo_name" do |repo_name|
repo = find_repo(repo_name)
room = params["room"]
if room_id = ChatService.room_id(room)
repo.update_attributes!(:room_id => room_id)
[200, "Room for #{repo.name} updated to #{room}"]
else
[403, "Unknown room: #{room.inspect}"]
end
end
# Update a repository's context
put %r{\/([-_\.0-9a-zA-Z]+)\/context} do |repo_name|
context = params["context"]
repo = find_repo(repo_name)
if repo
repo.context = context
repo.save
[200, "Context #{context} set for #{repo_name}"]
else
[404, "Unknown Repository #{repo_name}"]
end
end
# Get the status of all projects.
get "/" do
content_type "text/plain"
repos = Repository.all(:include => [:branches, :commits, :builds]).map do |repo|
master = repo.branch_for("master")
"%-17s %-13s %-10s %40s" % [
repo.name,
master.status,
repo.campfire_room,
repo.uri
]
end
repos.join("\n")
end
# Get the lasts builds
get "/builds" do
limit = params["limit"]
building = params["building"]
builds = Build.unscoped
if building.blank? || building == 'false'
builds = builds.completed
else
builds = builds.building
end
builds = builds.limit(limit) unless limit.blank?
builds.map! do |build|
build_to_hash(build)
end
builds.to_json
end
# Get information about how a project is configured
get %r{\/show\/([-_\.0-9a-zA-Z]+)} do |repo_name|
repo = find_repo(repo_name)
res = {
:name => repo.name,
:configured_job_template => repo.job_template,
:used_job_template => repo.job_config_path.basename.to_s,
:repo => repo.uri,
:room_id => repo.room_id,
:enabled => repo.enabled,
:hook_url => repo.hook_url,
:context => repo.context
}
res.to_json
end
delete %r{\/([-_\.0-9a-zA-Z]+)} do |repo_name|
repo = find_repo(repo_name)
repo.destroy
"Janky project #{repo_name} deleted"
end
# Delete a repository's context
delete %r{\/([-_\.0-9a-zA-Z]+)\/context} do |repo_name|
repo = find_repo(repo_name)
if repo
repo.context = nil
repo.save
[200, "Context removed for #{repo_name}"]
else
[404, "Unknown Repository #{repo_name}"]
end
end
# Get the status of a repository's branch.
get %r{\/([-_\.0-9a-zA-Z]+)\/([-_\+\.a-zA-z0-9\/]+)} do |repo_name, branch_name|
limit = params["limit"]
repo = find_repo(repo_name)
branch = repo.branch_for(branch_name)
builds = branch.queued_builds.limit(limit).map do |build|
build_to_hash(build)
end
builds.to_json
end
# Learn everything you need to know about Janky.
get "/help" do
content_type "text/plain"
<<-EOS
ci build janky
ci build janky/fix-everything
ci setup github/janky [name]
ci setup github/janky name template
ci toggle janky
ci rooms
ci set room janky development
ci set context janky ci/janky
ci unset context janky
ci status
ci status janky
ci status janky/master
ci builds limit [building]
ci show janky
ci delete janky
EOS
end
get "/boomtown" do
fail "BOOM (janky)"
end
private
def build_to_hash(build)
{ :sha1 => build.sha1,
:repo => build.repo_name,
:branch => build.branch_name,
:user => build.user,
:green => build.green?,
:building => build.building?,
:queued => build.queued?,
:pending => build.pending?,
:number => build.number,
:status => (build.green? ? "was successful" : "failed"),
:compare => build.compare,
:duration => build.duration,
:web_url => build.web_url }
end
end
end
Make all of the hubot messages more consistent in style and grammatical correctness.
module Janky
# Web API taylored for Hubot's needs. Supports setting up and disabling
# repositories, querying the status of branch or a repository and triggering
# builds.
#
# The client side implementation is at
# <https://github.com/github/hubot-scripts/blob/master/src/scripts/janky.coffee>
class Hubot < Sinatra::Base
register Helpers
# Setup a new repository.
post "/setup" do
nwo = params["nwo"]
name = params["name"]
tmpl = params["template"]
repo = Repository.setup(nwo, name, tmpl)
if repo
url = "#{settings.base_url}#{repo.name}"
[201, "Set up repo `#{repo.name}` (#{repo.uri}) with template `#{repo.job_config_path.basename}` at #{url}."]
else
[400, "Couldn't access #{nwo}; check its permissions."]
end
end
# Activate/deactivate auto-build for the given repository.
post "/toggle/:repo_name" do |repo_name|
repo = find_repo(repo_name)
status = repo.toggle_auto_build ? "enabled" : "disabled"
[200, "#{repo.name} is now #{status}."]
end
# Build a repository's branch.
post %r{\/([-_\.0-9a-zA-Z]+)\/([-_\.a-zA-z0-9\/]+)} do |repo_name, branch_name|
repo = find_repo(repo_name)
branch = repo.branch_for(branch_name)
room_id = (params["room_id"] rescue nil)
user = params["user"]
build = branch.head_build_for(room_id, user)
build ||= repo.build_sha(branch_name, user, room_id)
if build
build.run
[201, "Going to town on `#{build.repo_name}/#{build.branch_name}`..."]
else
[404, "Unknown branch `#{branch_name.inspect}`; make sure you've actually pushed it."]
end
end
# Get a list of available rooms.
get "/rooms" do
Yajl.dump(ChatService.room_names)
end
# Update a repository's notification room.
put "/:repo_name" do |repo_name|
repo = find_repo(repo_name)
room = params["room"]
if room_id = ChatService.room_id(room)
repo.update_attributes!(:room_id => room_id)
[200, "Room for repository `#{repo.name}` updated to `#{room}`."]
else
[403, "Unknown room `#{room.inspect}`."]
end
end
# Update a repository's context
put %r{\/([-_\.0-9a-zA-Z]+)\/context} do |repo_name|
context = params["context"]
repo = find_repo(repo_name)
if repo
repo.context = context
repo.save
[200, "Context `#{context}` set for `#{repo_name}`."]
else
[404, "Unknown repo `#{repo_name}`."]
end
end
# Get the status of all projects.
get "/" do
content_type "text/plain"
repos = Repository.all(:include => [:branches, :commits, :builds]).map do |repo|
master = repo.branch_for("master")
"%-17s %-13s %-10s %40s" % [
repo.name,
master.status,
repo.campfire_room,
repo.uri
]
end
repos.join("\n")
end
# Get the lasts builds
get "/builds" do
limit = params["limit"]
building = params["building"]
builds = Build.unscoped
if building.blank? || building == 'false'
builds = builds.completed
else
builds = builds.building
end
builds = builds.limit(limit) unless limit.blank?
builds.map! do |build|
build_to_hash(build)
end
builds.to_json
end
# Get information about how a project is configured
get %r{\/show\/([-_\.0-9a-zA-Z]+)} do |repo_name|
repo = find_repo(repo_name)
res = {
:name => repo.name,
:configured_job_template => repo.job_template,
:used_job_template => repo.job_config_path.basename.to_s,
:repo => repo.uri,
:room_id => repo.room_id,
:enabled => repo.enabled,
:hook_url => repo.hook_url,
:context => repo.context
}
res.to_json
end
delete %r{\/([-_\.0-9a-zA-Z]+)} do |repo_name|
repo = find_repo(repo_name)
repo.destroy
"Repo `#{repo_name}` successfully unlinked from Janky."
end
# Delete a repository's context
delete %r{\/([-_\.0-9a-zA-Z]+)\/context} do |repo_name|
repo = find_repo(repo_name)
if repo
repo.context = nil
repo.save
[200, "Context removed for repo `#{repo_name}`."]
else
[404, "Unknown repo `#{repo_name}`."]
end
end
# Get the status of a repository's branch.
get %r{\/([-_\.0-9a-zA-Z]+)\/([-_\+\.a-zA-z0-9\/]+)} do |repo_name, branch_name|
limit = params["limit"]
repo = find_repo(repo_name)
branch = repo.branch_for(branch_name)
builds = branch.queued_builds.limit(limit).map do |build|
build_to_hash(build)
end
builds.to_json
end
# Learn everything you need to know about Janky.
get "/help" do
content_type "text/plain"
<<-EOS
ci build janky
ci build janky/fix-everything
ci setup github/janky [name]
ci setup github/janky name template
ci toggle janky
ci rooms
ci set room janky development
ci set context janky ci/janky
ci unset context janky
ci status
ci status janky
ci status janky/master
ci builds limit [building]
ci show janky
ci delete janky
EOS
end
get "/boomtown" do
fail "BOOM (janky)"
end
private
def build_to_hash(build)
{ :sha1 => build.sha1,
:repo => build.repo_name,
:branch => build.branch_name,
:user => build.user,
:green => build.green?,
:building => build.building?,
:queued => build.queued?,
:pending => build.pending?,
:number => build.number,
:status => (build.green? ? "was successful" : "failed"),
:compare => build.compare,
:duration => build.duration,
:web_url => build.web_url }
end
end
end
|
module Jdl
VERSION = "0.0.4"
end
add version
module Jdl
VERSION = "0.0.5"
end
|
# encoding: UTF-8
require 'csv'
module Jekyll
class Site
attr_accessor :config, :layouts, :posts, :pages, :static_files,
:exclude, :include, :source, :dest, :lsi, :highlighter,
:permalink_style, :time, :future, :unpublished, :safe, :plugins, :limit_posts,
:show_drafts, :keep_files, :baseurl, :data, :file_read_opts, :gems,
:plugin_manager
attr_accessor :converters, :generators
# Public: Initialize a new Site.
#
# config - A Hash containing site configuration details.
def initialize(config)
self.config = config.clone
%w[safe lsi highlighter baseurl exclude include future unpublished
show_drafts limit_posts keep_files gems].each do |opt|
self.send("#{opt}=", config[opt])
end
self.source = File.expand_path(config['source'])
self.dest = File.expand_path(config['destination'])
self.permalink_style = config['permalink'].to_sym
self.plugin_manager = Jekyll::PluginManager.new(self)
self.plugins = plugin_manager.plugins_path
self.file_read_opts = {}
self.file_read_opts[:encoding] = config['encoding'] if config['encoding']
reset
setup
end
# Public: Read, process, and write this Site to output.
#
# Returns nothing.
def process
reset
read
generate
render
cleanup
write
end
# Reset Site details.
#
# Returns nothing
def reset
self.time = (config['time'] ? Utils.parse_date(config['time'].to_s, "Invalid time in _config.yml.") : Time.now)
self.layouts = {}
self.posts = []
self.pages = []
self.static_files = []
self.data = {}
@collections = nil
if limit_posts < 0
raise ArgumentError, "limit_posts must be a non-negative number"
end
end
# Load necessary libraries, plugins, converters, and generators.
#
# Returns nothing.
def setup
ensure_not_in_dest
plugin_manager.conscientious_require
self.converters = instantiate_subclasses(Jekyll::Converter)
self.generators = instantiate_subclasses(Jekyll::Generator)
end
# Check that the destination dir isn't the source dir or a directory
# parent to the source dir.
def ensure_not_in_dest
dest_pathname = Pathname.new(dest)
Pathname.new(source).ascend do |path|
if path == dest_pathname
raise Errors::FatalException.new "Destination directory cannot be or contain the Source directory."
end
end
end
# The list of collections and their corresponding Jekyll::Collection instances.
# If config['collections'] is set, a new instance is created for each item in the collection.
# If config['collections'] is not set, a new hash is returned.
#
# Returns a Hash containing collection name-to-instance pairs.
def collections
@collections ||= Hash[collection_names.map { |coll| [coll, Jekyll::Collection.new(self, coll)] } ]
end
# The list of collection names.
#
# Returns an array of collection names from the configuration,
# or an empty array if the `collections` key is not set.
def collection_names
case config['collections']
when Hash
config['collections'].keys
when Array
config['collections']
when nil
[]
else
raise ArgumentError, "Your `collections` key must be a hash or an array."
end
end
# Read Site data from disk and load it into internal data structures.
#
# Returns nothing.
def read
self.layouts = LayoutReader.new(self).read
read_directories
read_data(config['data_source'])
read_collections
end
# Recursively traverse directories to find posts, pages and static files
# that will become part of the site according to the rules in
# filter_entries.
#
# dir - The String relative path of the directory to read. Default: ''.
#
# Returns nothing.
def read_directories(dir = '')
base = File.join(source, dir)
entries = Dir.chdir(base) { filter_entries(Dir.entries('.'), base) }
read_posts(dir)
read_drafts(dir) if show_drafts
posts.sort!
limit_posts! if limit_posts > 0 # limit the posts if :limit_posts option is set
entries.each do |f|
f_abs = File.join(base, f)
if File.directory?(f_abs)
f_rel = File.join(dir, f)
read_directories(f_rel) unless dest.sub(/\/$/, '') == f_abs
elsif Utils.has_yaml_header?(f_abs)
page = Page.new(self, source, dir, f)
pages << page if publisher.publish?(page)
else
static_files << StaticFile.new(self, source, dir, f)
end
end
pages.sort_by!(&:name)
end
# Read all the files in <source>/<dir>/_posts and create a new Post
# object with each one.
#
# dir - The String relative path of the directory to read.
#
# Returns nothing.
def read_posts(dir)
posts = read_content(dir, '_posts', Post)
posts.each do |post|
aggregate_post_info(post) if publisher.publish?(post)
end
end
# Read all the files in <source>/<dir>/_drafts and create a new Post
# object with each one.
#
# dir - The String relative path of the directory to read.
#
# Returns nothing.
def read_drafts(dir)
drafts = read_content(dir, '_drafts', Draft)
drafts.each do |draft|
if draft.published?
aggregate_post_info(draft)
end
end
end
def read_content(dir, magic_dir, klass)
get_entries(dir, magic_dir).map do |entry|
klass.new(self, source, dir, entry) if klass.valid?(entry)
end.reject do |entry|
entry.nil?
end
end
# Read and parse all yaml files under <source>/<dir>
#
# Returns nothing
def read_data(dir)
base = Jekyll.sanitized_path(source, dir)
read_data_to(base, self.data)
end
# Read and parse all yaml files under <dir> and add them to the
# <data> variable.
#
# dir - The string absolute path of the directory to read.
# data - The variable to which data will be added.
#
# Returns nothing
def read_data_to(dir, data)
return unless File.directory?(dir) && (!safe || !File.symlink?(dir))
entries = Dir.chdir(dir) do
Dir['*.{yaml,yml,json,csv}'] + Dir['*'].select { |fn| File.directory?(fn) }
end
entries.each do |entry|
path = Jekyll.sanitized_path(dir, entry)
next if File.symlink?(path) && safe
key = sanitize_filename(File.basename(entry, '.*'))
if File.directory?(path)
read_data_to(path, data[key] = {})
else
case File.extname(path).downcase
when '.csv'
data[key] = CSV.read(path, headers: true).map(&:to_hash)
else
data[key] = SafeYAML.load_file(path)
end
end
end
end
# Read in all collections specified in the configuration
#
# Returns nothing.
def read_collections
collections.each do |_, collection|
collection.read unless collection.label.eql?("data")
end
end
# Run each of the Generators.
#
# Returns nothing.
def generate
generators.each do |generator|
generator.generate(self)
end
end
# Render the site to the destination.
#
# Returns nothing.
def render
relative_permalinks_deprecation_method
collections.each do |label, collection|
collection.docs.each do |document|
document.output = Jekyll::Renderer.new(self, document).run
end
end
payload = site_payload
[posts, pages].flatten.each do |page_or_post|
page_or_post.render(layouts, payload)
end
rescue Errno::ENOENT => e
# ignore missing layout dir
end
# Remove orphaned files and empty directories in destination.
#
# Returns nothing.
def cleanup
site_cleaner.cleanup!
end
# Write static files, pages, and posts.
#
# Returns nothing.
def write
each_site_file { |item| item.write(dest) }
end
# Construct a Hash of Posts indexed by the specified Post attribute.
#
# post_attr - The String name of the Post attribute.
#
# Examples
#
# post_attr_hash('categories')
# # => { 'tech' => [<Post A>, <Post B>],
# # 'ruby' => [<Post B>] }
#
# Returns the Hash: { attr => posts } where
# attr - One of the values for the requested attribute.
# posts - The Array of Posts with the given attr value.
def post_attr_hash(post_attr)
# Build a hash map based on the specified post attribute ( post attr =>
# array of posts ) then sort each array in reverse order.
hash = Hash.new { |h, key| h[key] = [] }
posts.each { |p| p.send(post_attr.to_sym).each { |t| hash[t] << p } }
hash.values.each { |posts| posts.sort!.reverse! }
hash
end
def tags
post_attr_hash('tags')
end
def categories
post_attr_hash('categories')
end
# Prepare site data for site payload. The method maintains backward compatibility
# if the key 'data' is already used in _config.yml.
#
# Returns the Hash to be hooked to site.data.
def site_data
config['data'] || data
end
# The Hash payload containing site-wide data.
#
# Returns the Hash: { "site" => data } where data is a Hash with keys:
# "time" - The Time as specified in the configuration or the
# current time if none was specified.
# "posts" - The Array of Posts, sorted chronologically by post date
# and then title.
# "pages" - The Array of all Pages.
# "html_pages" - The Array of HTML Pages.
# "categories" - The Hash of category values and Posts.
# See Site#post_attr_hash for type info.
# "tags" - The Hash of tag values and Posts.
# See Site#post_attr_hash for type info.
def site_payload
{
"jekyll" => {
"version" => Jekyll::VERSION,
"environment" => Jekyll.env
},
"site" => Utils.deep_merge_hashes(config,
Utils.deep_merge_hashes(Hash[collections.map{|label, coll| [label, coll.docs]}], {
"time" => time,
"posts" => posts.sort { |a, b| b <=> a },
"pages" => pages,
"static_files" => static_files.sort { |a, b| a.relative_path <=> b.relative_path },
"html_pages" => pages.select { |page| page.html? || page.url.end_with?("/") },
"categories" => post_attr_hash('categories'),
"tags" => post_attr_hash('tags'),
"collections" => collections,
"documents" => documents,
"data" => site_data
}))
}
end
# Filter out any files/directories that are hidden or backup files (start
# with "." or "#" or end with "~"), or contain site content (start with "_"),
# or are excluded in the site configuration, unless they are web server
# files such as '.htaccess'.
#
# entries - The Array of String file/directory entries to filter.
#
# Returns the Array of filtered entries.
def filter_entries(entries, base_directory = nil)
EntryFilter.new(self, base_directory).filter(entries)
end
# Get the implementation class for the given Converter.
#
# klass - The Class of the Converter to fetch.
#
# Returns the Converter instance implementing the given Converter.
def getConverterImpl(klass)
matches = converters.select { |c| c.class == klass }
if impl = matches.first
impl
else
raise "Converter implementation not found for #{klass}"
end
end
# Create array of instances of the subclasses of the class or module
# passed in as argument.
#
# klass - class or module containing the subclasses which should be
# instantiated
#
# Returns array of instances of subclasses of parameter
def instantiate_subclasses(klass)
klass.descendants.select do |c|
!safe || c.safe
end.sort.map do |c|
c.new(config)
end
end
# Read the entries from a particular directory for processing
#
# dir - The String relative path of the directory to read
# subfolder - The String directory to read
#
# Returns the list of entries to process
def get_entries(dir, subfolder)
base = File.join(source, dir, subfolder)
return [] unless File.exist?(base)
entries = Dir.chdir(base) { filter_entries(Dir['**/*'], base) }
entries.delete_if { |e| File.directory?(File.join(base, e)) }
end
# Aggregate post information
#
# post - The Post object to aggregate information for
#
# Returns nothing
def aggregate_post_info(post)
posts << post
end
def relative_permalinks_deprecation_method
if config['relative_permalinks'] && has_relative_page?
Jekyll.logger.warn "Deprecation:", "Starting in 2.0, permalinks for pages" +
" in subfolders must be relative to the" +
" site source directory, not the parent" +
" directory. Check http://jekyllrb.com/docs/upgrading/"+
" for more info."
end
end
def docs_to_write
documents.select(&:write?)
end
def documents
collections.reduce(Set.new) do |docs, (_, collection)|
docs + collection.docs + collection.files
end.to_a
end
def each_site_file
%w(posts pages static_files docs_to_write).each do |type|
send(type).each do |item|
yield item
end
end
end
def frontmatter_defaults
@frontmatter_defaults ||= FrontmatterDefaults.new(self)
end
private
def has_relative_page?
pages.any? { |page| page.uses_relative_permalinks }
end
def limit_posts!
limit = posts.length < limit_posts ? posts.length : limit_posts
self.posts = posts[-limit, limit]
end
def site_cleaner
@site_cleaner ||= Cleaner.new(self)
end
def sanitize_filename(name)
name.gsub!(/[^\w\s_-]+/, '')
name.gsub!(/(^|\b\s)\s+($|\s?\b)/, '\\1\\2')
name.gsub(/\s+/, '_')
end
def publisher
@publisher ||= Publisher.new(self)
end
end
end
hashrockets in CSV loading
# encoding: UTF-8
require 'csv'
module Jekyll
class Site
attr_accessor :config, :layouts, :posts, :pages, :static_files,
:exclude, :include, :source, :dest, :lsi, :highlighter,
:permalink_style, :time, :future, :unpublished, :safe, :plugins, :limit_posts,
:show_drafts, :keep_files, :baseurl, :data, :file_read_opts, :gems,
:plugin_manager
attr_accessor :converters, :generators
# Public: Initialize a new Site.
#
# config - A Hash containing site configuration details.
def initialize(config)
self.config = config.clone
%w[safe lsi highlighter baseurl exclude include future unpublished
show_drafts limit_posts keep_files gems].each do |opt|
self.send("#{opt}=", config[opt])
end
self.source = File.expand_path(config['source'])
self.dest = File.expand_path(config['destination'])
self.permalink_style = config['permalink'].to_sym
self.plugin_manager = Jekyll::PluginManager.new(self)
self.plugins = plugin_manager.plugins_path
self.file_read_opts = {}
self.file_read_opts[:encoding] = config['encoding'] if config['encoding']
reset
setup
end
# Public: Read, process, and write this Site to output.
#
# Returns nothing.
def process
reset
read
generate
render
cleanup
write
end
# Reset Site details.
#
# Returns nothing
def reset
self.time = (config['time'] ? Utils.parse_date(config['time'].to_s, "Invalid time in _config.yml.") : Time.now)
self.layouts = {}
self.posts = []
self.pages = []
self.static_files = []
self.data = {}
@collections = nil
if limit_posts < 0
raise ArgumentError, "limit_posts must be a non-negative number"
end
end
# Load necessary libraries, plugins, converters, and generators.
#
# Returns nothing.
def setup
ensure_not_in_dest
plugin_manager.conscientious_require
self.converters = instantiate_subclasses(Jekyll::Converter)
self.generators = instantiate_subclasses(Jekyll::Generator)
end
# Check that the destination dir isn't the source dir or a directory
# parent to the source dir.
def ensure_not_in_dest
dest_pathname = Pathname.new(dest)
Pathname.new(source).ascend do |path|
if path == dest_pathname
raise Errors::FatalException.new "Destination directory cannot be or contain the Source directory."
end
end
end
# The list of collections and their corresponding Jekyll::Collection instances.
# If config['collections'] is set, a new instance is created for each item in the collection.
# If config['collections'] is not set, a new hash is returned.
#
# Returns a Hash containing collection name-to-instance pairs.
def collections
@collections ||= Hash[collection_names.map { |coll| [coll, Jekyll::Collection.new(self, coll)] } ]
end
# The list of collection names.
#
# Returns an array of collection names from the configuration,
# or an empty array if the `collections` key is not set.
def collection_names
case config['collections']
when Hash
config['collections'].keys
when Array
config['collections']
when nil
[]
else
raise ArgumentError, "Your `collections` key must be a hash or an array."
end
end
# Read Site data from disk and load it into internal data structures.
#
# Returns nothing.
def read
self.layouts = LayoutReader.new(self).read
read_directories
read_data(config['data_source'])
read_collections
end
# Recursively traverse directories to find posts, pages and static files
# that will become part of the site according to the rules in
# filter_entries.
#
# dir - The String relative path of the directory to read. Default: ''.
#
# Returns nothing.
def read_directories(dir = '')
base = File.join(source, dir)
entries = Dir.chdir(base) { filter_entries(Dir.entries('.'), base) }
read_posts(dir)
read_drafts(dir) if show_drafts
posts.sort!
limit_posts! if limit_posts > 0 # limit the posts if :limit_posts option is set
entries.each do |f|
f_abs = File.join(base, f)
if File.directory?(f_abs)
f_rel = File.join(dir, f)
read_directories(f_rel) unless dest.sub(/\/$/, '') == f_abs
elsif Utils.has_yaml_header?(f_abs)
page = Page.new(self, source, dir, f)
pages << page if publisher.publish?(page)
else
static_files << StaticFile.new(self, source, dir, f)
end
end
pages.sort_by!(&:name)
end
# Read all the files in <source>/<dir>/_posts and create a new Post
# object with each one.
#
# dir - The String relative path of the directory to read.
#
# Returns nothing.
def read_posts(dir)
posts = read_content(dir, '_posts', Post)
posts.each do |post|
aggregate_post_info(post) if publisher.publish?(post)
end
end
# Read all the files in <source>/<dir>/_drafts and create a new Post
# object with each one.
#
# dir - The String relative path of the directory to read.
#
# Returns nothing.
def read_drafts(dir)
drafts = read_content(dir, '_drafts', Draft)
drafts.each do |draft|
if draft.published?
aggregate_post_info(draft)
end
end
end
def read_content(dir, magic_dir, klass)
get_entries(dir, magic_dir).map do |entry|
klass.new(self, source, dir, entry) if klass.valid?(entry)
end.reject do |entry|
entry.nil?
end
end
# Read and parse all yaml files under <source>/<dir>
#
# Returns nothing
def read_data(dir)
base = Jekyll.sanitized_path(source, dir)
read_data_to(base, self.data)
end
# Read and parse all yaml files under <dir> and add them to the
# <data> variable.
#
# dir - The string absolute path of the directory to read.
# data - The variable to which data will be added.
#
# Returns nothing
def read_data_to(dir, data)
return unless File.directory?(dir) && (!safe || !File.symlink?(dir))
entries = Dir.chdir(dir) do
Dir['*.{yaml,yml,json,csv}'] + Dir['*'].select { |fn| File.directory?(fn) }
end
entries.each do |entry|
path = Jekyll.sanitized_path(dir, entry)
next if File.symlink?(path) && safe
key = sanitize_filename(File.basename(entry, '.*'))
if File.directory?(path)
read_data_to(path, data[key] = {})
else
case File.extname(path).downcase
when '.csv'
data[key] = CSV.read(path, :headers => true).map(&:to_hash)
else
data[key] = SafeYAML.load_file(path)
end
end
end
end
# Read in all collections specified in the configuration
#
# Returns nothing.
def read_collections
collections.each do |_, collection|
collection.read unless collection.label.eql?("data")
end
end
# Run each of the Generators.
#
# Returns nothing.
def generate
generators.each do |generator|
generator.generate(self)
end
end
# Render the site to the destination.
#
# Returns nothing.
def render
relative_permalinks_deprecation_method
collections.each do |label, collection|
collection.docs.each do |document|
document.output = Jekyll::Renderer.new(self, document).run
end
end
payload = site_payload
[posts, pages].flatten.each do |page_or_post|
page_or_post.render(layouts, payload)
end
rescue Errno::ENOENT => e
# ignore missing layout dir
end
# Remove orphaned files and empty directories in destination.
#
# Returns nothing.
def cleanup
site_cleaner.cleanup!
end
# Write static files, pages, and posts.
#
# Returns nothing.
def write
each_site_file { |item| item.write(dest) }
end
# Construct a Hash of Posts indexed by the specified Post attribute.
#
# post_attr - The String name of the Post attribute.
#
# Examples
#
# post_attr_hash('categories')
# # => { 'tech' => [<Post A>, <Post B>],
# # 'ruby' => [<Post B>] }
#
# Returns the Hash: { attr => posts } where
# attr - One of the values for the requested attribute.
# posts - The Array of Posts with the given attr value.
def post_attr_hash(post_attr)
# Build a hash map based on the specified post attribute ( post attr =>
# array of posts ) then sort each array in reverse order.
hash = Hash.new { |h, key| h[key] = [] }
posts.each { |p| p.send(post_attr.to_sym).each { |t| hash[t] << p } }
hash.values.each { |posts| posts.sort!.reverse! }
hash
end
def tags
post_attr_hash('tags')
end
def categories
post_attr_hash('categories')
end
# Prepare site data for site payload. The method maintains backward compatibility
# if the key 'data' is already used in _config.yml.
#
# Returns the Hash to be hooked to site.data.
def site_data
config['data'] || data
end
# The Hash payload containing site-wide data.
#
# Returns the Hash: { "site" => data } where data is a Hash with keys:
# "time" - The Time as specified in the configuration or the
# current time if none was specified.
# "posts" - The Array of Posts, sorted chronologically by post date
# and then title.
# "pages" - The Array of all Pages.
# "html_pages" - The Array of HTML Pages.
# "categories" - The Hash of category values and Posts.
# See Site#post_attr_hash for type info.
# "tags" - The Hash of tag values and Posts.
# See Site#post_attr_hash for type info.
def site_payload
{
"jekyll" => {
"version" => Jekyll::VERSION,
"environment" => Jekyll.env
},
"site" => Utils.deep_merge_hashes(config,
Utils.deep_merge_hashes(Hash[collections.map{|label, coll| [label, coll.docs]}], {
"time" => time,
"posts" => posts.sort { |a, b| b <=> a },
"pages" => pages,
"static_files" => static_files.sort { |a, b| a.relative_path <=> b.relative_path },
"html_pages" => pages.select { |page| page.html? || page.url.end_with?("/") },
"categories" => post_attr_hash('categories'),
"tags" => post_attr_hash('tags'),
"collections" => collections,
"documents" => documents,
"data" => site_data
}))
}
end
# Filter out any files/directories that are hidden or backup files (start
# with "." or "#" or end with "~"), or contain site content (start with "_"),
# or are excluded in the site configuration, unless they are web server
# files such as '.htaccess'.
#
# entries - The Array of String file/directory entries to filter.
#
# Returns the Array of filtered entries.
def filter_entries(entries, base_directory = nil)
EntryFilter.new(self, base_directory).filter(entries)
end
# Get the implementation class for the given Converter.
#
# klass - The Class of the Converter to fetch.
#
# Returns the Converter instance implementing the given Converter.
def getConverterImpl(klass)
matches = converters.select { |c| c.class == klass }
if impl = matches.first
impl
else
raise "Converter implementation not found for #{klass}"
end
end
# Create array of instances of the subclasses of the class or module
# passed in as argument.
#
# klass - class or module containing the subclasses which should be
# instantiated
#
# Returns array of instances of subclasses of parameter
def instantiate_subclasses(klass)
klass.descendants.select do |c|
!safe || c.safe
end.sort.map do |c|
c.new(config)
end
end
# Read the entries from a particular directory for processing
#
# dir - The String relative path of the directory to read
# subfolder - The String directory to read
#
# Returns the list of entries to process
def get_entries(dir, subfolder)
base = File.join(source, dir, subfolder)
return [] unless File.exist?(base)
entries = Dir.chdir(base) { filter_entries(Dir['**/*'], base) }
entries.delete_if { |e| File.directory?(File.join(base, e)) }
end
# Aggregate post information
#
# post - The Post object to aggregate information for
#
# Returns nothing
def aggregate_post_info(post)
posts << post
end
def relative_permalinks_deprecation_method
if config['relative_permalinks'] && has_relative_page?
Jekyll.logger.warn "Deprecation:", "Starting in 2.0, permalinks for pages" +
" in subfolders must be relative to the" +
" site source directory, not the parent" +
" directory. Check http://jekyllrb.com/docs/upgrading/"+
" for more info."
end
end
def docs_to_write
documents.select(&:write?)
end
def documents
collections.reduce(Set.new) do |docs, (_, collection)|
docs + collection.docs + collection.files
end.to_a
end
def each_site_file
%w(posts pages static_files docs_to_write).each do |type|
send(type).each do |item|
yield item
end
end
end
def frontmatter_defaults
@frontmatter_defaults ||= FrontmatterDefaults.new(self)
end
private
def has_relative_page?
pages.any? { |page| page.uses_relative_permalinks }
end
def limit_posts!
limit = posts.length < limit_posts ? posts.length : limit_posts
self.posts = posts[-limit, limit]
end
def site_cleaner
@site_cleaner ||= Cleaner.new(self)
end
def sanitize_filename(name)
name.gsub!(/[^\w\s_-]+/, '')
name.gsub!(/(^|\b\s)\s+($|\s?\b)/, '\\1\\2')
name.gsub(/\s+/, '_')
end
def publisher
@publisher ||= Publisher.new(self)
end
end
end
|
module Danger
# Links JIRA issues to a pull request.
#
# @example Check PR for the following JIRA project keys and links them
#
# jira.check(key: "KEY", url: "https://myjira.atlassian.net/browse")
#
# @see RestlessThinker/danger-jira
# @tags jira
#
class DangerJira < Plugin
# Checks PR for JIRA keys and links them
#
# @param [Array] key
# An array of JIRA project keys KEY-123, JIRA-125 etc.
#
# @param [String] url
# The JIRA url hosted instance.
#
# @param [String] emoji
# The emoji you want to display in the message.
#
# @param [Boolean] search_title
# Option to search JIRA issues from PR title
#
# @param [Boolean] search_commits
# Option to search JIRA issues from commit messages
#
# @param [Boolean] fail_on_warning
# Option to fail danger if no JIRA issue found
#
# @param [Boolean] report_missing
# Option to report if no JIRA issue was found
#
# @param [Boolean] skippable
# Option to skip the report if 'no-jira' is provided on the PR title, description or commits
#
# @return [void]
#
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true)
throw Error("'key' missing - must supply JIRA issue key") if key.nil?
throw Error("'url' missing - must supply JIRA installation URL") if url.nil?
return if skippable && should_skip_jira?(search_title: search_title)
jira_issues = find_jira_issues(
key: key,
search_title: search_title,
search_commits: search_commits
)
if !jira_issues.empty?
jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ")
message("#{emoji} #{jira_urls}")
elsif report_missing
msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)"
if fail_on_warning
fail(msg)
else
warn(msg)
end
end
end
private
def find_jira_issues(key: nil, search_title: true, search_commits: false)
# Support multiple JIRA projects
keys = key.kind_of?(Array) ? key.join("|") : key
jira_key_regex_string = "((?:#{keys})-[0-9]+)"
regexp = Regexp.new(/#{jira_key_regex_string}/)
jira_issues = []
if search_title
github.pr_title.gsub(regexp) do |match|
jira_issues << match
end
end
if search_commits
git.commits.map do |commit|
commit.message.gsub(regexp) do |match|
jira_issues << match
end
end
end
if jira_issues.empty?
github.pr_body.gsub(regexp) do |match|
jira_issues << match
end
end
return jira_issues.uniq
end
def should_skip_jira?(search_title: true)
# Consider first occurrence of 'no-jira'
regexp = Regexp.new("no-jira", true)
if search_title
github.pr_title.gsub(regexp) do |match|
return true unless match.empty?
end
end
github.pr_body.gsub(regexp) do |match|
return true unless match.empty?
end
return false
end
def ensure_url_ends_with_slash(url)
return "#{url}/" unless url.end_with?("/")
return url
end
def link(href: nil, issue: nil)
return "<a href='#{href}#{issue}'>#{issue}</a>"
end
end
end
Support Gitlab
module Danger
# Links JIRA issues to a pull request.
#
# @example Check PR for the following JIRA project keys and links them
#
# jira.check(key: "KEY", url: "https://myjira.atlassian.net/browse")
#
# @see RestlessThinker/danger-jira
# @tags jira
#
class DangerJira < Plugin
# Checks PR for JIRA keys and links them
#
# @param [Array] key
# An array of JIRA project keys KEY-123, JIRA-125 etc.
#
# @param [String] url
# The JIRA url hosted instance.
#
# @param [String] emoji
# The emoji you want to display in the message.
#
# @param [Boolean] search_title
# Option to search JIRA issues from PR title
#
# @param [Boolean] search_commits
# Option to search JIRA issues from commit messages
#
# @param [Boolean] fail_on_warning
# Option to fail danger if no JIRA issue found
#
# @param [Boolean] report_missing
# Option to report if no JIRA issue was found
#
# @param [Boolean] skippable
# Option to skip the report if 'no-jira' is provided on the PR title, description or commits
#
# @return [void]
#
def check(key: nil, url: nil, emoji: ":link:", search_title: true, search_commits: false, fail_on_warning: false, report_missing: true, skippable: true)
throw Error("'key' missing - must supply JIRA issue key") if key.nil?
throw Error("'url' missing - must supply JIRA installation URL") if url.nil?
return if skippable && should_skip_jira?(search_title: search_title)
jira_issues = find_jira_issues(
key: key,
search_title: search_title,
search_commits: search_commits
)
if !jira_issues.empty?
jira_urls = jira_issues.map { |issue| link(href: ensure_url_ends_with_slash(url), issue: issue) }.join(", ")
message("#{emoji} #{jira_urls}")
elsif report_missing
msg = "This PR does not contain any JIRA issue keys in the PR title or commit messages (e.g. KEY-123)"
if fail_on_warning
fail(msg)
else
warn(msg)
end
end
end
private
def vcs_host
return gitlab if defined? @dangerfile.gitlab
return github
end
def find_jira_issues(key: nil, search_title: true, search_commits: false)
# Support multiple JIRA projects
keys = key.kind_of?(Array) ? key.join("|") : key
jira_key_regex_string = "((?:#{keys})-[0-9]+)"
regexp = Regexp.new(/#{jira_key_regex_string}/)
jira_issues = []
if search_title
vcs_host.pr_title.gsub(regexp) do |match|
jira_issues << match
end
end
if search_commits
git.commits.map do |commit|
commit.message.gsub(regexp) do |match|
jira_issues << match
end
end
end
if jira_issues.empty?
vcs_host.pr_body.gsub(regexp) do |match|
jira_issues << match
end
end
return jira_issues.uniq
end
def should_skip_jira?(search_title: true)
# Consider first occurrence of 'no-jira'
regexp = Regexp.new("no-jira", true)
if search_title
vcs_host.pr_title.gsub(regexp) do |match|
return true unless match.empty?
end
end
vcs_host.pr_body.gsub(regexp) do |match|
return true unless match.empty?
end
return false
end
def ensure_url_ends_with_slash(url)
return "#{url}/" unless url.end_with?("/")
return url
end
def link(href: nil, issue: nil)
return "<a href='#{href}#{issue}'>#{issue}</a>"
end
end
end
|
require 'rubygems'
require 'time'
require 'open-uri'
require 'nokogiri'
class JobCentral
BASE_URI = "http://xmlfeed.jobcentral.com"
class Employer < Struct.new(:name, :file_uri, :file_size, :date_updated, :jobs)
def self.all
@employers = []
((html/"table")[-1]/"tr").each_with_index do |element, idx|
next unless idx >= 2
attributes = element/"td"
employer = Employer.new
employer.name = attributes[0].text
employer.file_uri = BASE_URI + (attributes[1]/"a").attr('href')
employer.file_size = attributes[2].text
employer.date_updated = Time.parse attributes[3].text
@employers << employer
end
@employers
end
def self.read(uri = BASE_URI + "/index.asp")
open(uri).read
end
def self.html
Nokogiri::HTML read
end
def read_jobs
read file_uri
end
def xml
Nokogiri::XML read_jobs
end
def jobs
@jobs = []
(xml/"job").each do |element|
job = Job.new
job.guid = element.at("guid").text
job.title = element.at("title").text
job.description = element.at("description").text
job.link = element.at("link").text
job.imagelink = element.at("imagelink").text
job.expiration_date = Date.parse(element.at("expiration_date").text)
job.employer_name = element.at("employer").text
job.location = element.at("location").text
element.css("industry").each do |industry|
job.industries << industry.text
end
@jobs << job
end
@jobs
end
end
class Job < Struct.new(:guid, :title, :description, :link, :imagelink, :industries, :expiration_date, :employer_name, :location)
def industries
@industries ||= []
end
end
end
revert stupid refactoring masked by mocks
require 'rubygems'
require 'time'
require 'open-uri'
require 'nokogiri'
class JobCentral
BASE_URI = "http://xmlfeed.jobcentral.com"
class Employer < Struct.new(:name, :file_uri, :file_size, :date_updated, :jobs)
def self.all
@employers = []
((html/"table")[-1]/"tr").each_with_index do |element, idx|
next unless idx >= 2
attributes = element/"td"
employer = Employer.new
employer.name = attributes[0].text
employer.file_uri = BASE_URI + (attributes[1]/"a").attr('href')
employer.file_size = attributes[2].text
employer.date_updated = Time.parse attributes[3].text
@employers << employer
end
@employers
end
def self.read(uri = BASE_URI + "/index.asp")
open(uri).read
end
def self.html
Nokogiri::HTML read
end
def read_jobs
open(file_uri).read
end
def xml
Nokogiri::XML read_jobs
end
def jobs
@jobs = []
(xml/"job").each do |element|
job = Job.new
job.guid = element.at("guid").text
job.title = element.at("title").text
job.description = element.at("description").text
job.link = element.at("link").text
job.imagelink = element.at("imagelink").text
job.expiration_date = Date.parse(element.at("expiration_date").text)
job.employer_name = element.at("employer").text
job.location = element.at("location").text
element.css("industry").each do |industry|
job.industries << industry.text
end
@jobs << job
end
@jobs
end
end
class Job < Struct.new(:guid, :title, :description, :link, :imagelink, :industries, :expiration_date, :employer_name, :location)
def industries
@industries ||= []
end
end
end
|
def list_in_dir(dir)
puts dir
Dir[dir + '/*'].each do |d|
list_in_dir(d)
end
end
list_in_dir('.')
Add indentation.
def list_in_dir(dir, depth = 0)
puts " " * depth + dir
Dir[dir + '/*'].each do |d|
list_in_dir(d, depth + 1)
end
end
list_in_dir('.') |
module Kcl
VERSION = '0.0.3'
end
Bump up version to 1.0.0
module Kcl
VERSION = '1.0.0'
end
|
class Knj::Datarow
attr_reader :data, :ob
def self.required_data
@required_data = [] if !@required_data
return @required_data
end
def self.depending_data
@depending_data = [] if !@depending_data
return @depending_data
end
def is_knj?; return true; end
def self.is_nullstamp?(stamp)
return true if !stamp or stamp == "0000-00-00 00:00:00" or stamp == "0000-00-00"
return false
end
def self.has_many(arr)
arr.each do |val|
if val.is_a?(Array)
classname, colname, methodname = *val
elsif val.is_a?(Hash)
classname = val[:class]
colname = val[:col]
methodname = val[:method]
if val[:depends]
depending_data << {
:colname => colname,
:classname => classname
}
end
else
raise "Unknown argument: '#{val.class.name}'."
end
if !methodname
methodname = "#{classname.to_s.downcase}s".to_sym
end
define_method(methodname) do |*args|
merge_args = args[0] if args and args[0]
merge_args = {} if !merge_args
return ob.list(classname, {colname.to_s => self.id}.merge(merge_args))
end
end
end
def self.has_one(arr)
arr.each do |val|
methodname = nil
colname = nil
classname = nil
if val.is_a?(Symbol)
classname = val
methodname = val.to_s.downcase.to_sym
colname = "#{val.to_s.downcase}_id".to_sym
elsif val.is_a?(Array)
classname, colname, methodname = *val
elsif val.is_a?(Hash)
classname, colname, methodname = val[:class], val[:col], val[:method]
if val[:required]
colname = "#{classname.to_s.downcase}_id".to_sym if !colname
required_data << {
:col => colname,
:class => classname
}
end
else
raise "Unknown argument-type: '#{arr.class.name}'."
end
methodname = classname.to_s.downcase if !methodname
colname = "#{classname.to_s.downcase}_id".to_sym if !colname
define_method(methodname) do
return ob.get_try(self, colname, classname)
end
methodname_html = "#{methodname.to_s}_html".to_sym
define_method(methodname_html) do |*args|
obj = self.send(methodname)
return ob.events.call(:no_html, classname) if !obj
raise "Class '#{classname}' does not have a 'html'-method." if !obj.respond_to?(:html)
return obj.html(*args)
end
end
end
def self.table
return self.name.split("::").last
end
def self.columns(d)
columns_load(d) if !@columns
return @columns
end
def self.columns_load(d)
return nil if @columns
@columns = d.db.tables[table].columns
end
def self.columns_sqlhelper_args
return @columns_sqlhelper_args
end
def self.list(d)
sql = "SELECT * FROM #{d.db.enc_table}#{table}#{d.db.enc_table} WHERE 1=1"
ret = list_helper(d)
d.args.each do |key, val|
raise "Invalid key: '#{key}'."
end
sql += ret[:sql_where]
sql += ret[:sql_order]
sql += ret[:sql_limit]
return d.ob.list_bysql(table, sql)
end
def self.load_columns(d)
if @columns_sqlhelper_args_working
sleep 0.1 while @columns_sqlhelper_args_working
return false
end
begin
@columns_sqlhelper_args_working = true
cols = self.columns(d)
sqlhelper_args = {
:db => d.db,
:table => table,
:cols_bools => [],
:cols_date => [],
:cols_dbrows => [],
:cols_num => [],
:cols_str => []
}
cols.each do |col_name, col_obj|
col_type = col_obj.type
col_type = "int" if col_type == "bigint" or col_type == "tinyint" or col_type == "mediumint" or col_type == "smallint"
if col_type == "enum" and col_obj.maxlength == "'0','1'"
sqlhelper_args[:cols_bools] << col_name
method_name = "#{col_name}?"
define_method(method_name.to_sym) do
return true if self[col_name.to_sym].to_s == "1"
return false
end
elsif col_type == "int" and col_name.slice(-3, 3) == "_id"
sqlhelper_args[:cols_dbrows] << col_name
elsif col_type == "int" or col_type == "bigint"
sqlhelper_args[:cols_num] << col_name
elsif col_type == "varchar" or col_type == "text" or col_type == "enum"
sqlhelper_args[:cols_str] << col_name
elsif col_type == "date" or col_type == "datetime"
sqlhelper_args[:cols_date] << col_name
method_name = "#{col_name}_str".to_sym
define_method(method_name) do |*args|
if Knj::Datet.is_nullstamp?(self[col_name.to_sym])
return ob.events.call(:no_date, classname)
end
return Knj::Datet.in(self[col_name.to_sym]).out(*args)
end
end
end
@columns_sqlhelper_args = sqlhelper_args
ensure
@columns_sqlhelper_args_working = false
end
end
def self.list_helper(d)
load_columns(d) if !@columns_sqlhelper_args
return d.ob.sqlhelper(d.args, @columns_sqlhelper_args)
end
def table
return self.class.name.split("::").last
end
def initialize(d)
@ob = d.ob
raise "No ob given." if !@ob
if d.data.is_a?(Hash)
@data = d.data
elsif d.data
@data = {:id => d.data}
self.reload
else
raise Knj::Errors::InvalidData, "Could not figure out the data from '#{d.data.class.name}'."
end
end
def db
return @ob.db
end
def reload
data = self.db.single(self.table, {:id => @data[:id]})
if !data
raise Knj::Errors::NotFound, "Could not find any data for the object with ID: '#{@data[:id]}' in the table '#{self.table}'."
end
@data = data
end
def update(newdata)
self.db.update(self.table, newdata, {:id => @data[:id]})
self.reload
if self.ob
self.ob.call("object" => self, "signal" => "update")
end
end
def destroy
@ob = nil
@data = nil
end
def has_key?(key)
return @data.has_key?(key.to_sym)
end
def [](key)
raise "No valid key given." if !key.is_a?(Symbol)
raise "No data was loaded on the object? Maybe you are trying to call a deleted object?" if !@data
return @data[key] if @data.has_key?(key)
raise "No such key: #{key}."
end
def []=(key, value)
self.update(key.to_sym => value)
self.reload
end
def id
raise "No data on object." if !@data
return @data[:id]
end
def name
if @data.has_key?(:title)
return @data[:title]
elsif @data.has_key?(:name)
return @data[:name]
end
obj_methods = self.class.instance_methods(false)
[:name, :title].each do |method_name|
return self.method(method_name).call if obj_methods.index(method_name)
end
raise "Couldnt figure out the title/name of the object on class #{self.class.name}."
end
alias :title :name
def each(&args)
return @data.each(&args)
end
end
The dynamic defines will no longer override methods of the same name.
class Knj::Datarow
attr_reader :data, :ob
def self.required_data
@required_data = [] if !@required_data
return @required_data
end
def self.depending_data
@depending_data = [] if !@depending_data
return @depending_data
end
def is_knj?; return true; end
def self.is_nullstamp?(stamp)
return true if !stamp or stamp == "0000-00-00 00:00:00" or stamp == "0000-00-00"
return false
end
def self.has_many(arr)
arr.each do |val|
if val.is_a?(Array)
classname, colname, methodname = *val
elsif val.is_a?(Hash)
classname = val[:class]
colname = val[:col]
methodname = val[:method]
if val[:depends]
depending_data << {
:colname => colname,
:classname => classname
}
end
else
raise "Unknown argument: '#{val.class.name}'."
end
if !methodname
methodname = "#{classname.to_s.downcase}s".to_sym
end
define_method(methodname) do |*args|
merge_args = args[0] if args and args[0]
merge_args = {} if !merge_args
return ob.list(classname, {colname.to_s => self.id}.merge(merge_args))
end
end
end
def self.has_one(arr)
arr.each do |val|
methodname = nil
colname = nil
classname = nil
if val.is_a?(Symbol)
classname = val
methodname = val.to_s.downcase.to_sym
colname = "#{val.to_s.downcase}_id".to_sym
elsif val.is_a?(Array)
classname, colname, methodname = *val
elsif val.is_a?(Hash)
classname, colname, methodname = val[:class], val[:col], val[:method]
if val[:required]
colname = "#{classname.to_s.downcase}_id".to_sym if !colname
required_data << {
:col => colname,
:class => classname
}
end
else
raise "Unknown argument-type: '#{arr.class.name}'."
end
methodname = classname.to_s.downcase if !methodname
colname = "#{classname.to_s.downcase}_id".to_sym if !colname
define_method(methodname) do
return ob.get_try(self, colname, classname)
end
methodname_html = "#{methodname.to_s}_html".to_sym
define_method(methodname_html) do |*args|
obj = self.send(methodname)
return ob.events.call(:no_html, classname) if !obj
raise "Class '#{classname}' does not have a 'html'-method." if !obj.respond_to?(:html)
return obj.html(*args)
end
end
end
def self.table
return self.name.split("::").last
end
def self.columns(d)
columns_load(d) if !@columns
return @columns
end
def self.columns_load(d)
return nil if @columns
@columns = d.db.tables[table].columns
end
def self.columns_sqlhelper_args
return @columns_sqlhelper_args
end
def self.list(d)
sql = "SELECT * FROM #{d.db.enc_table}#{table}#{d.db.enc_table} WHERE 1=1"
ret = list_helper(d)
d.args.each do |key, val|
raise "Invalid key: '#{key}'."
end
sql += ret[:sql_where]
sql += ret[:sql_order]
sql += ret[:sql_limit]
return d.ob.list_bysql(table, sql)
end
def self.load_columns(d)
if @columns_sqlhelper_args_working
sleep 0.1 while @columns_sqlhelper_args_working
return false
end
begin
@columns_sqlhelper_args_working = true
cols = self.columns(d)
inst_methods = instance_methods(false)
sqlhelper_args = {
:db => d.db,
:table => table,
:cols_bools => [],
:cols_date => [],
:cols_dbrows => [],
:cols_num => [],
:cols_str => []
}
cols.each do |col_name, col_obj|
col_type = col_obj.type
col_type = "int" if col_type == "bigint" or col_type == "tinyint" or col_type == "mediumint" or col_type == "smallint"
if col_type == "enum" and col_obj.maxlength == "'0','1'"
sqlhelper_args[:cols_bools] << col_name
method_name = "#{col_name}?".to_sym
if !inst_methods.index(method_name)
define_method(method_name) do
return true if self[col_name.to_sym].to_s == "1"
return false
end
end
elsif col_type == "int" and col_name.slice(-3, 3) == "_id"
sqlhelper_args[:cols_dbrows] << col_name
elsif col_type == "int" or col_type == "bigint"
sqlhelper_args[:cols_num] << col_name
elsif col_type == "varchar" or col_type == "text" or col_type == "enum"
sqlhelper_args[:cols_str] << col_name
elsif col_type == "date" or col_type == "datetime"
sqlhelper_args[:cols_date] << col_name
method_name = "#{col_name}_str".to_sym
if !inst_methods.index(method_name)
define_method(method_name) do |*args|
if Knj::Datet.is_nullstamp?(self[col_name.to_sym])
return ob.events.call(:no_date, classname)
end
return Knj::Datet.in(self[col_name.to_sym]).out(*args)
end
end
end
end
@columns_sqlhelper_args = sqlhelper_args
ensure
@columns_sqlhelper_args_working = false
end
end
def self.list_helper(d)
load_columns(d) if !@columns_sqlhelper_args
return d.ob.sqlhelper(d.args, @columns_sqlhelper_args)
end
def table
return self.class.name.split("::").last
end
def initialize(d)
@ob = d.ob
raise "No ob given." if !@ob
if d.data.is_a?(Hash)
@data = d.data
elsif d.data
@data = {:id => d.data}
self.reload
else
raise Knj::Errors::InvalidData, "Could not figure out the data from '#{d.data.class.name}'."
end
end
def db
return @ob.db
end
def reload
data = self.db.single(self.table, {:id => @data[:id]})
if !data
raise Knj::Errors::NotFound, "Could not find any data for the object with ID: '#{@data[:id]}' in the table '#{self.table}'."
end
@data = data
end
def update(newdata)
self.db.update(self.table, newdata, {:id => @data[:id]})
self.reload
if self.ob
self.ob.call("object" => self, "signal" => "update")
end
end
def destroy
@ob = nil
@data = nil
end
def has_key?(key)
return @data.has_key?(key.to_sym)
end
def [](key)
raise "No valid key given." if !key.is_a?(Symbol)
raise "No data was loaded on the object? Maybe you are trying to call a deleted object?" if !@data
return @data[key] if @data.has_key?(key)
raise "No such key: #{key}."
end
def []=(key, value)
self.update(key.to_sym => value)
self.reload
end
def id
raise "No data on object." if !@data
return @data[:id]
end
def name
if @data.has_key?(:title)
return @data[:title]
elsif @data.has_key?(:name)
return @data[:name]
end
obj_methods = self.class.instance_methods(false)
[:name, :title].each do |method_name|
return self.method(method_name).call if obj_methods.index(method_name)
end
raise "Couldnt figure out the title/name of the object on class #{self.class.name}."
end
alias :title :name
def each(&args)
return @data.each(&args)
end
end |
# OpenSSL and Base64 are required to support signed_request
require 'openssl'
require 'base64'
module Koala
module Facebook
class OAuth
attr_reader :app_id, :app_secret, :oauth_callback_url
# Creates a new OAuth client.
#
# @param app_id [String, Integer] a Facebook application ID
# @param app_secret a Facebook application secret
# @param oauth_callback_url the URL in your app to which users authenticating with OAuth will be sent
def initialize(app_id, app_secret, oauth_callback_url = nil)
@app_id = app_id
@app_secret = app_secret
@oauth_callback_url = oauth_callback_url
end
# Parses the cookie set Facebook's JavaScript SDK.
#
# @note this method can only be called once per session, as the OAuth code
# Facebook supplies can only be redeemed once. Your application
# must handle cross-request storage of this information; you can no
# longer call this method multiple times. (This works out, as the
# method has to make a call to FB's servers anyway, which you don't
# want on every call.)
#
# @param cookie_hash a set of cookies that includes the Facebook cookie.
# You can pass Rack/Rails/Sinatra's cookie hash directly to this method.
#
# @return the authenticated user's information as a hash, or nil.
def get_user_info_from_cookies(cookie_hash)
if signed_cookie = cookie_hash["fbsr_#{@app_id}"]
parse_signed_cookie(signed_cookie)
elsif unsigned_cookie = cookie_hash["fbs_#{@app_id}"]
parse_unsigned_cookie(unsigned_cookie)
end
end
alias_method :get_user_info_from_cookie, :get_user_info_from_cookies
# Parses the cookie set Facebook's JavaScript SDK and returns only the user ID.
#
# @note (see #get_user_info_from_cookie)
#
# @param (see #get_user_info_from_cookie)
#
# @return the authenticated user's Facebook ID, or nil.
def get_user_from_cookies(cookies)
Koala::Utils.deprecate("Due to Facebook changes, you can only redeem an OAuth code once; it is therefore recommended not to use this method, as it will consume the code without providing you the access token. See https://developers.facebook.com/roadmap/completed-changes/#december-2012.")
if signed_cookie = cookies["fbsr_#{@app_id}"]
if components = parse_signed_request(signed_cookie)
components["user_id"]
end
elsif info = get_user_info_from_cookies(cookies)
# Parsing unsigned cookie
info["uid"]
end
end
alias_method :get_user_from_cookie, :get_user_from_cookies
# URLs
# Builds an OAuth URL, where users will be prompted to log in and for any desired permissions.
# When the users log in, you receive a callback with their
# See http://developers.facebook.com/docs/authentication/.
#
# @see #url_for_access_token
#
# @note The server-side authentication and dialog methods should only be used
# if your application can't use the Facebook Javascript SDK,
# which provides a much better user experience.
# See http://developers.facebook.com/docs/reference/javascript/.
#
# @param options any query values to add to the URL, as well as any special/required values listed below.
# @option options permissions an array or comma-separated string of desired permissions
# @option options state a unique string to serve as a CSRF (cross-site request
# forgery) token -- highly recommended for security. See
# https://developers.facebook.com/docs/howtos/login/server-side-login/
#
# @raise ArgumentError if no OAuth callback was specified in OAuth#new or in options as :redirect_uri
#
# @return an OAuth URL you can send your users to
def url_for_oauth_code(options = {})
# for permissions, see http://developers.facebook.com/docs/authentication/permissions
if permissions = options.delete(:permissions)
options[:scope] = permissions.is_a?(Array) ? permissions.join(",") : permissions
end
url_options = {:client_id => @app_id}.merge(options)
# Creates the URL for oauth authorization for a given callback and optional set of permissions
build_url("https://#{Koala.config.dialog_host}/dialog/oauth", true, url_options)
end
# Once you receive an OAuth code, you need to redeem it from Facebook using an appropriate URL.
# (This is done by your server behind the scenes.)
# See http://developers.facebook.com/docs/authentication/.
#
# @see #url_for_oauth_code
#
# @note (see #url_for_oauth_code)
#
# @param code an OAuth code received from Facebook
# @param options any additional query parameters to add to the URL
#
# @raise (see #url_for_oauth_code)
#
# @return an URL your server can query for the user's access token
def url_for_access_token(code, options = {})
# Creates the URL for the token corresponding to a given code generated by Facebook
url_options = {
:client_id => @app_id,
:code => code,
:client_secret => @app_secret
}.merge(options)
build_url("https://#{Koala.config.graph_server}/oauth/access_token", true, url_options)
end
# Builds a URL for a given dialog (feed, friends, OAuth, pay, send, etc.)
# See http://developers.facebook.com/docs/reference/dialogs/.
#
# @note (see #url_for_oauth_code)
#
# @param dialog_type the kind of Facebook dialog you want to show
# @param options any additional query parameters to add to the URL
#
# @return an URL your server can query for the user's access token
def url_for_dialog(dialog_type, options = {})
# some endpoints require app_id, some client_id, supply both doesn't seem to hurt
url_options = {:app_id => @app_id, :client_id => @app_id}.merge(options)
build_url("http://#{Koala.config.dialog_host}/dialog/#{dialog_type}", true, url_options)
end
# Generates a 'client code' from a server side long-lived access token. With the generated
# code, it can be sent to a client application which can then use it to get a long-lived
# access token from Facebook. After which the clients can use that access token to make
# requests to Facebook without having to use the server token, yet the server access token
# remains valid.
# See https://developers.facebook.com/docs/facebook-login/access-tokens/#long-via-code
#
# @param access_token a user's long lived (server) access token
#
# @raise Koala::Facebook::ServerError if Facebook returns a server error (status >= 500)
# @raise Koala::Facebook::OAuthTokenRequestError if Facebook returns an error response (status >= 400)
# @raise Koala::Facebook::BadFacebookResponse if Facebook returns a blank response
# @raise Koala::KoalaError if response does not contain 'code' hash key
#
# @return a string of the generated 'code'
def generate_client_code(access_token)
response = fetch_token_string({redirect_uri: @oauth_callback_url, access_token: access_token}, false, 'client_code')
# Facebook returns an empty body in certain error conditions
if response == ''
raise BadFacebookResponse.new(200, '', 'generate_client_code received an error: empty response body')
else
result = MultiJson.load(response)
end
result.has_key?('code') ? result['code'] : raise(Koala::KoalaError.new("Facebook returned a valid response without the expected 'code' in the body (response = #{response})"))
end
# access tokens
# Fetches an access token, token expiration, and other info from Facebook.
# Useful when you've received an OAuth code using the server-side authentication process.
# @see url_for_oauth_code
#
# @note (see #url_for_oauth_code)
#
# @param code (see #url_for_access_token)
# @param options any additional parameters to send to Facebook when redeeming the token
#
# @raise Koala::Facebook::OAuthTokenRequestError if Facebook returns an error response
#
# @return a hash of the access token info returned by Facebook (token, expiration, etc.)
def get_access_token_info(code, options = {})
# convenience method to get a parsed token from Facebook for a given code
# should this require an OAuth callback URL?
get_token_from_server({:code => code, :redirect_uri => options[:redirect_uri] || @oauth_callback_url}, false, options)
end
# Fetches the access token (ignoring expiration and other info) from Facebook.
# Useful when you've received an OAuth code using the server-side authentication process.
# @see get_access_token_info
#
# @note (see #url_for_oauth_code)
#
# @param (see #get_access_token_info)
#
# @raise (see #get_access_token_info)
#
# @return the access token
def get_access_token(code, options = {})
# upstream methods will throw errors if needed
if info = get_access_token_info(code, options)
string = info["access_token"]
end
end
# Fetches the application's access token, along with any other information provided by Facebook.
# See http://developers.facebook.com/docs/authentication/ (search for App Login).
#
# @param options any additional parameters to send to Facebook when redeeming the token
#
# @return the application access token and other information (expiration, etc.)
def get_app_access_token_info(options = {})
# convenience method to get a the application's sessionless access token
get_token_from_server({:grant_type => 'client_credentials'}, true, options)
end
# Fetches the application's access token (ignoring expiration and other info).
# @see get_app_access_token_info
#
# @param (see #get_app_access_token_info)
#
# @return the application access token
def get_app_access_token(options = {})
if info = get_app_access_token_info(options)
string = info["access_token"]
end
end
# Fetches an access_token with extended expiration time, along with any other information provided by Facebook.
# See https://developers.facebook.com/docs/offline-access-deprecation/#extend_token (search for fb_exchange_token).
#
# @param access_token the access token to exchange
# @param options any additional parameters to send to Facebook when exchanging tokens.
#
# @return the access token with extended expiration time and other information (expiration, etc.)
def exchange_access_token_info(access_token, options = {})
get_token_from_server({
:grant_type => 'fb_exchange_token',
:fb_exchange_token => access_token
}, true, options)
end
# Fetches an access token with extended expiration time (ignoring expiration and other info).
# @see exchange_access_token_info
#
# @param (see #exchange_access_token_info)
#
# @return A new access token or the existing one, set to expire in 60 days.
def exchange_access_token(access_token, options = {})
if info = exchange_access_token_info(access_token, options)
info["access_token"]
end
end
# Parses a signed request string provided by Facebook to canvas apps or in a secure cookie.
#
# @param input the signed request from Facebook
#
# @raise OAuthSignatureError if the signature is incomplete, invalid, or using an unsupported algorithm
#
# @return a hash of the validated request information
def parse_signed_request(input)
encoded_sig, encoded_envelope = input.split('.', 2)
raise OAuthSignatureError, 'Invalid (incomplete) signature data' unless encoded_sig && encoded_envelope
signature = base64_url_decode(encoded_sig).unpack("H*").first
envelope = MultiJson.load(base64_url_decode(encoded_envelope))
raise OAuthSignatureError, "Unsupported algorithm #{envelope['algorithm']}" if envelope['algorithm'] != 'HMAC-SHA256'
# now see if the signature is valid (digest, key, data)
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, @app_secret, encoded_envelope)
raise OAuthSignatureError, 'Invalid signature' if (signature != hmac)
envelope
end
# Old session key code
# @deprecated Facebook no longer provides session keys.
def get_token_info_from_session_keys(sessions, options = {})
Koala::Utils.deprecate("Facebook no longer provides session keys. The relevant OAuth methods will be removed in the next release.")
# fetch the OAuth tokens from Facebook
response = fetch_token_string({
:type => 'client_cred',
:sessions => sessions.join(",")
}, true, "exchange_sessions", options)
# Facebook returns an empty body in certain error conditions
if response == ""
raise BadFacebookResponse.new(200, '', "get_token_from_session_key received an error (empty response body) for sessions #{sessions.inspect}!")
end
MultiJson.load(response)
end
# @deprecated (see #get_token_info_from_session_keys)
def get_tokens_from_session_keys(sessions, options = {})
# get the original hash results
results = get_token_info_from_session_keys(sessions, options)
# now recollect them as just the access tokens
results.collect { |r| r ? r["access_token"] : nil }
end
# @deprecated (see #get_token_info_from_session_keys)
def get_token_from_session_key(session, options = {})
# convenience method for a single key
# gets the overlaoded strings automatically
get_tokens_from_session_keys([session], options)[0]
end
protected
def get_token_from_server(args, post = false, options = {})
# fetch the result from Facebook's servers
response = fetch_token_string(args, post, "access_token", options)
parse_access_token(response)
end
def parse_access_token(response_text)
components = response_text.split("&").inject({}) do |hash, bit|
key, value = bit.split("=")
hash.merge!(key => value)
end
components
end
def parse_unsigned_cookie(fb_cookie)
# remove the opening/closing quote
fb_cookie = fb_cookie.gsub(/\"/, "")
# since we no longer get individual cookies, we have to separate out the components ourselves
components = {}
fb_cookie.split("&").map {|param| param = param.split("="); components[param[0]] = param[1]}
# generate the signature and make sure it matches what we expect
auth_string = components.keys.sort.collect {|a| a == "sig" ? nil : "#{a}=#{components[a]}"}.reject {|a| a.nil?}.join("")
sig = Digest::MD5.hexdigest(auth_string + @app_secret)
sig == components["sig"] && (components["expires"] == "0" || Time.now.to_i < components["expires"].to_i) ? components : nil
end
def parse_signed_cookie(fb_cookie)
components = parse_signed_request(fb_cookie)
if code = components["code"]
begin
token_info = get_access_token_info(code, :redirect_uri => '')
rescue Koala::Facebook::OAuthTokenRequestError => err
if err.fb_error_type == 'OAuthException' && err.fb_error_message =~ /Code was invalid or expired/
return nil
else
raise
end
end
components.merge(token_info) if token_info
else
Koala::Utils.logger.warn("Signed cookie didn't contain Facebook OAuth code! Components: #{components}")
nil
end
end
def fetch_token_string(args, post = false, endpoint = "access_token", options = {})
response = Koala.make_request("/oauth/#{endpoint}", {
:client_id => @app_id,
:client_secret => @app_secret
}.merge!(args), post ? "post" : "get", {:use_ssl => true}.merge!(options))
raise ServerError.new(response.status, response.body) if response.status >= 500
raise OAuthTokenRequestError.new(response.status, response.body) if response.status >= 400
response.body
end
# base 64
# directly from https://github.com/facebook/crypto-request-examples/raw/master/sample.rb
def base64_url_decode(str)
str += '=' * (4 - str.length.modulo(4))
Base64.decode64(str.tr('-_', '+/'))
end
def build_url(base, require_redirect_uri = false, url_options = {})
if require_redirect_uri && !(url_options[:redirect_uri] ||= url_options.delete(:callback) || @oauth_callback_url)
raise ArgumentError, "build_url must get a callback either from the OAuth object or in the parameters!"
end
"#{base}?#{Koala::HTTPService.encode_params(url_options)}"
end
end
end
end
changed to make backwards compatible
# OpenSSL and Base64 are required to support signed_request
require 'openssl'
require 'base64'
module Koala
module Facebook
class OAuth
attr_reader :app_id, :app_secret, :oauth_callback_url
# Creates a new OAuth client.
#
# @param app_id [String, Integer] a Facebook application ID
# @param app_secret a Facebook application secret
# @param oauth_callback_url the URL in your app to which users authenticating with OAuth will be sent
def initialize(app_id, app_secret, oauth_callback_url = nil)
@app_id = app_id
@app_secret = app_secret
@oauth_callback_url = oauth_callback_url
end
# Parses the cookie set Facebook's JavaScript SDK.
#
# @note this method can only be called once per session, as the OAuth code
# Facebook supplies can only be redeemed once. Your application
# must handle cross-request storage of this information; you can no
# longer call this method multiple times. (This works out, as the
# method has to make a call to FB's servers anyway, which you don't
# want on every call.)
#
# @param cookie_hash a set of cookies that includes the Facebook cookie.
# You can pass Rack/Rails/Sinatra's cookie hash directly to this method.
#
# @return the authenticated user's information as a hash, or nil.
def get_user_info_from_cookies(cookie_hash)
if signed_cookie = cookie_hash["fbsr_#{@app_id}"]
parse_signed_cookie(signed_cookie)
elsif unsigned_cookie = cookie_hash["fbs_#{@app_id}"]
parse_unsigned_cookie(unsigned_cookie)
end
end
alias_method :get_user_info_from_cookie, :get_user_info_from_cookies
# Parses the cookie set Facebook's JavaScript SDK and returns only the user ID.
#
# @note (see #get_user_info_from_cookie)
#
# @param (see #get_user_info_from_cookie)
#
# @return the authenticated user's Facebook ID, or nil.
def get_user_from_cookies(cookies)
Koala::Utils.deprecate("Due to Facebook changes, you can only redeem an OAuth code once; it is therefore recommended not to use this method, as it will consume the code without providing you the access token. See https://developers.facebook.com/roadmap/completed-changes/#december-2012.")
if signed_cookie = cookies["fbsr_#{@app_id}"]
if components = parse_signed_request(signed_cookie)
components["user_id"]
end
elsif info = get_user_info_from_cookies(cookies)
# Parsing unsigned cookie
info["uid"]
end
end
alias_method :get_user_from_cookie, :get_user_from_cookies
# URLs
# Builds an OAuth URL, where users will be prompted to log in and for any desired permissions.
# When the users log in, you receive a callback with their
# See http://developers.facebook.com/docs/authentication/.
#
# @see #url_for_access_token
#
# @note The server-side authentication and dialog methods should only be used
# if your application can't use the Facebook Javascript SDK,
# which provides a much better user experience.
# See http://developers.facebook.com/docs/reference/javascript/.
#
# @param options any query values to add to the URL, as well as any special/required values listed below.
# @option options permissions an array or comma-separated string of desired permissions
# @option options state a unique string to serve as a CSRF (cross-site request
# forgery) token -- highly recommended for security. See
# https://developers.facebook.com/docs/howtos/login/server-side-login/
#
# @raise ArgumentError if no OAuth callback was specified in OAuth#new or in options as :redirect_uri
#
# @return an OAuth URL you can send your users to
def url_for_oauth_code(options = {})
# for permissions, see http://developers.facebook.com/docs/authentication/permissions
if permissions = options.delete(:permissions)
options[:scope] = permissions.is_a?(Array) ? permissions.join(",") : permissions
end
url_options = {:client_id => @app_id}.merge(options)
# Creates the URL for oauth authorization for a given callback and optional set of permissions
build_url("https://#{Koala.config.dialog_host}/dialog/oauth", true, url_options)
end
# Once you receive an OAuth code, you need to redeem it from Facebook using an appropriate URL.
# (This is done by your server behind the scenes.)
# See http://developers.facebook.com/docs/authentication/.
#
# @see #url_for_oauth_code
#
# @note (see #url_for_oauth_code)
#
# @param code an OAuth code received from Facebook
# @param options any additional query parameters to add to the URL
#
# @raise (see #url_for_oauth_code)
#
# @return an URL your server can query for the user's access token
def url_for_access_token(code, options = {})
# Creates the URL for the token corresponding to a given code generated by Facebook
url_options = {
:client_id => @app_id,
:code => code,
:client_secret => @app_secret
}.merge(options)
build_url("https://#{Koala.config.graph_server}/oauth/access_token", true, url_options)
end
# Builds a URL for a given dialog (feed, friends, OAuth, pay, send, etc.)
# See http://developers.facebook.com/docs/reference/dialogs/.
#
# @note (see #url_for_oauth_code)
#
# @param dialog_type the kind of Facebook dialog you want to show
# @param options any additional query parameters to add to the URL
#
# @return an URL your server can query for the user's access token
def url_for_dialog(dialog_type, options = {})
# some endpoints require app_id, some client_id, supply both doesn't seem to hurt
url_options = {:app_id => @app_id, :client_id => @app_id}.merge(options)
build_url("http://#{Koala.config.dialog_host}/dialog/#{dialog_type}", true, url_options)
end
# Generates a 'client code' from a server side long-lived access token. With the generated
# code, it can be sent to a client application which can then use it to get a long-lived
# access token from Facebook. After which the clients can use that access token to make
# requests to Facebook without having to use the server token, yet the server access token
# remains valid.
# See https://developers.facebook.com/docs/facebook-login/access-tokens/#long-via-code
#
# @param access_token a user's long lived (server) access token
#
# @raise Koala::Facebook::ServerError if Facebook returns a server error (status >= 500)
# @raise Koala::Facebook::OAuthTokenRequestError if Facebook returns an error response (status >= 400)
# @raise Koala::Facebook::BadFacebookResponse if Facebook returns a blank response
# @raise Koala::KoalaError if response does not contain 'code' hash key
#
# @return a string of the generated 'code'
def generate_client_code(access_token)
response = fetch_token_string({:redirect_uri => @oauth_callback_url, :access_token => access_token}, false, 'client_code')
# Facebook returns an empty body in certain error conditions
if response == ''
raise BadFacebookResponse.new(200, '', 'generate_client_code received an error: empty response body')
else
result = MultiJson.load(response)
end
result.has_key?('code') ? result['code'] : raise(Koala::KoalaError.new("Facebook returned a valid response without the expected 'code' in the body (response = #{response})"))
end
# access tokens
# Fetches an access token, token expiration, and other info from Facebook.
# Useful when you've received an OAuth code using the server-side authentication process.
# @see url_for_oauth_code
#
# @note (see #url_for_oauth_code)
#
# @param code (see #url_for_access_token)
# @param options any additional parameters to send to Facebook when redeeming the token
#
# @raise Koala::Facebook::OAuthTokenRequestError if Facebook returns an error response
#
# @return a hash of the access token info returned by Facebook (token, expiration, etc.)
def get_access_token_info(code, options = {})
# convenience method to get a parsed token from Facebook for a given code
# should this require an OAuth callback URL?
get_token_from_server({:code => code, :redirect_uri => options[:redirect_uri] || @oauth_callback_url}, false, options)
end
# Fetches the access token (ignoring expiration and other info) from Facebook.
# Useful when you've received an OAuth code using the server-side authentication process.
# @see get_access_token_info
#
# @note (see #url_for_oauth_code)
#
# @param (see #get_access_token_info)
#
# @raise (see #get_access_token_info)
#
# @return the access token
def get_access_token(code, options = {})
# upstream methods will throw errors if needed
if info = get_access_token_info(code, options)
string = info["access_token"]
end
end
# Fetches the application's access token, along with any other information provided by Facebook.
# See http://developers.facebook.com/docs/authentication/ (search for App Login).
#
# @param options any additional parameters to send to Facebook when redeeming the token
#
# @return the application access token and other information (expiration, etc.)
def get_app_access_token_info(options = {})
# convenience method to get a the application's sessionless access token
get_token_from_server({:grant_type => 'client_credentials'}, true, options)
end
# Fetches the application's access token (ignoring expiration and other info).
# @see get_app_access_token_info
#
# @param (see #get_app_access_token_info)
#
# @return the application access token
def get_app_access_token(options = {})
if info = get_app_access_token_info(options)
string = info["access_token"]
end
end
# Fetches an access_token with extended expiration time, along with any other information provided by Facebook.
# See https://developers.facebook.com/docs/offline-access-deprecation/#extend_token (search for fb_exchange_token).
#
# @param access_token the access token to exchange
# @param options any additional parameters to send to Facebook when exchanging tokens.
#
# @return the access token with extended expiration time and other information (expiration, etc.)
def exchange_access_token_info(access_token, options = {})
get_token_from_server({
:grant_type => 'fb_exchange_token',
:fb_exchange_token => access_token
}, true, options)
end
# Fetches an access token with extended expiration time (ignoring expiration and other info).
# @see exchange_access_token_info
#
# @param (see #exchange_access_token_info)
#
# @return A new access token or the existing one, set to expire in 60 days.
def exchange_access_token(access_token, options = {})
if info = exchange_access_token_info(access_token, options)
info["access_token"]
end
end
# Parses a signed request string provided by Facebook to canvas apps or in a secure cookie.
#
# @param input the signed request from Facebook
#
# @raise OAuthSignatureError if the signature is incomplete, invalid, or using an unsupported algorithm
#
# @return a hash of the validated request information
def parse_signed_request(input)
encoded_sig, encoded_envelope = input.split('.', 2)
raise OAuthSignatureError, 'Invalid (incomplete) signature data' unless encoded_sig && encoded_envelope
signature = base64_url_decode(encoded_sig).unpack("H*").first
envelope = MultiJson.load(base64_url_decode(encoded_envelope))
raise OAuthSignatureError, "Unsupported algorithm #{envelope['algorithm']}" if envelope['algorithm'] != 'HMAC-SHA256'
# now see if the signature is valid (digest, key, data)
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA256.new, @app_secret, encoded_envelope)
raise OAuthSignatureError, 'Invalid signature' if (signature != hmac)
envelope
end
# Old session key code
# @deprecated Facebook no longer provides session keys.
def get_token_info_from_session_keys(sessions, options = {})
Koala::Utils.deprecate("Facebook no longer provides session keys. The relevant OAuth methods will be removed in the next release.")
# fetch the OAuth tokens from Facebook
response = fetch_token_string({
:type => 'client_cred',
:sessions => sessions.join(",")
}, true, "exchange_sessions", options)
# Facebook returns an empty body in certain error conditions
if response == ""
raise BadFacebookResponse.new(200, '', "get_token_from_session_key received an error (empty response body) for sessions #{sessions.inspect}!")
end
MultiJson.load(response)
end
# @deprecated (see #get_token_info_from_session_keys)
def get_tokens_from_session_keys(sessions, options = {})
# get the original hash results
results = get_token_info_from_session_keys(sessions, options)
# now recollect them as just the access tokens
results.collect { |r| r ? r["access_token"] : nil }
end
# @deprecated (see #get_token_info_from_session_keys)
def get_token_from_session_key(session, options = {})
# convenience method for a single key
# gets the overlaoded strings automatically
get_tokens_from_session_keys([session], options)[0]
end
protected
def get_token_from_server(args, post = false, options = {})
# fetch the result from Facebook's servers
response = fetch_token_string(args, post, "access_token", options)
parse_access_token(response)
end
def parse_access_token(response_text)
components = response_text.split("&").inject({}) do |hash, bit|
key, value = bit.split("=")
hash.merge!(key => value)
end
components
end
def parse_unsigned_cookie(fb_cookie)
# remove the opening/closing quote
fb_cookie = fb_cookie.gsub(/\"/, "")
# since we no longer get individual cookies, we have to separate out the components ourselves
components = {}
fb_cookie.split("&").map {|param| param = param.split("="); components[param[0]] = param[1]}
# generate the signature and make sure it matches what we expect
auth_string = components.keys.sort.collect {|a| a == "sig" ? nil : "#{a}=#{components[a]}"}.reject {|a| a.nil?}.join("")
sig = Digest::MD5.hexdigest(auth_string + @app_secret)
sig == components["sig"] && (components["expires"] == "0" || Time.now.to_i < components["expires"].to_i) ? components : nil
end
def parse_signed_cookie(fb_cookie)
components = parse_signed_request(fb_cookie)
if code = components["code"]
begin
token_info = get_access_token_info(code, :redirect_uri => '')
rescue Koala::Facebook::OAuthTokenRequestError => err
if err.fb_error_type == 'OAuthException' && err.fb_error_message =~ /Code was invalid or expired/
return nil
else
raise
end
end
components.merge(token_info) if token_info
else
Koala::Utils.logger.warn("Signed cookie didn't contain Facebook OAuth code! Components: #{components}")
nil
end
end
def fetch_token_string(args, post = false, endpoint = "access_token", options = {})
response = Koala.make_request("/oauth/#{endpoint}", {
:client_id => @app_id,
:client_secret => @app_secret
}.merge!(args), post ? "post" : "get", {:use_ssl => true}.merge!(options))
raise ServerError.new(response.status, response.body) if response.status >= 500
raise OAuthTokenRequestError.new(response.status, response.body) if response.status >= 400
response.body
end
# base 64
# directly from https://github.com/facebook/crypto-request-examples/raw/master/sample.rb
def base64_url_decode(str)
str += '=' * (4 - str.length.modulo(4))
Base64.decode64(str.tr('-_', '+/'))
end
def build_url(base, require_redirect_uri = false, url_options = {})
if require_redirect_uri && !(url_options[:redirect_uri] ||= url_options.delete(:callback) || @oauth_callback_url)
raise ArgumentError, "build_url must get a callback either from the OAuth object or in the parameters!"
end
"#{base}?#{Koala::HTTPService.encode_params(url_options)}"
end
end
end
end
|
require 'thor'
require 'yaml'
require 'net/ssh'
require 'rspec/core/rake_task'
require "highline/import"
require_relative '../kondate'
require 'fileutils'
require 'shellwords'
require 'find'
module Kondate
class CLI < Thor
# cf. http://qiita.com/KitaitiMakoto/items/c6b9d6311c20a3cc21f9
def self.exit_on_failure?
true
end
class_option :config, :aliases => ["-c"], :type => :string, :default => nil
class_option :dry_run, :type => :boolean, :default => false
# default_command :itamae
def initialize(args = [], opts = [], config = {})
super
Config.configure(@options)
end
desc "init [target_dir = .]", "Initialize kondate directory tree"
def init(target_dir = '.')
Config.kondate_directories.each do |_, dir|
$stdout.puts "mkdir -p #{File.join(target_dir, dir)}"
FileUtils.mkdir_p(File.join(target_dir, dir)) unless @options[:dry_run]
end
templates_dir = File.join(Kondate::ROOT, 'lib', 'kondate', 'templates')
templates_dir_length = templates_dir.length
Find.find(templates_dir).select {|f| File.file?(f) }.each do |src|
next if File.basename(src) == '.gitkeep'
dst = File.join(target_dir, src[templates_dir_length+1 .. -1])
dst_dir = File.dirname(dst)
unless Dir.exist?(dst_dir)
$stdout.puts "mkdir -p #{dst_dir}"
FileUtils.mkdir_p(dst_dir) unless @options[:dry_run]
end
$stdout.puts "cp #{src} #{dst}"
FileUtils.copy(src, dst) unless @options[:dry_run]
end
end
desc "itamae <host>", "Execute itamae"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :profile, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Save profiling data", :banner => "PATH"
def itamae(host)
builder, property_files = build_property_files(host)
property_files.each do |role, property_file|
ENV['TARGET_HOST'] = host
ENV['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/itamae/kondate"
command = "bundle exec itamae ssh"
command << " -h #{host}"
properties = YAML.load_file(property_file)
if @options[:vagrant]
command << " --vagrant"
else
config = Net::SSH::Config.for(host)
command << " -u #{properties['ssh_user'] || config[:user] || ENV['USER']}"
command << " -i #{(properties['ssh_keys'] || []).first || (config[:ssh_keys] || []).first || (File.exist?(File.expand_path('~/.ssh/id_dsa')) ? '~/.ssh/id_dsa' : '~/.ssh/id_rsa')}"
command << " -p #{properties['ssh_port'] || config[:port] || 22}"
end
command << " -y #{property_file}"
command << " -l=debug" if @options[:debug]
command << " --dry-run" if @options[:dry_run]
command << " --profile=#{@options[:profile]}" if @options[:profile]
command << " bootstrap.rb"
$stdout.puts command
exit(-1) unless system(command)
end
end
desc "serverspec <host>", "Execute serverspec"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
def serverspec(host)
builder, property_files = build_property_files(host)
ENV['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/serverspec/kondate"
ENV['TARGET_VAGRANT'] = '1' if @options[:vagrant]
property_files.each do |role, property_file|
RSpec::Core::RakeTask.new([host, role].join(':'), :recipe) do |t, args|
ENV['TARGET_HOST'] = host
ENV['TARGET_NODE_FILE'] = property_file
recipes = YAML.load_file(property_file)['attributes'].keys.map {|recipe|
File.join(Config.middleware_recipes_serverspec_dir, recipe)
}.compact
recipes << File.join(Config.roles_recipes_serverspec_dir, role)
t.pattern = '{' + recipes.join(',') + '}_spec.rb'
end
Rake::Task["#{host}:#{role}"].invoke(@options[:recipe])
end
end
private
def build_property_files(host)
builder = PropertyBuilder.new(host)
roles = builder.filter_roles(@options[:role])
if roles.nil? or roles.empty?
$stderr.puts 'No role'
exit(1)
end
$stdout.puts "roles: [#{roles.join(', ')}]"
property_files = {}
roles.each do |role|
if path = builder.install(role, @options[:recipe])
property_files[role] = path
$stdout.puts "# #{role}"
$stdout.puts mask_secrets(File.read(path))
else
$stdout.puts "# #{role} (no attribute, skipped)"
end
end
if property_files.empty?
$stderr.puts "Nothing to run"
exit(1)
end
if @options[:confirm]
prompt = ask "Proceed? (y/n):"
exit(0) unless prompt == 'y'
end
[builder, property_files]
end
def mask_secrets(str)
str.gsub(/(.*key[^:]*): (.*)$/, '\1: *******').
gsub(/(.*password[^:]*): (.*)$/, '\1: *******')
end
end
end
Support itamae recipe-graph option
require 'thor'
require 'yaml'
require 'net/ssh'
require 'rspec/core/rake_task'
require "highline/import"
require_relative '../kondate'
require 'fileutils'
require 'shellwords'
require 'find'
module Kondate
class CLI < Thor
# cf. http://qiita.com/KitaitiMakoto/items/c6b9d6311c20a3cc21f9
def self.exit_on_failure?
true
end
class_option :config, :aliases => ["-c"], :type => :string, :default => nil
class_option :dry_run, :type => :boolean, :default => false
# default_command :itamae
def initialize(args = [], opts = [], config = {})
super
Config.configure(@options)
end
desc "init [target_dir = .]", "Initialize kondate directory tree"
def init(target_dir = '.')
Config.kondate_directories.each do |_, dir|
$stdout.puts "mkdir -p #{File.join(target_dir, dir)}"
FileUtils.mkdir_p(File.join(target_dir, dir)) unless @options[:dry_run]
end
templates_dir = File.join(Kondate::ROOT, 'lib', 'kondate', 'templates')
templates_dir_length = templates_dir.length
Find.find(templates_dir).select {|f| File.file?(f) }.each do |src|
next if File.basename(src) == '.gitkeep'
dst = File.join(target_dir, src[templates_dir_length+1 .. -1])
dst_dir = File.dirname(dst)
unless Dir.exist?(dst_dir)
$stdout.puts "mkdir -p #{dst_dir}"
FileUtils.mkdir_p(dst_dir) unless @options[:dry_run]
end
$stdout.puts "cp #{src} #{dst}"
FileUtils.copy(src, dst) unless @options[:dry_run]
end
end
desc "itamae <host>", "Execute itamae"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :profile, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Save profiling data", :banner => "PATH"
option :recipe_graph, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Write recipe dependency graph in DOT", :banner => "PATH"
def itamae(host)
builder, property_files = build_property_files(host)
property_files.each do |role, property_file|
ENV['TARGET_HOST'] = host
ENV['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/itamae/kondate"
command = "bundle exec itamae ssh"
command << " -h #{host}"
properties = YAML.load_file(property_file)
if @options[:vagrant]
command << " --vagrant"
else
config = Net::SSH::Config.for(host)
command << " -u #{properties['ssh_user'] || config[:user] || ENV['USER']}"
command << " -i #{(properties['ssh_keys'] || []).first || (config[:ssh_keys] || []).first || (File.exist?(File.expand_path('~/.ssh/id_dsa')) ? '~/.ssh/id_dsa' : '~/.ssh/id_rsa')}"
command << " -p #{properties['ssh_port'] || config[:port] || 22}"
end
command << " -y #{property_file}"
command << " -l=debug" if @options[:debug]
command << " --dry-run" if @options[:dry_run]
command << " --profile=#{@options[:profile]}" if @options[:profile]
command << " --recipe-graph=#{@options[:recipe_graph]}" if @options[:recipe_graph]
command << " bootstrap.rb"
$stdout.puts command
exit(-1) unless system(command)
end
end
desc "serverspec <host>", "Execute serverspec"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
def serverspec(host)
builder, property_files = build_property_files(host)
ENV['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/serverspec/kondate"
ENV['TARGET_VAGRANT'] = '1' if @options[:vagrant]
property_files.each do |role, property_file|
RSpec::Core::RakeTask.new([host, role].join(':'), :recipe) do |t, args|
ENV['TARGET_HOST'] = host
ENV['TARGET_NODE_FILE'] = property_file
recipes = YAML.load_file(property_file)['attributes'].keys.map {|recipe|
File.join(Config.middleware_recipes_serverspec_dir, recipe)
}.compact
recipes << File.join(Config.roles_recipes_serverspec_dir, role)
t.pattern = '{' + recipes.join(',') + '}_spec.rb'
end
Rake::Task["#{host}:#{role}"].invoke(@options[:recipe])
end
end
private
def build_property_files(host)
builder = PropertyBuilder.new(host)
roles = builder.filter_roles(@options[:role])
if roles.nil? or roles.empty?
$stderr.puts 'No role'
exit(1)
end
$stdout.puts "roles: [#{roles.join(', ')}]"
property_files = {}
roles.each do |role|
if path = builder.install(role, @options[:recipe])
property_files[role] = path
$stdout.puts "# #{role}"
$stdout.puts mask_secrets(File.read(path))
else
$stdout.puts "# #{role} (no attribute, skipped)"
end
end
if property_files.empty?
$stderr.puts "Nothing to run"
exit(1)
end
if @options[:confirm]
prompt = ask "Proceed? (y/n):"
exit(0) unless prompt == 'y'
end
[builder, property_files]
end
def mask_secrets(str)
str.gsub(/(.*key[^:]*): (.*)$/, '\1: *******').
gsub(/(.*password[^:]*): (.*)$/, '\1: *******')
end
end
end
|
require 'thor'
require 'yaml'
require 'net/ssh'
require "highline/import"
require_relative '../kondate'
require 'fileutils'
require 'shellwords'
require 'find'
require 'facter'
require 'parallel'
module Kondate
class CLI < Thor
# cf. http://qiita.com/KitaitiMakoto/items/c6b9d6311c20a3cc21f9
def self.exit_on_failure?
true
end
class_option :config, :aliases => ["-c"], :type => :string, :default => nil
class_option :dry_run, :type => :boolean, :default => false
# default_command :itamae
def initialize(args = [], opts = [], config = {})
super
Config.configure(@options)
end
desc "init [target_dir]", "Initialize kondate directory tree"
def init(target_dir)
Config.kondate_directories.each do |_, dir|
$stdout.puts "mkdir -p #{File.join(target_dir, dir)}"
FileUtils.mkdir_p(File.join(target_dir, dir)) unless @options[:dry_run]
end
templates_dir = File.join(Kondate::ROOT, 'lib', 'kondate', 'templates')
templates_dir_length = templates_dir.length
Find.find(templates_dir).select {|f| File.file?(f) }.each do |src|
next if File.basename(src) == '.gitkeep'
dst = File.join(target_dir, src[templates_dir_length+1 .. -1])
dst_dir = File.dirname(dst)
unless Dir.exist?(dst_dir)
$stdout.puts "mkdir -p #{dst_dir}"
FileUtils.mkdir_p(dst_dir) unless @options[:dry_run]
end
$stdout.puts "cp #{src} #{dst}"
FileUtils.copy(src, dst) unless @options[:dry_run]
end
end
desc "itamae <host>", "Execute itamae"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :profile, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Save profiling data", :banner => "PATH"
option :recipe_graph, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Write recipe dependency graph in DOT", :banner => "PATH"
def itamae(host)
property_files = build_property_files(host)
begin
if proceed?(property_files)
exit(-1) unless do_itamae(host, property_files)
end
ensure
clean_property_files(property_files)
end
end
desc "itamae-role <role>", "Execute itamae for multiple hosts in the role"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :profile, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Save profiling data", :banner => "PATH"
option :recipe_graph, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Write recipe dependency graph in DOT", :banner => "PATH"
option :parallel, :aliases => ["-p"], :type => :numeric, :default => Facter['processorcount'].value.to_i
def itamae_role(role)
$stdout.puts "Number of parallels is #{@options[:parallel]}"
hosts = Kondate::Config.host_plugin.get_hosts(role)
if hosts.nil? or hosts.empty?
$stderr.puts 'No host'
exit(1)
end
$stdout.puts "Target hosts are [#{hosts.join(", ")}]"
property_files_of_host, summarized_property_files, hosts_of_role = build_property_files_of_host(hosts)
begin
if proceed?(summarized_property_files, hosts_of_role)
successes = Parallel.map(hosts, in_processes: @options[:parallel]) do |host|
do_itamae(host, property_files_of_host[host])
end
exit(-1) unless successes.all?
end
ensure
clean_property_files_of_host(property_files_of_host)
end
end
desc "serverspec <host>", "Execute serverspec"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
def serverspec(host)
property_files = build_property_files(host)
begin
if proceed?(property_files)
exit(-1) unless do_serverspec(host, property_files)
end
ensure
clean_property_files(property_files)
end
end
desc "serverspec-role <role>", "Execute serverspec for multiple hosts in the role"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :parallel, :aliases => ["-p"], :type => :numeric, :default => Facter['processorcount'].value.to_i
def serverspec_role(role)
$stdout.puts "Number of parallels is #{@options[:parallel]}"
hosts = Kondate::Config.host_plugin.get_hosts(role)
if hosts.nil? or hosts.empty?
$stderr.puts 'No host'
exit(1)
end
$stdout.puts "Target hosts are [#{hosts.join(", ")}]"
property_files_of_host, summarized_property_files, hosts_of_role = build_property_files_of_host(hosts)
begin
if proceed?(summarized_property_files, hosts_of_role)
successes = Parallel.map(hosts, in_processes: @options[:parallel]) do |host|
do_serverspec(host, property_files_of_host[host])
end
exit(-1) unless successes.all?
end
ensure
clean_property_files_of_host(property_files_of_host)
end
end
private
def do_itamae(host, property_files)
env = {}
env['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/itamae/kondate"
property_files.each do |role, property_file|
next if property_file.nil?
command = "bundle exec itamae ssh"
command << " -h #{host}"
properties = YAML.load_file(property_file)
if @options[:vagrant]
command << " --vagrant"
else
config = Net::SSH::Config.for(host)
command << " -u #{properties['ssh_user'] || config[:user] || ENV['USER']}"
command << " -i #{(properties['ssh_keys'] || []).first || (config[:ssh_keys] || []).first || (File.exist?(File.expand_path('~/.ssh/id_dsa')) ? '~/.ssh/id_dsa' : '~/.ssh/id_rsa')}"
command << " -p #{properties['ssh_port'] || config[:port] || 22}"
end
command << " -y #{property_file}"
command << " -l=debug" if @options[:debug]
command << " --dry-run" if @options[:dry_run]
command << " --profile=#{@options[:profile]}" if @options[:profile]
command << " --recipe-graph=#{@options[:recipe_graph]}" if @options[:recipe_graph]
command << " bootstrap.rb"
$stdout.puts "env #{env.map {|k, v| "#{k}=#{v.shellescape}" }.join(' ')} #{command}"
return false unless system(env, command)
end
true
end
def do_serverspec(host, property_files)
env = {}
env['TARGET_VAGRANT'] = '1' if @options[:vagrant]
env['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/serverspec/kondate"
property_files.each do |role, property_file|
next if property_file.nil?
recipes = YAML.load_file(property_file)['attributes'].keys.map {|recipe|
File.join(Config.middleware_recipes_serverspec_dir, recipe)
}.compact
recipes << File.join(Config.roles_recipes_serverspec_dir, role)
spec_files = recipes.map {|recipe| "#{recipe}_spec.rb"}.select! {|spec| File.exist?(spec) }
env['TARGET_HOST'] = host
env['TARGET_NODE_FILE'] = property_file
command = "bundle exec rspec #{spec_files.map{|f| f.shellescape }.join(' ')}"
$stdout.puts "env #{env.map {|k, v| "#{k}=#{v.shellescape}" }.join(' ')} #{command}"
return false unless system(env, command)
end
true
end
def proceed?(property_files, hosts_of_role = {})
print_property_files(property_files, hosts_of_role)
if property_files.values.compact.empty?
$stderr.puts "Nothing to run"
false
elsif @options[:confirm]
prompt = ask "Proceed? (y/n):"
prompt == 'y'
else
true
end
end
def print_property_files(property_files, hosts_of_role = {})
roles = property_files.keys
if roles.nil? or roles.empty?
$stderr.puts 'No role'
return
end
$stdout.puts "Show property files for roles: [#{roles.join(", ")}]"
property_files.each do |role, property_file|
hosts = hosts_of_role[role]
if hosts.nil? # itamae
$stdout.print "Show property file for role: #{role}"
else # itamae_role
$stdout.print "Show representative property file for role: #{role}"
$stdout.print " [#{hosts.join(", ")}]"
end
if property_file
$stdout.puts
$stdout.puts mask_secrets(File.read(property_file))
else
$stdout.puts " (no attribute, skipped)"
end
end
end
def clean_property_files(property_files)
property_files.values.each do |file|
File.unlink(file) rescue nil
end
end
def clean_property_files_of_host(property_files_of_host)
property_files_of_host.values.each do |property_files|
clean_property_files(property_files)
end
end
# @return [Hash] key value pairs whoses keys are roles and values are path (or nil)
def build_property_files(host)
builder = PropertyBuilder.new(host)
roles = builder.filter_roles(@options[:role])
property_files = {}
roles.each do |role|
if path = builder.install(role, @options[:recipe])
property_files[role] = path
else
property_files[role] = nil
end
end
property_files
end
def build_property_files_of_host(hosts)
summarized_property_files = {}
property_files_of_host = {}
hosts_of_role = {}
hosts.each do |host|
property_files = build_property_files(host)
property_files_of_host[host] = property_files
property_files.each {|role, path| summarized_property_files[role] ||= path }
property_files.each {|role, path| (hosts_of_role[role] ||= []) << host }
end
[property_files_of_host, summarized_property_files, hosts_of_role]
end
def mask_secrets(str)
str.gsub(/(.*key[^:]*): (.*)$/, '\1: *******').
gsub(/(.*password[^:]*): (.*)$/, '\1: *******')
end
end
end
refactoring: DRY
require 'thor'
require 'yaml'
require 'net/ssh'
require "highline/import"
require_relative '../kondate'
require 'fileutils'
require 'shellwords'
require 'find'
require 'facter'
require 'parallel'
module Kondate
class CLI < Thor
# cf. http://qiita.com/KitaitiMakoto/items/c6b9d6311c20a3cc21f9
def self.exit_on_failure?
true
end
class_option :config, :aliases => ["-c"], :type => :string, :default => nil
class_option :dry_run, :type => :boolean, :default => false
# default_command :itamae
def initialize(args = [], opts = [], config = {})
super
Config.configure(@options)
end
desc "init [target_dir]", "Initialize kondate directory tree"
def init(target_dir)
Config.kondate_directories.each do |_, dir|
$stdout.puts "mkdir -p #{File.join(target_dir, dir)}"
FileUtils.mkdir_p(File.join(target_dir, dir)) unless @options[:dry_run]
end
templates_dir = File.join(Kondate::ROOT, 'lib', 'kondate', 'templates')
templates_dir_length = templates_dir.length
Find.find(templates_dir).select {|f| File.file?(f) }.each do |src|
next if File.basename(src) == '.gitkeep'
dst = File.join(target_dir, src[templates_dir_length+1 .. -1])
dst_dir = File.dirname(dst)
unless Dir.exist?(dst_dir)
$stdout.puts "mkdir -p #{dst_dir}"
FileUtils.mkdir_p(dst_dir) unless @options[:dry_run]
end
$stdout.puts "cp #{src} #{dst}"
FileUtils.copy(src, dst) unless @options[:dry_run]
end
end
desc "itamae <host>", "Execute itamae"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :profile, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Save profiling data", :banner => "PATH"
option :recipe_graph, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Write recipe dependency graph in DOT", :banner => "PATH"
def itamae(host)
with_host(host) {|property_files| do_itamae(host, property_files) }
end
desc "itamae-role <role>", "Execute itamae for multiple hosts in the role"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :profile, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Save profiling data", :banner => "PATH"
option :recipe_graph, :type => :string, :default => nil, :desc => "[EXPERIMENTAL] Write recipe dependency graph in DOT", :banner => "PATH"
option :parallel, :aliases => ["-p"], :type => :numeric, :default => Facter['processorcount'].value.to_i
def itamae_role(role)
with_role(role) {|host, property_files| do_itamae(host, property_files) }
end
desc "serverspec <host>", "Execute serverspec"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
def serverspec(host)
with_host(host) {|property_files| do_serverspec(host, property_files) }
end
desc "serverspec-role <role>", "Execute serverspec for multiple hosts in the role"
option :role, :type => :array, :default => []
option :recipe, :type => :array, :default => []
option :debug, :aliases => ["-d"], :type => :boolean, :default => false
option :confirm, :type => :boolean, :default => true
option :vagrant, :type => :boolean, :default => false
option :parallel, :aliases => ["-p"], :type => :numeric, :default => Facter['processorcount'].value.to_i
def serverspec_role(role)
with_role(role) {|host, property_files| do_serverspec(host, property_files) }
end
private
def with_host(host, &block)
property_files = build_property_files(host)
begin
print_property_files(property_files)
if proceed?(property_files)
exit(-1) unless yield(property_files)
end
ensure
clean_property_files(property_files)
end
end
def with_role(role, &block)
$stdout.puts "Number of parallels is #{@options[:parallel]}"
hosts = Kondate::Config.host_plugin.get_hosts(role)
if hosts.nil? or hosts.empty?
$stderr.puts 'No host'
exit(1)
end
$stdout.puts "Target hosts are [#{hosts.join(", ")}]"
property_files_of_host, summarized_property_files, hosts_of_role = build_property_files_of_host(hosts)
begin
print_property_files(summarized_property_files, hosts_of_role)
if proceed?(summarized_property_files)
successes = Parallel.map(hosts, in_processes: @options[:parallel]) do |host|
yield(host, property_files_of_host[host])
end
exit(-1) unless successes.all?
end
ensure
property_files_of_host.values.each {|property_files| clean_property_files(property_files) }
end
end
def do_itamae(host, property_files)
env = {}
env['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/itamae/kondate"
property_files.each do |role, property_file|
next if property_file.nil?
command = "bundle exec itamae ssh"
command << " -h #{host}"
properties = YAML.load_file(property_file)
if @options[:vagrant]
command << " --vagrant"
else
config = Net::SSH::Config.for(host)
command << " -u #{properties['ssh_user'] || config[:user] || ENV['USER']}"
command << " -i #{(properties['ssh_keys'] || []).first || (config[:ssh_keys] || []).first || (File.exist?(File.expand_path('~/.ssh/id_dsa')) ? '~/.ssh/id_dsa' : '~/.ssh/id_rsa')}"
command << " -p #{properties['ssh_port'] || config[:port] || 22}"
end
command << " -y #{property_file}"
command << " -l=debug" if @options[:debug]
command << " --dry-run" if @options[:dry_run]
command << " --profile=#{@options[:profile]}" if @options[:profile]
command << " --recipe-graph=#{@options[:recipe_graph]}" if @options[:recipe_graph]
command << " bootstrap.rb"
$stdout.puts "env #{env.map {|k, v| "#{k}=#{v.shellescape}" }.join(' ')} #{command}"
return false unless system(env, command)
end
true
end
def do_serverspec(host, property_files)
env = {}
env['TARGET_VAGRANT'] = '1' if @options[:vagrant]
env['RUBYOPT'] = "-I #{Config.plugin_dir} -r bundler/setup -r ext/serverspec/kondate"
property_files.each do |role, property_file|
next if property_file.nil?
recipes = YAML.load_file(property_file)['attributes'].keys.map {|recipe|
File.join(Config.middleware_recipes_serverspec_dir, recipe)
}.compact
recipes << File.join(Config.roles_recipes_serverspec_dir, role)
spec_files = recipes.map {|recipe| "#{recipe}_spec.rb"}.select! {|spec| File.exist?(spec) }
env['TARGET_HOST'] = host
env['TARGET_NODE_FILE'] = property_file
command = "bundle exec rspec #{spec_files.map{|f| f.shellescape }.join(' ')}"
$stdout.puts "env #{env.map {|k, v| "#{k}=#{v.shellescape}" }.join(' ')} #{command}"
return false unless system(env, command)
end
true
end
def proceed?(property_files)
if property_files.values.compact.empty?
$stderr.puts "Nothing to run"
false
elsif @options[:confirm]
prompt = ask "Proceed? (y/n):"
prompt == 'y'
else
true
end
end
def print_property_files(property_files, hosts_of_role = {})
roles = property_files.keys
if roles.nil? or roles.empty?
$stderr.puts 'No role'
return
end
$stdout.puts "Show property files for roles: [#{roles.join(", ")}]"
property_files.each do |role, property_file|
hosts = hosts_of_role[role]
if hosts.nil? # itamae
$stdout.print "Show property file for role: #{role}"
else # itamae_role
$stdout.print "Show representative property file for role: #{role}"
$stdout.print " [#{hosts.join(", ")}]"
end
if property_file
$stdout.puts
$stdout.puts mask_secrets(File.read(property_file))
else
$stdout.puts " (no attribute, skipped)"
end
end
end
def clean_property_files(property_files)
property_files.values.each do |file|
File.unlink(file) rescue nil
end
end
# @return [Hash] key value pairs whoses keys are roles and values are path (or nil)
def build_property_files(host)
builder = PropertyBuilder.new(host)
roles = builder.filter_roles(@options[:role])
property_files = {}
roles.each do |role|
if path = builder.install(role, @options[:recipe])
property_files[role] = path
else
property_files[role] = nil
end
end
property_files
end
def build_property_files_of_host(hosts)
summarized_property_files = {}
property_files_of_host = {}
hosts_of_role = {}
hosts.each do |host|
property_files = build_property_files(host)
property_files_of_host[host] = property_files
property_files.each {|role, path| summarized_property_files[role] ||= path }
property_files.each {|role, path| (hosts_of_role[role] ||= []) << host }
end
[property_files_of_host, summarized_property_files, hosts_of_role]
end
def mask_secrets(str)
str.gsub(/(.*key[^:]*): (.*)$/, '\1: *******').
gsub(/(.*password[^:]*): (.*)$/, '\1: *******')
end
end
end
|
module Kris
class Plugin
class << self
def autoload(robot)
Dir.glob(File.expand_path('./plugin/*.rb')).each do |file|
require file
klass = eval(filename_classify(File.basename(file, '.rb'))).new(robot)
yield klass
end
end
def filename_classify(filename)
filename.split('_').map(&:capitalize).join
end
end
COMMAND_NAMES = %w(
ADMIN
AWAY
CREDITS
CYCLE
DALINFO
INVITE
ISON
JOIN
KICK
KNOCK
LICENSE
LINKS
LIST
LUSERS
MAP
MODE
MOTD
NAMES
NICK
NOTICE
PART
PASS
PING
PONG
PRIVMSG
QUIT
RULES
SETNAME
SILENCE
STATS
TIME
TOPIC
USER
USERHOST
VERSION
VHOST
WATCH
WHO
WHOIS
WHOWAS
).freeze
def initialize(robot)
@robot = robot
end
def boot
load_callbacks
start_notification_scheduler
end
protected
# Call response method is for backwords compatibility
def on_privmsg(message)
response(message)
end
# Override this method if you want get scheduled notification.
def notify; end
def notice(channel, message)
@robot.notice(channel, ":#{message}")
end
def privmsg(channel, message)
@robot.privmsg(channel, ":#{message}")
end
def reply(channel, reply_to, message)
@robot.privmsg(channel, ":#{reply_to}: #{message}")
end
private
def load_callbacks
COMMAND_NAMES.each do |name|
method_name = "on_#{name.downcase}"
next unless self.class.method_defined?(method_name)
@robot.send(method_name) do |message|
send(method_name, message)
end
end
end
def start_notification_scheduler
return unless self.class.public_method_defined?(:notify)
Thread.start do
loop do
notify
sleep 1
end
end
end
end
end
call respoonse method if defined
module Kris
class Plugin
class << self
def autoload(robot)
Dir.glob(File.expand_path('./plugin/*.rb')).each do |file|
require file
klass = eval(filename_classify(File.basename(file, '.rb'))).new(robot)
yield klass
end
end
def filename_classify(filename)
filename.split('_').map(&:capitalize).join
end
end
COMMAND_NAMES = %w(
ADMIN
AWAY
CREDITS
CYCLE
DALINFO
INVITE
ISON
JOIN
KICK
KNOCK
LICENSE
LINKS
LIST
LUSERS
MAP
MODE
MOTD
NAMES
NICK
NOTICE
PART
PASS
PING
PONG
PRIVMSG
QUIT
RULES
SETNAME
SILENCE
STATS
TIME
TOPIC
USER
USERHOST
VERSION
VHOST
WATCH
WHO
WHOIS
WHOWAS
).freeze
def initialize(robot)
@robot = robot
end
def boot
load_callbacks
start_notification_scheduler
end
protected
# Call response method is for backwords compatibility
def on_privmsg(message)
response(message) if self.class.method_defined?(:response)
end
# Override this method if you want get scheduled notification.
def notify; end
def notice(channel, message)
@robot.notice(channel, ":#{message}")
end
def privmsg(channel, message)
@robot.privmsg(channel, ":#{message}")
end
def reply(channel, reply_to, message)
@robot.privmsg(channel, ":#{reply_to}: #{message}")
end
private
def load_callbacks
COMMAND_NAMES.each do |name|
method_name = "on_#{name.downcase}"
next unless self.class.method_defined?(method_name)
@robot.send(method_name) do |message|
send(method_name, message)
end
end
end
def start_notification_scheduler
return unless self.class.public_method_defined?(:notify)
Thread.start do
loop do
notify
sleep 1
end
end
end
end
end
|
module Akc::Controllers
class CheckOutAkc < R '/check_out_akc/(\d+)'
def get(id)
@user = User.find(id)
render :check_out_akc
end
end
class OzQuizReleased < R '/oz_quiz_released/(\d+)'
def get(id)
@user = User.find(id)
render :oz_quiz_released
end
end
class Index < R '/'
@cacheable = true
def get
#z = Time.now
@users = User.find(:all, :include => :latest_score, :order => 'high_score DESC, akc_scores.when DESC', :limit => 3)
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 3)
@users_by_scores_submitted = User.find(:all, :order => 'total_scores DESC', :limit => 3)
@shouts = Shout.find(:all, :order => "posted DESC", :limit => 5)
@shout = Shout.new
@user = User.new
@user_count = User.count
@score_count = Score.count
#puts "time in controller: #{Time.now - z}"
render :index
end
end
class UpdateUser < R '/users/update'
def get
return unless logged_in?
@user = current_user
render :update_user
end
def post
return unless logged_in?
@user = current_user
if @user.update_attributes(:has_avatar => input.has_avatar, :avatar => (!input.avatar.nil? ? input.avatar[:tempfile] : nil))
add_success("User updated")
redirect "/users/#{@user.id}"
else
@user.errors.full_messages.each { |msg| add_error(msg) }
render :update_user
end
end
end
class AddScore < R '/add/(.*?)/(\d+)/(.*?)/(.*?)/(\d+)'
def get(source, version, name, crypt, score)
source = CGI.unescape(source).gsub(/ +/, ' ')
name = CGI.unescape(name).gsub(/ +/, ' ')
crypt = CGI.unescape(crypt).gsub(/ +/, ' ')
# User.transaction do
source = (source == '' ? 'dashboard' : source)
user = User.find_by_name(name)
if user
unless user.crypt == crypt
return mab { text "0|http://akc.bloople.net/invalid_crypt" }
end
else
user = User.create(:name => name, :crypt => crypt, :seen_oz_quiz_released => true)
end
Score.create(:version => version, :user => user, :score => score, :when => Time.now, :source => source)
if !user.seen_oz_quiz_released?
user.seen_oz_quiz_released = true
user.save!
return mab { text "0|http://akc.bloople.net/oz_quiz_released/#{user.id}" }
else
return mab { text "" }
end
end
# end
end
class HighScores < R '/high_scores'
@cacheable = true
def get
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 1000)
@users = User.find(:all, :include => :latest_score, :order => 'high_score DESC, akc_scores.when DESC', :limit => 1000)
render :high_scores
end
end
class HighScoresAbsolute < R '/high_scores_absolute.rss'
def get
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 50)
render :high_scores_absolute
end
end
class HighScoresAverage < R '/high_scores_average.rss'
def get
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 50)
@users = User.find(:all, :include => :latest_score, :order => 'high_score DESC, akc_scores.when DESC', :limit => 50)
render :high_scores_average
end
end
class Statistics
def get
render :statistics
end
end
class ScoresByDateGraph < R '/scores_by_date_graph'
@cacheable = true
def get
scores = ActiveRecord::Base.connection.select_all("SELECT COUNT(id) AS count, DATE(akc_scores.when) AS date FROM akc_scores GROUP BY DATE(akc_scores.when) ORDER BY DATE(akc_scores.when) ASC")
days = []
counts = []
scores.each do |s|
days << Date.parse(s['date'])
counts << s['count'].to_i
end
g = Gruff::Line.new('984x480')
g.instance_variable_set(:@raw_columns, 1230.0)
g.instance_variable_set(:@raw_rows, 600)
g.instance_variable_set(:@scale, 0.8)
g.data("Scores", counts)
lr = LinearRegression.new(counts)
g.data("Trend line", lr.fit)
g.labels = { 0 => "#{days.first.mday} #{Date::MONTHNAMES[days.first.month]} #{days.first.year}", (days.size - 1) => "#{days.last.mday} #{Date::MONTHNAMES[days.last.month]} #{days.last.year}" }
g.theme_37signals
g.minimum_value = [lr.fit.min, 0].min
g.title = "Scores submitted per day"
@headers['Content-Type'] = 'image/png'
@headers['Content-Disposition'] = 'inline'
g.to_blob
end
end
class HighScoresGraph < R '/high_scores_graph'
@cacheable = true
def get
scores = Score.find(:all, :order => "score DESC", :limit => 50)
g = Gruff::Line.new('984x480')
g.instance_variable_set(:@raw_columns, 1230.0)
g.instance_variable_set(:@raw_rows, 600)
g.instance_variable_set(:@scale, 0.8)
g.data("Scores", scores.map { |s| s.score })
labels = {}
scores.each_with_index do |s, i|
labels[i] = s.when if labels.empty? or (labels.values.last.month != s.when.month)
end
labels.each_pair { |(key, val)| labels[key] = "#{Date::MONTHNAMES[val.month]} #{val.year}" }
lr = LinearRegression.new(scores.map { |s| s.score })
g.data("Trend line", lr.fit)
first = scores.first.when
last = scores.last.when
g.labels = { 0 => "#{first.mday} #{Date::MONTHNAMES[first.month]} #{first.year}", (scores.size - 1) => "#{last.mday} #{Date::MONTHNAMES[last.month]} #{last.year}" }
g.theme_37signals
g.minimum_value = [lr.fit.min, 0].min
g.title = "Top 50 high scores"
@headers['Content-Type'] = 'image/png'
@headers['Content-Disposition'] = 'inline'
g.to_blob
end
end
class ScoresForUser < R '/scores_for_user'
def post
@search_term = input.name
@users = User.find(:all, :conditions => "name LIKE #{ActiveRecord::Base.connection.quote("%#{@search_term}%")}")
render :scores_for_user
end
end
class LatestScoresByUser < R '/users/(\d+)/latest_scores.rss'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :order => 'akc_scores.when DESC', :limit => 50)
render :latest_scores_by_user
end
end
class HighScoresByUser < R '/users/(\d+)/high_scores.rss'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :order => 'score DESC', :limit => 50)
render :high_scores_by_user
end
end
class Login < R '/users/login', '/users/logout'
def post
login input.username, input.password
if logged_in?
add_success("Logged in!")
redirect(Index)
else
add_error("Your username or password was incorrect.")
get
end
end
def get
logout
render :login
end
end
Logout = Login
class ShowUser < R '/users/(\d+)'
def get(id)
@user = User.find(id)
@latest_scores = @user.scores.find(:all, :order => 'akc_scores.when DESC', :limit => 10)
@high_scores = @user.scores.find(:all, :order => 'score DESC', :limit => 10)
@first_score = @user.scores.find(:first, :order => 'akc_scores.when ASC', :limit => 1)
@user.increment!(:view_count)
render :show
end
end
class ShowAllScoresForUser < R '/users/(\d+)/all_scores'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :order => 'akc_scores.when DESC')
render :show_all_scores_for_user
end
end
class ShowUserScoresGraph < R '/users/(\d+)/scores_graph'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :include => :user, :order => "akc_scores.when ASC")
g = Gruff::Line.new('984x480')
g.instance_variable_set(:@raw_columns, 1230.0)
g.instance_variable_set(:@raw_rows, 600)
g.instance_variable_set(:@scale, 0.8)
g.data("Scores", @scores.map { |s| s.score })
labels = {}
@scores.each_with_index do |s, i|
labels[i] = s.when if labels.empty? or (labels.values.last.month != s.when.month)
end
labels.each_pair { |(key, val)| labels[key] = "#{Date::MONTHNAMES[val.month]} #{val.year}" }
lr = LinearRegression.new(@scores.map { |s| s.score })
g.data("Trend line", lr.fit)
g.labels = labels
g.theme_37signals
g.minimum_value = [lr.fit.min, 0].min
g.title = "Scores over time"
@headers['Content-Type'] = 'image/png'
@headers['Content-Disposition'] = 'inline'
g.to_blob
end
end
class AddShout < R '/add_shout'
def post
@shout = Shout.new(:username => input.username, :text => input.text, :captcha => input.captcha, :posted => Time.now.getgm)
if @shout.save
add_success("Your shout has been published; it may take up to 10 minutes for your shout to appear on this page.")
else
@shout.errors.full_messages.each { |msg| add_error(msg) }
end
redirect '/'
end
end
class InvalidCrypt < R '/invalid_crypt'
def get
render :invalid_crypt
end
end
include StaticAssetsClass
end
Change shout published text
module Akc::Controllers
class CheckOutAkc < R '/check_out_akc/(\d+)'
def get(id)
@user = User.find(id)
render :check_out_akc
end
end
class OzQuizReleased < R '/oz_quiz_released/(\d+)'
def get(id)
@user = User.find(id)
render :oz_quiz_released
end
end
class Index < R '/'
@cacheable = true
def get
#z = Time.now
@users = User.find(:all, :include => :latest_score, :order => 'high_score DESC, akc_scores.when DESC', :limit => 3)
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 3)
@users_by_scores_submitted = User.find(:all, :order => 'total_scores DESC', :limit => 3)
@shouts = Shout.find(:all, :order => "posted DESC", :limit => 5)
@shout = Shout.new
@user = User.new
@user_count = User.count
@score_count = Score.count
#puts "time in controller: #{Time.now - z}"
render :index
end
end
class UpdateUser < R '/users/update'
def get
return unless logged_in?
@user = current_user
render :update_user
end
def post
return unless logged_in?
@user = current_user
if @user.update_attributes(:has_avatar => input.has_avatar, :avatar => (!input.avatar.nil? ? input.avatar[:tempfile] : nil))
add_success("User updated")
redirect "/users/#{@user.id}"
else
@user.errors.full_messages.each { |msg| add_error(msg) }
render :update_user
end
end
end
class AddScore < R '/add/(.*?)/(\d+)/(.*?)/(.*?)/(\d+)'
def get(source, version, name, crypt, score)
source = CGI.unescape(source).gsub(/ +/, ' ')
name = CGI.unescape(name).gsub(/ +/, ' ')
crypt = CGI.unescape(crypt).gsub(/ +/, ' ')
# User.transaction do
source = (source == '' ? 'dashboard' : source)
user = User.find_by_name(name)
if user
unless user.crypt == crypt
return mab { text "0|http://akc.bloople.net/invalid_crypt" }
end
else
user = User.create(:name => name, :crypt => crypt, :seen_oz_quiz_released => true)
end
Score.create(:version => version, :user => user, :score => score, :when => Time.now, :source => source)
if !user.seen_oz_quiz_released?
user.seen_oz_quiz_released = true
user.save!
return mab { text "0|http://akc.bloople.net/oz_quiz_released/#{user.id}" }
else
return mab { text "" }
end
end
# end
end
class HighScores < R '/high_scores'
@cacheable = true
def get
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 1000)
@users = User.find(:all, :include => :latest_score, :order => 'high_score DESC, akc_scores.when DESC', :limit => 1000)
render :high_scores
end
end
class HighScoresAbsolute < R '/high_scores_absolute.rss'
def get
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 50)
render :high_scores_absolute
end
end
class HighScoresAverage < R '/high_scores_average.rss'
def get
@scores = Score.find(:all, :include => :user, :order => 'score DESC', :limit => 50)
@users = User.find(:all, :include => :latest_score, :order => 'high_score DESC, akc_scores.when DESC', :limit => 50)
render :high_scores_average
end
end
class Statistics
def get
render :statistics
end
end
class ScoresByDateGraph < R '/scores_by_date_graph'
@cacheable = true
def get
scores = ActiveRecord::Base.connection.select_all("SELECT COUNT(id) AS count, DATE(akc_scores.when) AS date FROM akc_scores GROUP BY DATE(akc_scores.when) ORDER BY DATE(akc_scores.when) ASC")
days = []
counts = []
scores.each do |s|
days << Date.parse(s['date'])
counts << s['count'].to_i
end
g = Gruff::Line.new('984x480')
g.instance_variable_set(:@raw_columns, 1230.0)
g.instance_variable_set(:@raw_rows, 600)
g.instance_variable_set(:@scale, 0.8)
g.data("Scores", counts)
lr = LinearRegression.new(counts)
g.data("Trend line", lr.fit)
g.labels = { 0 => "#{days.first.mday} #{Date::MONTHNAMES[days.first.month]} #{days.first.year}", (days.size - 1) => "#{days.last.mday} #{Date::MONTHNAMES[days.last.month]} #{days.last.year}" }
g.theme_37signals
g.minimum_value = [lr.fit.min, 0].min
g.title = "Scores submitted per day"
@headers['Content-Type'] = 'image/png'
@headers['Content-Disposition'] = 'inline'
g.to_blob
end
end
class HighScoresGraph < R '/high_scores_graph'
@cacheable = true
def get
scores = Score.find(:all, :order => "score DESC", :limit => 50)
g = Gruff::Line.new('984x480')
g.instance_variable_set(:@raw_columns, 1230.0)
g.instance_variable_set(:@raw_rows, 600)
g.instance_variable_set(:@scale, 0.8)
g.data("Scores", scores.map { |s| s.score })
labels = {}
scores.each_with_index do |s, i|
labels[i] = s.when if labels.empty? or (labels.values.last.month != s.when.month)
end
labels.each_pair { |(key, val)| labels[key] = "#{Date::MONTHNAMES[val.month]} #{val.year}" }
lr = LinearRegression.new(scores.map { |s| s.score })
g.data("Trend line", lr.fit)
first = scores.first.when
last = scores.last.when
g.labels = { 0 => "#{first.mday} #{Date::MONTHNAMES[first.month]} #{first.year}", (scores.size - 1) => "#{last.mday} #{Date::MONTHNAMES[last.month]} #{last.year}" }
g.theme_37signals
g.minimum_value = [lr.fit.min, 0].min
g.title = "Top 50 high scores"
@headers['Content-Type'] = 'image/png'
@headers['Content-Disposition'] = 'inline'
g.to_blob
end
end
class ScoresForUser < R '/scores_for_user'
def post
@search_term = input.name
@users = User.find(:all, :conditions => "name LIKE #{ActiveRecord::Base.connection.quote("%#{@search_term}%")}")
render :scores_for_user
end
end
class LatestScoresByUser < R '/users/(\d+)/latest_scores.rss'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :order => 'akc_scores.when DESC', :limit => 50)
render :latest_scores_by_user
end
end
class HighScoresByUser < R '/users/(\d+)/high_scores.rss'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :order => 'score DESC', :limit => 50)
render :high_scores_by_user
end
end
class Login < R '/users/login', '/users/logout'
def post
login input.username, input.password
if logged_in?
add_success("Logged in!")
redirect(Index)
else
add_error("Your username or password was incorrect.")
get
end
end
def get
logout
render :login
end
end
Logout = Login
class ShowUser < R '/users/(\d+)'
def get(id)
@user = User.find(id)
@latest_scores = @user.scores.find(:all, :order => 'akc_scores.when DESC', :limit => 10)
@high_scores = @user.scores.find(:all, :order => 'score DESC', :limit => 10)
@first_score = @user.scores.find(:first, :order => 'akc_scores.when ASC', :limit => 1)
@user.increment!(:view_count)
render :show
end
end
class ShowAllScoresForUser < R '/users/(\d+)/all_scores'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :order => 'akc_scores.when DESC')
render :show_all_scores_for_user
end
end
class ShowUserScoresGraph < R '/users/(\d+)/scores_graph'
def get(id)
@user = User.find(id)
@scores = @user.scores.find(:all, :include => :user, :order => "akc_scores.when ASC")
g = Gruff::Line.new('984x480')
g.instance_variable_set(:@raw_columns, 1230.0)
g.instance_variable_set(:@raw_rows, 600)
g.instance_variable_set(:@scale, 0.8)
g.data("Scores", @scores.map { |s| s.score })
labels = {}
@scores.each_with_index do |s, i|
labels[i] = s.when if labels.empty? or (labels.values.last.month != s.when.month)
end
labels.each_pair { |(key, val)| labels[key] = "#{Date::MONTHNAMES[val.month]} #{val.year}" }
lr = LinearRegression.new(@scores.map { |s| s.score })
g.data("Trend line", lr.fit)
g.labels = labels
g.theme_37signals
g.minimum_value = [lr.fit.min, 0].min
g.title = "Scores over time"
@headers['Content-Type'] = 'image/png'
@headers['Content-Disposition'] = 'inline'
g.to_blob
end
end
class AddShout < R '/add_shout'
def post
@shout = Shout.new(:username => input.username, :text => input.text, :captcha => input.captcha, :posted => Time.now.getgm)
if @shout.save
add_success("Your shout has been published; it may take up to 10 minutes for your shout to be visible to other people.")
else
@shout.errors.full_messages.each { |msg| add_error(msg) }
end
redirect '/'
end
end
class InvalidCrypt < R '/invalid_crypt'
def get
render :invalid_crypt
end
end
include StaticAssetsClass
end |
require "prawn/measurement_extensions"
class LabelMaker
def initialize(template)
@template = template
end
def generate
build.render
end
private
def build
render_labels
render_footer(90.mm)
render_footer(188.mm)
pdf
end
def render_labels
%i(top center bottom).each do |vposition|
%i(left center right).each do |hposition|
pdf.svg @template, {
enable_web_requests: false,
position: hposition,
vposition: vposition
}
end
end
self
end
def render_footer(hposition)
path = Rails.root.join('app', 'assets', 'images', 'brygglogg-logo-hires.png')
pdf.image path, width: 1.cm, at: [25.mm, hposition]
pdf.image path, width: 1.cm, at: [145.mm, hposition]
pdf.font "Merriweather" do
pdf.text_box "Etiketter utskrivna från Brygglogg.se",
at: [42.mm, hposition - 2.mm]
end
self
end
def pdf
return @pdf if @pdf.present?
@pdf ||= Prawn::Document.new(
page_size: "A4",
margin: 42
)
@pdf.font_families.update("Merriweather" => { normal: Rails.root.join('app', 'assets', 'fonts', 'merriweather.ttf') })
@pdf
end
end
Center promotion text between labels
require "prawn/measurement_extensions"
class LabelMaker
def initialize(template)
@template = template
end
def generate
build.render
end
private
def build
render_labels
render_footer(90.mm)
render_footer(188.mm)
pdf
end
def render_labels
%i(top center bottom).each do |vposition|
%i(left center right).each do |hposition|
pdf.svg @template, {
enable_web_requests: false,
position: hposition,
vposition: vposition
}
end
end
self
end
def render_footer(hposition)
path = Rails.root.join('app', 'assets', 'images', 'brygglogg-logo-hires.png')
pdf.image path, width: 1.cm, at: [25.mm, hposition]
pdf.image path, width: 1.cm, at: [145.mm, hposition]
pdf.font "Merriweather" do
pdf.text_box "Etiketter utskrivna från Brygglogg.se",
at: [52.mm, hposition - 2.mm]
end
self
end
def pdf
return @pdf if @pdf.present?
@pdf ||= Prawn::Document.new(
page_size: "A4",
margin: 42
)
@pdf.font_families.update("Merriweather" => { normal: Rails.root.join('app', 'assets', 'fonts', 'merriweather.ttf') })
@pdf
end
end
|
require "legacy_uuid/version"
module LegacyUUID
REGIONS = {
au: 1,
nz: 2,
gb: 3,
us: 4,
}
def self.region_component(region)
REGIONS.fetch(region.to_sym).to_s(16).rjust(4, "0")
end
def self.id_component(id)
id.to_i.to_s(16).rjust(12, "0")
end
def self.from(uid, prefix:)
region, id = uid.split("-")
"#{prefix}-#{region_component(region)}-4000-8000-#{id_component(id)}"
end
def self.from_campaign(uid)
from(uid, prefix: "eda1e64c")
end
def self.from_charity(uid)
from(uid, prefix: "edb1e64c")
end
end
Legacy UK uses uk key not gb
require "legacy_uuid/version"
module LegacyUUID
REGIONS = {
au: 1,
nz: 2,
uk: 3,
us: 4,
}
def self.region_component(region)
REGIONS.fetch(region.to_sym).to_s(16).rjust(4, "0")
end
def self.id_component(id)
id.to_i.to_s(16).rjust(12, "0")
end
def self.from(uid, prefix:)
region, id = uid.split("-")
"#{prefix}-#{region_component(region)}-4000-8000-#{id_component(id)}"
end
def self.from_campaign(uid)
from(uid, prefix: "eda1e64c")
end
def self.from_charity(uid)
from(uid, prefix: "edb1e64c")
end
end
|
module Lev
VERSION = "7.0.2"
end
7.0.3
module Lev
VERSION = "7.0.3"
end
|
require 'link_shrink/version'
require 'link_shrink/options'
require 'link_shrink/request'
require 'link_shrink/json_parser'
require 'link_shrink/shrinkers/base'
require 'link_shrink/shrinkers/google'
require 'link_shrink/shrinkers/tinyurl'
require 'link_shrink/shrinkers/isgd'
require 'link_shrink/config'
# @author Jonah Ruiz <jonah@pixelhipsters.com>
# Creates a short URL and QR codes
module LinkShrink
extend self
include LinkShrink::Request
# Returns a short URL or JSON response
# example: shrink_url('http://www.wtf.com', { json: true, qr_code: true })
# example: shrink_url('http://www.wtf.com', { qr_code: true })
#
# @param url [String] long URL to be shortened
# @param options [Hash] format to be returned
# @return [String] generated short URL or JSON response
def shrink_url(url, options = { json: false, qr_code: false })
process_request(url, options)
rescue
'Problem generating short URL. Try again.'
end
# Returns a QR code URL
# example: generate_qr_code('http://www.wtf.com', { image_size: '300x300' })
#
# @param url [String] long URL to be shortened
# @param options [Hash] image_size: '300x300' for a custom size
# @return [String] QR code URL using default or custom size
def generate_qr_code(url, options = {})
new_url = process_request(url, {})
image_size = options.fetch(:image_size, {})
Config.api.generate_chart_url(new_url, image_size)
end
# Yield's to Config for options
#
# @param <config> [String] api interface to use
# @param <api_key> [String] api key to use
def configure
yield LinkShrink::Config if block_given?
end
end
Add Owly API class to require from linkshrink module
require 'link_shrink/version'
require 'link_shrink/options'
require 'link_shrink/request'
require 'link_shrink/json_parser'
require 'link_shrink/shrinkers/base'
require 'link_shrink/shrinkers/google'
require 'link_shrink/shrinkers/tinyurl'
require 'link_shrink/shrinkers/isgd'
require 'link_shrink/shrinkers/owly'
require 'link_shrink/config'
# @author Jonah Ruiz <jonah@pixelhipsters.com>
# Creates a short URL and QR codes
module LinkShrink
extend self
include LinkShrink::Request
# Returns a short URL or JSON response
# example: shrink_url('http://www.wtf.com', { json: true, qr_code: true })
# example: shrink_url('http://www.wtf.com', { qr_code: true })
#
# @param url [String] long URL to be shortened
# @param options [Hash] format to be returned
# @return [String] generated short URL or JSON response
def shrink_url(url, options = { json: false, qr_code: false })
process_request(url, options)
rescue
'Problem generating short URL. Try again.'
end
# Returns a QR code URL
# example: generate_qr_code('http://www.wtf.com', { image_size: '300x300' })
#
# @param url [String] long URL to be shortened
# @param options [Hash] image_size: '300x300' for a custom size
# @return [String] QR code URL using default or custom size
def generate_qr_code(url, options = {})
new_url = process_request(url, {})
image_size = options.fetch(:image_size, {})
Config.api.generate_chart_url(new_url, image_size)
end
# Yield's to Config for options
#
# @param <config> [String] api interface to use
# @param <api_key> [String] api key to use
def configure
yield LinkShrink::Config if block_given?
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'octopress-font-awesome/version'
Gem::Specification.new do |spec|
spec.name = "octopress-font-awesome"
spec.version = OctopressFontAwesome::VERSION
spec.authors = ["Wang Jian"]
spec.email = ["wantee.wang@gmail.com"]
spec.summary = %q{Quickly and easily add Font Awesome icons to your posts with octopress ink.}
spec.description = %q{Quickly and easily add Font Awesome icons to your posts with octopress ink.}
spec.homepage = "https://github.com/wantee/octopress-font-awesome.git"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").grep(%r{^(bin/|lib/|assets/|changelog|readme|license)}i)
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.9"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "clash"
spec.add_runtime_dependency "octopress-asset-pipeline", "~> 2.0.4"
spec.add_runtime_dependency "octopress-ink", "~> 1.1"
end
downgrade bundler dependecise for travis
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'octopress-font-awesome/version'
Gem::Specification.new do |spec|
spec.name = "octopress-font-awesome"
spec.version = OctopressFontAwesome::VERSION
spec.authors = ["Wang Jian"]
spec.email = ["wantee.wang@gmail.com"]
spec.summary = %q{Quickly and easily add Font Awesome icons to your posts with octopress ink.}
spec.description = %q{Quickly and easily add Font Awesome icons to your posts with octopress ink.}
spec.homepage = "https://github.com/wantee/octopress-font-awesome.git"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").grep(%r{^(bin/|lib/|assets/|changelog|readme|license)}i)
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "clash"
spec.add_runtime_dependency "octopress-asset-pipeline", "~> 2.0.4"
spec.add_runtime_dependency "octopress-ink", "~> 1.1"
end
|
require 'sinatra'
require 'omniauth-fitbit'
require 'fitgem'
require 'dalli'
require 'securerandom'
require 'sequel'
require 'yaml'
require 'celluloid/autostart'
require 'securerandom'
require 'erubis'
# TODO: LOCALIZATION
# Specifically timezones:
# - time calculations need to work based on user's local time rather than UTC
# - date ranges need to be based on user's local date, not the date in Grenwich
INTENSITIES = {
"EASY" => 250,
"MEDIUM" => 500,
"KINDAHARD" => 750,
"HARDER" => 1000
}
ALLOWED_SPANS = [ "1d", "1w", "1m", "3m", "6m", "1y" ]
# Other potentials: 7d, 30d
OPTIONS = YAML.load_file("/etc/fitstats.rc")
DB = Sequel.connect("mysql2://#{OPTIONS['db_user']}:#{OPTIONS['db_password']}@#{OPTIONS['db_host']}/#{OPTIONS['db_name']}")
def config(key)
DB[:config][:key => key][:value]
end
CONSUMER_KEY = config("fitbit_consumer_key")
CONSUMER_SECRET = config("fitbit_consumer_secret")
set :bind => config("bind_address")
use Rack::Session::Cookie, :secret => config("session_secret"), :expire_after => 2592000
use OmniAuth::Builder do
provider :fitbit, CONSUMER_KEY, CONSUMER_SECRET
end
CACHE = Dalli::Client.new('127.0.0.1:11211', {:namespace => "fitstats_v0.1", :compress => "true", :expires_in => 1200})
# Monkey-patch some useful stuff into fitgem
module Fitgem
class Client
def initialize(opts)
missing = [:consumer_key, :consumer_secret] - opts.keys
if missing.size > 0
raise Fitgem::InvalidArgumentError, "Missing required options: #{missing.join(',')}"
end
@consumer_key = opts[:consumer_key]
@consumer_secret = opts[:consumer_secret]
@ssl = opts[:ssl]
@token = opts[:token]
@secret = opts[:secret]
@proxy = opts[:proxy] if opts[:proxy]
@user_id = opts[:user_id] || '-'
@raise_on_error = opts[:raise_on_error] if opts[:raise_on_error]
@api_unit_system = opts[:unit_system] || Fitgem::ApiUnitSystem.US
@api_version = API_VERSION
end
def get(path, headers={})
result = raw_get(path, headers)
raise result.value() if @raise_on_error and !result.is_a?(Net::HTTPSuccess)
extract_response_body result
end
# Get details about the daily food (calorie) goal
#
# @return [Hash] Food goal information.
def daily_food_goal
get("/user/#{@user_id}/foods/log/goal.json")
end
end
end
get "/" do
@user = DB[:user][:fitbit_uid => session[:uid]]
if @user then
erb :index
else
erb :login
end
end
def fitbit_client()
Fitgem::Client.new ({
:consumer_key => CONSUMER_KEY,
:consumer_secret => CONSUMER_SECRET,
:token => @user[:fitbit_oauth_token],
:secret => @user[:fitbit_oauth_secret],
:unit_system => Fitgem::ApiUnitSystem.METRIC,
:raise_on_error => true
})
end
before '/stats/:obfuscator/*' do
@user = DB[:user][:obfuscator => params[:obfuscator]]
halt 404 if !@user
end
before '/stats/:obfuscator/*/:span' do
halt 404 if !ALLOWED_SPANS.include?(params[:span])
end
before "/stats/:obfuscator/:chart/:span" do
@cache_key = "user#{@user[:id]}_#{params[:chart]}_#{params[:span]}"
end
before "/stats/:obfuscator/:chart" do
@cache_key = "user#{@user[:id]}_#{params[:chart]}"
end
get "/stats/:obfuscator/weight" do
weight_chart("1y")
end
get "/stats/:obfuscator/weight/:span" do
weight_chart(params[:span])
end
def format_time(time, time_span)
["1d", "7d", "1w"].include?(time_span) ? Time.parse(time).strftime("%a") : time
end
def invalidate_request_cache(user_id, chart)
cache_key = "user#{user_id}_#{chart}"
CACHE.delete(cache_key)
for span in ALLOWED_SPANS do
CACHE.delete(cache_key + "_" + span)
end
end
def simple_sequence_chart(resource, title, time_span)
fitbit = fitbit_client()
CACHE.fetch(@cache_key) {
steps = resiliant_request { fitbit.data_by_time_range(resource, {:base_date => "today", :period => time_span}).values[0] }
datapoints = Array.new
steps.each { |item|
datapoints.push( {
"title" => format_time(item["dateTime"], time_span),
"value" => item["value"]
} )
}
create_graph(title, {"fitbit" => datapoints}, 60)
}
end
def extrapolate_todays_calories(current)
now = Time.now
mins_elapsed = now.min + (now.hour * 60)
bmr_per_min = bmr.to_f / 1440.0
mins_remaining = 1440 - mins_elapsed
(current + (mins_remaining * bmr_per_min)).to_i
end
def calorie_chart(time_span)
CACHE.fetch(@cache_key) {
# Use futures to parallelize http requests
cals_in_future = Celluloid::Future.new {
resiliant_request("in") { fitbit_client().data_by_time_range("/foods/log/caloriesIn", {:base_date => "today", :period => time_span}).values[0] }
}
cals_out_future = Celluloid::Future.new {
resiliant_request("out") { fitbit_client().data_by_time_range("/activities/tracker/calories", {:base_date => "today", :period => time_span}).values[0] }
}
deficit_future = Celluloid::Future.new {
resiliant_request("deficit") { INTENSITIES[fitbit_client().daily_food_goal.values[0]["intensity"]] }
}
cals_in = cals_in_future.value
cals_out = cals_out_future.value
deficit = deficit_future.value
datapoints = Array.new
for i in 0 .. (cals_in.size - 1)
date = cals_in[i]["dateTime"]
daily_out = cals_out[i]["value"].to_i
target = (Date.parse(date) == Date.today ? extrapolate_todays_calories(daily_out) : daily_out) - deficit
datapoints.push({
"title" => format_time(date, time_span),
"value" => cals_in[i]["value"].to_i - target
})
end
create_graph("calories", {"food" => datapoints}, 60)
}
end
def weight_chart(time_span)
CACHE.fetch(@cache_key, 10800) {
weight_future = Celluloid::Future.new {
resiliant_request("weight") { fitbit_client().data_by_time_range("/body/weight", {:base_date => "today", :period => time_span}).values[0] }
}
weight_goal_future = Celluloid::Future.new {
resiliant_request("goal") { fitbit_client().body_weight_goal["goal"]["weight"] }
}
weight = weight_future.value
weight_goal = weight_goal_future.value
datapoints = Array.new
weight.each { |item|
datapoints.push( { "title" => item["dateTime"], "value" => item["value"] } )
if (item["dateTime"] == Date.today.to_s)
DB[:user].where(:fitbit_uid => session[:uid]).update( :weight => item["value"].to_f )
@user = DB[:user][:fitbit_uid => session[:uid]]
end
}
create_graph("Weight", {"weight" => datapoints}, 60, (weight_goal.to_f * 0.9).to_s, nil, "kg")
}
end
def create_graph(title, sequences, refresh_interval, y_min = nil, y_max = nil, y_unit = nil)
graph = {
"graph" => {
"title" => title,
"refreshEveryNSeconds" => refresh_interval,
"datasequences" => sequences.keys.map {|sequence_title|
{
"title" => sequence_title,
"datapoints" => sequences[sequence_title]
}
}
}
}
if (y_min || y_max || y_unit) then
y = {}
y["minValue"] = y_min if y_min
y["maxValue"] = y_max if y_max
y["units"] = {"suffix" => y_unit} if y_unit
graph["graph"]["yAxis"] = y
end
MultiJson.encode( graph )
end
def resiliant_request(request_name = nil)
begin
key = @cache_key + (request_name ? "_" + request_name : "") + "_request"
new = yield
CACHE.set(key, new, 86400)
new
rescue => e
e.backtrace
CACHE.get(key) or raise
end
end
get "/stats/:obfuscator/steps" do
simple_sequence_chart("/activities/tracker/steps", "steps", "7d")
end
get "/stats/:obfuscator/steps/:span" do
simple_sequence_chart("/activities/tracker/steps", "steps", params[:span])
end
get "/stats/:obfuscator/floors" do
simple_sequence_chart("/activities/tracker/floors", "floors", "7d")
end
get "/stats/:obfuscator/floors/:span" do
simple_sequence_chart("/activities/tracker/floors", "floors", params[:span])
end
get "/stats/:obfuscator/calories" do
calorie_chart("7d")
end
get "/stats/:obfuscator/calories/:span" do
calorie_chart(params[:span])
end
post "/api/subscriber-endpoint" do
status 204
for update in MultiJson.load(params['updates'][:tempfile].read) do
case update["collectionType"]
when "activities"
invalidate_request_cache(update["subscriptionId"], "steps")
invalidate_request_cache(update["subscriptionId"], "floors")
invalidate_request_cache(update["subscriptionId"], "calories")
when "foods"
invalidate_request_cache(update["subscriptionId"], "calories")
when "body"
invalidate_request_cache(update["subscriptionId"], "weight")
end
end
end
get "/auth/fitbit/callback" do
auth = request.env['omniauth.auth']
name = auth["info"]["display_name"]
fitbit_id = auth["uid"]
token = auth["credentials"]["token"]
secret = auth["credentials"]["secret"]
users = DB[:user]
@user = users[:fitbit_uid => fitbit_id]
if @user
@user.update( { :fitbit_oauth_token => token, :fitbit_oauth_secret => secret } )
else
users.insert({ :name => name, :fitbit_uid => fitbit_id, :fitbit_oauth_token => token, :fitbit_oauth_secret => secret, :obfuscator => SecureRandom.urlsafe_base64(64) })
@user = users[:fitbit_uid => fitbit_id]
end
session[:uid] = fitbit_id
refresh_personal_info
refresh_subscription
redirect to('/')
end
# handle oauth failure
get '/auth/failure' do
params[:message]
end
def refresh_personal_info(force = false)
if (Date.today - @user[:personal_data_last_updated]).to_i > 28
info = fitbit_client.user_info["user"]
DB[:user].where(:fitbit_uid => session[:uid]).update(
:height => info["height"],
:weight => info["weight"],
:name => info["displayName"],
:sex => info["gender"],
:birth_date => info["dateOfBirth"],
:personal_data_last_updated => Date.today
)
@user = DB[:user][:fitbit_uid => session[:uid]]
end
end
def bmr
refresh_personal_info()
age = ((Date.today - @user[:birth_date]).to_i / 365.25).to_f
if @user[:sex] == 'MALE'
# 88.362 + (13.397 * @user[:weight]) + (4.799 * @user[:height]) - (5.677 * age)
(9.99 * @user[:weight].to_f) + (6.25 * @user[:height].to_f) - (4.92 * age) + 5
else
# 447.593 + (9.247 * @user[:weight]) + (3.098 * @user[:height]) - (4.330 * age)
(9.99 * @user[:weight]) + (6.25 * @user[:height].to_i) - (4.92 * age) - 161
end
end
get '/stats/:obfuscator/subscription' do
fitbit_client().subscriptions({:type => :all})
end
def add_subscription
fitbit = fitbit_client()
fitbit.create_subscription({:type => :all, :subscription_id => @user[:id]})
end
def delete_subscription
fitbit = fitbit_client()
for subscription in fitbit.subscriptions({:type => :all}).values[0] do
fitbit.remove_subscription({:type => :all, :subscription_id => subscription["subscriptionId"]})
end
end
def refresh_subscription
delete_subscription
add_subscription
end
get '/stats/:obfuscator/refresh-subscription' do
refresh_subscriptions
redirect to ("stats/#{@user[:obfuscator]}/subscription")
end
get '/stats/:obfuscator/test' do
halt 500
end
oauth tokens are now correctly updated in the DB when reissued
require 'sinatra'
require 'omniauth-fitbit'
require 'fitgem'
require 'dalli'
require 'securerandom'
require 'sequel'
require 'yaml'
require 'celluloid/autostart'
require 'securerandom'
require 'erubis'
# TODO: LOCALIZATION
# Specifically timezones:
# - time calculations need to work based on user's local time rather than UTC
# - date ranges need to be based on user's local date, not the date in Grenwich
INTENSITIES = {
"EASY" => 250,
"MEDIUM" => 500,
"KINDAHARD" => 750,
"HARDER" => 1000
}
ALLOWED_SPANS = [ "1d", "1w", "1m", "3m", "6m", "1y" ]
# Other potentials: 7d, 30d
OPTIONS = YAML.load_file("/etc/fitstats.rc")
DB = Sequel.connect("mysql2://#{OPTIONS['db_user']}:#{OPTIONS['db_password']}@#{OPTIONS['db_host']}/#{OPTIONS['db_name']}")
def config(key)
DB[:config][:key => key][:value]
end
CONSUMER_KEY = config("fitbit_consumer_key")
CONSUMER_SECRET = config("fitbit_consumer_secret")
set :bind => config("bind_address")
use Rack::Session::Cookie, :secret => config("session_secret"), :expire_after => 2592000
use OmniAuth::Builder do
provider :fitbit, CONSUMER_KEY, CONSUMER_SECRET
end
CACHE = Dalli::Client.new('127.0.0.1:11211', {:namespace => "fitstats_v0.1", :compress => "true", :expires_in => 1200})
# Monkey-patch some useful stuff into fitgem
module Fitgem
class Client
def initialize(opts)
missing = [:consumer_key, :consumer_secret] - opts.keys
if missing.size > 0
raise Fitgem::InvalidArgumentError, "Missing required options: #{missing.join(',')}"
end
@consumer_key = opts[:consumer_key]
@consumer_secret = opts[:consumer_secret]
@ssl = opts[:ssl]
@token = opts[:token]
@secret = opts[:secret]
@proxy = opts[:proxy] if opts[:proxy]
@user_id = opts[:user_id] || '-'
@raise_on_error = opts[:raise_on_error] if opts[:raise_on_error]
@api_unit_system = opts[:unit_system] || Fitgem::ApiUnitSystem.US
@api_version = API_VERSION
end
def get(path, headers={})
result = raw_get(path, headers)
raise result.value() if @raise_on_error and !result.is_a?(Net::HTTPSuccess)
extract_response_body result
end
# Get details about the daily food (calorie) goal
#
# @return [Hash] Food goal information.
def daily_food_goal
get("/user/#{@user_id}/foods/log/goal.json")
end
end
end
get "/" do
@user = DB[:user][:fitbit_uid => session[:uid]]
if @user then
erb :index
else
erb :login
end
end
def fitbit_client()
Fitgem::Client.new ({
:consumer_key => CONSUMER_KEY,
:consumer_secret => CONSUMER_SECRET,
:token => @user[:fitbit_oauth_token],
:secret => @user[:fitbit_oauth_secret],
:unit_system => Fitgem::ApiUnitSystem.METRIC,
:raise_on_error => true
})
end
before '/stats/:obfuscator/*' do
@user = DB[:user][:obfuscator => params[:obfuscator]]
halt 404 if !@user
end
before '/stats/:obfuscator/*/:span' do
halt 404 if !ALLOWED_SPANS.include?(params[:span])
end
before "/stats/:obfuscator/:chart/:span" do
@cache_key = "user#{@user[:id]}_#{params[:chart]}_#{params[:span]}"
end
before "/stats/:obfuscator/:chart" do
@cache_key = "user#{@user[:id]}_#{params[:chart]}"
end
get "/stats/:obfuscator/weight" do
weight_chart("1y")
end
get "/stats/:obfuscator/weight/:span" do
weight_chart(params[:span])
end
def format_time(time, time_span)
["1d", "7d", "1w"].include?(time_span) ? Time.parse(time).strftime("%a") : time
end
def invalidate_request_cache(user_id, chart)
cache_key = "user#{user_id}_#{chart}"
CACHE.delete(cache_key)
for span in ALLOWED_SPANS do
CACHE.delete(cache_key + "_" + span)
end
end
def simple_sequence_chart(resource, title, time_span)
fitbit = fitbit_client()
CACHE.fetch(@cache_key) {
steps = resiliant_request { fitbit.data_by_time_range(resource, {:base_date => "today", :period => time_span}).values[0] }
datapoints = Array.new
steps.each { |item|
datapoints.push( {
"title" => format_time(item["dateTime"], time_span),
"value" => item["value"]
} )
}
create_graph(title, {"fitbit" => datapoints}, 60)
}
end
def extrapolate_todays_calories(current)
now = Time.now
mins_elapsed = now.min + (now.hour * 60)
bmr_per_min = bmr.to_f / 1440.0
mins_remaining = 1440 - mins_elapsed
(current + (mins_remaining * bmr_per_min)).to_i
end
def calorie_chart(time_span)
CACHE.fetch(@cache_key) {
# Use futures to parallelize http requests
cals_in_future = Celluloid::Future.new {
resiliant_request("in") { fitbit_client().data_by_time_range("/foods/log/caloriesIn", {:base_date => "today", :period => time_span}).values[0] }
}
cals_out_future = Celluloid::Future.new {
resiliant_request("out") { fitbit_client().data_by_time_range("/activities/tracker/calories", {:base_date => "today", :period => time_span}).values[0] }
}
deficit_future = Celluloid::Future.new {
resiliant_request("deficit") { INTENSITIES[fitbit_client().daily_food_goal.values[0]["intensity"]] }
}
cals_in = cals_in_future.value
cals_out = cals_out_future.value
deficit = deficit_future.value
datapoints = Array.new
for i in 0 .. (cals_in.size - 1)
date = cals_in[i]["dateTime"]
daily_out = cals_out[i]["value"].to_i
target = (Date.parse(date) == Date.today ? extrapolate_todays_calories(daily_out) : daily_out) - deficit
datapoints.push({
"title" => format_time(date, time_span),
"value" => cals_in[i]["value"].to_i - target
})
end
create_graph("calories", {"food" => datapoints}, 60)
}
end
def weight_chart(time_span)
CACHE.fetch(@cache_key, 10800) {
weight_future = Celluloid::Future.new {
resiliant_request("weight") { fitbit_client().data_by_time_range("/body/weight", {:base_date => "today", :period => time_span}).values[0] }
}
weight_goal_future = Celluloid::Future.new {
resiliant_request("goal") { fitbit_client().body_weight_goal["goal"]["weight"] }
}
weight = weight_future.value
weight_goal = weight_goal_future.value
datapoints = Array.new
weight.each { |item|
datapoints.push( { "title" => item["dateTime"], "value" => item["value"] } )
if (item["dateTime"] == Date.today.to_s)
DB[:user].where(:fitbit_uid => session[:uid]).update( :weight => item["value"].to_f )
@user = DB[:user][:fitbit_uid => session[:uid]]
end
}
create_graph("Weight", {"weight" => datapoints}, 60, (weight_goal.to_f * 0.9).to_s, nil, "kg")
}
end
def create_graph(title, sequences, refresh_interval, y_min = nil, y_max = nil, y_unit = nil)
graph = {
"graph" => {
"title" => title,
"refreshEveryNSeconds" => refresh_interval,
"datasequences" => sequences.keys.map {|sequence_title|
{
"title" => sequence_title,
"datapoints" => sequences[sequence_title]
}
}
}
}
if (y_min || y_max || y_unit) then
y = {}
y["minValue"] = y_min if y_min
y["maxValue"] = y_max if y_max
y["units"] = {"suffix" => y_unit} if y_unit
graph["graph"]["yAxis"] = y
end
MultiJson.encode( graph )
end
def resiliant_request(request_name = nil)
begin
key = @cache_key + (request_name ? "_" + request_name : "") + "_request"
new = yield
CACHE.set(key, new, 86400)
new
rescue => e
e.backtrace
CACHE.get(key) or raise
end
end
get "/stats/:obfuscator/steps" do
simple_sequence_chart("/activities/tracker/steps", "steps", "7d")
end
get "/stats/:obfuscator/steps/:span" do
simple_sequence_chart("/activities/tracker/steps", "steps", params[:span])
end
get "/stats/:obfuscator/floors" do
simple_sequence_chart("/activities/tracker/floors", "floors", "7d")
end
get "/stats/:obfuscator/floors/:span" do
simple_sequence_chart("/activities/tracker/floors", "floors", params[:span])
end
get "/stats/:obfuscator/calories" do
calorie_chart("7d")
end
get "/stats/:obfuscator/calories/:span" do
calorie_chart(params[:span])
end
post "/api/subscriber-endpoint" do
status 204
for update in MultiJson.load(params['updates'][:tempfile].read) do
case update["collectionType"]
when "activities"
invalidate_request_cache(update["subscriptionId"], "steps")
invalidate_request_cache(update["subscriptionId"], "floors")
invalidate_request_cache(update["subscriptionId"], "calories")
when "foods"
invalidate_request_cache(update["subscriptionId"], "calories")
when "body"
invalidate_request_cache(update["subscriptionId"], "weight")
end
end
end
get "/auth/fitbit/callback" do
auth = request.env['omniauth.auth']
name = auth["info"]["display_name"]
fitbit_id = auth["uid"]
token = auth["credentials"]["token"]
secret = auth["credentials"]["secret"]
users = DB[:user]
@user = users[:fitbit_uid => fitbit_id]
if @user
DB[:user].where(:fitbit_uid => fitbit_id).update(
{ :fitbit_oauth_token => token, :fitbit_oauth_secret => secret }
)
@user = users[:fitbit_uid => fitbit_id]
else
users.insert({ :name => name, :fitbit_uid => fitbit_id, :fitbit_oauth_token => token, :fitbit_oauth_secret => secret, :obfuscator => SecureRandom.urlsafe_base64(64) })
@user = users[:fitbit_uid => fitbit_id]
end
session[:uid] = fitbit_id
refresh_personal_info
refresh_subscription
redirect to('/')
end
# handle oauth failure
get '/auth/failure' do
params[:message]
end
def refresh_personal_info(force = false)
if (Date.today - @user[:personal_data_last_updated]).to_i > 28
info = fitbit_client.user_info["user"]
DB[:user].where(:fitbit_uid => session[:uid]).update(
:height => info["height"],
:weight => info["weight"],
:name => info["displayName"],
:sex => info["gender"],
:birth_date => info["dateOfBirth"],
:personal_data_last_updated => Date.today
)
@user = DB[:user][:fitbit_uid => session[:uid]]
end
end
def bmr
refresh_personal_info()
age = ((Date.today - @user[:birth_date]).to_i / 365.25).to_f
if @user[:sex] == 'MALE'
# 88.362 + (13.397 * @user[:weight]) + (4.799 * @user[:height]) - (5.677 * age)
(9.99 * @user[:weight].to_f) + (6.25 * @user[:height].to_f) - (4.92 * age) + 5
else
# 447.593 + (9.247 * @user[:weight]) + (3.098 * @user[:height]) - (4.330 * age)
(9.99 * @user[:weight]) + (6.25 * @user[:height].to_i) - (4.92 * age) - 161
end
end
get '/stats/:obfuscator/subscription' do
fitbit_client().subscriptions({:type => :all})
end
def add_subscription
fitbit = fitbit_client()
fitbit.create_subscription({:type => :all, :subscription_id => @user[:id]})
end
def delete_subscription
fitbit = fitbit_client()
for subscription in fitbit.subscriptions({:type => :all}).values[0] do
fitbit.remove_subscription({:type => :all, :subscription_id => subscription["subscriptionId"]})
end
end
def refresh_subscription
delete_subscription
add_subscription
end
get '/stats/:obfuscator/refresh-subscription' do
refresh_subscriptions
redirect to ("stats/#{@user[:obfuscator]}/subscription")
end
get '/stats/:obfuscator/test' do
halt 500
end
|
require "formula"
class Vte3 < Formula
homepage "http://developer.gnome.org/vte/"
url "http://ftp.gnome.org/pub/gnome/sources/vte/0.36/vte-0.36.3.tar.xz"
sha1 "a7acc1594eb6fa249edccb059c21132b3aa2657b"
depends_on "pkg-config" => :build
depends_on "intltool" => :build
depends_on "gettext"
depends_on "glib"
depends_on "gtk+3"
depends_on "pygtk"
depends_on "gobject-introspection"
depends_on :python
def install
args = [
"--disable-dependency-tracking",
"--prefix=#{prefix}",
"--disable-Bsymbolic",
"--enable-introspection=yes",
]
if build.with? "python"
# pygtk-codegen-2.0 has been deprecated and replaced by
# pygobject-codegen-2.0, but the vte Makefile does not detect this.
ENV["PYGTK_CODEGEN"] = Formula["pygobject"].bin/"pygobject-codegen-2.0"
args << "--enable-python"
end
system "./configure", *args
system "make install"
end
end
Delete vte3.rb
|
# encoding: utf-8
class MagicCloud
DEFAULT_WIDTH = 256
DEFAULT_HEIGHT = 256
def initialize(words, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT)
@words, @width, @height = words, width, height
@tags = words.map{|word, value|
Tag.new(word, value, self)
}.sort_by(&:size).reverse
@board = BitCollisionBoard.new(width, height)
#@board = MaskCollisionBoard.new(width, height)
@bounds = nil
@visible_tags = []
layout!
end
def draw(palette = nil)
palette ||= Color20.new
img = Magick::Image.new(width, height)
visible_tags.each_with_index do |tag, idx|
canvas = Magick::Draw.new
canvas.text_align(Magick::CenterAlign)
canvas.font_style(Magick::NormalStyle)
canvas.font_family('Arial')
canvas.pointsize = tag.size
canvas.fill = palette.color(idx)
canvas.translate(tag.x, tag.y)
canvas.rotate(tag.rotate) if tag.rotate
canvas.text 0, 0, tag.text
canvas.draw(img)
end
img
end
attr_reader :words, :width, :height
attr_reader :tags, :visible_tags
attr_reader :bounds, :board
def layout!
make_sprites!
layout_sprites!
end
def make_sprites!
spriter = Spriter.new(self)
spriter.sprite_all!(tags)
end
def layout_sprites!
tags.each_with_index do |tag, i|
#p "tag #{i}: #{tag.text} × #{tag.size}"
# find place (each next tag is harder to place)
if tag.find_place
visible_tags.push(tag)
if bounds
bounds.adjust!(tag.rect)
else
@bounds = tag.rect
end
end
end
end
end
require 'magic_cloud/rect'
require 'magic_cloud/spriter'
require 'magic_cloud/palettes'
require 'magic_cloud/tag'
require 'magic_cloud/collision_board'
Ooops. Requiring RMagick
# encoding: utf-8
require 'RMagick'
class MagicCloud
DEFAULT_WIDTH = 256
DEFAULT_HEIGHT = 256
def initialize(words, width = DEFAULT_WIDTH, height = DEFAULT_HEIGHT)
@words, @width, @height = words, width, height
@tags = words.map{|word, value|
Tag.new(word, value, self)
}.sort_by(&:size).reverse
@board = BitCollisionBoard.new(width, height)
#@board = MaskCollisionBoard.new(width, height)
@bounds = nil
@visible_tags = []
layout!
end
def draw(palette = nil)
palette ||= Color20.new
img = Magick::Image.new(width, height)
visible_tags.each_with_index do |tag, idx|
canvas = Magick::Draw.new
canvas.text_align(Magick::CenterAlign)
canvas.font_style(Magick::NormalStyle)
canvas.font_family('Arial')
canvas.pointsize = tag.size
canvas.fill = palette.color(idx)
canvas.translate(tag.x, tag.y)
canvas.rotate(tag.rotate) if tag.rotate
canvas.text 0, 0, tag.text
canvas.draw(img)
end
img
end
attr_reader :words, :width, :height
attr_reader :tags, :visible_tags
attr_reader :bounds, :board
def layout!
make_sprites!
layout_sprites!
end
def make_sprites!
spriter = Spriter.new(self)
spriter.sprite_all!(tags)
end
def layout_sprites!
tags.each_with_index do |tag, i|
#p "tag #{i}: #{tag.text} × #{tag.size}"
# find place (each next tag is harder to place)
if tag.find_place
visible_tags.push(tag)
if bounds
bounds.adjust!(tag.rect)
else
@bounds = tag.rect
end
end
end
end
end
require 'magic_cloud/rect'
require 'magic_cloud/spriter'
require 'magic_cloud/palettes'
require 'magic_cloud/tag'
require 'magic_cloud/collision_board'
|
module Memorylogic
def self.included(klass)
klass.class_eval do
after_filter :log_memory_usage
end
end
private
def log_memory_usage
if logger
memory_usage = `ps -o rss= -p #{Process.pid}`.to_i
logger.info("Memory usage: #{memory_usage} | PID: #{$$}")
end
end
end
ActiveSupport::BufferedLogger.class_eval do
def add_with_memory_info(severity, message = nil, progname = nil, &block)
memory_usage = `ps -o rss= -p #{$$}`.to_i
message ||= ""
message += " (mem #{memory_usage})"
add_without_memory_info(severity, message, progname, &block)
end
alias_method_chain :add, :memory_info
end
cleanup
module Memorylogic
def self.included(klass)
klass.class_eval do
after_filter :log_memory_usage
end
end
def self.memory_usage
`ps -o rss= -p #{Process.pid}`.to_i
end
private
def log_memory_usage
if logger
logger.info("Memory usage: #{Memorylogic.memory_usage} | PID: #{Process.pid}")
end
end
end
ActiveSupport::BufferedLogger.class_eval do
def add_with_memory_info(severity, message = nil, progname = nil, &block)
message ||= ""
message += "\nMemory usage: #{Memorylogic.memory_usage}\n\n"
add_without_memory_info(severity, message, progname, &block)
end
alias_method_chain :add, :memory_info
end |
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/concern'
require 'rails/generators'
module Rails
module Generators
module Testing
module Behaviour
extend ActiveSupport::Concern
included do
class_attribute :destination_root, :current_path, :generator_class, :default_arguments
# Generators frequently change the current path using +FileUtils.cd+.
# So we need to store the path at file load and revert back to it after each test.
self.current_path = File.expand_path(Dir.pwd)
self.default_arguments = []
end
module ClassMethods
# Sets which generator should be tested:
#
# tests AppGenerator
def tests(klass)
self.generator_class = klass
end
# Sets default arguments on generator invocation. This can be overwritten when
# invoking it.
#
# arguments %w(app_name --skip-active-record)
def arguments(array)
self.default_arguments = array
end
# Sets the destination of generator files:
#
# destination File.expand_path("../tmp", File.dirname(__FILE__))
def destination(path)
self.destination_root = path
end
end
# Runs the generator configured for this class. The first argument is an array like
# command line arguments:
#
# class AppGeneratorTest < Rails::Generators::TestCase
# tests AppGenerator
# destination File.expand_path("../tmp", File.dirname(__FILE__))
# teardown :cleanup_destination_root
#
# test "database.yml is not created when skipping Active Record" do
# run_generator %w(myapp --skip-active-record)
# assert_no_file "config/database.yml"
# end
# end
#
# You can provide a configuration hash as second argument. This method returns the output
# printed by the generator.
def run_generator(args=self.default_arguments, config={})
without_thor_debug do
capture(:stdout) do
args += ['--skip-bundle'] unless args.include? '--dev'
self.generator_class.start(args, config.reverse_merge(destination_root: destination_root))
end
end
end
# Instantiate the generator.
def generator(args=self.default_arguments, options={}, config={})
@generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
end
# Create a Rails::Generators::GeneratedAttribute by supplying the
# attribute type and, optionally, the attribute name:
#
# create_generated_attribute(:string, 'name')
def create_generated_attribute(attribute_type, name = 'test', index = nil)
Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':'))
end
protected
def destination_root_is_set? # :nodoc:
raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root
end
def ensure_current_path # :nodoc:
cd current_path
end
def prepare_destination # :nodoc:
rm_rf(destination_root)
mkdir_p(destination_root)
end
def migration_file_name(relative) # :nodoc:
absolute = File.expand_path(relative, destination_root)
dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
end
# TODO: remove this once Bundler 1.5.2 is released
def without_thor_debug # :nodoc:
thor_debug, ENV['THOR_DEBUG'] = ENV['THOR_DEBUG'], nil
yield
ensure
ENV['THOR_DEBUG'] = thor_debug
end
end
end
end
end
Removing without_thor_debug
a1d0c0fa3d8ca97edc8f2a1d6ba96af19221dbad
as bundler 1.5.2 is out now
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/hash/reverse_merge'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/concern'
require 'rails/generators'
module Rails
module Generators
module Testing
module Behaviour
extend ActiveSupport::Concern
included do
class_attribute :destination_root, :current_path, :generator_class, :default_arguments
# Generators frequently change the current path using +FileUtils.cd+.
# So we need to store the path at file load and revert back to it after each test.
self.current_path = File.expand_path(Dir.pwd)
self.default_arguments = []
end
module ClassMethods
# Sets which generator should be tested:
#
# tests AppGenerator
def tests(klass)
self.generator_class = klass
end
# Sets default arguments on generator invocation. This can be overwritten when
# invoking it.
#
# arguments %w(app_name --skip-active-record)
def arguments(array)
self.default_arguments = array
end
# Sets the destination of generator files:
#
# destination File.expand_path("../tmp", File.dirname(__FILE__))
def destination(path)
self.destination_root = path
end
end
# Runs the generator configured for this class. The first argument is an array like
# command line arguments:
#
# class AppGeneratorTest < Rails::Generators::TestCase
# tests AppGenerator
# destination File.expand_path("../tmp", File.dirname(__FILE__))
# teardown :cleanup_destination_root
#
# test "database.yml is not created when skipping Active Record" do
# run_generator %w(myapp --skip-active-record)
# assert_no_file "config/database.yml"
# end
# end
#
# You can provide a configuration hash as second argument. This method returns the output
# printed by the generator.
def run_generator(args=self.default_arguments, config={})
capture(:stdout) do
args += ['--skip-bundle'] unless args.include? '--dev'
self.generator_class.start(args, config.reverse_merge(destination_root: destination_root))
end
end
# Instantiate the generator.
def generator(args=self.default_arguments, options={}, config={})
@generator ||= self.generator_class.new(args, options, config.reverse_merge(destination_root: destination_root))
end
# Create a Rails::Generators::GeneratedAttribute by supplying the
# attribute type and, optionally, the attribute name:
#
# create_generated_attribute(:string, 'name')
def create_generated_attribute(attribute_type, name = 'test', index = nil)
Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(':'))
end
protected
def destination_root_is_set? # :nodoc:
raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root
end
def ensure_current_path # :nodoc:
cd current_path
end
def prepare_destination # :nodoc:
rm_rf(destination_root)
mkdir_p(destination_root)
end
def migration_file_name(relative) # :nodoc:
absolute = File.expand_path(relative, destination_root)
dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, '')
Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first
end
end
end
end
end
|
require 'httparty'
require 'nokogiri'
require 'open-uri'
require 'yaml'
%w(version league division team game player pitcher batter).each do |file|
require "mlb_gameday/#{file}"
end
module MLBGameday
API_URL = 'http://gd2.mlb.com/components/game/mlb'
BATTER = '/year_%{year}/batters/%{id}'
PITCHER = '/year_%{year}/pitchers/%{id}'
BOXSCORE = '/year_%{year}/month_%{month}/day_%{day}/gid_%{gid}/boxscore'
GAMECENTER = '/year_%{year}/month_%{month}/day_%{day}/gid_%{gid}/gamecenter'
LINESCORE = '/year_%{year}/month_%{month}/day_%{day}/gid_%{gid}/linescore'
SCOREBOARD = '/year_%Y/month_%m/day_%d/miniscoreboard'
class API
attr_reader :leagues
def initialize
@leagues = YAML.load File.open File.join(
File.dirname(File.expand_path __FILE__), '../resources/data.yml'
)
end
def league(name)
return name if name.is_a? MLBGameday::League
@leagues[name]
end
def team(name)
return name if name.is_a? MLBGameday::Team
teams.each do |team|
return team if team.names.include? name.downcase
end
nil
end
def teams
@teams ||= divisions.map(&:teams).map(&:values).flatten
end
def division(league, name)
@leagues[league][name]
end
def divisions
@divisions ||= @leagues[:AL].divisions.values +
@leagues[:NL].divisions.values
end
def pitcher(id)
return nil if id.empty?
MLBGameday::Pitcher.new id: id, xml: pitcher_xml(id)
end
def batter(id)
return nil if id.empty?
MLBGameday::Batter.new id: id, xml: batter_xml(id)
end
def game(gid)
MLBGameday::Game.new(
self,
gid,
gamecenter: gamecenter_xml(gid),
linescore: linescore_xml(gid),
boxscore: boxscore_xml(gid)
)
end
def find_games(team: nil, date: nil)
doc = scoreboard_xml(date || Date.today)
if team
code = team(team).code
doc.xpath('//games/game').map do |game|
next unless [game.xpath('@home_name_abbrev').text,
game.xpath('@away_name_abbrev').text].include? code
game game.xpath('@gameday_link').text
end.compact!
else
doc.xpath('//games/game').map do |game|
game game.xpath('@gameday_link').to_s
end
end
end
def scoreboard_xml(date)
fetch_xml date.strftime SCOREBOARD
end
def linescore_xml(gid)
year, month, day, _ = gid.split '_'
fetch_xml LINESCORE, year: year, month: month, day: day, gid: gid
end
def boxscore_xml(gid)
year, month, day, _ = gid.split '_'
fetch_xml BOXSCORE, year: year, month: month, day: day, gid: gid
rescue
nil
end
def gamecenter_xml(gid)
year, month, day, _ = gid.split '_'
fetch_xml GAMECENTER, year: year, month: month, day: day, gid: gid
rescue
nil
end
def batter_xml(id, year: nil)
# We only really want one piece of data from this file...
year_data = fetch_xml BATTER, id: id, year: (year || Date.today.year)
gid = year_data.xpath('//batting/@game_id').text
year, month, day, _ = gid.split '/'
fetch_xml "/year_#{year}/month_#{month}/day_#{day}/" \
"gid_#{gid.gsub(/[^a-z0-9]/, '_')}/batters/#{id}"
end
def pitcher_xml(id, year: nil)
# We only really want one piece of data from this file...
year_data = fetch_xml PITCHER, id: id, year: (year || Date.today.year)
gid = year_data.xpath('//pitching/@game_id').text
year, month, day, _ = gid.split '/'
fetch_xml "/year_#{year}/month_#{month}/day_#{day}/" \
"gid_#{gid.gsub(/[^a-z0-9]/, '_')}/pitchers/#{id}"
end
protected
def fetch_xml(path, interpolations = {})
Nokogiri::XML open format(API_URL + path + '.xml', interpolations)
end
end
end
Use Psych library to load YAML
Signed-off-by: Steven Hoffman <f5bcacb8ce1651b7d1e56f2693431f20e085fdeb@valenciamgmt.com>
require 'httparty'
require 'nokogiri'
require 'open-uri'
require 'psych'
%w(version league division team game player pitcher batter).each do |file|
require "mlb_gameday/#{file}"
end
module MLBGameday
API_URL = 'http://gd2.mlb.com/components/game/mlb'
BATTER = '/year_%{year}/batters/%{id}'
PITCHER = '/year_%{year}/pitchers/%{id}'
BOXSCORE = '/year_%{year}/month_%{month}/day_%{day}/gid_%{gid}/boxscore'
GAMECENTER = '/year_%{year}/month_%{month}/day_%{day}/gid_%{gid}/gamecenter'
LINESCORE = '/year_%{year}/month_%{month}/day_%{day}/gid_%{gid}/linescore'
SCOREBOARD = '/year_%Y/month_%m/day_%d/miniscoreboard'
class API
attr_reader :leagues
def initialize
@leagues = Psych.load File.open File.join(
File.dirname(File.expand_path __FILE__), '../resources/data.yml'
)
end
def league(name)
return name if name.is_a? MLBGameday::League
@leagues[name]
end
def team(name)
return name if name.is_a? MLBGameday::Team
teams.each do |team|
return team if team.names.include? name.downcase
end
nil
end
def teams
@teams ||= divisions.map(&:teams).map(&:values).flatten
end
def division(league, name)
@leagues[league][name]
end
def divisions
@divisions ||= @leagues[:AL].divisions.values +
@leagues[:NL].divisions.values
end
def pitcher(id)
return nil if id.empty?
MLBGameday::Pitcher.new id: id, xml: pitcher_xml(id)
end
def batter(id)
return nil if id.empty?
MLBGameday::Batter.new id: id, xml: batter_xml(id)
end
def game(gid)
MLBGameday::Game.new(
self,
gid,
gamecenter: gamecenter_xml(gid),
linescore: linescore_xml(gid),
boxscore: boxscore_xml(gid)
)
end
def find_games(team: nil, date: nil)
doc = scoreboard_xml(date || Date.today)
if team
code = team(team).code
doc.xpath('//games/game').map do |game|
next unless [game.xpath('@home_name_abbrev').text,
game.xpath('@away_name_abbrev').text].include? code
game game.xpath('@gameday_link').text
end.compact!
else
doc.xpath('//games/game').map do |game|
game game.xpath('@gameday_link').to_s
end
end
end
def scoreboard_xml(date)
fetch_xml date.strftime SCOREBOARD
end
def linescore_xml(gid)
year, month, day, _ = gid.split '_'
fetch_xml LINESCORE, year: year, month: month, day: day, gid: gid
end
def boxscore_xml(gid)
year, month, day, _ = gid.split '_'
fetch_xml BOXSCORE, year: year, month: month, day: day, gid: gid
rescue
nil
end
def gamecenter_xml(gid)
year, month, day, _ = gid.split '_'
fetch_xml GAMECENTER, year: year, month: month, day: day, gid: gid
rescue
nil
end
def batter_xml(id, year: nil)
# We only really want one piece of data from this file...
year_data = fetch_xml BATTER, id: id, year: (year || Date.today.year)
gid = year_data.xpath('//batting/@game_id').text
year, month, day, _ = gid.split '/'
fetch_xml "/year_#{year}/month_#{month}/day_#{day}/" \
"gid_#{gid.gsub(/[^a-z0-9]/, '_')}/batters/#{id}"
end
def pitcher_xml(id, year: nil)
# We only really want one piece of data from this file...
year_data = fetch_xml PITCHER, id: id, year: (year || Date.today.year)
gid = year_data.xpath('//pitching/@game_id').text
year, month, day, _ = gid.split '/'
fetch_xml "/year_#{year}/month_#{month}/day_#{day}/" \
"gid_#{gid.gsub(/[^a-z0-9]/, '_')}/pitchers/#{id}"
end
protected
def fetch_xml(path, interpolations = {})
Nokogiri::XML open format(API_URL + path + '.xml', interpolations)
end
end
end
|
module MMS
VERSION = '0.0.6'
end
Bumped version
module MMS
VERSION = '0.0.7'
end
|
# encoding: utf-8
require_relative './post/document_validator'
require_relative '../cache_key'
class Post < ActiveRecord::Base
class CanonicalPathConflict < StandardError; end
include TsVectorTags
include CacheKey
has_and_belongs_to_many :locations, :uniq => true,
:after_add => :increment_unread_counts,
:after_remove => :decrement_unread_counts
validates_presence_of :realm
validate :canonical_path_must_be_valid
validates_with DocumentValidator
validates_format_of :klass, :with => /^post(\.|$)/
# TODO: Remove '.' from allowed characters in external_id when parlor
# has been updated
validates_format_of :external_id,
:with => /^[a-zA-Z_-]/,
:if => lambda { |record| !record.external_id.nil? },
:message => "must start with a non-digit character"
before_validation :assign_realm, :set_default_klass
before_save :revert_unmodified_values
before_save :update_conflicted
before_save :attach_canonical_path
before_destroy :attach_canonical_path
before_save :update_readmarks_according_to_deleted_status
before_save :update_external_id_according_to_deleted_status
after_update :invalidate_cache
before_destroy :invalidate_cache
default_scope where("not deleted")
serialize :document
serialize :external_document
serialize :protected
serialize :sensitive
scope :by_path, ->(path) {
conditions = Pebbles::Path.to_conditions(path)
if conditions.empty?
nil
else
select("distinct posts.*").
joins(:locations).
where(locations: conditions)
end
}
scope :by_uid, lambda { |uid|
_klass, _path, _oid = Pebbles::Uid.parse(uid)
scope = by_path(_path)
scope = scope.where("klass in (?)", _klass.split('|')) unless _klass == '*'
scope = scope.where("posts.id = ?", _oid.to_i) unless _oid.nil? || _oid == '' || _oid == '*'
scope
}
scope :by_occurrence, lambda { |label|
select('posts.*').select('occurrence_entries.at').joins(:occurrence_entries).where(:occurrence_entries => {:label => label})
}
scope :occurs_after, lambda { |timestamp|
where("occurrence_entries.at >= ?", timestamp.utc)
}
scope :occurs_before, lambda { |timestamp|
where("occurrence_entries.at < ?", timestamp.utc)
}
# FIXME: In order to support the "deleted" filter, queries must be performed with default scope disabled.
scope :filtered_by, lambda { |filters|
scope = relation
scope = scope.where("not deleted") unless filters['deleted'] == 'include'
scope = scope.where("posts.created_at > ?", Time.parse(filters['created_after'])) if filters['created_after']
scope = scope.where("posts.created_at < ?", Time.parse(filters['created_before'])) if filters['created_before']
scope = scope.where(:realm => filters['realm']) if filters['realm']
scope = scope.where(:klass => filters['klass'].split(',').map(&:strip)) if filters['klass']
scope = scope.where(:external_id => filters['external_id'].split(',').map(&:strip)) if filters['external_id']
if filters['tags']
# Use a common tags scope if filter is an array or comma separated list
if filters['tags'].is_a?(Array) || (filters['tags'] =~ /\,/)
scope = scope.with_tags(filters['tags'])
else
scope = scope.with_tags_query(filters['tags'])
end
end
scope = scope.where("published") unless ['include', 'only'].include?(filters['unpublished'])
scope = scope.where("published is false") if filters['unpublished'] == 'only'
scope = scope.where(:created_by => filters['created_by']) if filters['created_by']
scope
}
scope :with_restrictions, lambda { |identity|
scope = relation
if !identity || !identity.respond_to?(:id)
scope = scope.where("not restricted and not deleted and published")
elsif !identity.god
scope = scope.
joins(:locations).
joins("left outer join group_locations on group_locations.location_id = locations.id").
joins("left outer join group_memberships on group_memberships.group_id = group_locations.group_id and group_memberships.identity_id = #{identity.id}").
where(['(not restricted and not deleted and published) or created_by = ? or group_memberships.identity_id = ?', identity.id, identity.id])
end
scope
}
def bling
puts "BAM: #{self.attributes}"
end
def attributes_for_export
attributes.update('document' => merged_document).merge('paths' => paths.to_a, 'uid' => uid)
end
# TODO: This method does not respect access-groups!? This is not a problem since we currently avoid
# going this route.
def visible_to?(identity)
return true if !restricted && !deleted && published
return false if nobody?(identity)
identity.god || identity.id == created_by
end
def nobody?(identity)
!identity || !identity.respond_to?(:id)
end
def editable_by?(identity)
return false if nobody?(identity)
return (identity.god && identity.realm == self.realm) || identity.id == created_by
end
def may_be_managed_by?(identity)
new_record? || editable_by?(identity)
end
def external_document=(external_document)
write_attribute('external_document', external_document)
self.external_document_updated_at = Time.now
end
def document=(doc)
write_attribute('document', doc)
self.document_updated_at = Time.now
end
# Override getters on serialized attributes with dup so the
# attributes become dirty when we use the old value on the setter
def external_document
ed = read_attribute('external_document')
ed.dup if ed
end
def document
d = read_attribute('document')
d.dup if d
end
def protected
p = read_attribute('protected')
p.dup if p
end
def sensitive
p = read_attribute('sensitive')
p.dup if p
end
def merged_document
doc = (external_document || {}).merge(document || {}).merge((occurrences.empty? ? {} : {'occurrences' => occurrences}))
doc.empty? ? {} : doc
end
def uid
"#{klass}:#{canonical_path}$#{id}"
end
def uid=(value)
self.klass, self.canonical_path, _oid = Pebbles::Uid.parse(value)
unless _oid.nil? || _oid == "#{self.id}"
raise ArgumentError, "Do not assign oid. It is managed by the model. (omit '...$#{_oid}' from uid)"
end
end
def self.find_by_uid(uid)
return nil unless Pebbles::Uid.oid(uid)
self.by_uid(uid).first
end
def self.find_by_external_id_and_uid(external_id, provided_uid)
return nil if external_id.nil?
uid = Pebbles::Uid.new(provided_uid)
post = self.where(:realm => uid.realm, :external_id => external_id).first
if post && post.canonical_path != uid.path
fail CanonicalPathConflict.new(post.uid)
end
post
end
# Accepts an array of `Pebbles::Uid.cache_key(uid)`s
def self.cached_find_all_by_uid(cache_keys)
result = Hash[
$memcached.get_multi(cache_keys.map {|key| CacheKey.wrap(key) }).map do |key, value|
post = Post.instantiate(Yajl::Parser.parse(value))
post.readonly!
[CacheKey.unwrap(key), post]
end
]
(cache_keys-result.keys).each do |key|
post = Post.find_by_uid(key)
if post
$memcached.set(post.cache_key, post.attributes.to_json) if post
post = Post.instantiate(Yajl::Parser.parse(post.attributes.to_json))
end
result[key] = post
end
cache_keys.map {|key| result[key]}
end
def add_path!(path)
self.paths << path
self.save!
end
def remove_path!(path)
self.paths.delete path
self.save!
end
# Add an occurrence without having to save the post.
# This is to avoid race conditions
def add_occurrences!(event, at = [])
Array(at).each do |time|
OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)
end
end
def remove_occurrences!(event)
OccurrenceEntry.where(:post_id => id, :label => event).destroy_all
end
def replace_occurrences!(event, at = [])
remove_occurrences!(event)
add_occurrences!(event, at)
end
private
def invalidate_cache
$memcached.delete(cache_key)
end
def assign_realm
self.realm = self.canonical_path[/^[^\.]*/] if self.canonical_path
end
# Ensures that the post is attached to its canonical path
def attach_canonical_path
self.paths |= [self.canonical_path]
end
def canonical_path_must_be_valid
unless Pebbles::Uid.valid_path?(self.canonical_path)
error.add :base, "#{self.canonical_path.inspect} is an invalid path."
end
end
def set_default_klass
self.klass ||= "post"
end
def increment_unread_counts(location)
Readmark.post_added(location.path.to_s, self.id) unless self.deleted?
end
def decrement_unread_counts(location)
Readmark.post_removed(location.path.to_s, self.id) unless self.deleted?
end
def revert_unmodified_values
# When updating a Post that has an external_document, make sure only the actual *changed* (overridden)
# fields are kept in the `document` hash.
return if document.nil? or external_document.nil?
document.reject! { |key, value| external_document[key] == value }
end
def update_conflicted
return if document.nil? or external_document.nil?
overridden_fields = external_document.keys & document.keys
self.conflicted = (external_document_updated_at > document_updated_at and overridden_fields.any?)
true
end
def update_readmarks_according_to_deleted_status
if self.deleted_changed?
# We are using the locations relation directly to make sure we are not
# picking up any unsynced changes that may have been applied to the
# paths attribute.
paths = self.locations.map { |location| location.path.to_s }
if self.deleted
paths.each { |path| Readmark.post_removed(path, self.id)}
else
paths.each { |path| Readmark.post_added(path, self.id)}
end
end
end
def update_external_id_according_to_deleted_status
# A deleted post should not lock its external_id but we
# archive it to post.document in order to make forensics easier.
if self.deleted_changed?
if self.deleted && self.external_id != nil
doc = self.document || {} # TODO: never have posts with nil document
doc.merge!('external_id' => self.external_id)
self.document = doc
self.external_id = nil
end
end
end
end
Remove silly method
# encoding: utf-8
require_relative './post/document_validator'
require_relative '../cache_key'
class Post < ActiveRecord::Base
class CanonicalPathConflict < StandardError; end
include TsVectorTags
include CacheKey
has_and_belongs_to_many :locations, :uniq => true,
:after_add => :increment_unread_counts,
:after_remove => :decrement_unread_counts
validates_presence_of :realm
validate :canonical_path_must_be_valid
validates_with DocumentValidator
validates_format_of :klass, :with => /^post(\.|$)/
# TODO: Remove '.' from allowed characters in external_id when parlor
# has been updated
validates_format_of :external_id,
:with => /^[a-zA-Z_-]/,
:if => lambda { |record| !record.external_id.nil? },
:message => "must start with a non-digit character"
before_validation :assign_realm, :set_default_klass
before_save :revert_unmodified_values
before_save :update_conflicted
before_save :attach_canonical_path
before_destroy :attach_canonical_path
before_save :update_readmarks_according_to_deleted_status
before_save :update_external_id_according_to_deleted_status
after_update :invalidate_cache
before_destroy :invalidate_cache
default_scope where("not deleted")
serialize :document
serialize :external_document
serialize :protected
serialize :sensitive
scope :by_path, ->(path) {
conditions = Pebbles::Path.to_conditions(path)
if conditions.empty?
nil
else
select("distinct posts.*").
joins(:locations).
where(locations: conditions)
end
}
scope :by_uid, lambda { |uid|
_klass, _path, _oid = Pebbles::Uid.parse(uid)
scope = by_path(_path)
scope = scope.where("klass in (?)", _klass.split('|')) unless _klass == '*'
scope = scope.where("posts.id = ?", _oid.to_i) unless _oid.nil? || _oid == '' || _oid == '*'
scope
}
scope :by_occurrence, lambda { |label|
select('posts.*').select('occurrence_entries.at').joins(:occurrence_entries).where(:occurrence_entries => {:label => label})
}
scope :occurs_after, lambda { |timestamp|
where("occurrence_entries.at >= ?", timestamp.utc)
}
scope :occurs_before, lambda { |timestamp|
where("occurrence_entries.at < ?", timestamp.utc)
}
# FIXME: In order to support the "deleted" filter, queries must be performed with default scope disabled.
scope :filtered_by, lambda { |filters|
scope = relation
scope = scope.where("not deleted") unless filters['deleted'] == 'include'
scope = scope.where("posts.created_at > ?", Time.parse(filters['created_after'])) if filters['created_after']
scope = scope.where("posts.created_at < ?", Time.parse(filters['created_before'])) if filters['created_before']
scope = scope.where(:realm => filters['realm']) if filters['realm']
scope = scope.where(:klass => filters['klass'].split(',').map(&:strip)) if filters['klass']
scope = scope.where(:external_id => filters['external_id'].split(',').map(&:strip)) if filters['external_id']
if filters['tags']
# Use a common tags scope if filter is an array or comma separated list
if filters['tags'].is_a?(Array) || (filters['tags'] =~ /\,/)
scope = scope.with_tags(filters['tags'])
else
scope = scope.with_tags_query(filters['tags'])
end
end
scope = scope.where("published") unless ['include', 'only'].include?(filters['unpublished'])
scope = scope.where("published is false") if filters['unpublished'] == 'only'
scope = scope.where(:created_by => filters['created_by']) if filters['created_by']
scope
}
scope :with_restrictions, lambda { |identity|
scope = relation
if !identity || !identity.respond_to?(:id)
scope = scope.where("not restricted and not deleted and published")
elsif !identity.god
scope = scope.
joins(:locations).
joins("left outer join group_locations on group_locations.location_id = locations.id").
joins("left outer join group_memberships on group_memberships.group_id = group_locations.group_id and group_memberships.identity_id = #{identity.id}").
where(['(not restricted and not deleted and published) or created_by = ? or group_memberships.identity_id = ?', identity.id, identity.id])
end
scope
}
def attributes_for_export
attributes.update('document' => merged_document).merge('paths' => paths.to_a, 'uid' => uid)
end
# TODO: This method does not respect access-groups!? This is not a problem since we currently avoid
# going this route.
def visible_to?(identity)
return true if !restricted && !deleted && published
return false if nobody?(identity)
identity.god || identity.id == created_by
end
def nobody?(identity)
!identity || !identity.respond_to?(:id)
end
def editable_by?(identity)
return false if nobody?(identity)
return (identity.god && identity.realm == self.realm) || identity.id == created_by
end
def may_be_managed_by?(identity)
new_record? || editable_by?(identity)
end
def external_document=(external_document)
write_attribute('external_document', external_document)
self.external_document_updated_at = Time.now
end
def document=(doc)
write_attribute('document', doc)
self.document_updated_at = Time.now
end
# Override getters on serialized attributes with dup so the
# attributes become dirty when we use the old value on the setter
def external_document
ed = read_attribute('external_document')
ed.dup if ed
end
def document
d = read_attribute('document')
d.dup if d
end
def protected
p = read_attribute('protected')
p.dup if p
end
def sensitive
p = read_attribute('sensitive')
p.dup if p
end
def merged_document
doc = (external_document || {}).merge(document || {}).merge((occurrences.empty? ? {} : {'occurrences' => occurrences}))
doc.empty? ? {} : doc
end
def uid
"#{klass}:#{canonical_path}$#{id}"
end
def uid=(value)
self.klass, self.canonical_path, _oid = Pebbles::Uid.parse(value)
unless _oid.nil? || _oid == "#{self.id}"
raise ArgumentError, "Do not assign oid. It is managed by the model. (omit '...$#{_oid}' from uid)"
end
end
def self.find_by_uid(uid)
return nil unless Pebbles::Uid.oid(uid)
self.by_uid(uid).first
end
def self.find_by_external_id_and_uid(external_id, provided_uid)
return nil if external_id.nil?
uid = Pebbles::Uid.new(provided_uid)
post = self.where(:realm => uid.realm, :external_id => external_id).first
if post && post.canonical_path != uid.path
fail CanonicalPathConflict.new(post.uid)
end
post
end
# Accepts an array of `Pebbles::Uid.cache_key(uid)`s
def self.cached_find_all_by_uid(cache_keys)
result = Hash[
$memcached.get_multi(cache_keys.map {|key| CacheKey.wrap(key) }).map do |key, value|
post = Post.instantiate(Yajl::Parser.parse(value))
post.readonly!
[CacheKey.unwrap(key), post]
end
]
(cache_keys-result.keys).each do |key|
post = Post.find_by_uid(key)
if post
$memcached.set(post.cache_key, post.attributes.to_json) if post
post = Post.instantiate(Yajl::Parser.parse(post.attributes.to_json))
end
result[key] = post
end
cache_keys.map {|key| result[key]}
end
def add_path!(path)
self.paths << path
self.save!
end
def remove_path!(path)
self.paths.delete path
self.save!
end
# Add an occurrence without having to save the post.
# This is to avoid race conditions
def add_occurrences!(event, at = [])
Array(at).each do |time|
OccurrenceEntry.create!(:post_id => id, :label => event, :at => time)
end
end
def remove_occurrences!(event)
OccurrenceEntry.where(:post_id => id, :label => event).destroy_all
end
def replace_occurrences!(event, at = [])
remove_occurrences!(event)
add_occurrences!(event, at)
end
private
def invalidate_cache
$memcached.delete(cache_key)
end
def assign_realm
self.realm = self.canonical_path[/^[^\.]*/] if self.canonical_path
end
# Ensures that the post is attached to its canonical path
def attach_canonical_path
self.paths |= [self.canonical_path]
end
def canonical_path_must_be_valid
unless Pebbles::Uid.valid_path?(self.canonical_path)
error.add :base, "#{self.canonical_path.inspect} is an invalid path."
end
end
def set_default_klass
self.klass ||= "post"
end
def increment_unread_counts(location)
Readmark.post_added(location.path.to_s, self.id) unless self.deleted?
end
def decrement_unread_counts(location)
Readmark.post_removed(location.path.to_s, self.id) unless self.deleted?
end
def revert_unmodified_values
# When updating a Post that has an external_document, make sure only the actual *changed* (overridden)
# fields are kept in the `document` hash.
return if document.nil? or external_document.nil?
document.reject! { |key, value| external_document[key] == value }
end
def update_conflicted
return if document.nil? or external_document.nil?
overridden_fields = external_document.keys & document.keys
self.conflicted = (external_document_updated_at > document_updated_at and overridden_fields.any?)
true
end
def update_readmarks_according_to_deleted_status
if self.deleted_changed?
# We are using the locations relation directly to make sure we are not
# picking up any unsynced changes that may have been applied to the
# paths attribute.
paths = self.locations.map { |location| location.path.to_s }
if self.deleted
paths.each { |path| Readmark.post_removed(path, self.id)}
else
paths.each { |path| Readmark.post_added(path, self.id)}
end
end
end
def update_external_id_according_to_deleted_status
# A deleted post should not lock its external_id but we
# archive it to post.document in order to make forensics easier.
if self.deleted_changed?
if self.deleted && self.external_id != nil
doc = self.document || {} # TODO: never have posts with nil document
doc.merge!('external_id' => self.external_id)
self.document = doc
self.external_id = nil
end
end
end
end
|
framework 'Foundation'
##
# Classes, modules, methods, and constants relevant to working with the
# Mac OS X keychain.
module Keychain
end
require 'mr_keychain/version'
require 'mr_keychain/keychain'
require 'mr_keychain/item'
require 'mr_keychain/keychain_exception'
Define KSecAttrPassword
In order to provide a proper abstraction through the #[] accessors.
framework 'Foundation'
##
# Classes, modules, methods, and constants relevant to working with the
# Mac OS X keychain.
module Keychain
end
unless Kernel.const_defined?(:KSecAttrPassword)
# This is a special constant that allows {Keychain::Item} to treat a
# password as if it were like the other keychain item attributes.
# @return [Symbol]
KSecAttrPassword = :password
end
require 'mr_keychain/version'
require 'mr_keychain/keychain'
require 'mr_keychain/item'
require 'mr_keychain/keychain_exception'
|
require 'ast_node'
require 'graphite'
#
# Author:: Jose Fernandez (@magec)
# Copyright:: Copyright (c) 2011 UOC (Universitat Oberta de Catalunya)
# License:: GNU General Public License version 2 or later
#
# This program and entire repository is free software; you can
# redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software
# Foundation; either version 2 of the License, or 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
##
# This class allows the transformation between graphite and munin config. It constructs an AST parsing the munin config information and
# allows to output a valid graphic in graphite url format
# Jose Fernandez 2011
#
class MuninGraph
def initialize(config)
@raw_config = config
parse_config
end
def config=(config)
@config = config
self.root.config = config
end
def to_graphite
graph = Graphite::MyGraph.new
self.root.compile
graph.url = self.root.url
self.root.properties[:category] ||= "other"
graph.name = "#{@config[:hostname]}.#{self.root.properties[:category]}.#{self.root.properties[:metric]}"
graph.name = "#{@config[:graphite][:graph_prefix]}.#{graph.name}" if @config[:graphite][:graph_prefix] && @config[:graphite][:graph_prefix] != ""
return graph
end
attr_reader :root
# This array of hashes will be used to match what kind of line we are dealing with and
# to know the corresponding ast node class
TOKENS = [
{:matcher => /^graph_title .*/, :klass => GraphTitleGlobalDeclarationNode},
{:matcher => /^create_args .*/, :klass => CreateArgsGlobalDeclarationNode},
{:matcher => /^graph_args .*/, :klass => GraphArgsGlobalDeclarationNode},
{:matcher => /^graph_category .*/, :klass => GraphCategoryGlobalDeclarationNode},
{:matcher => /^graph_info .*/, :klass => GraphInfoGlobalDeclarationNode},
{:matcher => /^graph_order .*/, :klass => GraphOrderGlobalDeclarationNode},
{:matcher => /^graph_vlabel .*/, :klass => GraphVLabelGlobalDeclarationNode},
{:matcher => /^graph_total .*/, :klass => GraphTotalGlobalDeclarationNode},
{:matcher => /^graph_scale .*/, :klass => GraphScaleGlobalDeclarationNode},
{:matcher => /^graph .*/, :klass => GraphGlobalDeclarationNode},
{:matcher => /^host_name .*/, :klass => HostNameGlobalDeclarationNode},
{:matcher => /^update .*/, :klass => UpdateGlobalDeclarationNode},
{:matcher => /^graph_period .*/, :klass => GraphPeriodGlobalDeclarationNode},
{:matcher => /^graph_vtitle .*/, :klass => GraphVTitleGlobalDeclarationNode},
{:matcher => /^service_order .*/, :klass => ServiceOrderGlobalDeclarationNode},
{:matcher => /^graph_width .*/, :klass => GraphWidthGlobalDeclarationNode},
{:matcher => /^graph_height .*/, :klass => GraphHeightGlobalDeclarationNode},
{:matcher => /^graph_printfformat .*/, :klass => GraphPrintFormatGlobalDeclarationNode},
{:matcher => /([\w\-_]+)\.label\ .*$/,:klass => LabelFieldPropertyNode},
{:matcher => /([\w\-_]+)\.cdef\ .*$/,:klass => CDefFieldPropertyNode},
{:matcher => /([\w\-_]+)\.draw\ .*$/,:klass => DrawFieldPropertyNode},
{:matcher => /([\w\-_]+)\.graph\ .*$/,:klass => GraphFieldPropertyNode},
{:matcher => /([\w\-_]+)\.info\ .*$/,:klass => InfoFieldPropertyNode},
{:matcher => /([\w\-_]+)\.extinfo\ .*$/,:klass => ExtInfoFieldPropertyNode},
{:matcher => /([\w\-_]+)\.max\ .*$/,:klass => MaxFieldPropertyNode},
{:matcher => /([\w\-_]+)\.min\ .*$/,:klass => MinFieldPropertyNode},
{:matcher => /([\w\-_]+)\.negative\ .*$/,:klass => NegativeFieldPropertyNode},
{:matcher => /([\w\-_]+)\.type\ .*$/,:klass => TypeFieldPropertyNode},
{:matcher => /([\w\-_]+)\.warning\ .*$/,:klass => WarningFieldPropertyNode},
{:matcher => /([\w\-_]+)\.critical\ .*$/,:klass => CriticalFieldPropertyNode},
{:matcher => /([\w\-_]+)\.colour\ .*$/,:klass => ColourFieldPropertyNode},
{:matcher => /([\w\-_]+)\.skipdraw\ .*$/,:klass => SkipDrawFieldPropertyNode},
{:matcher => /([\w\-_]+)\.sum\ .*$/,:klass => SumFieldPropertyNode},
{:matcher => /([\w\-_]+)\.stack\ .*$/,:klass => StackFieldPropertyNode},
{:matcher => /([\w\-_]+)\.linevalue\[:color\[:label\]\]\ .*$/,:klass => LineValueFieldPropertyNode},
{:matcher => /([\w\-_]+)\.oldname\ .*$/,:klass => OldNameFieldPropertyNode},
{:matcher => /([\w\-_]+)\.value\ .*$/,:klass => ValueFieldPropertyNode}
]
def parse_config
@root = ASTNode.new("")
@root.parent = nil
current_node = @root
@raw_config.each_line do |line|
# For every line of config we match against every token
TOKENS.each do |token|
if line =~ token[:matcher]
# When we find a match...
if token[:klass].new("").is_a? FieldPropertyNode
# In Property field we have to set it to a FieldDeclarationNode (an artificial node grouping those fields)
if !current_node.is_a? FieldDeclarationNode
# A new FieldDeclaration has to ve created
node = FieldDeclarationNode.new("")
node.properties[:field_name] = $1
current_node.add_child node
current_node = node
elsif current_node.properties[:field_name] != $1
if (aux = @root.children_of_class(FieldDeclarationNode).find { |i| i.properties[:field_name] == $1 } )
current_node = aux
else
# We use the one declared before (note that different metrics could not be interlaced)
node = FieldDeclarationNode.new("")
node.properties[:field_name] = $1
current_node.parent.add_child node
current_node = node
end
end
current_node.add_child token[:klass].send("new",line)
else
@root.add_child token[:klass].send("new",line)
end
break
end
end
end
end
end
Now the regexp is the official one
require 'ast_node'
require 'graphite'
#
# Author:: Jose Fernandez (@magec)
# Copyright:: Copyright (c) 2011 UOC (Universitat Oberta de Catalunya)
# License:: GNU General Public License version 2 or later
#
# This program and entire repository is free software; you can
# redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software
# Foundation; either version 2 of the License, or 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
##
# This class allows the transformation between graphite and munin config. It constructs an AST parsing the munin config information and
# allows to output a valid graphic in graphite url format
# Jose Fernandez 2011
#
class MuninGraph
def initialize(config)
@raw_config = config
parse_config
end
def config=(config)
@config = config
self.root.config = config
end
def to_graphite
graph = Graphite::MyGraph.new
self.root.compile
graph.url = self.root.url
self.root.properties[:category] ||= "other"
graph.name = "#{@config[:hostname]}.#{self.root.properties[:category]}.#{self.root.properties[:metric]}"
graph.name = "#{@config[:graphite][:graph_prefix]}.#{graph.name}" if @config[:graphite][:graph_prefix] && @config[:graphite][:graph_prefix] != ""
return graph
end
attr_reader :root
# This array of hashes will be used to match what kind of line we are dealing with and
# to know the corresponding ast node class
TOKENS = [
{:matcher => /^graph_title .*/, :klass => GraphTitleGlobalDeclarationNode},
{:matcher => /^create_args .*/, :klass => CreateArgsGlobalDeclarationNode},
{:matcher => /^graph_args .*/, :klass => GraphArgsGlobalDeclarationNode},
{:matcher => /^graph_category .*/, :klass => GraphCategoryGlobalDeclarationNode},
{:matcher => /^graph_info .*/, :klass => GraphInfoGlobalDeclarationNode},
{:matcher => /^graph_order .*/, :klass => GraphOrderGlobalDeclarationNode},
{:matcher => /^graph_vlabel .*/, :klass => GraphVLabelGlobalDeclarationNode},
{:matcher => /^graph_total .*/, :klass => GraphTotalGlobalDeclarationNode},
{:matcher => /^graph_scale .*/, :klass => GraphScaleGlobalDeclarationNode},
{:matcher => /^graph .*/, :klass => GraphGlobalDeclarationNode},
{:matcher => /^host_name .*/, :klass => HostNameGlobalDeclarationNode},
{:matcher => /^update .*/, :klass => UpdateGlobalDeclarationNode},
{:matcher => /^graph_period .*/, :klass => GraphPeriodGlobalDeclarationNode},
{:matcher => /^graph_vtitle .*/, :klass => GraphVTitleGlobalDeclarationNode},
{:matcher => /^service_order .*/, :klass => ServiceOrderGlobalDeclarationNode},
{:matcher => /^graph_width .*/, :klass => GraphWidthGlobalDeclarationNode},
{:matcher => /^graph_height .*/, :klass => GraphHeightGlobalDeclarationNode},
{:matcher => /^graph_printfformat .*/, :klass => GraphPrintFormatGlobalDeclarationNode},
{:matcher => /([\w_]+)\.label\ .*$/,:klass => LabelFieldPropertyNode},
{:matcher => /([\w_]+)\.cdef\ .*$/,:klass => CDefFieldPropertyNode},
{:matcher => /([\w_]+)\.draw\ .*$/,:klass => DrawFieldPropertyNode},
{:matcher => /([\w_]+)\.graph\ .*$/,:klass => GraphFieldPropertyNode},
{:matcher => /([\w_]+)\.info\ .*$/,:klass => InfoFieldPropertyNode},
{:matcher => /([\w_]+)\.extinfo\ .*$/,:klass => ExtInfoFieldPropertyNode},
{:matcher => /([\w_]+)\.max\ .*$/,:klass => MaxFieldPropertyNode},
{:matcher => /([\w_]+)\.min\ .*$/,:klass => MinFieldPropertyNode},
{:matcher => /([\w_]+)\.negative\ .*$/,:klass => NegativeFieldPropertyNode},
{:matcher => /([\w_]+)\.type\ .*$/,:klass => TypeFieldPropertyNode},
{:matcher => /([\w_]+)\.warning\ .*$/,:klass => WarningFieldPropertyNode},
{:matcher => /([\w_]+)\.critical\ .*$/,:klass => CriticalFieldPropertyNode},
{:matcher => /([\w_]+)\.colour\ .*$/,:klass => ColourFieldPropertyNode},
{:matcher => /([\w_]+)\.skipdraw\ .*$/,:klass => SkipDrawFieldPropertyNode},
{:matcher => /([\w_]+)\.sum\ .*$/,:klass => SumFieldPropertyNode},
{:matcher => /([\w_]+)\.stack\ .*$/,:klass => StackFieldPropertyNode},
{:matcher => /([\w_]+)\.linevalue\[:color\[:label\]\]\ .*$/,:klass => LineValueFieldPropertyNode},
{:matcher => /([\w_]+)\.oldname\ .*$/,:klass => OldNameFieldPropertyNode},
{:matcher => /([\w_]+)\.value\ .*$/,:klass => ValueFieldPropertyNode}
]
def parse_config
@root = ASTNode.new("")
@root.parent = nil
current_node = @root
@raw_config.each_line do |line|
# For every line of config we match against every token
TOKENS.each do |token|
if line =~ token[:matcher]
# When we find a match...
if token[:klass].new("").is_a? FieldPropertyNode
# In Property field we have to set it to a FieldDeclarationNode (an artificial node grouping those fields)
if !current_node.is_a? FieldDeclarationNode
# A new FieldDeclaration has to ve created
node = FieldDeclarationNode.new("")
node.properties[:field_name] = $1
current_node.add_child node
current_node = node
elsif current_node.properties[:field_name] != $1
if (aux = @root.children_of_class(FieldDeclarationNode).find { |i| i.properties[:field_name] == $1 } )
current_node = aux
else
# We use the one declared before (note that different metrics could not be interlaced)
node = FieldDeclarationNode.new("")
node.properties[:field_name] = $1
current_node.parent.add_child node
current_node = node
end
end
current_node.add_child token[:klass].send("new",line)
else
@root.add_child token[:klass].send("new",line)
end
break
end
end
end
end
end
|
module EtTools
class NatMonitor
require 'net/http'
require 'net/ping'
require 'fog'
require 'yaml'
def initialize(conf_file = nil)
@conf = defaults.merge load_conf(conf_file)
end
def load_conf(conf_file = nil)
YAML.load_file(conf_file || '/etc/nat_monitor.yml')
end
def run
validate!
output 'Starting NAT Monitor'
main_loop
end
def validate!
case
when !@conf['route_table_id']
output 'route_table_id not specified'
exit 1
when !route_exists?(@conf['route_table_id'])
output "Route #{@conf['route_table_id']} not found"
exit 2
when @conf['nodes'].count < 3
output '3 or more nodes are required to create a quorum'
exit 3
end
end
def output(message)
puts message
end
def defaults
{ 'pings' => 3,
'ping_timeout' => 1,
'heartbeat_interval' => 10 }
end
def main_loop
loop do
heartbeat
sleep @conf['heartbeat_interval']
end
end
def heartbeat
if am_i_master?
output "Looks like I'm the master"
return
end
un = unreachable_nodes
return if un.empty?
if un.count == other_nodes.keys.count # return if I'm unreachable...
output "No nodes are reachable. Seems I'm the unreachable one."
return
end
cm = current_master
unless un.include?(cm) # ...unless master is unreachable
output "Unreachable nodes: #{un.inspect}"
output "Current master (#{cm}) is still reachable"
return
end
steal_route
end
def steal_route
output 'Stealing route 0.0.0.0/0 on route table ' \
"#{@conf['route_table_id']}"
return if @conf['mocking']
connection.replace_route(
@conf['route_table_id'],
'0.0.0.0/0',
my_instance_id
)
end
def unreachable_nodes
other_nodes.select { |_node, ip| !pingable?(ip) }
end
def other_nodes
@other_nodes ||= begin
nodes = @conf['nodes'].dup
nodes.delete my_instance_id
nodes
end
end
def pingable?(ip)
p = Net::Ping::External.new(ip)
p.timeout = @conf['ping_timeout']
p.ping?
end
def route_exists?(route_id)
connection.route_tables.map(&:id).include? route_id
end
def connection
@connection ||= begin
if @conf['aws_access_key_id']
options = { aws_access_key_id: @conf['aws_access_key_id'],
aws_secret_access_key: @conf['aws_secret_access_key'] }
else
options = { use_iam_profile: true }
end
options[:endpoint] = @conf['aws_url'] if @conf['aws_url']
Fog::Compute::AWS.new(options)
end
end
def current_master
default_r =
connection.route_tables.get(@conf['route_table_id']).routes.find do |r|
r['destinationCidrBlock'] == '0.0.0.0/0'
end
default_r['instanceId']
end
def my_instance_id
@my_instance_id ||= begin
Net::HTTP.get(
'169.254.169.254',
'/latest/meta-data/instance-id'
)
end
end
def am_i_master?
master_node? my_instance_id
end
def master_node?(node_id)
current_master == node_id
end
end
end
Add syslog logging
module EtTools
class NatMonitor
require 'net/http'
require 'net/ping'
require 'fog'
require 'yaml'
require 'syslog'
def initialize(conf_file = nil)
@conf = defaults.merge load_conf(conf_file)
end
def load_conf(conf_file = nil)
YAML.load_file(conf_file || '/etc/nat_monitor.yml')
end
def run
validate!
output 'Starting NAT Monitor'
main_loop
end
def validate!
case
when !@conf['route_table_id']
output 'route_table_id not specified'
exit 1
when !route_exists?(@conf['route_table_id'])
output "Route #{@conf['route_table_id']} not found"
exit 2
when @conf['nodes'].count < 3
output '3 or more nodes are required to create a quorum'
exit 3
end
end
def defaults
{ 'pings' => 3,
'ping_timeout' => 1,
'heartbeat_interval' => 10 }
end
def main_loop
loop do
heartbeat
sleep @conf['heartbeat_interval']
end
end
def heartbeat
if am_i_master?
output "Looks like I'm the master"
return
end
un = unreachable_nodes
return if un.empty?
if un.count == other_nodes.keys.count # return if I'm unreachable...
output "No nodes are reachable. Seems I'm the unreachable one."
return
end
cm = current_master
unless un.include?(cm) # ...unless master is unreachable
output "Unreachable nodes: #{un.inspect}"
output "Current master (#{cm}) is still reachable"
return
end
steal_route
end
def steal_route
output 'Stealing route 0.0.0.0/0 on route table ' \
"#{@conf['route_table_id']}"
return if @conf['mocking']
connection.replace_route(
@conf['route_table_id'],
'0.0.0.0/0',
my_instance_id
)
end
def unreachable_nodes
other_nodes.select { |_node, ip| !pingable?(ip) }
end
def other_nodes
@other_nodes ||= begin
nodes = @conf['nodes'].dup
nodes.delete my_instance_id
nodes
end
end
def pingable?(ip)
p = Net::Ping::External.new(ip)
p.timeout = @conf['ping_timeout']
p.ping?
end
def route_exists?(route_id)
connection.route_tables.map(&:id).include? route_id
end
def connection
@connection ||= begin
if @conf['aws_access_key_id']
options = { aws_access_key_id: @conf['aws_access_key_id'],
aws_secret_access_key: @conf['aws_secret_access_key'] }
else
options = { use_iam_profile: true }
end
options[:endpoint] = @conf['aws_url'] if @conf['aws_url']
Fog::Compute::AWS.new(options)
end
end
def current_master
default_r =
connection.route_tables.get(@conf['route_table_id']).routes.find do |r|
r['destinationCidrBlock'] == '0.0.0.0/0'
end
default_r['instanceId']
end
def my_instance_id
@my_instance_id ||= begin
Net::HTTP.get(
'169.254.169.254',
'/latest/meta-data/instance-id'
)
end
end
def am_i_master?
master_node? my_instance_id
end
def master_node?(node_id)
current_master == node_id
end
private
def output(message)
puts message
log message
end
def log(message, level = 'info')
Syslog.open($PROGRAM_NAME, Syslog::LOG_PID | Syslog::LOG_CONS) do |s|
s.send(level, message)
end
end
end
end
|
# coding: utf-8
require 'natto/binding'
require 'natto/option_parse'
require 'natto/struct'
module Natto
# `MeCab` is a wrapper class for the `mecab` tagger.
# Options to the `mecab` tagger are passed in as a string
# (MeCab command-line style) or as a Ruby-style hash at
# initialization.
#
# ## Usage
#
# require 'rubygems' if RUBY_VERSION.to_f < 1.9
# require 'natto'
#
# nm = Natto::MeCab.new('-Ochasen')
# => #<Natto::MeCab:0x28d3bdc8 \
# @tagger=#<FFI::Pointer address=0x28afb980>, \
# @filepath="/usr/local/lib/libmecab.so" \
# @options={:output_format_type=>"chasen"}, \
# @dicts=[#<Natto::DictionaryInfo:0x289a1f14 \
# @filepath="/usr/local/lib/mecab/dic/ipadic/sys.dic", \
# charset=utf8 \
# type=0>], \
# @version=0.996>
#
# nm.parse('凡人にしか見えねえ風景ってのがあるんだよ。') do |n|
# puts "#{n.surface}\t#{n.feature}"
# end
# 凡人 名詞,一般,*,*,*,*,凡人,ボンジン,ボンジン
# に 助詞,格助詞,一般,*,*,*,に,ニ,ニ
# しか 助詞,係助詞,*,*,*,*,しか,シカ,シカ
# 見え 動詞,自立,*,*,一段,未然形,見える,ミエ,ミエ
# ねえ 助動詞,*,*,*,特殊・ナイ,音便基本形,ない,ネエ,ネー
# 風景 名詞,一般,*,*,*,*,風景,フウケイ,フーケイ
# って 助詞,格助詞,連語,*,*,*,って,ッテ,ッテ
# の 名詞,非自立,一般,*,*,*,の,ノ,ノ
# が 助詞,格助詞,一般,*,*,*,が,ガ,ガ
# ある 動詞,自立,*,*,五段・ラ行,基本形,ある,アル,アル
# ん 名詞,非自立,一般,*,*,*,ん,ン,ン
# だ 助動詞,*,*,*一般,特殊・ダ,基本形,だ,ダ,ダ
# よ 助詞,終助詞,*,*,*,*,よ,ã¨,ヨ
# 。 記号,句点,*,*,*,*,。,。,。
# BOS/EOS,*,*,*,*,*,*,*,*BOS
#
class MeCab
include Natto::Binding
include Natto::OptionParse
attr_reader :tagger, :filepath, :options, :dicts, :version
# Initializes the wrapped `mecab` instance with the
# given `options`.
#
# Options supported are:
#
# - :rcfile -- resource file
# - :dicdir -- system dicdir
# - :userdic -- user dictionary
# - :lattice_level -- lattice information level (DEPRECATED)
# - :output_format_type -- output format type (wakati, chasen, yomi, etc.)
# - :all_morphs -- output all morphs (default false)
# - :nbest -- output N best results (integer, default 1), requires lattice level >= 1
# - :partial -- partial parsing mode
# - :marginal -- output marginal probability
# - :max_grouping_size -- maximum grouping size for unknown words (default 24)
# - :node_format -- user-defined node format
# - :unk_format -- user-defined unknown node format
# - :bos_format -- user-defined beginning-of-sentence format
# - :eos_format -- user-defined end-of-sentence format
# - :eon_format -- user-defined end-of-NBest format
# - :unk_feature -- feature for unknown word
# - :input_buffer_size -- set input buffer size (default 8192)
# - :allocate_sentence -- allocate new memory for input sentence
# - :theta -- temperature parameter theta (float, default 0.75)
# - :cost_factor -- cost factor (integer, default 700)
#
# <p>MeCab command-line arguments (-F) or long (--node-format) may be used in
# addition to Ruby-style `Hash`es</p>
# <i>Use single-quotes to preserve format options that contain escape chars.</i><br/>
# e.g.<br/>
#
# nm = Natto::MeCab.new(:node_format=>'%m¥t%f[7]¥n')
# => #<Natto::MeCab:0x28d2ae10
# @tagger=#<FFI::Pointer address=0x28a97980>, \
# @filepath="/usr/local/lib/libmecab.so", \
# @options={:node_format=>"%m¥t%f[7]¥n"}, \
# @dicts=[#<Natto::DictionaryInfo:0x28d2a85c \
# @filepath="/usr/local/lib/mecab/dic/ipadic/sys.dic" \
# charset=utf8, \
# type=0>] \
# @version=0.996>
#
# puts nm.parse('才能とは求める人間に与えられるものではない。')
# 才能 サイノウ
# と ト
# は ハ
# 求 モトメル
# 人間 ニンゲン
# に ニ
# 与え アタエ
# られる ラレル
# もの モノ
# で デ
# は ハ
# ない ナイ
# 。 。
# EOS
#
# @param [Hash or String]
# @raise [MeCabError] if `mecab` cannot be initialized with the given `options`
def initialize(options={})
@options = self.class.parse_mecab_options(options)
@dicts = []
opt_str = self.class.build_options_str(@options)
@tagger = self.class.mecab_new2(opt_str)
@filepath = self.class.find_library
raise MeCabError.new("Could not initialize MeCab with options: '#{opt_str}'") if @tagger.address == 0x0
self.mecab_set_theta(@tagger, @options[:theta]) if @options[:theta]
self.mecab_set_lattice_level(@tagger, @options[:lattice_level]) if @options[:lattice_level]
self.mecab_set_all_morphs(@tagger, 1) if @options[:all_morphs]
self.mecab_set_partial(@tagger, 1) if @options[:partial]
# Set mecab parsing implementations for N-best and regular parsing,
# for both parsing as string and yielding a node object
if @options[:nbest] && @options[:nbest] > 1
# N-Best parsing implementations
self.mecab_set_lattice_level(@tagger, (@options[:lattice_level] || 1))
@parse_tostr = lambda do |text|
retval = self.mecab_nbest_sparse_tostr(@tagger, @options[:nbest], text) ||
raise(MeCabError.new(self.mecab_strerror(@tagger)))
retval.force_encoding(Encoding.default_external)
end
@parse_tonodes = lambda do |text|
self.mecab_nbest_init(@tagger, text)
n = self.mecab_nbest_next_tonode(@tagger)
raise(MeCabError.new(self.mecab_strerror(@tagger))) if n.nil? || n.address==0x0
Enumerator.new do |y|
nlen = @options[:nbest]
nlen.times do |i|
s = text.bytes.to_a
while n && n.address != 0x0
mn = Natto::MeCabNode.new(n)
# ignore BOS nodes, since mecab does so
if !mn.is_bos?
s = s.drop_while {|e| (e==0xa || e==0x20)}
if !s.empty?
sarr = []
mn.length.times { sarr << s.shift }
surf = sarr.pack('C*')
mn.surface = surf.force_encoding(Encoding.default_external)
end
if @options[:output_format_type] || @options[:node_format]
mn.feature = self.mecab_format_node(@tagger, n).force_encoding(Encoding.default_external)
end
y.yield mn
end
n = mn.next
end
n = self.mecab_nbest_next_tonode(@tagger)
end
end
end
else
# default parsing implementations
@parse_tostr = lambda do |text|
retval = self.mecab_sparse_tostr(@tagger, text) ||
raise(MeCabError.new(self.mecab_strerror(@tagger)))
retval.force_encoding(Encoding.default_external)
end
@parse_tonodes = lambda do |text|
n = self.mecab_sparse_tonode(@tagger, text)
raise(MeCabError.new(self.mecab_strerror(@tagger))) if n.nil? || n.address==0x0
Enumerator.new do |y|
mn = Natto::MeCabNode.new(n)
n = mn.next if mn.next.address!=0x0
s = text.bytes.to_a
while n && n.address!=0x0
mn = Natto::MeCabNode.new(n)
s = s.drop_while {|e| (e==0xa || e==0x20)}
if !s.empty?
sarr = []
mn.length.times { sarr << s.shift }
surf = sarr.pack('C*')
mn.surface = surf.force_encoding(Encoding.default_external)
end
# TODO file issue for this bug!
# and write some tests for this case
if @options[:output_format_type] || @options[:node_format]
mn.feature = self.mecab_format_node(@tagger, n).force_encoding(Encoding.default_external)
end
y.yield mn
n = mn.next
end
end
end
end
@dicts << Natto::DictionaryInfo.new(Natto::Binding.mecab_dictionary_info(@tagger))
while @dicts.last.next.address != 0x0
@dicts << Natto::DictionaryInfo.new(@dicts.last.next)
end
@version = self.mecab_version
ObjectSpace.define_finalizer(self, self.class.create_free_proc(@tagger))
end
# Parses the given string `text`. If a block is passed to this method,
# then node parsing will be used and each node yielded to the given block.
#
# @param [String] text
# @return parsing result from `mecab`
# @raise [MeCabError] if the `mecab` tagger cannot parse the given `text`
# @raise [ArgumentError] if the given string `text` argument is `nil`
# @see MeCabNode
def parse(text)
raise ArgumentError.new 'Text to parse cannot be nil' if text.nil?
if block_given?
@parse_tonodes.call(text).each {|n| yield n }
else
@parse_tostr.call(text)
end
end
# TODO remove this method in next release
# DEPRECATED: use parse instead, this convenience method is useless.
# Parses the given string `str`, and returns
# a list of `mecab` nodes.
# @param [String] str
# @return [Array] of parsed `mecab` nodes.
# @raise [MeCabError] if the `mecab` tagger cannot parse the given string `str`
# @raise [ArgumentError] if the given string `str` argument is `nil`
# @see MeCabNode
def parse_as_nodes(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
raise ArgumentError.new 'String to parse cannot be nil' if str.nil?
@parse_tonodes.call(str)
end
# TODO remove this method in next release
# DEPRECATED: use parse instead, this convenience method is useless.
# Parses the given string `str`, and returns
# a list of `mecab` result strings.
# @param [String] str
# @return [Array] of parsed `mecab` result strings.
# @raise [MeCabError] if the `mecab` tagger cannot parse the given string `str`
# @raise [ArgumentError] if the given string `str` argument is `nil`
def parse_as_strings(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
raise ArgumentError.new 'String to parse cannot be nil' if str.nil?
@parse_tostr.call(str).lines.to_a
end
# TODO remove this method in next release
# DEPRECATED: use parse instead.
def readnodes(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
parse_as_nodes(str)
end
# TODO remove this method in next release
# DEPRECATED: use parse instead.
def readlines(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
parse_as_strings(str)
end
# Returns human-readable details for the wrapped `mecab` tagger.
# Overrides `Object#to_s`.
#
# - encoded object id
# - underlying FFI pointer to the `mecab` tagger
# - real file path to `mecab` library
# - options hash
# - list of dictionaries
# - MeCab version
#
# @return [String] encoded object id, underlying FFI pointer, file path to `mecab` library, options hash, list of dictionaries and MeCab version
def to_s
[ super.chop,
"@tagger=#{@tagger},",
"@filepath=\"#{@filepath}\",",
"@options=#{@options.inspect},",
"@dicts=#{@dicts.to_s},",
"@version=#{@version.to_s}>" ].join(' ')
end
# Overrides `Object#inspect`.
#
# @return [String] encoded object id, FFI pointer, options hash,
# list of dictionaries, and MeCab version
# @see #to_s
def inspect
self.to_s
end
# Returns a `Proc` that will properly free resources
# when this `MeCab` instance is garbage collected.
# The `Proc` returned is registered to be invoked
# after the `MeCab` instance owning `ptr`
# has been destroyed.
#
# @param [FFI::Pointer] ptr
# @return [Proc] to release `mecab` resources properly
def self.create_free_proc(ptr)
Proc.new do
self.mecab_destroy(ptr)
end
end
end
# `MeCabError` is a general error class
# for the `Natto` module.
class MeCabError < RuntimeError; end
end
# Copyright (c) 2014-2015, Brooke M. Fujita.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
natto.rb edited online with Bitbucket; changing filepath attribute to libpath, to help discern it from a dictionary's filepath value.
# coding: utf-8
require 'natto/binding'
require 'natto/option_parse'
require 'natto/struct'
module Natto
# `MeCab` is a wrapper class for the `mecab` tagger.
# Options to the `mecab` tagger are passed in as a string
# (MeCab command-line style) or as a Ruby-style hash at
# initialization.
#
# ## Usage
#
# require 'rubygems' if RUBY_VERSION.to_f < 1.9
# require 'natto'
#
# nm = Natto::MeCab.new('-Ochasen')
# => #<Natto::MeCab:0x28d3bdc8 \
# @tagger=#<FFI::Pointer address=0x28afb980>, \
# @libpath="/usr/local/lib/libmecab.so" \
# @options={:output_format_type=>"chasen"}, \
# @dicts=[#<Natto::DictionaryInfo:0x289a1f14 \
# @filepath="/usr/local/lib/mecab/dic/ipadic/sys.dic", \
# charset=utf8 \
# type=0>], \
# @version=0.996>
#
# nm.parse('凡人にしか見えねえ風景ってのがあるんだよ。') do |n|
# puts "#{n.surface}\t#{n.feature}"
# end
# 凡人 名詞,一般,*,*,*,*,凡人,ボンジン,ボンジン
# に 助詞,格助詞,一般,*,*,*,に,ニ,ニ
# しか 助詞,係助詞,*,*,*,*,しか,シカ,シカ
# 見え 動詞,自立,*,*,一段,未然形,見える,ミエ,ミエ
# ねえ 助動詞,*,*,*,特殊・ナイ,音便基本形,ない,ネエ,ネー
# 風景 名詞,一般,*,*,*,*,風景,フウケイ,フーケイ
# って 助詞,格助詞,連語,*,*,*,って,ッテ,ッテ
# の 名詞,非自立,一般,*,*,*,の,ノ,ノ
# が 助詞,格助詞,一般,*,*,*,が,ガ,ガ
# ある 動詞,自立,*,*,五段・ラ行,基本形,ある,アル,アル
# ん 名詞,非自立,一般,*,*,*,ん,ン,ン
# だ 助動詞,*,*,*一般,特殊・ダ,基本形,だ,ダ,ダ
# よ 助詞,終助詞,*,*,*,*,よ,ã¨,ヨ
# 。 記号,句点,*,*,*,*,。,。,。
# BOS/EOS,*,*,*,*,*,*,*,*BOS
#
class MeCab
include Natto::Binding
include Natto::OptionParse
attr_reader :tagger, :libpath, :options, :dicts, :version
# Initializes the wrapped `mecab` instance with the
# given `options`.
#
# Options supported are:
#
# - :rcfile -- resource file
# - :dicdir -- system dicdir
# - :userdic -- user dictionary
# - :lattice_level -- lattice information level (DEPRECATED)
# - :output_format_type -- output format type (wakati, chasen, yomi, etc.)
# - :all_morphs -- output all morphs (default false)
# - :nbest -- output N best results (integer, default 1), requires lattice level >= 1
# - :partial -- partial parsing mode
# - :marginal -- output marginal probability
# - :max_grouping_size -- maximum grouping size for unknown words (default 24)
# - :node_format -- user-defined node format
# - :unk_format -- user-defined unknown node format
# - :bos_format -- user-defined beginning-of-sentence format
# - :eos_format -- user-defined end-of-sentence format
# - :eon_format -- user-defined end-of-NBest format
# - :unk_feature -- feature for unknown word
# - :input_buffer_size -- set input buffer size (default 8192)
# - :allocate_sentence -- allocate new memory for input sentence
# - :theta -- temperature parameter theta (float, default 0.75)
# - :cost_factor -- cost factor (integer, default 700)
#
# <p>MeCab command-line arguments (-F) or long (--node-format) may be used in
# addition to Ruby-style `Hash`es</p>
# <i>Use single-quotes to preserve format options that contain escape chars.</i><br/>
# e.g.<br/>
#
# nm = Natto::MeCab.new(:node_format=>'%m¥t%f[7]¥n')
# => #<Natto::MeCab:0x28d2ae10
# @tagger=#<FFI::Pointer address=0x28a97980>, \
# @libpath="/usr/local/lib/libmecab.so", \
# @options={:node_format=>"%m¥t%f[7]¥n"}, \
# @dicts=[#<Natto::DictionaryInfo:0x28d2a85c \
# @filepath="/usr/local/lib/mecab/dic/ipadic/sys.dic" \
# charset=utf8, \
# type=0>] \
# @version=0.996>
#
# puts nm.parse('才能とは求める人間に与えられるものではない。')
# 才能 サイノウ
# と ト
# は ハ
# 求 モトメル
# 人間 ニンゲン
# に ニ
# 与え アタエ
# られる ラレル
# もの モノ
# で デ
# は ハ
# ない ナイ
# 。 。
# EOS
#
# @param [Hash or String]
# @raise [MeCabError] if `mecab` cannot be initialized with the given `options`
def initialize(options={})
@options = self.class.parse_mecab_options(options)
@dicts = []
opt_str = self.class.build_options_str(@options)
@tagger = self.class.mecab_new2(opt_str)
@libpath = self.class.find_library
raise MeCabError.new("Could not initialize MeCab with options: '#{opt_str}'") if @tagger.address == 0x0
self.mecab_set_theta(@tagger, @options[:theta]) if @options[:theta]
self.mecab_set_lattice_level(@tagger, @options[:lattice_level]) if @options[:lattice_level]
self.mecab_set_all_morphs(@tagger, 1) if @options[:all_morphs]
self.mecab_set_partial(@tagger, 1) if @options[:partial]
# Set mecab parsing implementations for N-best and regular parsing,
# for both parsing as string and yielding a node object
if @options[:nbest] && @options[:nbest] > 1
# N-Best parsing implementations
self.mecab_set_lattice_level(@tagger, (@options[:lattice_level] || 1))
@parse_tostr = lambda do |text|
retval = self.mecab_nbest_sparse_tostr(@tagger, @options[:nbest], text) ||
raise(MeCabError.new(self.mecab_strerror(@tagger)))
retval.force_encoding(Encoding.default_external)
end
@parse_tonodes = lambda do |text|
self.mecab_nbest_init(@tagger, text)
n = self.mecab_nbest_next_tonode(@tagger)
raise(MeCabError.new(self.mecab_strerror(@tagger))) if n.nil? || n.address==0x0
Enumerator.new do |y|
nlen = @options[:nbest]
nlen.times do |i|
s = text.bytes.to_a
while n && n.address != 0x0
mn = Natto::MeCabNode.new(n)
# ignore BOS nodes, since mecab does so
if !mn.is_bos?
s = s.drop_while {|e| (e==0xa || e==0x20)}
if !s.empty?
sarr = []
mn.length.times { sarr << s.shift }
surf = sarr.pack('C*')
mn.surface = surf.force_encoding(Encoding.default_external)
end
if @options[:output_format_type] || @options[:node_format]
mn.feature = self.mecab_format_node(@tagger, n).force_encoding(Encoding.default_external)
end
y.yield mn
end
n = mn.next
end
n = self.mecab_nbest_next_tonode(@tagger)
end
end
end
else
# default parsing implementations
@parse_tostr = lambda do |text|
retval = self.mecab_sparse_tostr(@tagger, text) ||
raise(MeCabError.new(self.mecab_strerror(@tagger)))
retval.force_encoding(Encoding.default_external)
end
@parse_tonodes = lambda do |text|
n = self.mecab_sparse_tonode(@tagger, text)
raise(MeCabError.new(self.mecab_strerror(@tagger))) if n.nil? || n.address==0x0
Enumerator.new do |y|
mn = Natto::MeCabNode.new(n)
n = mn.next if mn.next.address!=0x0
s = text.bytes.to_a
while n && n.address!=0x0
mn = Natto::MeCabNode.new(n)
s = s.drop_while {|e| (e==0xa || e==0x20)}
if !s.empty?
sarr = []
mn.length.times { sarr << s.shift }
surf = sarr.pack('C*')
mn.surface = surf.force_encoding(Encoding.default_external)
end
if @options[:output_format_type] || @options[:node_format]
mn.feature = self.mecab_format_node(@tagger, n).force_encoding(Encoding.default_external)
end
y.yield mn
n = mn.next
end
end
end
end
@dicts << Natto::DictionaryInfo.new(Natto::Binding.mecab_dictionary_info(@tagger))
while @dicts.last.next.address != 0x0
@dicts << Natto::DictionaryInfo.new(@dicts.last.next)
end
@version = self.mecab_version
ObjectSpace.define_finalizer(self, self.class.create_free_proc(@tagger))
end
# Parses the given string `text`. If a block is passed to this method,
# then node parsing will be used and each node yielded to the given block.
#
# @param [String] text
# @return parsing result from `mecab`
# @raise [MeCabError] if the `mecab` tagger cannot parse the given `text`
# @raise [ArgumentError] if the given string `text` argument is `nil`
# @see MeCabNode
def parse(text)
raise ArgumentError.new 'Text to parse cannot be nil' if text.nil?
if block_given?
@parse_tonodes.call(text).each {|n| yield n }
else
@parse_tostr.call(text)
end
end
# TODO remove this method in next release
# DEPRECATED: use parse instead, this convenience method is useless.
# Parses the given string `str`, and returns
# a list of `mecab` nodes.
# @param [String] str
# @return [Array] of parsed `mecab` nodes.
# @raise [MeCabError] if the `mecab` tagger cannot parse the given string `str`
# @raise [ArgumentError] if the given string `str` argument is `nil`
# @see MeCabNode
def parse_as_nodes(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
raise ArgumentError.new 'String to parse cannot be nil' if str.nil?
@parse_tonodes.call(str)
end
# TODO remove this method in next release
# DEPRECATED: use parse instead, this convenience method is useless.
# Parses the given string `str`, and returns
# a list of `mecab` result strings.
# @param [String] str
# @return [Array] of parsed `mecab` result strings.
# @raise [MeCabError] if the `mecab` tagger cannot parse the given string `str`
# @raise [ArgumentError] if the given string `str` argument is `nil`
def parse_as_strings(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
raise ArgumentError.new 'String to parse cannot be nil' if str.nil?
@parse_tostr.call(str).lines.to_a
end
# TODO remove this method in next release
# DEPRECATED: use parse instead.
def readnodes(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
parse_as_nodes(str)
end
# TODO remove this method in next release
# DEPRECATED: use parse instead.
def readlines(str)
$stderr.puts 'DEPRECATED: use parse instead'
$stderr.puts ' This method will be removed in the next release!'
parse_as_strings(str)
end
# Returns human-readable details for the wrapped `mecab` tagger.
# Overrides `Object#to_s`.
#
# - encoded object id
# - underlying FFI pointer to the `mecab` tagger
# - real file path to `mecab` library
# - options hash
# - list of dictionaries
# - MeCab version
#
# @return [String] encoded object id, underlying FFI pointer, file path to `mecab` library, options hash, list of dictionaries and MeCab version
def to_s
[ super.chop,
"@tagger=#{@tagger},",
"@libpath=\"#{@libpath}\",",
"@options=#{@options.inspect},",
"@dicts=#{@dicts.to_s},",
"@version=#{@version.to_s}>" ].join(' ')
end
# Overrides `Object#inspect`.
#
# @return [String] encoded object id, FFI pointer, options hash,
# list of dictionaries, and MeCab version
# @see #to_s
def inspect
self.to_s
end
# Returns a `Proc` that will properly free resources
# when this `MeCab` instance is garbage collected.
# The `Proc` returned is registered to be invoked
# after the `MeCab` instance owning `ptr`
# has been destroyed.
#
# @param [FFI::Pointer] ptr
# @return [Proc] to release `mecab` resources properly
def self.create_free_proc(ptr)
Proc.new do
self.mecab_destroy(ptr)
end
end
end
# `MeCabError` is a general error class
# for the `Natto` module.
class MeCabError < RuntimeError; end
end
# Copyright (c) 2014-2015, Brooke M. Fujita.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
require 'socket'
require 'timeout'
module Net #:nodoc:
module NTP
TIMEOUT = 60 #:nodoc:
NTP_ADJ = 2208988800 #:nodoc:
NTP_FIELDS = [ :byte1, :stratum, :poll, :precision, :delay, :delay_fb,
:disp, :disp_fb, :ident, :ref_time, :ref_time_fb, :org_time,
:org_time_fb, :recv_time, :recv_time_fb, :trans_time,
:trans_time_fb ]
MODE = {
0 => 'reserved',
1 => 'symmetric active',
2 => 'symmetric passive',
3 => 'client',
4 => 'server',
5 => 'broadcast',
6 => 'reserved for NTP control message',
7 => 'reserved for private use'
}
STRATUM = {
0 => 'unspecified or unavailable',
1 => 'primary reference (e.g., radio clock)'
}
2.upto(15) do |i|
STRATUM[i] = 'secondary reference (via NTP or SNTP)'
end
16.upto(255) do |i|
STRATUM[i] = 'reserved'
end
REFERENCE_CLOCK_IDENTIFIER = {
'LOCL' => 'uncalibrated local clock used as a primary reference for a subnet without external means of synchronization',
'PPS' => 'atomic clock or other pulse-per-second source individually calibrated to national standards',
'ACTS' => 'NIST dialup modem service',
'USNO' => 'USNO modem service',
'PTB' => 'PTB (Germany) modem service',
'TDF' => 'Allouis (France) Radio 164 kHz',
'DCF' => 'Mainflingen (Germany) Radio 77.5 kHz',
'MSF' => 'Rugby (UK) Radio 60 kHz',
'WWV' => 'Ft. Collins (US) Radio 2.5, 5, 10, 15, 20 MHz',
'WWVB' => 'Boulder (US) Radio 60 kHz',
'WWVH' => 'Kaui Hawaii (US) Radio 2.5, 5, 10, 15 MHz',
'CHU' => 'Ottawa (Canada) Radio 3330, 7335, 14670 kHz',
'LORC' => 'LORAN-C radionavigation system',
'OMEG' => 'OMEGA radionavigation system',
'GPS' => 'Global Positioning Service',
'GOES' => 'Geostationary Orbit Environment Satellite'
}
LEAP_INDICATOR = {
0 => 'no warning',
1 => 'last minute has 61 seconds',
2 => 'last minute has 59 seconds)',
3 => 'alarm condition (clock not synchronized)'
}
###
# Sends an NTP datagram to the specified NTP server and returns
# a hash based upon RFC1305 and RFC2030.
def self.get(host="pool.ntp.org", port="ntp", timeout=TIMEOUT)
sock = UDPSocket.new
sock.connect(host, port)
client_time_send = Time.new.to_i
client_localtime = client_time_send
client_adj_localtime = client_localtime + NTP_ADJ
client_frac_localtime = frac2bin(client_adj_localtime)
ntp_msg = (['00011011']+Array.new(12, 0)+[client_localtime, client_frac_localtime.to_s]).pack("B8 C3 N10 B32")
sock.print ntp_msg
sock.flush
data = nil
Timeout::timeout(timeout) do |t|
data = sock.recvfrom(960)[0]
end
Response.new(data)
end
def self.frac2bin(frac) #:nodoc:
bin = ''
while bin.length < 32
bin += ( frac * 2 ).to_i.to_s
frac = ( frac * 2 ) - ( frac * 2 ).to_i
end
bin
end
private_class_method :frac2bin
class Response
def initialize(raw_data)
@raw_data = raw_data
@client_time_receive = Time.new.to_i
end
def leap_indicator
@leap_indicator ||= (packet_data_by_field[:byte1][0] & 0xC0) >> 6
end
def leap_indicator_text
@leap_indicator_text ||= LEAP_INDICATOR[leap_indicator]
end
def version_number
@version_number ||= (packet_data_by_field[:byte1][0] & 0x38) >> 3
end
def mode
@mode ||= (packet_data_by_field[:byte1][0] & 0x07)
end
def mode_text
@mode_text ||= MODE[mode]
end
def stratum
@stratum ||= packet_data_by_field[:stratum]
end
def stratum_text
@stratum_text ||= STRATUM[stratum]
end
def poll_interval
@poll_interval ||= packet_data_by_field[:poll]
end
def precision
@precision ||= packet_data_by_field[:precision] - 255
end
def root_delay
@root_delay ||= bin2frac(packet_data_by_field[:delay_fb])
end
def root_dispersion
@root_dispersion ||= packet_data_by_field[:disp]
end
def reference_clock_identifier
@reference_clock_identifier ||= unpack_ip(packet_data_by_field[:stratum], packet_data_by_field[:ident])
end
def reference_clock_identifier_text
@reference_clock_identifier_text ||= REFERENCE_CLOCK_IDENTIFIER[reference_clock_identifier]
end
def reference_timestamp
@reference_timestamp ||= ((packet_data_by_field[:ref_time] + bin2frac(packet_data_by_field[:ref_time_fb])) - NTP_ADJ)
end
def originate_timestamp
@originate_timestamp ||= (packet_data_by_field[:org_time] + bin2frac(packet_data_by_field[:org_time_fb]))
end
def receive_timestamp
@receive_timestamp ||= ((packet_data_by_field[:recv_time] + bin2frac(packet_data_by_field[:recv_time_fb])) - NTP_ADJ)
end
def transmit_timestamp
@transmit_timestamp ||= ((packet_data_by_field[:trans_time] + bin2frac(packet_data_by_field[:trans_time_fb])) - NTP_ADJ)
end
def time
@time ||= Time.at(receive_timestamp)
end
protected
def packet_data_by_field #:nodoc:
if !@packet_data_by_field
@packetdata = @raw_data.unpack("a C3 n B16 n B16 H8 N B32 N B32 N B32 N B32");
@packet_data_by_field = {}
NTP_FIELDS.each do |field|
@packet_data_by_field[field] = @packetdata.shift
end
end
@packet_data_by_field
end
def bin2frac(bin) #:nodoc:
frac = 0
bin.reverse.split("").each do |b|
frac = ( frac + b.to_i ) / 2.0
end
frac
end
def unpack_ip(stratum, tmp_ip) #:nodoc:
if stratum < 2
[tmp_ip].pack("H8").unpack("A4")[0]
else
ipbytes = [tmp_ip].pack("H8").unpack("C4")
sprintf("%d.%d.%d.%d", ipbytes[0], ipbytes[1], ipbytes[2], ipbytes[3])
end
end
end
end
end
Initializing @packet_data_by_field
require 'socket'
require 'timeout'
module Net #:nodoc:
module NTP
TIMEOUT = 60 #:nodoc:
NTP_ADJ = 2208988800 #:nodoc:
NTP_FIELDS = [ :byte1, :stratum, :poll, :precision, :delay, :delay_fb,
:disp, :disp_fb, :ident, :ref_time, :ref_time_fb, :org_time,
:org_time_fb, :recv_time, :recv_time_fb, :trans_time,
:trans_time_fb ]
MODE = {
0 => 'reserved',
1 => 'symmetric active',
2 => 'symmetric passive',
3 => 'client',
4 => 'server',
5 => 'broadcast',
6 => 'reserved for NTP control message',
7 => 'reserved for private use'
}
STRATUM = {
0 => 'unspecified or unavailable',
1 => 'primary reference (e.g., radio clock)'
}
2.upto(15) do |i|
STRATUM[i] = 'secondary reference (via NTP or SNTP)'
end
16.upto(255) do |i|
STRATUM[i] = 'reserved'
end
REFERENCE_CLOCK_IDENTIFIER = {
'LOCL' => 'uncalibrated local clock used as a primary reference for a subnet without external means of synchronization',
'PPS' => 'atomic clock or other pulse-per-second source individually calibrated to national standards',
'ACTS' => 'NIST dialup modem service',
'USNO' => 'USNO modem service',
'PTB' => 'PTB (Germany) modem service',
'TDF' => 'Allouis (France) Radio 164 kHz',
'DCF' => 'Mainflingen (Germany) Radio 77.5 kHz',
'MSF' => 'Rugby (UK) Radio 60 kHz',
'WWV' => 'Ft. Collins (US) Radio 2.5, 5, 10, 15, 20 MHz',
'WWVB' => 'Boulder (US) Radio 60 kHz',
'WWVH' => 'Kaui Hawaii (US) Radio 2.5, 5, 10, 15 MHz',
'CHU' => 'Ottawa (Canada) Radio 3330, 7335, 14670 kHz',
'LORC' => 'LORAN-C radionavigation system',
'OMEG' => 'OMEGA radionavigation system',
'GPS' => 'Global Positioning Service',
'GOES' => 'Geostationary Orbit Environment Satellite'
}
LEAP_INDICATOR = {
0 => 'no warning',
1 => 'last minute has 61 seconds',
2 => 'last minute has 59 seconds)',
3 => 'alarm condition (clock not synchronized)'
}
###
# Sends an NTP datagram to the specified NTP server and returns
# a hash based upon RFC1305 and RFC2030.
def self.get(host="pool.ntp.org", port="ntp", timeout=TIMEOUT)
sock = UDPSocket.new
sock.connect(host, port)
client_time_send = Time.new.to_i
client_localtime = client_time_send
client_adj_localtime = client_localtime + NTP_ADJ
client_frac_localtime = frac2bin(client_adj_localtime)
ntp_msg = (['00011011']+Array.new(12, 0)+[client_localtime, client_frac_localtime.to_s]).pack("B8 C3 N10 B32")
sock.print ntp_msg
sock.flush
data = nil
Timeout::timeout(timeout) do |t|
data = sock.recvfrom(960)[0]
end
Response.new(data)
end
def self.frac2bin(frac) #:nodoc:
bin = ''
while bin.length < 32
bin += ( frac * 2 ).to_i.to_s
frac = ( frac * 2 ) - ( frac * 2 ).to_i
end
bin
end
private_class_method :frac2bin
class Response
def initialize(raw_data)
@raw_data = raw_data
@client_time_receive = Time.new.to_i
@packet_data_by_field = nil
end
def leap_indicator
@leap_indicator ||= (packet_data_by_field[:byte1][0] & 0xC0) >> 6
end
def leap_indicator_text
@leap_indicator_text ||= LEAP_INDICATOR[leap_indicator]
end
def version_number
@version_number ||= (packet_data_by_field[:byte1][0] & 0x38) >> 3
end
def mode
@mode ||= (packet_data_by_field[:byte1][0] & 0x07)
end
def mode_text
@mode_text ||= MODE[mode]
end
def stratum
@stratum ||= packet_data_by_field[:stratum]
end
def stratum_text
@stratum_text ||= STRATUM[stratum]
end
def poll_interval
@poll_interval ||= packet_data_by_field[:poll]
end
def precision
@precision ||= packet_data_by_field[:precision] - 255
end
def root_delay
@root_delay ||= bin2frac(packet_data_by_field[:delay_fb])
end
def root_dispersion
@root_dispersion ||= packet_data_by_field[:disp]
end
def reference_clock_identifier
@reference_clock_identifier ||= unpack_ip(packet_data_by_field[:stratum], packet_data_by_field[:ident])
end
def reference_clock_identifier_text
@reference_clock_identifier_text ||= REFERENCE_CLOCK_IDENTIFIER[reference_clock_identifier]
end
def reference_timestamp
@reference_timestamp ||= ((packet_data_by_field[:ref_time] + bin2frac(packet_data_by_field[:ref_time_fb])) - NTP_ADJ)
end
def originate_timestamp
@originate_timestamp ||= (packet_data_by_field[:org_time] + bin2frac(packet_data_by_field[:org_time_fb]))
end
def receive_timestamp
@receive_timestamp ||= ((packet_data_by_field[:recv_time] + bin2frac(packet_data_by_field[:recv_time_fb])) - NTP_ADJ)
end
def transmit_timestamp
@transmit_timestamp ||= ((packet_data_by_field[:trans_time] + bin2frac(packet_data_by_field[:trans_time_fb])) - NTP_ADJ)
end
def time
@time ||= Time.at(receive_timestamp)
end
protected
def packet_data_by_field #:nodoc:
if !@packet_data_by_field
@packetdata = @raw_data.unpack("a C3 n B16 n B16 H8 N B32 N B32 N B32 N B32");
@packet_data_by_field = {}
NTP_FIELDS.each do |field|
@packet_data_by_field[field] = @packetdata.shift
end
end
@packet_data_by_field
end
def bin2frac(bin) #:nodoc:
frac = 0
bin.reverse.split("").each do |b|
frac = ( frac + b.to_i ) / 2.0
end
frac
end
def unpack_ip(stratum, tmp_ip) #:nodoc:
if stratum < 2
[tmp_ip].pack("H8").unpack("A4")[0]
else
ipbytes = [tmp_ip].pack("H8").unpack("C4")
sprintf("%d.%d.%d.%d", ipbytes[0], ipbytes[1], ipbytes[2], ipbytes[3])
end
end
end
end
end
|
module Netzke
# Functionality:
# * data operations - get, post, delete, create
# * column resize and move
# * permissions
# * sorting - TODO
# * pagination - TODO
# * validation - TODO
# * properties and column configuration
#
class Grid < Base
# define connection points between client side and server side of Grid. See implementation of equally named methods below.
interface :get_data, :post_data, :delete_data
def property_widgets
[{
:columns => {
:widget_class_name => "Grid",
:data_class_name => column_manager_class_name,
:ext_config => {:title => false, :properties => false},
:active => true
}
},{
:general => {
:widget_class_name => "PreferenceGrid",
:host_widget_name => @id_name,
:default_properties => available_permissions.map{ |k| {:name => "permissions.#{k}", :value => @permissions[k.to_sym]}},
:ext_config => {:title => false}
}
}]
end
def get_records(conditions = nil)
raise ArgumentError, "No data_class_name specified for widget '#{config[:name]}'" if !config[:data_class_name]
records = config[:data_class_name].constantize.find(:all, :conditions => conditions)
output_array = []
records.each do |r|
r_array = []
self.get_columns.each do |column|
r_array << r.send(column[:name])
end
output_array << r_array
end
output_array
end
# get columns from layout manager
def get_columns
return nil if config[:layout_manager] == false # TODO: also return nil if we don't have the Layout or GridColumn class
layout = layout_manager_class.by_widget(id_name)
layout ||= column_manager_class.create_layout_for_widget(self)
layout.items_hash
end
## API
def post_data(params = {})
data = JSON.parse(params.delete(:updated_records))
if !data.empty?
if @permissions[:update]
# log.info { "!!! data: #{data.inspect}" }
klass = config[:data_class_name].constantize
updated_records = 0
data.each do |record|
if existing_record = klass.find_by_id(record['id'])
updated_records += 1 if existing_record.update_attributes(record)
else
end
end
flash :notice => "Updated #{updated_records} records"
else
flash :error => "You don't have permissions to update data"
end
end
data = JSON.parse(params.delete(:new_records))
if !data.empty?
if @permissions[:create]
# log.info { "!!! data: #{data.inspect}" }
klass = config[:data_class_name].constantize
updated_records = 0
data.each do |record|
if existing_record = klass.create(record)
updated_records += 1 # if existing_record.update_attributes(record)
else
end
end
flash :notice => "Created #{updated_records} records"
else
flash :error => "You don't have permissions to add new data"
end
end
{:success => true, :flash => @flash}
end
def get_data(params = {})
if @permissions[:read]
records = get_records(params[:filters])
# records.to_json
{:data => records, :total => records.size}
else
flash :error => "You don't have permissions to read data"
{:success => false, :flash => @flash}
end
end
def delete_data(params = {})
if @permissions[:delete]
record_ids = JSON.parse(params.delete(:records))
klass = config[:data_class_name].constantize
klass.delete(record_ids)
flash :notice => "Deleted #{record_ids.size} record(s)"
success = true
else
flash :error => "You don't have permissions to delete data"
success = false
end
{:success => success, :flash => @flash}
end
## Data for properties grid
def properties__columns__get_data(params = {})
columns_widget = aggregatee_instance(:properties__columns)
layout_id = layout_manager_class.by_widget(id_name).id
columns_widget.interface_get_data(params.merge(:filters => {:layout_id => layout_id}))
end
def properties__general__load_source(params = {})
w = aggregatee_instance(:properties__general)
w.interface_load_source(params)
end
# we pass column config at the time of instantiating the JS class
def js_config
res = super
res.merge!(:columns => get_columns || config[:columns]) # first try to get columns from DB, then from config
res.merge!(:data_class_name => config[:data_class_name])
res
end
protected
def layout_manager_class_name
"NetzkeLayout"
end
def layout_manager_class
layout_manager_class_name.constantize
rescue NameError
nil
end
def column_manager_class_name
"NetzkeGridColumn"
end
def column_manager_class
column_manager_class_name.constantize
rescue NameError
nil
end
def available_permissions
%w(read update create delete)
end
#
# JS class generation section
#
public
def js_base_class
'Ext.grid.EditorGridPanel'
end
def js_default_config
super.merge({
:store => "ds".l,
:cm => "cm".l,
:sel_model => "new Ext.grid.RowSelectionModel()".l,
:auto_scroll => true,
:click_to_edit => 2,
:track_mouse_over => true,
:bbar => "config.actions".l,
#custom configs
:auto_load_data => true
})
end
def js_before_constructor
<<-JS
this.recordConfig = [];
if (!config.columns) {
this.feedback('No columns defined for grid #{id_name}');
}
Ext.each(config.columns, function(column){this.recordConfig.push({name:column.name})}, this);
this.Row = Ext.data.Record.create(this.recordConfig);
var ds = new Ext.data.Store({
proxy: this.proxy = new Ext.data.HttpProxy({url:config.interface.getData}),
reader: new Ext.data.ArrayReader({root: "data", totalProperty: "total", successProperty: "succes", id:0}, this.Row)
});
this.cmConfig = [];
Ext.each(config.columns, function(c){
var editor = c.readOnly ? null : new Ext.form.TextField({selectOnFocus:true})
this.cmConfig.push({
header: c.label || c.name,
dataIndex: c.name,
hidden: c.hidden,
width: c.width,
editor: editor
})
}, this);
var cm = new Ext.grid.ColumnModel(this.cmConfig);
this.addEvents("refresh");
JS
end
def js_extend_properties
{
:on_widget_load => <<-JS.l,
function(){
if (this.initialConfig.autoLoadData) {
this.loadWithFeedback()
}
}
JS
:load_with_feedback => <<-JS.l,
function(){
var exceptionHandler = function(proxy, options, response, error){
// console.info(error);
if (response.status == 200 && (responseObject = Ext.decode(response.responseText)) && responseObject.flash){
this.feedback(responseObject.flash)
} else {
if (error){
this.feedback(error.message);
} else {
this.feedback(response.statusText)
}
}
}.createDelegate(this);
this.store.proxy.on('loadexception', exceptionHandler);
this.store.load({callback:function(r, options, success){
this.store.proxy.un('loadexception', exceptionHandler);
}, scope:this});
}
JS
:add => <<-JS.l,
function(){
var rowConfig = {};
Ext.each(this.initialConfig.columns, function(c){
rowConfig[c.name] = c.defaultValue || ''; // FIXME: if the user is happy with all the defaults, the record won't be 'dirty'
}, this);
var r = new this.Row(rowConfig); // TODO: add default values
r.set('id', -r.id); // to distinguish new records by negative values
this.stopEditing();
this.store.add(r);
this.store.newRecords = this.store.newRecords || []
this.store.newRecords.push(r);
// console.info(this.store.newRecords);
this.tryStartEditing(this.store.indexOf(r));
}
JS
:edit => <<-JS.l,
function(){
var row = this.getSelectionModel().getSelected();
if (row){
this.tryStartEditing(this.store.indexOf(row))
}
}
JS
# try editing the first editable (not hidden, not read-only) sell
:try_start_editing => <<-JS.l,
function(row){
if (row == null) return;
var editableColumns = this.getColumnModel().getColumnsBy(function(columnConfig, index){
return !columnConfig.hidden && !!columnConfig.editor;
});
// console.info(editableColumns);
var firstEditableColumn = editableColumns[0];
if (firstEditableColumn){
this.startEditing(row, firstEditableColumn.id);
}
}
JS
:delete => <<-JS.l,
function() {
if (this.getSelectionModel().hasSelection()){
Ext.Msg.confirm('Deleting row(s)', 'Are you sure?', function(btn){
if (btn == 'yes') {
var records = []
this.getSelectionModel().each(function(r){
records.push(r.get('id'));
}, this);
Ext.Ajax.request({
url: this.initialConfig.interface.deleteData,
params: {records: Ext.encode(records)},
success:function(r){
var m = Ext.decode(r.responseText);
this.loadWithFeedback();
this.feedback(m.flash);
},
scope:this
});
}
}, this);
}
}
JS
:submit => <<-JS.l,
function(){
var newRecords = [];
if (this.store.newRecords){
Ext.each(this.store.newRecords, function(r){
newRecords.push(r.getChanges())
r.commit() // commit the changes, so that they are not picked up by getModifiedRecords() further down
}, this);
delete this.store.newRecords;
}
var updatedRecords = [];
Ext.each(this.store.getModifiedRecords(),
function(record) {
var completeRecordData = {};
Ext.apply(completeRecordData, Ext.apply(record.getChanges(), {id:record.get('id')}));
updatedRecords.push(completeRecordData);
},
this);
if (newRecords.length > 0 || updatedRecords.length > 0) {
Ext.Ajax.request({
url:this.initialConfig.interface.postData,
params: {
updated_records: Ext.encode(updatedRecords),
new_records: Ext.encode(newRecords),
filters: this.store.baseParams.filters
},
success:function(response){
var m = Ext.decode(response.responseText);
if (m.success) {
this.loadWithFeedback();
this.store.commitChanges();
this.feedback(m.flash);
} else {
this.feedback(m.flash);
}
},
failure:function(response){
this.feedback('Bad response from server');
},
scope:this
});
}
}
JS
:refresh_click => <<-JS.l,
function() {
// console.info(this);
if (this.fireEvent('refresh', this) !== false) this.loadWithFeedback();
}
JS
}
end
def tools
[{:id => 'refresh', :on => {:click => 'refreshClick'}}]
end
def actions
[{
:text => 'Add', :handler => 'add', :disabled => @pref['permissions.create'] == false
},{
:text => 'Edit', :handler => 'edit', :disabled => @pref['permissions.update'] == false
},{
:text => 'Delete', :handler => 'delete', :disabled => @pref['permissions.delete'] == false
},{
:text => 'Apply', :handler => 'submit', :disabled => @pref['permissions.update'] == false && @pref['permissions.create'] == false
}]
end
# Uncomment to enable a menu duplicating the actions
# def js_menus
# [{:text => "config.dataClassName".l, :menu => "config.actions".l}]
# end
# include ColumnOperations
include PropertiesTool # it will load aggregation with name :properties into a modal window
end
end
confirm message
module Netzke
# Functionality:
# * data operations - get, post, delete, create
# * column resize and move
# * permissions
# * sorting - TODO
# * pagination - TODO
# * validation - TODO
# * properties and column configuration
#
class Grid < Base
# define connection points between client side and server side of Grid. See implementation of equally named methods below.
interface :get_data, :post_data, :delete_data
def property_widgets
[{
:columns => {
:widget_class_name => "Grid",
:data_class_name => column_manager_class_name,
:ext_config => {:title => false, :properties => false},
:active => true
}
},{
:general => {
:widget_class_name => "PreferenceGrid",
:host_widget_name => @id_name,
:default_properties => available_permissions.map{ |k| {:name => "permissions.#{k}", :value => @permissions[k.to_sym]}},
:ext_config => {:title => false}
}
}]
end
def get_records(conditions = nil)
raise ArgumentError, "No data_class_name specified for widget '#{config[:name]}'" if !config[:data_class_name]
records = config[:data_class_name].constantize.find(:all, :conditions => conditions)
output_array = []
records.each do |r|
r_array = []
self.get_columns.each do |column|
r_array << r.send(column[:name])
end
output_array << r_array
end
output_array
end
# get columns from layout manager
def get_columns
return nil if config[:layout_manager] == false # TODO: also return nil if we don't have the Layout or GridColumn class
layout = layout_manager_class.by_widget(id_name)
layout ||= column_manager_class.create_layout_for_widget(self)
layout.items_hash
end
## API
def post_data(params = {})
data = JSON.parse(params.delete(:updated_records))
if !data.empty?
if @permissions[:update]
# log.info { "!!! data: #{data.inspect}" }
klass = config[:data_class_name].constantize
updated_records = 0
data.each do |record|
if existing_record = klass.find_by_id(record['id'])
updated_records += 1 if existing_record.update_attributes(record)
else
end
end
flash :notice => "Updated #{updated_records} records"
else
flash :error => "You don't have permissions to update data"
end
end
data = JSON.parse(params.delete(:new_records))
if !data.empty?
if @permissions[:create]
# log.info { "!!! data: #{data.inspect}" }
klass = config[:data_class_name].constantize
updated_records = 0
data.each do |record|
if existing_record = klass.create(record)
updated_records += 1 # if existing_record.update_attributes(record)
else
end
end
flash :notice => "Created #{updated_records} records"
else
flash :error => "You don't have permissions to add new data"
end
end
{:success => true, :flash => @flash}
end
def get_data(params = {})
if @permissions[:read]
records = get_records(params[:filters])
# records.to_json
{:data => records, :total => records.size}
else
flash :error => "You don't have permissions to read data"
{:success => false, :flash => @flash}
end
end
def delete_data(params = {})
if @permissions[:delete]
record_ids = JSON.parse(params.delete(:records))
klass = config[:data_class_name].constantize
klass.delete(record_ids)
flash :notice => "Deleted #{record_ids.size} record(s)"
success = true
else
flash :error => "You don't have permissions to delete data"
success = false
end
{:success => success, :flash => @flash}
end
## Data for properties grid
def properties__columns__get_data(params = {})
columns_widget = aggregatee_instance(:properties__columns)
layout_id = layout_manager_class.by_widget(id_name).id
columns_widget.interface_get_data(params.merge(:filters => {:layout_id => layout_id}))
end
def properties__general__load_source(params = {})
w = aggregatee_instance(:properties__general)
w.interface_load_source(params)
end
# we pass column config at the time of instantiating the JS class
def js_config
res = super
res.merge!(:columns => get_columns || config[:columns]) # first try to get columns from DB, then from config
res.merge!(:data_class_name => config[:data_class_name])
res
end
protected
def layout_manager_class_name
"NetzkeLayout"
end
def layout_manager_class
layout_manager_class_name.constantize
rescue NameError
nil
end
def column_manager_class_name
"NetzkeGridColumn"
end
def column_manager_class
column_manager_class_name.constantize
rescue NameError
nil
end
def available_permissions
%w(read update create delete)
end
#
# JS class generation section
#
public
def js_base_class
'Ext.grid.EditorGridPanel'
end
def js_default_config
super.merge({
:store => "ds".l,
:cm => "cm".l,
:sel_model => "new Ext.grid.RowSelectionModel()".l,
:auto_scroll => true,
:click_to_edit => 2,
:track_mouse_over => true,
:bbar => "config.actions".l,
#custom configs
:auto_load_data => true
})
end
def js_before_constructor
<<-JS
this.recordConfig = [];
if (!config.columns) {
this.feedback('No columns defined for grid #{id_name}');
}
Ext.each(config.columns, function(column){this.recordConfig.push({name:column.name})}, this);
this.Row = Ext.data.Record.create(this.recordConfig);
var ds = new Ext.data.Store({
proxy: this.proxy = new Ext.data.HttpProxy({url:config.interface.getData}),
reader: new Ext.data.ArrayReader({root: "data", totalProperty: "total", successProperty: "succes", id:0}, this.Row)
});
this.cmConfig = [];
Ext.each(config.columns, function(c){
var editor = c.readOnly ? null : new Ext.form.TextField({selectOnFocus:true})
this.cmConfig.push({
header: c.label || c.name,
dataIndex: c.name,
hidden: c.hidden,
width: c.width,
editor: editor
})
}, this);
var cm = new Ext.grid.ColumnModel(this.cmConfig);
this.addEvents("refresh");
JS
end
def js_extend_properties
{
:on_widget_load => <<-JS.l,
function(){
if (this.initialConfig.autoLoadData) {
this.loadWithFeedback()
}
}
JS
:load_with_feedback => <<-JS.l,
function(){
var exceptionHandler = function(proxy, options, response, error){
// console.info(error);
if (response.status == 200 && (responseObject = Ext.decode(response.responseText)) && responseObject.flash){
this.feedback(responseObject.flash)
} else {
if (error){
this.feedback(error.message);
} else {
this.feedback(response.statusText)
}
}
}.createDelegate(this);
this.store.proxy.on('loadexception', exceptionHandler);
this.store.load({callback:function(r, options, success){
this.store.proxy.un('loadexception', exceptionHandler);
}, scope:this});
}
JS
:add => <<-JS.l,
function(){
var rowConfig = {};
Ext.each(this.initialConfig.columns, function(c){
rowConfig[c.name] = c.defaultValue || ''; // FIXME: if the user is happy with all the defaults, the record won't be 'dirty'
}, this);
var r = new this.Row(rowConfig); // TODO: add default values
r.set('id', -r.id); // to distinguish new records by negative values
this.stopEditing();
this.store.add(r);
this.store.newRecords = this.store.newRecords || []
this.store.newRecords.push(r);
// console.info(this.store.newRecords);
this.tryStartEditing(this.store.indexOf(r));
}
JS
:edit => <<-JS.l,
function(){
var row = this.getSelectionModel().getSelected();
if (row){
this.tryStartEditing(this.store.indexOf(row))
}
}
JS
# try editing the first editable (not hidden, not read-only) sell
:try_start_editing => <<-JS.l,
function(row){
if (row == null) return;
var editableColumns = this.getColumnModel().getColumnsBy(function(columnConfig, index){
return !columnConfig.hidden && !!columnConfig.editor;
});
// console.info(editableColumns);
var firstEditableColumn = editableColumns[0];
if (firstEditableColumn){
this.startEditing(row, firstEditableColumn.id);
}
}
JS
:delete => <<-JS.l,
function() {
if (this.getSelectionModel().hasSelection()){
Ext.Msg.confirm('Confirm', 'Are you sure?', function(btn){
if (btn == 'yes') {
var records = []
this.getSelectionModel().each(function(r){
records.push(r.get('id'));
}, this);
Ext.Ajax.request({
url: this.initialConfig.interface.deleteData,
params: {records: Ext.encode(records)},
success:function(r){
var m = Ext.decode(r.responseText);
this.loadWithFeedback();
this.feedback(m.flash);
},
scope:this
});
}
}, this);
}
}
JS
:submit => <<-JS.l,
function(){
var newRecords = [];
if (this.store.newRecords){
Ext.each(this.store.newRecords, function(r){
newRecords.push(r.getChanges())
r.commit() // commit the changes, so that they are not picked up by getModifiedRecords() further down
}, this);
delete this.store.newRecords;
}
var updatedRecords = [];
Ext.each(this.store.getModifiedRecords(),
function(record) {
var completeRecordData = {};
Ext.apply(completeRecordData, Ext.apply(record.getChanges(), {id:record.get('id')}));
updatedRecords.push(completeRecordData);
},
this);
if (newRecords.length > 0 || updatedRecords.length > 0) {
Ext.Ajax.request({
url:this.initialConfig.interface.postData,
params: {
updated_records: Ext.encode(updatedRecords),
new_records: Ext.encode(newRecords),
filters: this.store.baseParams.filters
},
success:function(response){
var m = Ext.decode(response.responseText);
if (m.success) {
this.loadWithFeedback();
this.store.commitChanges();
this.feedback(m.flash);
} else {
this.feedback(m.flash);
}
},
failure:function(response){
this.feedback('Bad response from server');
},
scope:this
});
}
}
JS
:refresh_click => <<-JS.l,
function() {
// console.info(this);
if (this.fireEvent('refresh', this) !== false) this.loadWithFeedback();
}
JS
}
end
def tools
[{:id => 'refresh', :on => {:click => 'refreshClick'}}]
end
def actions
[{
:text => 'Add', :handler => 'add', :disabled => @pref['permissions.create'] == false
},{
:text => 'Edit', :handler => 'edit', :disabled => @pref['permissions.update'] == false
},{
:text => 'Delete', :handler => 'delete', :disabled => @pref['permissions.delete'] == false
},{
:text => 'Apply', :handler => 'submit', :disabled => @pref['permissions.update'] == false && @pref['permissions.create'] == false
}]
end
# Uncomment to enable a menu duplicating the actions
# def js_menus
# [{:text => "config.dataClassName".l, :menu => "config.actions".l}]
# end
# include ColumnOperations
include PropertiesTool # it will load aggregation with name :properties into a modal window
end
end |
require 'epp-client'
require 'time'
require File.dirname(__FILE__) + '/nominet-epp/version'
require File.dirname(__FILE__) + '/nominet-epp/operations'
require File.dirname(__FILE__) + '/nominet-epp/helpers'
# Nominet EPP Module
module NominetEPP
# Front end interface Client to the NominetEPP Service
class Client
# Standard EPP Services to be used
SERVICE_URNS = EPP::Client::DEFAULT_SERVICES
# Additional Nominet specific service extensions
SERVICE_EXTENSION_URNS = %w(
urn:ietf:params:xml:ns:secDNS-1.1
http://www.nominet.org.uk/epp/xml/domain-nom-ext-1.2
http://www.nominet.org.uk/epp/xml/contact-nom-ext-1.0
http://www.nominet.org.uk/epp/xml/std-notifications-1.2
http://www.nominet.org.uk/epp/xml/std-handshake-1.0
http://www.nominet.org.uk/epp/xml/std-warning-1.1
http://www.nominet.org.uk/epp/xml/std-release-1.0)
# Create a new instance of NominetEPP::Client
#
# @param [String] tag Nominet TAG
# @param [String] passwd Nominet TAG EPP Password
# @param [String] server Nominet EPP Server address (nil forces default)
# @param [String] address_family 'AF_INET' or 'AF_INET6' or either of the
# appropriate socket constants. Will cause connections to be
# limited to this address family. Default try all addresses.
def initialize(tag, passwd, server = 'epp.nominet.org.uk', address_family = nil)
@tag, @server = tag, (server || 'epp.nominet.org.uk')
@client = EPP::Client.new(tag, passwd, server, :services => SERVICE_URNS,
:extensions => SERVICE_EXTENSION_URNS, :address_family => address_family)
end
# @see Object#inspect
def inspect
"#<#{self.class} #{@tag}@#{@server}>"
end
# Returns the last EPP::Request sent
#
# @return [EPP::Request] last sent request
def last_request
@client._last_request
end
# Returns the last EPP::Response received
#
# @return [EPP::Response] last received response
def last_response
@client._last_response
end
# Returns the last EPP message received
#
# @return [String] last EPP message
# @see #last_response
def last_message
last_response.message
end
# Returns the last Nominet failData response found
#
# @note This is presently only set by certain method calls,
# so it may not always be present.
# @return [Hash] last failData found
def last_error_info
@error_info
end
# @return [Hash] Nominet Namespaces by prefixes
def namespaces(name = nil)
@namespaces ||= begin
(SERVICE_URNS + SERVICE_EXTENSION_URNS).inject({}) do |ns, urn|
ns[namespace_name(urn)] = urn
ns
end
end
return @namespaces if name.nil?
return @namespaces[name.to_sym]
end
# @return [Hash] Nominet Schema Locations by prefix
def schemaLocations
@schemaLocations ||= begin
namespaces.inject({}) do |schema, ns|
name, urn = ns
schema[name] = "#{urn} #{schema_name(urn)}.xsd"
schema
end
end
end
include Helpers
include Operations::Check
include Operations::Create
include Operations::Delete
include Operations::Handshake
include Operations::Hello
include Operations::Info
include Operations::Poll
include Operations::Release
include Operations::Renew
include Operations::Update
private
# @param [XML::Node] node XML Node to find the value from
# @param [String] xpath XPath Expression for the value
# @return [String] node value
def node_value(node, xpath)
n = node.find(xpath, namespaces).first
n && n.content.strip
end
# @param [String] name XML Element name
# @param [Symbol] ns_prefix Namespace Prefix
# @param [Symbol] ns_name Namespace name in +namespaces+ if it doesn't match +ns_prefix+.
# @yield [node, ns] block to populate node
# @yieldparam [XML::Node] node XML Node to populate
# @yieldparam [XML::Namespace] ns XML Namespace of the node
# @return [XML::Node] newly created node
def new_node(name, ns_prefix, ns_name = ns_prefix, &block)
node = XML::Node.new(name)
node.namespaces.namespace = ns = XML::Namespace.new(node, ns_prefix.to_s, namespaces[ns_prefix])
node['xsi:schemaLocation'] = schemaLocations[ns_prefix] if schemaLocations.has_key?(ns_prefix)
case block.arity
when 0
yield
when 1
yield node
when 2
yield node, ns
end
node
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :domain namespace
# @see new_node
def domain(node_name, &block)
new_node(node_name, :domain, &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :contact namespace
# @see new_node
def contact(node_name, &block)
new_node(node_name, :contact, &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :notification namespace
# @see new_node
def notification(node_name, &block)
new_node(node_name, :n, :"std-notifications", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :release namespace
# @see new_node
def release(node_name, &block)
new_node(node_name, :r, :"std-release", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :handshake namespace
# @see new_node
def handshake(node_name, &block)
new_node(node_name, :h, :"std-handshake", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :host namespace
# @see new_node
def host(node_name, &block)
new_node(node_name, :host, &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :domain-ext namespace
# @see new_node
def domain_ext(node_name, &block)
new_node(node_name, :"domain-nom-ext", :"domain-ext", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :domain-ext namespace
# @see new_node
def contact_ext(node_name, &block)
new_node(node_name, :"contact-nom-ext", :"contact-ext", &block)
end
def namespace_name(urn)
case urn
when /\Aurn\:/
urn.split(':').last.split('-',2).first.to_sym
else
urn.split('/').last.split('-')[0...-1].join('-').to_sym
end
end
def schema_name(urn)
case urn
when /\Aurn\:/
urn.split(':').last
else
urn.split('/').last
end
end
end
end
Document Client #{namespace,schema}_name methods.
require 'epp-client'
require 'time'
require File.dirname(__FILE__) + '/nominet-epp/version'
require File.dirname(__FILE__) + '/nominet-epp/operations'
require File.dirname(__FILE__) + '/nominet-epp/helpers'
# Nominet EPP Module
module NominetEPP
# Front end interface Client to the NominetEPP Service
class Client
# Standard EPP Services to be used
SERVICE_URNS = EPP::Client::DEFAULT_SERVICES
# Additional Nominet specific service extensions
SERVICE_EXTENSION_URNS = %w(
urn:ietf:params:xml:ns:secDNS-1.1
http://www.nominet.org.uk/epp/xml/domain-nom-ext-1.2
http://www.nominet.org.uk/epp/xml/contact-nom-ext-1.0
http://www.nominet.org.uk/epp/xml/std-notifications-1.2
http://www.nominet.org.uk/epp/xml/std-handshake-1.0
http://www.nominet.org.uk/epp/xml/std-warning-1.1
http://www.nominet.org.uk/epp/xml/std-release-1.0)
# Create a new instance of NominetEPP::Client
#
# @param [String] tag Nominet TAG
# @param [String] passwd Nominet TAG EPP Password
# @param [String] server Nominet EPP Server address (nil forces default)
# @param [String] address_family 'AF_INET' or 'AF_INET6' or either of the
# appropriate socket constants. Will cause connections to be
# limited to this address family. Default try all addresses.
def initialize(tag, passwd, server = 'epp.nominet.org.uk', address_family = nil)
@tag, @server = tag, (server || 'epp.nominet.org.uk')
@client = EPP::Client.new(tag, passwd, server, :services => SERVICE_URNS,
:extensions => SERVICE_EXTENSION_URNS, :address_family => address_family)
end
# @see Object#inspect
def inspect
"#<#{self.class} #{@tag}@#{@server}>"
end
# Returns the last EPP::Request sent
#
# @return [EPP::Request] last sent request
def last_request
@client._last_request
end
# Returns the last EPP::Response received
#
# @return [EPP::Response] last received response
def last_response
@client._last_response
end
# Returns the last EPP message received
#
# @return [String] last EPP message
# @see #last_response
def last_message
last_response.message
end
# Returns the last Nominet failData response found
#
# @note This is presently only set by certain method calls,
# so it may not always be present.
# @return [Hash] last failData found
def last_error_info
@error_info
end
# @return [Hash] Nominet Namespaces by prefixes
def namespaces(name = nil)
@namespaces ||= begin
(SERVICE_URNS + SERVICE_EXTENSION_URNS).inject({}) do |ns, urn|
ns[namespace_name(urn)] = urn
ns
end
end
return @namespaces if name.nil?
return @namespaces[name.to_sym]
end
# @return [Hash] Nominet Schema Locations by prefix
def schemaLocations
@schemaLocations ||= begin
namespaces.inject({}) do |schema, ns|
name, urn = ns
schema[name] = "#{urn} #{schema_name(urn)}.xsd"
schema
end
end
end
include Helpers
include Operations::Check
include Operations::Create
include Operations::Delete
include Operations::Handshake
include Operations::Hello
include Operations::Info
include Operations::Poll
include Operations::Release
include Operations::Renew
include Operations::Update
private
# @param [XML::Node] node XML Node to find the value from
# @param [String] xpath XPath Expression for the value
# @return [String] node value
def node_value(node, xpath)
n = node.find(xpath, namespaces).first
n && n.content.strip
end
# @param [String] name XML Element name
# @param [Symbol] ns_prefix Namespace Prefix
# @param [Symbol] ns_name Namespace name in +namespaces+ if it doesn't match +ns_prefix+.
# @yield [node, ns] block to populate node
# @yieldparam [XML::Node] node XML Node to populate
# @yieldparam [XML::Namespace] ns XML Namespace of the node
# @return [XML::Node] newly created node
def new_node(name, ns_prefix, ns_name = ns_prefix, &block)
node = XML::Node.new(name)
node.namespaces.namespace = ns = XML::Namespace.new(node, ns_prefix.to_s, namespaces[ns_prefix])
node['xsi:schemaLocation'] = schemaLocations[ns_prefix] if schemaLocations.has_key?(ns_prefix)
case block.arity
when 0
yield
when 1
yield node
when 2
yield node, ns
end
node
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :domain namespace
# @see new_node
def domain(node_name, &block)
new_node(node_name, :domain, &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :contact namespace
# @see new_node
def contact(node_name, &block)
new_node(node_name, :contact, &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :notification namespace
# @see new_node
def notification(node_name, &block)
new_node(node_name, :n, :"std-notifications", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :release namespace
# @see new_node
def release(node_name, &block)
new_node(node_name, :r, :"std-release", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :handshake namespace
# @see new_node
def handshake(node_name, &block)
new_node(node_name, :h, :"std-handshake", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :host namespace
# @see new_node
def host(node_name, &block)
new_node(node_name, :host, &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :domain-ext namespace
# @see new_node
def domain_ext(node_name, &block)
new_node(node_name, :"domain-nom-ext", :"domain-ext", &block)
end
# @param [String] node_name XML Element name
# @yield [node, ns] block to populate node
# @return [XML::Node] new node in :domain-ext namespace
# @see new_node
def contact_ext(node_name, &block)
new_node(node_name, :"contact-nom-ext", :"contact-ext", &block)
end
# Returns the name of the given namespace
# @internal
# @param [String] urn Namespace URN or URI
# @return [String] the name of the given namespace
def namespace_name(urn)
case urn
when /\Aurn\:/
urn.split(':').last.split('-',2).first.to_sym
else
urn.split('/').last.split('-')[0...-1].join('-').to_sym
end
end
# Returns the name of the given schema
# @internal
# @param [String] urn Schema URN or URI
# @return [String] the name of the given schema
def schema_name(urn)
case urn
when /\Aurn\:/
urn.split(':').last
else
urn.split('/').last
end
end
end
end
|
module Nyara
class Route
REQUIRED_ATTRS = [:http_method, :scope, :prefix, :suffix, :controller, :id, :conv]
attr_reader *REQUIRED_ATTRS
attr_writer :http_method, :id
# NOTE `id` is stored in symbol for C-side conenience, but returns as string for Ruby-side goodness
def id
@id.to_s
end
# optional
attr_accessor :accept_exts, :accept_mimes, :classes
# @private
attr_accessor :path, :blk
def initialize &p
instance_eval &p if p
end
# http_method in string form
def http_method_to_s
m, _ = HTTP_METHODS.find{|k,v| v == http_method}
m
end
# nil for get / post
def http_method_override
m = http_method_to_s
if m != 'GET' and m != 'POST'
m
end
end
# enum all combinations of matching selectors
def selectors
if classes
[id, *classes, *classes.map{|k| "#{k}:#{http_method_to_s}"}, ":#{http_method_to_s}"]
else
[id, ":#{http_method_to_s}"]
end
end
# find blocks in filters that match selectors
def matched_lifecycle_callbacks filters
actions = []
selectors = selectors()
if selectors and filters
# iterate with filter's order to preserve define order
filters.each do |sel, blks|
actions.concat blks if selectors.include?(sel)
end
end
actions
end
def path_template
File.join @scope, (@path.gsub '%z', '%s')
end
# Compute prefix, suffix, conv<br>
# NOTE routes may be inherited, so late-setting controller is necessary
def compile controller, scope
@controller = controller
@scope = scope
path = scope.sub /\/?$/, @path
if path.empty?
path = '/'
end
@prefix, suffix = analyse_path path
@suffix, @conv = compile_re suffix
end
# Compute accept_exts, accept_mimes
def set_accept_exts a
@accept_exts = {}
@accept_mimes = []
if a
a.each do |e|
e = e.to_s.dup.freeze
@accept_exts[e] = true
if MIME_TYPES[e]
v1, v2 = MIME_TYPES[e].split('/')
raise "bad mime type: #{MIME_TYPES[e].inspect}" if v1.nil? or v2.nil?
@accept_mimes << [v1, v2, e]
end
end
end
@accept_mimes = nil if @accept_mimes.empty?
@accept_exts = nil if @accept_exts.empty?
end
def validate
REQUIRED_ATTRS.each do |attr|
unless instance_variable_get("@#{attr}")
raise ArgumentError, "missing #{attr}"
end
end
raise ArgumentError, "id must be symbol" unless @id.is_a?(Symbol)
end
# ---
# private
# +++
TOKEN = /%(?:[sz]|(?>\.\d+)?[dfux])/
FORWARD_SPLIT = /(?=#{TOKEN})/
# #### Returns
#
# [str_re, conv]
#
def compile_re suffix
return ['', []] unless suffix
conv = []
segs = suffix.split(FORWARD_SPLIT).flat_map do |s|
if (s =~ TOKEN) == 0
part1 = s[TOKEN]
[part1, s.slice(part1.size..-1)]
else
s
end
end
re_segs = segs.map do |s|
case s
when /\A%(?>\.\d+)?([dfux])\z/
case $1
when 'd'
conv << :to_i
'(-?\d+)'
when 'f'
conv << :to_f
# just copied from scanf
'([-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))'
when 'u'
conv << :to_i
'(\d+)'
when 'x'
conv << :hex
'(\h+)'
end
when '%s'
conv << :to_s
'([^/]+)'
when '%z'
conv << :to_s
'(.*)'
else
Regexp.quote s
end
end
["^#{re_segs.join}$", conv]
end
# Split the path into 2 parts: <br>
# a fixed prefix and a variable suffix
def analyse_path path
raise 'path must contain no new line' if path.index "\n"
raise 'path must start with /' unless path.start_with? '/'
path.split(FORWARD_SPLIT, 2)
end
end
# class methods
class << Route
def routes
@routes || []
end
# #### Param
#
# * `controller` - string or class which inherits [Nyara::Controller](Controller.html)
#
# NOTE controller may be not defined when register_controller is called
def register_controller scope, controller
unless scope.is_a?(String)
raise ArgumentError, "route prefix should be a string"
end
scope = scope.dup.freeze
(@controllers ||= []) << [scope, controller]
end
def compile
@global_path_templates = {} # "name#id" => path
mapped_controllers = {}
@routes = @controllers.flat_map do |scope, c|
if c.is_a?(String)
c = name2const c
end
name = c.controller_name || const2name(c)
raise "#{c.inspect} is not a Nyara::Controller" unless Controller > c
if mapped_controllers[c]
raise "controller #{c.inspect} was already mapped"
end
mapped_controllers[c] = true
c.nyara_compile_routes(scope).each do |e|
@global_path_templates[name + e.id] = e.path_template
end
end
@routes.sort_by! &:prefix
@routes.reverse!
mapped_controllers.each do |c, _|
c.path_templates = @global_path_templates.merge c.path_templates
end
Ext.clear_route
@routes.each do |e|
Ext.register_route e
end
end
def global_path_template id
@global_path_templates[id]
end
# remove `.klass` and `:method` from selector, and validate selector format
def canonicalize_callback_selector selector
/\A
(?<id>\#\w++(?:\-\w++)*)?
(?<klass>\.\w++(?:\-\w++)*)?
(?<method>:\w+)?
\z/x =~ selector
unless id or klass or method
raise ArgumentError, "bad selector: #{selector.inspect}", caller[1..-1]
end
id.presence or selector.sub(/:\w+\z/, &:upcase)
end
def clear
# gc mark fail if wrong order?
Ext.clear_route
@controllers = []
end
def print_routes
puts "All routes:"
Nyara::Route.routes.each do |route|
cname = route.controller.to_s
cname.gsub!("Controller", "")
cname.downcase!
print "#{cname}#{route.id}".rjust(30), " "
print route.http_method_to_s.ljust(6), " "
print route.path_template
puts
end
end
# private
def const2name c
name = c.to_s.sub /Controller$/, ''
name.gsub!(/(?<!\b)[A-Z]/){|s| "_#{s.downcase}" }
name.gsub!(/[A-Z]/, &:downcase)
name
end
def name2const name
return Module.const_get(name) if name[0] =~ /[A-Z]/
name = name.gsub /(?<=\b|_)[a-z]/, &:upcase
name.gsub! '_', ''
name << 'Controller'
Module.const_get name
end
end
end
use correct route mapping in list routes
module Nyara
class Route
REQUIRED_ATTRS = [:http_method, :scope, :prefix, :suffix, :controller, :id, :conv]
attr_reader *REQUIRED_ATTRS
attr_writer :http_method, :id
# NOTE `id` is stored in symbol for C-side conenience, but returns as string for Ruby-side goodness
def id
@id.to_s
end
# optional
attr_accessor :accept_exts, :accept_mimes, :classes
# @private
attr_accessor :path, :blk
def initialize &p
instance_eval &p if p
end
# http_method in string form
def http_method_to_s
m, _ = HTTP_METHODS.find{|k,v| v == http_method}
m
end
# nil for get / post
def http_method_override
m = http_method_to_s
if m != 'GET' and m != 'POST'
m
end
end
# enum all combinations of matching selectors
def selectors
if classes
[id, *classes, *classes.map{|k| "#{k}:#{http_method_to_s}"}, ":#{http_method_to_s}"]
else
[id, ":#{http_method_to_s}"]
end
end
# find blocks in filters that match selectors
def matched_lifecycle_callbacks filters
actions = []
selectors = selectors()
if selectors and filters
# iterate with filter's order to preserve define order
filters.each do |sel, blks|
actions.concat blks if selectors.include?(sel)
end
end
actions
end
def path_template
File.join @scope, (@path.gsub '%z', '%s')
end
# Compute prefix, suffix, conv<br>
# NOTE routes may be inherited, so late-setting controller is necessary
def compile controller, scope
@controller = controller
@scope = scope
path = scope.sub /\/?$/, @path
if path.empty?
path = '/'
end
@prefix, suffix = analyse_path path
@suffix, @conv = compile_re suffix
end
# Compute accept_exts, accept_mimes
def set_accept_exts a
@accept_exts = {}
@accept_mimes = []
if a
a.each do |e|
e = e.to_s.dup.freeze
@accept_exts[e] = true
if MIME_TYPES[e]
v1, v2 = MIME_TYPES[e].split('/')
raise "bad mime type: #{MIME_TYPES[e].inspect}" if v1.nil? or v2.nil?
@accept_mimes << [v1, v2, e]
end
end
end
@accept_mimes = nil if @accept_mimes.empty?
@accept_exts = nil if @accept_exts.empty?
end
def validate
REQUIRED_ATTRS.each do |attr|
unless instance_variable_get("@#{attr}")
raise ArgumentError, "missing #{attr}"
end
end
raise ArgumentError, "id must be symbol" unless @id.is_a?(Symbol)
end
# ---
# private
# +++
TOKEN = /%(?:[sz]|(?>\.\d+)?[dfux])/
FORWARD_SPLIT = /(?=#{TOKEN})/
# #### Returns
#
# [str_re, conv]
#
def compile_re suffix
return ['', []] unless suffix
conv = []
segs = suffix.split(FORWARD_SPLIT).flat_map do |s|
if (s =~ TOKEN) == 0
part1 = s[TOKEN]
[part1, s.slice(part1.size..-1)]
else
s
end
end
re_segs = segs.map do |s|
case s
when /\A%(?>\.\d+)?([dfux])\z/
case $1
when 'd'
conv << :to_i
'(-?\d+)'
when 'f'
conv << :to_f
# just copied from scanf
'([-+]?(?:0[xX](?:\.\h+|\h+(?:\.\h*)?)[pP][-+]\d+|\d+(?![\d.])|\d*\.\d*(?:[eE][-+]?\d+)?))'
when 'u'
conv << :to_i
'(\d+)'
when 'x'
conv << :hex
'(\h+)'
end
when '%s'
conv << :to_s
'([^/]+)'
when '%z'
conv << :to_s
'(.*)'
else
Regexp.quote s
end
end
["^#{re_segs.join}$", conv]
end
# Split the path into 2 parts: <br>
# a fixed prefix and a variable suffix
def analyse_path path
raise 'path must contain no new line' if path.index "\n"
raise 'path must start with /' unless path.start_with? '/'
path.split(FORWARD_SPLIT, 2)
end
end
# class methods
class << Route
def routes
@routes || []
end
# #### Param
#
# * `controller` - string or class which inherits [Nyara::Controller](Controller.html)
#
# NOTE controller may be not defined when register_controller is called
def register_controller scope, controller
unless scope.is_a?(String)
raise ArgumentError, "route prefix should be a string"
end
scope = scope.dup.freeze
(@controllers ||= []) << [scope, controller]
end
def compile
@global_path_templates = {} # "name#id" => path
mapped_controllers = {}
@routes = @controllers.flat_map do |scope, c|
if c.is_a?(String)
c = name2const c
end
name = c.controller_name || const2name(c)
raise "#{c.inspect} is not a Nyara::Controller" unless Controller > c
if mapped_controllers[c]
raise "controller #{c.inspect} was already mapped"
end
mapped_controllers[c] = true
c.nyara_compile_routes(scope).each do |e|
@global_path_templates[name + e.id] = e.path_template
end
end
@routes.sort_by! &:prefix
@routes.reverse!
mapped_controllers.each do |c, _|
c.path_templates = @global_path_templates.merge c.path_templates
end
Ext.clear_route
@routes.each do |e|
Ext.register_route e
end
end
def global_path_template id
@global_path_templates[id]
end
# remove `.klass` and `:method` from selector, and validate selector format
def canonicalize_callback_selector selector
/\A
(?<id>\#\w++(?:\-\w++)*)?
(?<klass>\.\w++(?:\-\w++)*)?
(?<method>:\w+)?
\z/x =~ selector
unless id or klass or method
raise ArgumentError, "bad selector: #{selector.inspect}", caller[1..-1]
end
id.presence or selector.sub(/:\w+\z/, &:upcase)
end
def clear
# gc mark fail if wrong order?
Ext.clear_route
@controllers = []
end
def print_routes
puts "All routes:"
Nyara::Route.routes.each do |route|
cname = const2name route.controller
print "#{cname}#{route.id}".rjust(30), " "
print route.http_method_to_s.ljust(6), " "
print route.path_template
puts
end
end
# private
def const2name c
name = c.to_s.sub /Controller$/, ''
name.gsub!(/(?<!\b)[A-Z]/){|s| "_#{s.downcase}" }
name.gsub!(/[A-Z]/, &:downcase)
name
end
def name2const name
return Module.const_get(name) if name[0] =~ /[A-Z]/
name = name.gsub /(?<=\b|_)[a-z]/, &:upcase
name.gsub! '_', ''
name << 'Controller'
Module.const_get name
end
end
end
|
module Oni
VERSION = '0.3.0'
end # Oni
Bumped the version.
module Oni
VERSION = '0.3.1'
end # Oni
|
begin
require "rubygems"
require "operawatir"
require "spec/runner/formatter/base_text_formatter"
require "rbconfig"
rescue LoadError
end
#require "ruby-debug"
#debugger
module OperaWatir
module Helper
class << self
attr_accessor :browser_args, :persistent_browser, :inspectr
# Creates a new browser instance with browser arguments, and
# starts inspectr if required.
def new_browser
args = OperaWatir::Helper.browser_args
new_browser = args ? OperaWatir::Browser.new(*args) : OperaWatir::Browser.new
start_inspectr
return new_browser
end
# OperaHelper wrapper to start OperaWatir.
def execute
defaults
load_dependencies
configure
end
def configure
Spec::Runner.configure do |config|
config.include(PathHelper)
config.include(BrowserHelper)
if OperaWatir::Helper.persistent_browser == false
# TODO: Why does :suite fail here? Getting nil:NilClass if
# using before/after :suite.
config.before(:all) do
@browser = OperaWatir::Helper.new_browser
end
config.after(:all) do
@browser.quit if @browser
end
else
$browser = OperaWatir::Helper.new_browser
at_exit { $browser.quit }
end
end
end
# Sets defaults to OperaHelper's configuration options.
def defaults
OperaWatir::Helper.browser_args = [] if OperaWatir::Helper.browser_args.nil?
OperaWatir::Helper.persistent_browser = false
OperaWatir::Helper.inspectr = false
files "file://" + File.expand_path(Dir.pwd + "/interactive")
end
# Sets or returns base URI path, depending on provided with
# argument.
#
# Arguments:
#
# new_path:: new path to be set.
def files (new_path = nil)
if new_path
@files = new_path
else
@files
end
end
# Inititalizes and loads OperaWatir dependencies.
def load_dependencies
load_helper
load_environmental_variables
end
# Loads helper file.
def load_helper
# Load local helper file, if it exists
local_helper = "helper.rb"
if File.exists?(local_helper)
File.expand_path(File.dirname(local_helper))
require local_helper
end
end
# Environmental variables (OPERA_PATH, OPERA_ARGS, OPERA_INSPECTR)
# will overwrite both the default configuration options for
# OperaHelper as well as the settings from the test suite-specific
# helper.rb file.
def load_environmental_variables
path = ENV["OPERA_PATH"]
args = ENV["OPERA_ARGS"]
inspectr = ENV["OPERA_INSPECTR"]
# Path
if path.nil? and File.exists?(OperaWatir::Helper.browser_args[0].to_s)
# OPERA_PATH is not set, but helper path exists
executable = OperaWatir::Helper.browser_args[0]
OperaWatir::Helper.browser_args.shift
elsif not path.nil? and File.exists?(OperaWatir::Helper.browser_args[0].to_s)
# OPERA_PATH is set, and helper path exists
executable = path
OperaWatir::Helper.browser_args.shift
elsif not path.nil?
# OPERA_PATH is set
executable = path
else
# OPERA_PATH is not set, helper path does not exist
end
# Arguments
helper_args = OperaWatir::Helper.browser_args
OperaWatir::Helper.browser_args = [executable] if executable
args = "" if args.nil?
if args.size > 0
args.split(" ").each do |arg|
OperaWatir::Helper.browser_args.push(arg)
end
else
helper_args.each do |arg|
OperaWatir::Helper.browser_args.push(arg)
end
end
# inspectr
OperaWatir::Helper.inspectr = is_true(inspectr) if is_true(inspectr)
end
# inspectr is a tool that logs program crashes and freezes.
#
# Note that the environmental variable OPERA_INSPECTR takes true
# (boolean), "true" (string), 1 (integer) and "1" (string) as
# parameters, while OperaWatir::Helper.inspectr only takes true
# (boolean).
def start_inspectr
if OperaWatir::Helper.inspectr
pid = browser.pid
# Find executable for this OS
inspectr_path = File.expand_path(File.join(File.dirname(__FILE__), "..", "utils"))
case platform
when :linux
inspectr_path += "/inspectr"
when :macosx
inspectr_path += "/inspectr"
when :windows
inspectr_path += "/inspectr.exe"
else
puts "operahelper: Unable to detect platform!"
exit
end
unless (File.exists?(inspectr_path))
puts "operahelper: Not able to locate inspectr executable!"
exit
end
# Start inspecting
Thread.new do
puts "Starting inspectr on process id #" + pid.to_s
exec(inspectr_path + " " + pid.to_s)
end
end
end
# Returns the platform type.
def platform
@platform ||= case Config::CONFIG["host_os"]
when /java/
:java
when /mswin|msys|mingw32/
:windows
when /darwin/
:macosx
when /linux/
:linux
else
RUBY_PLATFORM
end
end
# Determines if a configuration file (helper.rb) is true or false.
# The use might enter “true”, 1 or true.
def is_true(value)
if value == true or value == "true" or value == 1 or value == "1"
true
elsif value == false or value == "false" or value == 0 or value == "0"
false
end
end
end
module BrowserHelper
def browser
@browser || $browser
end
end
=begin
module PersistentBrowserHelper
def browser
$browser
end
end
=end
module PathHelper
def files (path = nil)
#OperaWatir::Helper.files
OperaWatir::Helper.files(path)
end
end
end
end
class OperaHelperFormatter < Spec::Runner::Formatter::BaseTextFormatter
def example_failed(example, counter, failure)
message = sprintf("%-52s %52s\n", example.description, colorize_failure("FAILED", failure))
output.puts(message)
output.flush
end
def example_passed(example)
message = sprintf("%-52s %52s\n", example.description, green("PASSED"))
output.puts(message)
output.flush
end
def example_pending(example, message)
message = sprintf("%-50s %55s\n", example.description, blue("PENDING"))
output.puts(message)
output.flush
end
def example_failed(example, counter, failure)
message = sprintf("%-52s %52s\n", example.description, colorize_failure("FAILED", failure))
output.puts(message)
output.flush
end
def example_passed(example)
message = sprintf("%-52s %52s\n", example.description, green("PASSED"))
output.puts(message)
output.flush
end
def example_pending(example, message)
message = sprintf("%-50s %55s\n", example.description, blue("PENDING"))
output.puts(message)
output.flush
end
def example_group_started(example_group_proxy)
message = "\n" +
"-------------------------------------------------------------------------------------------------\n" +
example_group_proxy.description + " (" + example_group_proxy.examples.size.to_s + " examples)\n" +
"-------------------------------------------------------------------------------------------------\n"
output.puts(message)
output.flush
end
end
module Spec
module Runner
class Options
def formatters
@format_options = [["OperaHelperFormatter", @output_stream]]
@formatters ||= load_formatters(@format_options, EXAMPLE_FORMATTERS)
end
end
end
end
Spec::Runner.options.colour = true
OperaWatir::Helper.execute
Fixed loading of inspectr. browser method and @browser/$browser
variable not yet set, so we need to pass pid from new_browser.
begin
require "rubygems"
require "operawatir"
require "spec/runner/formatter/base_text_formatter"
require "rbconfig"
rescue LoadError
end
#require "ruby-debug"
#debugger
module OperaWatir
module Helper
class << self
attr_accessor :browser_args, :persistent_browser, :inspectr
# Creates a new browser instance with browser arguments, and
# starts inspectr if required.
def new_browser
args = OperaWatir::Helper.browser_args
new_browser = args ? OperaWatir::Browser.new(*args) : OperaWatir::Browser.new
start_inspectr(new_browser.pid) if OperaWatir::Helper.inspectr
return new_browser
end
# OperaHelper wrapper to start OperaWatir.
def execute
defaults
load_dependencies
configure
end
def configure
Spec::Runner.configure do |config|
config.include(PathHelper)
config.include(BrowserHelper)
if OperaWatir::Helper.persistent_browser == false
# TODO: Why does :suite fail here? Getting nil:NilClass if
# using before/after :suite.
config.before(:all) do
@browser = OperaWatir::Helper.new_browser
end
config.after(:all) do
@browser.quit if @browser
end
else
$browser = OperaWatir::Helper.new_browser
at_exit { $browser.quit }
end
end
end
# Sets defaults to OperaHelper's configuration options.
def defaults
OperaWatir::Helper.browser_args = [] if OperaWatir::Helper.browser_args.nil?
OperaWatir::Helper.persistent_browser = false
OperaWatir::Helper.inspectr = false
files "file://" + File.expand_path(Dir.pwd + "/interactive")
end
# Sets or returns base URI path, depending on provided with
# argument.
#
# Arguments:
#
# new_path:: new path to be set.
def files (new_path = nil)
if new_path
@files = new_path
else
@files
end
end
# Inititalizes and loads OperaWatir dependencies.
def load_dependencies
load_helper
load_environmental_variables
end
# Loads helper file.
def load_helper
# Load local helper file, if it exists
local_helper = "helper.rb"
if File.exists?(local_helper)
File.expand_path(File.dirname(local_helper))
require local_helper
end
end
# Environmental variables (OPERA_PATH, OPERA_ARGS, OPERA_INSPECTR)
# will overwrite both the default configuration options for
# OperaHelper as well as the settings from the test suite-specific
# helper.rb file.
def load_environmental_variables
path = ENV["OPERA_PATH"]
args = ENV["OPERA_ARGS"]
inspectr = ENV["OPERA_INSPECTR"]
# Path
if path.nil? and File.exists?(OperaWatir::Helper.browser_args[0].to_s)
# OPERA_PATH is not set, but helper path exists
executable = OperaWatir::Helper.browser_args[0]
OperaWatir::Helper.browser_args.shift
elsif not path.nil? and File.exists?(OperaWatir::Helper.browser_args[0].to_s)
# OPERA_PATH is set, and helper path exists
executable = path
OperaWatir::Helper.browser_args.shift
elsif not path.nil?
# OPERA_PATH is set
executable = path
else
# OPERA_PATH is not set, helper path does not exist
end
# Arguments
helper_args = OperaWatir::Helper.browser_args
OperaWatir::Helper.browser_args = [executable] if executable
args = "" if args.nil?
if args.size > 0
args.split(" ").each do |arg|
OperaWatir::Helper.browser_args.push(arg)
end
else
helper_args.each do |arg|
OperaWatir::Helper.browser_args.push(arg)
end
end
# inspectr
OperaWatir::Helper.inspectr = is_true(inspectr) if is_true(inspectr)
end
# inspectr is a tool that logs program crashes and freezes.
#
# Note that the environmental variable OPERA_INSPECTR takes true
# (boolean), "true" (string), 1 (integer) and "1" (string) as
# parameters, while OperaWatir::Helper.inspectr only takes true
# (boolean).
def start_inspectr (pid)
if OperaWatir::Helper.inspectr
# Find executable for this OS
inspectr_path = File.expand_path(File.join(File.dirname(__FILE__), "..", "utils"))
case platform
when :linux
inspectr_path += "/inspectr"
when :macosx
inspectr_path += "/inspectr"
when :windows
inspectr_path += "/inspectr.exe"
else
puts "operahelper: Unable to detect platform!"
exit
end
unless (File.exists?(inspectr_path))
puts "operahelper: Not able to locate inspectr executable!"
exit
end
# Start inspecting
Thread.new do
puts "Starting inspectr on process id #" + pid.to_s
exec(inspectr_path + " " + pid.to_s)
end
end
end
# Returns the platform type.
def platform
@platform ||= case Config::CONFIG["host_os"]
when /java/
:java
when /mswin|msys|mingw32/
:windows
when /darwin/
:macosx
when /linux/
:linux
else
RUBY_PLATFORM
end
end
# Determines if a configuration file (helper.rb) is true or false.
# The use might enter “true”, 1 or true.
def is_true(value)
if value == true or value == "true" or value == 1 or value == "1"
true
elsif value == false or value == "false" or value == 0 or value == "0"
false
end
end
end
module BrowserHelper
def browser
@browser || $browser
end
end
=begin
module PersistentBrowserHelper
def browser
$browser
end
end
=end
module PathHelper
def files (path = nil)
#OperaWatir::Helper.files
OperaWatir::Helper.files(path)
end
end
end
end
class OperaHelperFormatter < Spec::Runner::Formatter::BaseTextFormatter
def example_failed(example, counter, failure)
message = sprintf("%-52s %52s\n", example.description, colorize_failure("FAILED", failure))
output.puts(message)
output.flush
end
def example_passed(example)
message = sprintf("%-52s %52s\n", example.description, green("PASSED"))
output.puts(message)
output.flush
end
def example_pending(example, message)
message = sprintf("%-50s %55s\n", example.description, blue("PENDING"))
output.puts(message)
output.flush
end
def example_failed(example, counter, failure)
message = sprintf("%-52s %52s\n", example.description, colorize_failure("FAILED", failure))
output.puts(message)
output.flush
end
def example_passed(example)
message = sprintf("%-52s %52s\n", example.description, green("PASSED"))
output.puts(message)
output.flush
end
def example_pending(example, message)
message = sprintf("%-50s %55s\n", example.description, blue("PENDING"))
output.puts(message)
output.flush
end
def example_group_started(example_group_proxy)
message = "\n" +
"-------------------------------------------------------------------------------------------------\n" +
example_group_proxy.description + " (" + example_group_proxy.examples.size.to_s + " examples)\n" +
"-------------------------------------------------------------------------------------------------\n"
output.puts(message)
output.flush
end
end
module Spec
module Runner
class Options
def formatters
@format_options = [["OperaHelperFormatter", @output_stream]]
@formatters ||= load_formatters(@format_options, EXAMPLE_FORMATTERS)
end
end
end
end
Spec::Runner.options.colour = true
OperaWatir::Helper.execute
|
# -*- coding: utf-8 -*-
require 'nokogiri'
require 'oauth2'
require_relative 'data'
class OrcidClaim
@queue = :orcid
def initialize oauth, work
@oauth = oauth
@work = work
end
def self.perform oauth, work
OrcidClaim.new(oauth, work).perform
end
def perform
oauth_expired = false
begin
puts to_xml
# Need to check both since @oauth may or may not have been serialized back and forth from JSON.
uid = @oauth[:uid] || @oauth['uid']
logger.info "Claiming #{@work} for user #{uid}"
opts = {:site => settings.orcid[:site]}
client = OAuth2::Client.new(settings.orcid[:client_id], settings.orcid[:client_secret], opts)
token = OAuth2::AccessToken.new(client, @oauth['credentials']['token'])
headers = {'Accept' => 'application/json'}
response = token.post("https://api.orcid.org/#{uid}/orcid-works") do |post|
post.headers['Content-Type'] = 'application/orcid+xml'
post.body = to_xml
end
oauth_expired = !response.success?
rescue StandardError => e
puts e
end
!oauth_expired
end
def has_path? hsh, path
loc = hsh
path.each do |path_item|
if loc[path_item]
loc = loc[path_item]
else
loc = nil
break
end
end
loc != nil
end
def orcid_work_type internal_work_type
case internal_work_type
when 'journal_article' then 'journal-article'
when 'conference_paper' then 'conference-proceedings'
else ''
end
end
def pad_date_item item
result = nil
if item
begin
item_int = item.strip.to_i
if item_int >= 0 && item_int <= 11
item_str = item_int.to_s
if item_str.length < 2
result = "0" + item_str
elsif item_str.length == 2
result = item_str
end
end
rescue StandardError => e
# Ignore type conversion errors
end
end
result
end
def insert_id xml, type, value
xml.send(:'work-external-identifier') {
xml.send(:'work-external-identifier-type', type)
xml.send(:'work-external-identifier-id', value)
}
end
def insert_ids xml
xml.send(:'work-external-identifiers') {
insert_id(xml, 'doi', @work['doi'])
insert_id(xml, 'isbn', @work['proceedings']['isbn']) if has_path?(@work, ['proceedings', 'isbn'])
insert_id(xml, 'issn', @work['journal']['issn']) if has_path?(@work, ['journal', 'issn'])
}
end
def insert_pub_date xml
month_str = pad_date_item(@work['published']['month'])
day_str = pad_date_item(@work['published']['day'])
if @work['published']
xml.send(:'publication-date') {
xml.year(@work['published']['year'].to_i.to_s)
xml.month(month_str) if month_str
xml.day(day_str) if day_str
}
end
end
def insert_type xml
xml.send(:'work-type', orcid_work_type(@work['type']))
end
def insert_titles xml
subtitle = case @work['type']
when 'journal_article'
if has_path?(@work, ['journal', 'full_title'])
@work['journal']['full_title']
else
nil
end
when 'conference_paper'
if has_path?(@work, ['proceedings', 'title'])
@work['proceedings']['title']
else
nil
end
else
nil
end
if subtitle || @work['title']
xml.send(:'work-title') {
xml.title(@work['title']) if @work['title']
xml.subtitle(subtitle) if subtitle
}
end
end
def insert_contributors xml
if @work['contributors'] && !@work['contributors'].count.zero?
xml.send(:'work-contributors') {
@work['contributors'].each do |contributor|
full_name = ""
full_name = contributor['given_name'] if contributor['given_name']
full_name += " " + contributor['surname'] if contributor['surname']
if !full_name.empty?
xml.contributor {
xml.send(:'credit-name', full_name)
# TODO Insert contributor roles and sequence once available
# in 'dois' mongo collection.
#xml.send(:'contributor-attributes') {
# xml.send(:'contributor-role', 'author')
#}
}
end
end
}
end
end
def insert_citation xml
conn = Faraday.new
response = conn.get "http://data.crossref.org/#{@work['doi']}", {}, {
'Accept' => 'application/x-bibtex'
}
if response.status == 200
xml.send(:'work-citation') {
xml.send(:'work-citation-type', 'bibtex')
xml.citation {
xml.cdata(response.body)
}
}
end
end
def to_xml
root_attributes = {
:'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
:'xsi:schemaLocation' => 'http://www.orcid.org/ns/orcid http://orcid.github.com/ORCID-Parent/schemas/orcid-message/1.0.8/orcid-message-1.0.8.xsd',
:'xmlns' => 'http://www.orcid.org/ns/orcid'
}
Nokogiri::XML::Builder.new do |xml|
xml.send(:'orcid-message', root_attributes) {
xml.send(:'message-version', '1.0.8')
xml.send(:'orcid-profile') {
xml.send(:'orcid-activities') {
xml.send(:'orcid-works') {
xml.send(:'orcid-work') {
insert_titles(xml)
insert_citation(xml)
insert_type(xml)
insert_pub_date(xml)
insert_ids(xml)
insert_contributors(xml)
}
}
}
}
}
end.to_xml
end
end
Changed logging #6
# -*- coding: utf-8 -*-
require 'nokogiri'
require 'oauth2'
require_relative 'data'
class OrcidClaim
@queue = :orcid
def initialize oauth, work
@oauth = oauth
@work = work
end
def self.perform oauth, work
OrcidClaim.new(oauth, work).perform
end
def perform
oauth_expired = false
logger.info "Claiming #{@work} for user #{uid}"
begin
puts to_xml
# Need to check both since @oauth may or may not have been serialized back and forth from JSON.
uid = @oauth[:uid] || @oauth['uid']
opts = {:site => settings.orcid[:site]}
client = OAuth2::Client.new(settings.orcid[:client_id], settings.orcid[:client_secret], opts)
token = OAuth2::AccessToken.new(client, @oauth['credentials']['token'])
headers = {'Accept' => 'application/json'}
response = token.post("https://api.orcid.org/#{uid}/orcid-works") do |post|
post.headers['Content-Type'] = 'application/orcid+xml'
post.body = to_xml
end
oauth_expired = !response.success?
rescue StandardError => e
puts e
end
!oauth_expired
end
def has_path? hsh, path
loc = hsh
path.each do |path_item|
if loc[path_item]
loc = loc[path_item]
else
loc = nil
break
end
end
loc != nil
end
def orcid_work_type internal_work_type
case internal_work_type
when 'journal_article' then 'journal-article'
when 'conference_paper' then 'conference-proceedings'
else ''
end
end
def pad_date_item item
result = nil
if item
begin
item_int = item.strip.to_i
if item_int >= 0 && item_int <= 11
item_str = item_int.to_s
if item_str.length < 2
result = "0" + item_str
elsif item_str.length == 2
result = item_str
end
end
rescue StandardError => e
# Ignore type conversion errors
end
end
result
end
def insert_id xml, type, value
xml.send(:'work-external-identifier') {
xml.send(:'work-external-identifier-type', type)
xml.send(:'work-external-identifier-id', value)
}
end
def insert_ids xml
xml.send(:'work-external-identifiers') {
insert_id(xml, 'doi', @work['doi'])
insert_id(xml, 'isbn', @work['proceedings']['isbn']) if has_path?(@work, ['proceedings', 'isbn'])
insert_id(xml, 'issn', @work['journal']['issn']) if has_path?(@work, ['journal', 'issn'])
}
end
def insert_pub_date xml
month_str = pad_date_item(@work['published']['month'])
day_str = pad_date_item(@work['published']['day'])
if @work['published']
xml.send(:'publication-date') {
xml.year(@work['published']['year'].to_i.to_s)
xml.month(month_str) if month_str
xml.day(day_str) if day_str
}
end
end
def insert_type xml
xml.send(:'work-type', orcid_work_type(@work['type']))
end
def insert_titles xml
subtitle = case @work['type']
when 'journal_article'
if has_path?(@work, ['journal', 'full_title'])
@work['journal']['full_title']
else
nil
end
when 'conference_paper'
if has_path?(@work, ['proceedings', 'title'])
@work['proceedings']['title']
else
nil
end
else
nil
end
if subtitle || @work['title']
xml.send(:'work-title') {
xml.title(@work['title']) if @work['title']
xml.subtitle(subtitle) if subtitle
}
end
end
def insert_contributors xml
if @work['contributors'] && !@work['contributors'].count.zero?
xml.send(:'work-contributors') {
@work['contributors'].each do |contributor|
full_name = ""
full_name = contributor['given_name'] if contributor['given_name']
full_name += " " + contributor['surname'] if contributor['surname']
if !full_name.empty?
xml.contributor {
xml.send(:'credit-name', full_name)
# TODO Insert contributor roles and sequence once available
# in 'dois' mongo collection.
#xml.send(:'contributor-attributes') {
# xml.send(:'contributor-role', 'author')
#}
}
end
end
}
end
end
def insert_citation xml
conn = Faraday.new
response = conn.get "http://data.crossref.org/#{@work['doi']}", {}, {
'Accept' => 'application/x-bibtex'
}
if response.status == 200
xml.send(:'work-citation') {
xml.send(:'work-citation-type', 'bibtex')
xml.citation {
xml.cdata(response.body)
}
}
end
end
def to_xml
root_attributes = {
:'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
:'xsi:schemaLocation' => 'http://www.orcid.org/ns/orcid http://orcid.github.com/ORCID-Parent/schemas/orcid-message/1.0.8/orcid-message-1.0.8.xsd',
:'xmlns' => 'http://www.orcid.org/ns/orcid'
}
Nokogiri::XML::Builder.new do |xml|
xml.send(:'orcid-message', root_attributes) {
xml.send(:'message-version', '1.0.8')
xml.send(:'orcid-profile') {
xml.send(:'orcid-activities') {
xml.send(:'orcid-works') {
xml.send(:'orcid-work') {
insert_titles(xml)
insert_citation(xml)
insert_type(xml)
insert_pub_date(xml)
insert_ids(xml)
insert_contributors(xml)
}
}
}
}
}
end.to_xml
end
end
|
require 'yaml' #load config files
require 'net/http' # access the call to the API server
module PdfIT
class PDF
attr_accessor :api_key
attr_accessor :api_url
attr_accessor :htmldata
attr_accessor :baseurl
attr_accessor :errors
def create (options ={})
begin
#clean and set up the URL for the call to the API
url = self.api_url if self.api_url.present?
url ||= options[:url]
raise Exceptions::MissingURL.new("Missing Server URL Exception.") if url.nil? || url.blank?
url = URI.parse(url) if url.present?
htmldata = options[:html]
raise Exceptions::MissingHtml.new("Missing HTML data Exception.") if htmldata.nil? || htmldata.blank?
api_key = options[:api_key]
raise Exceptions::MissingApiKey.new("Missing API Key Exception.") if api_key.nil? || api_key.blank?
base_url = options[:base_url]
raise Exceptions::MissingBaseUrl.new("Missing Base URL Exception.") if base_url.nil? || base_url.blank?
post_args = {
'htmldata' => htmldata,
'baseurl' => base_url,
'apikey' => api_key
}
resp = Net::HTTP.post_form(url, post_args)
pdf_name = 'filename'
if resp.code == "200"
resp.body
elsif resp.code == "401"
raise Exceptions::Unauthorized.new("Unauthorized Exception.")
else
raise Exceptions::General.new("General Fault Exception.")
end
rescue Exception => exception
raise exception
end
end
private
def initialize(options = {})
if options.is_a?(String)
@options = YAML.load_file("config/#{options}")
else
@options = options
end
@options.symbolize_keys!
self.api_key = @options[:api_key]
self.api_url = @options[:api_url]
end
end
end
Fixed a miss for loading the default API KEY from the config file.
require 'yaml' #load config files
require 'net/http' # access the call to the API server
module PdfIT
class PDF
attr_accessor :api_key
attr_accessor :api_url
attr_accessor :htmldata
attr_accessor :baseurl
attr_accessor :errors
def create (options ={})
begin
#clean and set up the URL for the call to the API
url = self.api_url if self.api_url.present?
url ||= options[:url]
raise Exceptions::MissingURL.new("Missing Server URL Exception.") if url.nil? || url.blank?
url = URI.parse(url) if url.present?
htmldata = options[:html]
raise Exceptions::MissingHtml.new("Missing HTML data Exception.") if htmldata.nil? || htmldata.blank?
api_key = self.api_key if self.api_key.present?
api_key ||= options[:api_key]
raise Exceptions::MissingApiKey.new("Missing API Key Exception.") if api_key.nil? || api_key.blank?
base_url = options[:base_url]
raise Exceptions::MissingBaseUrl.new("Missing Base URL Exception.") if base_url.nil? || base_url.blank?
post_args = {
'htmldata' => htmldata,
'baseurl' => base_url,
'apikey' => api_key
}
resp = Net::HTTP.post_form(url, post_args)
pdf_name = 'filename'
if resp.code == "200"
resp.body
elsif resp.code == "401"
raise Exceptions::Unauthorized.new("Unauthorized Exception.")
else
raise Exceptions::General.new("General Fault Exception.")
end
rescue Exception => exception
raise exception
end
end
private
def initialize(options = {})
if options.is_a?(String)
@options = YAML.load_file("config/#{options}")
else
@options = options
end
@options.symbolize_keys!
self.api_key = @options[:api_key]
self.api_url = @options[:api_url]
end
end
end
|
module PgSync
class Sync
include Utils
def perform(options)
args = options.arguments
opts = options.to_hash
@options = opts
# only resolve commands from config, not CLI arguments
[:to, :from].each do |opt|
opts[opt] ||= resolve_source(config[opt.to_s])
end
# merge other config
[:to_safe, :exclude, :schemas].each do |opt|
opts[opt] ||= config[opt.to_s]
end
# TODO remove deprecations in 0.6.0
map_deprecations(args, opts)
# start
start_time = Time.now
if args.size > 2
raise Error, "Usage:\n pgsync [options]"
end
raise Error, "No source" unless source.exists?
raise Error, "No destination" unless destination.exists?
unless opts[:to_safe] || destination.local?
raise Error, "Danger! Add `to_safe: true` to `.pgsync.yml` if the destination is not localhost or 127.0.0.1"
end
print_description("From", source)
print_description("To", destination)
tables = TableResolver.new(args, opts, source, config).tables
# TODO uncomment for 0.6.0
# if opts[:in_batches] && tables.size > 1
# raise Error, "Cannot use --in-batches with multiple tables"
# end
confirm_tables_exist(source, tables, "source")
if opts[:list]
confirm_tables_exist(destination, tables, "destination")
list_items =
if args[0] == "groups"
(config["groups"] || {}).keys
else
tables.map { |t| t[:table] }
end
pretty_list list_items
else
if opts[:schema_first] || opts[:schema_only]
if opts[:preserve]
raise Error, "Cannot use --preserve with --schema-first or --schema-only"
end
log "* Dumping schema"
schema_tables = tables if !opts[:all_schemas] || opts[:tables] || opts[:groups] || args[0] || opts[:exclude]
SchemaSync.new(source: source, destination: destination, tables: schema_tables).perform
end
unless opts[:schema_only]
confirm_tables_exist(destination, tables, "destination")
table_syncs =
tables.map do |table|
TableSync.new(source: source, destination: destination, config: config, table: table[:table], opts: opts.merge(table[:opts]))
end
# show notes before we start
table_syncs.each do |ts|
ts.notes.each do |note|
warning "#{ts.table.sub("#{first_schema}.", "")}: #{note}"
end
end
# don't sync tables with no shared fields
# we show a warning message above
table_syncs.reject! { |ts| ts.shared_fields.empty? }
in_parallel(table_syncs) do |table_sync|
table_sync.sync
end
end
log_completed(start_time)
end
end
def first_schema
@first_schema ||= source.search_path.find { |sp| sp != "pg_catalog" }
end
def confirm_tables_exist(data_source, tables, description)
tables.map { |t| t[:table] }.each do |table|
unless data_source.table_exists?(table)
raise Error, "Table does not exist in #{description}: #{table}"
end
end
end
def map_deprecations(args, opts)
command = args[0]
case command
when "schema"
args.shift
opts[:schema_only] = true
deprecated "Use `psync --schema-only` instead"
when "tables"
args.shift
opts[:tables] = args.shift
deprecated "Use `pgsync #{opts[:tables]}` instead"
when "groups"
args.shift
opts[:groups] = args.shift
deprecated "Use `pgsync #{opts[:groups]}` instead"
end
if opts[:where]
opts[:sql] ||= String.new
opts[:sql] << " WHERE #{opts[:where]}"
deprecated "Use `\"WHERE #{opts[:where]}\"` instead"
end
if opts[:limit]
opts[:sql] ||= String.new
opts[:sql] << " LIMIT #{opts[:limit]}"
deprecated "Use `\"LIMIT #{opts[:limit]}\"` instead"
end
end
def config
@config ||= begin
file = config_file
if file
begin
YAML.load_file(file) || {}
rescue Psych::SyntaxError => e
raise Error, e.message
end
else
{}
end
end
end
def print_description(prefix, source)
location = " on #{source.host}:#{source.port}" if source.host
log "#{prefix}: #{source.dbname}#{location}"
end
def in_parallel(table_syncs, &block)
spinners = TTY::Spinner::Multi.new(format: :dots, output: output)
item_spinners = {}
start = lambda do |item, i|
message = ":spinner #{display_item(item)}"
spinner = spinners.register(message)
if @options[:in_batches]
# log instead of spin for non-tty
log message.sub(":spinner", "⠋")
else
spinner.auto_spin
end
item_spinners[item] = spinner
end
failed_tables = []
finish = lambda do |item, i, result|
spinner = item_spinners[item]
result_message = display_result(result)
if result[:status] == "success"
spinner.success(result_message)
else
# TODO add option to fail fast
spinner.error(result_message)
failed_tables << item.table.sub("#{first_schema}.", "")
fail_sync(failed_tables) if @options[:fail_fast]
end
unless spinner.send(:tty?)
status = result[:status] == "success" ? "✔" : "✖"
log [status, display_item(item), result_message].join(" ")
end
end
options = {start: start, finish: finish}
jobs = @options[:jobs]
if @options[:debug] || @options[:in_batches] || @options[:defer_constraints]
warning "--jobs ignored" if jobs
jobs = 0
end
if windows?
options[:in_threads] = jobs || 4
else
options[:in_processes] = jobs if jobs
end
maybe_defer_constraints do
# could try to use `raise Parallel::Kill` to fail faster with --fail-fast
# see `fast_faster` branch
# however, need to make sure connections are cleaned up properly
Parallel.each(table_syncs, **options) do |table_sync|
# must reconnect for new thread or process
# TODO only reconnect first time
unless options[:in_processes] == 0
source.reconnect
destination.reconnect
end
# TODO warn if there are non-deferrable constraints on the table
yield table_sync
end
end
fail_sync(failed_tables) if failed_tables.any?
end
def maybe_defer_constraints
if @options[:defer_constraints]
destination.transaction do
destination.execute("SET CONSTRAINTS ALL DEFERRED")
# create a transaction on the source
# to ensure we get a consistent snapshot
source.transaction do
yield
end
end
else
yield
end
end
def fail_sync(failed_tables)
raise Error, "Sync failed for #{failed_tables.size} table#{failed_tables.size == 1 ? nil : "s"}: #{failed_tables.join(", ")}"
end
def display_item(item)
messages = []
messages << item.table.sub("#{first_schema}.", "")
messages << item.opts[:sql] if item.opts[:sql]
messages.join(" ")
end
def display_result(result)
messages = []
messages << "- #{result[:time]}s" if result[:time]
messages << "(#{result[:message].lines.first.to_s.strip})" if result[:message]
messages.join(" ")
end
def pretty_list(items)
items.each do |item|
log item
end
end
def log_completed(start_time)
time = Time.now - start_time
message = "Completed in #{time.round(1)}s"
log colorize(message, :green)
end
def windows?
Gem.win_platform?
end
def source
@source ||= data_source(@options[:from])
end
def destination
@destination ||= data_source(@options[:to])
end
def data_source(url)
ds = DataSource.new(url)
ObjectSpace.define_finalizer(self, self.class.finalize(ds))
ds
end
def resolve_source(source)
if source
source = source.dup
source.gsub!(/\$\([^)]+\)/) do |m|
command = m[2..-2]
result = `#{command}`.chomp
unless $?.success?
raise Error, "Command exited with non-zero status:\n#{command}"
end
result
end
end
source
end
def self.finalize(ds)
# must use proc instead of stabby lambda
proc { ds.close }
end
end
end
Added todo [skip ci]
module PgSync
class Sync
include Utils
def perform(options)
args = options.arguments
opts = options.to_hash
@options = opts
# only resolve commands from config, not CLI arguments
[:to, :from].each do |opt|
opts[opt] ||= resolve_source(config[opt.to_s])
end
# merge other config
[:to_safe, :exclude, :schemas].each do |opt|
opts[opt] ||= config[opt.to_s]
end
# TODO remove deprecations in 0.6.0
map_deprecations(args, opts)
# start
start_time = Time.now
if args.size > 2
raise Error, "Usage:\n pgsync [options]"
end
raise Error, "No source" unless source.exists?
raise Error, "No destination" unless destination.exists?
unless opts[:to_safe] || destination.local?
raise Error, "Danger! Add `to_safe: true` to `.pgsync.yml` if the destination is not localhost or 127.0.0.1"
end
print_description("From", source)
print_description("To", destination)
tables = TableResolver.new(args, opts, source, config).tables
# TODO uncomment for 0.6.0
# if opts[:in_batches] && tables.size > 1
# raise Error, "Cannot use --in-batches with multiple tables"
# end
confirm_tables_exist(source, tables, "source")
if opts[:list]
confirm_tables_exist(destination, tables, "destination")
list_items =
if args[0] == "groups"
(config["groups"] || {}).keys
else
tables.map { |t| t[:table] }
end
pretty_list list_items
else
if opts[:schema_first] || opts[:schema_only]
if opts[:preserve]
raise Error, "Cannot use --preserve with --schema-first or --schema-only"
end
log "* Dumping schema"
schema_tables = tables if !opts[:all_schemas] || opts[:tables] || opts[:groups] || args[0] || opts[:exclude]
SchemaSync.new(source: source, destination: destination, tables: schema_tables).perform
end
unless opts[:schema_only]
confirm_tables_exist(destination, tables, "destination")
# TODO query columns, sequences, primary keys, etc
# for all tables at once and pass on initialization
table_syncs =
tables.map do |table|
TableSync.new(source: source, destination: destination, config: config, table: table[:table], opts: opts.merge(table[:opts]))
end
# show notes before we start
table_syncs.each do |ts|
ts.notes.each do |note|
warning "#{ts.table.sub("#{first_schema}.", "")}: #{note}"
end
end
# don't sync tables with no shared fields
# we show a warning message above
table_syncs.reject! { |ts| ts.shared_fields.empty? }
in_parallel(table_syncs) do |table_sync|
table_sync.sync
end
end
log_completed(start_time)
end
end
def first_schema
@first_schema ||= source.search_path.find { |sp| sp != "pg_catalog" }
end
def confirm_tables_exist(data_source, tables, description)
tables.map { |t| t[:table] }.each do |table|
unless data_source.table_exists?(table)
raise Error, "Table does not exist in #{description}: #{table}"
end
end
end
def map_deprecations(args, opts)
command = args[0]
case command
when "schema"
args.shift
opts[:schema_only] = true
deprecated "Use `psync --schema-only` instead"
when "tables"
args.shift
opts[:tables] = args.shift
deprecated "Use `pgsync #{opts[:tables]}` instead"
when "groups"
args.shift
opts[:groups] = args.shift
deprecated "Use `pgsync #{opts[:groups]}` instead"
end
if opts[:where]
opts[:sql] ||= String.new
opts[:sql] << " WHERE #{opts[:where]}"
deprecated "Use `\"WHERE #{opts[:where]}\"` instead"
end
if opts[:limit]
opts[:sql] ||= String.new
opts[:sql] << " LIMIT #{opts[:limit]}"
deprecated "Use `\"LIMIT #{opts[:limit]}\"` instead"
end
end
def config
@config ||= begin
file = config_file
if file
begin
YAML.load_file(file) || {}
rescue Psych::SyntaxError => e
raise Error, e.message
end
else
{}
end
end
end
def print_description(prefix, source)
location = " on #{source.host}:#{source.port}" if source.host
log "#{prefix}: #{source.dbname}#{location}"
end
def in_parallel(table_syncs, &block)
spinners = TTY::Spinner::Multi.new(format: :dots, output: output)
item_spinners = {}
start = lambda do |item, i|
message = ":spinner #{display_item(item)}"
spinner = spinners.register(message)
if @options[:in_batches]
# log instead of spin for non-tty
log message.sub(":spinner", "⠋")
else
spinner.auto_spin
end
item_spinners[item] = spinner
end
failed_tables = []
finish = lambda do |item, i, result|
spinner = item_spinners[item]
result_message = display_result(result)
if result[:status] == "success"
spinner.success(result_message)
else
# TODO add option to fail fast
spinner.error(result_message)
failed_tables << item.table.sub("#{first_schema}.", "")
fail_sync(failed_tables) if @options[:fail_fast]
end
unless spinner.send(:tty?)
status = result[:status] == "success" ? "✔" : "✖"
log [status, display_item(item), result_message].join(" ")
end
end
options = {start: start, finish: finish}
jobs = @options[:jobs]
if @options[:debug] || @options[:in_batches] || @options[:defer_constraints]
warning "--jobs ignored" if jobs
jobs = 0
end
if windows?
options[:in_threads] = jobs || 4
else
options[:in_processes] = jobs if jobs
end
maybe_defer_constraints do
# could try to use `raise Parallel::Kill` to fail faster with --fail-fast
# see `fast_faster` branch
# however, need to make sure connections are cleaned up properly
Parallel.each(table_syncs, **options) do |table_sync|
# must reconnect for new thread or process
# TODO only reconnect first time
unless options[:in_processes] == 0
source.reconnect
destination.reconnect
end
# TODO warn if there are non-deferrable constraints on the table
yield table_sync
end
end
fail_sync(failed_tables) if failed_tables.any?
end
def maybe_defer_constraints
if @options[:defer_constraints]
destination.transaction do
destination.execute("SET CONSTRAINTS ALL DEFERRED")
# create a transaction on the source
# to ensure we get a consistent snapshot
source.transaction do
yield
end
end
else
yield
end
end
def fail_sync(failed_tables)
raise Error, "Sync failed for #{failed_tables.size} table#{failed_tables.size == 1 ? nil : "s"}: #{failed_tables.join(", ")}"
end
def display_item(item)
messages = []
messages << item.table.sub("#{first_schema}.", "")
messages << item.opts[:sql] if item.opts[:sql]
messages.join(" ")
end
def display_result(result)
messages = []
messages << "- #{result[:time]}s" if result[:time]
messages << "(#{result[:message].lines.first.to_s.strip})" if result[:message]
messages.join(" ")
end
def pretty_list(items)
items.each do |item|
log item
end
end
def log_completed(start_time)
time = Time.now - start_time
message = "Completed in #{time.round(1)}s"
log colorize(message, :green)
end
def windows?
Gem.win_platform?
end
def source
@source ||= data_source(@options[:from])
end
def destination
@destination ||= data_source(@options[:to])
end
def data_source(url)
ds = DataSource.new(url)
ObjectSpace.define_finalizer(self, self.class.finalize(ds))
ds
end
def resolve_source(source)
if source
source = source.dup
source.gsub!(/\$\([^)]+\)/) do |m|
command = m[2..-2]
result = `#{command}`.chomp
unless $?.success?
raise Error, "Command exited with non-zero status:\n#{command}"
end
result
end
end
source
end
def self.finalize(ds)
# must use proc instead of stabby lambda
proc { ds.close }
end
end
end
|
require 'nokogiri'
require 'open-uri'
module Cinch
module Plugins
class Kmf
include Cinch::Plugin
match /(kmf)$/
match /(help kmf)$/, method: :help
def execute(m)
page = Nokogiri::HTML(open('http://ktmf.koreatimes.com/?page_id=867'))
lineup = []
page.css('tr td').first.css('p').each do |act|
next if act.text == ''
lineup << act.text
end
year = page.css('dt span').first.text
m.reply "KMF #{year}: #{lineup.join(', ')}"
end
def help(m)
m.reply 'returns recent/upcoming lineup for korea times music festival'
end
end
end
end
Update kmf plugin to also be able to return ticket availability
require 'nokogiri'
require 'open-uri'
require 'mechanize'
require 'time'
module Cinch
module Plugins
class Kmf
include Cinch::Plugin
match /(kmf)$/
match /(kmf) (.+)/, method: :with_sect
match /(help kmf)$/, method: :help
def execute(m)
page = Nokogiri::HTML(open('http://ktmf.koreatimes.com/?page_id=867'))
lineup = []
page.css('tr td').first.css('p').each do |act|
next if act.text == ''
lineup << act.text
end
year = page.css('dt span').first.text
m.reply "KMF #{year}: #{lineup.join(', ')}"
end
def with_sect(m, prefix, kmf, sect)
input_array = sect.split(/[[:space:]]/)
input = input_array.join(' ').downcase
section = " #{input}".downcase
agent = Mechanize.new
agent.get("https://ticket.koreatimes.com/member/login.html") do |page|
# LOGIN
login_page = page.form_with(:action => '/member/member_login_process.html?bURL=') do |form|
username_field = form.field_with(:name => "login_id")
username_field.value = ENV['KMF_LOGIN']
password_field = form.field_with(:name => "login_password")
password_field.value = ENV['KMF_PW']
form.submit
end
end
year = (Time.now.utc + Time.zone_offset('PDT')).strftime("%Y")
agent.get("https://ticket.koreatimes.com/ticket_#{year}/ticket.php?event_id=EV021")
count = 0
# p agent.page.parser.class
agent.page.parser.css('table#Table_01').first.css('tr td').each do |td|
count += 1 if td.text.split(/[[:space:]]/).join(' ').downcase != section
break if td.text.split(/[[:space:]]/).join(' ').downcase == section
end
return m.reply "invalid section bru" if count % 8 > 0
row = (count / 8) + 5
m.reply agent.page.parser.css('td font')[row].text
end
def help(m)
m.reply 'returns recent/upcoming lineup for korea times music festival'
m.reply 'returns ticket availability if section is specified'
end
end
end
end
|
module Plz
class Command
# @param headers [Hash]
# @param params [Hash]
# @param method [String]
# @param base_url [String]
# @param path [String]
def initialize(headers: nil, params: nil, method: nil, base_url: nil, path: nil)
@headers = headers
@params = params
@method = method
@base_url = base_url
@path = path
end
# Sends an HTTP request and logs out the response
def call
raw = client.send(@method.downcase, @path, @params, @headers)
puts Response.new(raw).render
end
private
# @return [Faraday::Connection]
def client
Faraday.new(url: @base_url) do |connection|
connection.request :json
connection.response :json
connection.adapter :net_http
end
end
end
end
Rescue an error and puts `connection refused`
module Plz
class Command
# @param headers [Hash]
# @param params [Hash]
# @param method [String]
# @param base_url [String]
# @param path [String]
def initialize(headers: nil, params: nil, method: nil, base_url: nil, path: nil)
@headers = headers
@params = params
@method = method
@base_url = base_url
@path = path
end
# Sends an HTTP request and logs out the response
def call
raw = client.send(@method.downcase, @path, @params, @headers)
puts Response.new(raw).render
rescue Faraday::ConnectionFailed => exception
puts exception
end
private
# @return [Faraday::Connection]
def client
Faraday.new(url: @base_url) do |connection|
connection.request :json
connection.response :json
connection.adapter :net_http
end
end
end
end
|
require "pmv_manager/version"
require "socket"
module PmvManager
MAX_PACKET_SIZE = 128 # 128 octets
RESPONSE_TIMEOUT = 1000
PMV_DEFAULT_PORT = 10
class InvalidPacketSize < StandardError; end
class Client
def initialize(pmv_address, pmv_ip, pmv_port=PmvManager::PMV_DEFAULT_PORT)
@pmv_address = pmv_address # integer
@pmv_ip = pmv_ip # string
@pmv_port = pmv_port # integer
@socket = UDPSocket.new # UDPSocket
@socket.connect @pmv_ip, @pmv_port
end
def socket
@socket
end
def send(command)
packaged_command = package(command)
@socket.send packaged_command, 0
resp, address = @socket.recvfrom PmvManager::MAX_PACKET_SIZE
puts resp
end
def package(command)
p = ("\x02#{[@pmv_address.to_s(16)].pack("H*")}#{command.definition}\x03").unpack("C*")
packaged_command = (p << p.inject(0) { |s, c| s ^ c }).pack("C*")
if packaged_command.length > PmvManager::MAX_PACKET_SIZE
raise PmvManager::InvalidPacketSize
else
packaged_command
end
end
end
class Command
def initialize(definition)
@definition = definition
end
def definition
@definition
end
end
class WriteCommand < Command
def initialize(definition)
super(definition)
@definition = "W" + @definition
end
end
class TestCommand < WriteCommand
def initialize
super("T")
end
end
class SetToForceModeCommand < WriteCommand
def initialize
super("B1")
end
end
class WriteMessageCommand < WriteCommand
def initialize(message)
super("I0007001" + message + "\x0D")
end
end
end
first commit
require "pmv_manager/version"
require "socket"
module PmvManager
MAX_PACKET_SIZE = 128 # 128 octets
RESPONSE_TIMEOUT = 1000
PMV_DEFAULT_PORT = 10
class Error < StandardError; end
class InvalidPacketSize < Error; end
class Client
def initialize(pmv_address, pmv_ip, pmv_port=PmvManager::PMV_DEFAULT_PORT)
@pmv_address = pmv_address # integer
@pmv_ip = pmv_ip # string
@pmv_port = pmv_port # integer
# @socket = UDPSocket.new # UDPSocket
# @socket.connect @pmv_ip, @pmv_port
end
# def socket
# @socket
# end
def send(command)
packaged_command = package(command)
# @socket.send packaged_command, 0
socket = UDPSocket.new
socket.send packaged_command, 0, @pmv_ip, @pmv_port
# resp, address = @socket.recvfrom PmvManager::MAX_PACKET_SIZE
resp, address = socket.recvfrom PmvManager::MAX_PACKET_SIZE
puts resp
end
def package(command)
p = ("\x02#{[@pmv_address.to_s(16)].pack("H*")}#{command.definition}\x03").unpack("C*")
packaged_command = (p << p.inject(0) { |s, c| s ^ c }).pack("C*")
if packaged_command.length > PmvManager::MAX_PACKET_SIZE
raise PmvManager::InvalidPacketSize
else
packaged_command
end
end
end
class Command
def initialize(definition)
@definition = definition
end
def definition
@definition
end
end
class WriteCommand < Command
def initialize(definition)
super(definition)
@definition = "W" + @definition
end
end
class TestCommand < WriteCommand
def initialize
super("T")
end
end
class SetToForceModeCommand < WriteCommand
def initialize
super("B1")
end
end
class WriteMessageCommand < WriteCommand
def initialize(message)
super("I0007001" + message + "\x0D")
end
end
end
|
require 'polyamorous/version'
if defined?(::ActiveRecord)
module Polyamorous
if defined?(Arel::InnerJoin)
InnerJoin = Arel::InnerJoin
OuterJoin = Arel::OuterJoin
else
InnerJoin = Arel::Nodes::InnerJoin
OuterJoin = Arel::Nodes::OuterJoin
end
if defined?(::ActiveRecord::Associations::JoinDependency)
JoinDependency = ::ActiveRecord::Associations::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::JoinDependency::JoinAssociation
JoinBase = ::ActiveRecord::Associations::JoinDependency::JoinBase
else
JoinDependency = ::ActiveRecord::Associations::ClassMethods::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation
JoinBase = ::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinBase
end
end
require 'polyamorous/tree_node'
require 'polyamorous/join'
active_record_version = ActiveRecord::VERSION::STRING
if defined?(Module.prepend) && active_record_version >= '4.1'
require 'polyamorous/activerecord_4.2/join_association'
require 'polyamorous/activerecord_4.2/join_dependency'
Polyamorous::JoinDependency.prepend(Polyamorous::JoinDependencyExtensions)
Polyamorous::JoinDependency.singleton_class.prepend(Polyamorous::JoinDependencyExtensions::ClassMethods)
Polyamorous::JoinAssociation.prepend(Polyamorous::JoinAssociationExtensions)
else
if active_record_version >= '4.1'
require 'polyamorous/activerecord_4.1/join_association'
require 'polyamorous/activerecord_4.1/join_dependency'
else
require 'polyamorous/activerecord_3_and_4.0/join_association'
require 'polyamorous/activerecord_3_and_4.0/join_dependency'
end
Polyamorous::JoinDependency.send(:include, Polyamorous::JoinDependencyExtensions)
Polyamorous::JoinAssociation.send(:include, Polyamorous::JoinAssociationExtensions)
end
Polyamorous::JoinBase.class_eval do
if method_defined?(:active_record)
alias_method :base_klass, :active_record
end
end
end
Use prepend for Ruby 2.0 and up
- prepend is a private method in 2.0 so we have to use `send(:prepend)`
- `defined?(Module.prepend)` returns non-nil only in Ruby 2.2, so check
RUBY_VERSION instead
- wrap lines at 80 characters
require 'polyamorous/version'
if defined?(::ActiveRecord)
module Polyamorous
if defined?(Arel::InnerJoin)
InnerJoin = Arel::InnerJoin
OuterJoin = Arel::OuterJoin
else
InnerJoin = Arel::Nodes::InnerJoin
OuterJoin = Arel::Nodes::OuterJoin
end
if defined?(::ActiveRecord::Associations::JoinDependency)
JoinDependency = ::ActiveRecord::Associations::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::JoinDependency::JoinAssociation
JoinBase = ::ActiveRecord::Associations::JoinDependency::JoinBase
else
JoinDependency = ::ActiveRecord::Associations::ClassMethods::JoinDependency
JoinAssociation = ::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinAssociation
JoinBase = ::ActiveRecord::Associations::ClassMethods::JoinDependency::JoinBase
end
end
require 'polyamorous/tree_node'
require 'polyamorous/join'
active_record_version = ActiveRecord::VERSION::STRING
if RUBY_VERSION >= '2.0' && active_record_version >= '4.1'
require 'polyamorous/activerecord_4.2/join_association'
require 'polyamorous/activerecord_4.2/join_dependency'
Polyamorous::JoinDependency
.send(:prepend, Polyamorous::JoinDependencyExtensions)
Polyamorous::JoinDependency.singleton_class
.send(:prepend, Polyamorous::JoinDependencyExtensions::ClassMethods)
Polyamorous::JoinAssociation
.send(:prepend, Polyamorous::JoinAssociationExtensions)
else
if active_record_version >= '4.1'
require 'polyamorous/activerecord_4.1/join_association'
require 'polyamorous/activerecord_4.1/join_dependency'
else
require 'polyamorous/activerecord_3_and_4.0/join_association'
require 'polyamorous/activerecord_3_and_4.0/join_dependency'
end
Polyamorous::JoinDependency
.send(:include, Polyamorous::JoinDependencyExtensions)
Polyamorous::JoinAssociation
.send(:include, Polyamorous::JoinAssociationExtensions)
end
Polyamorous::JoinBase.class_eval do
if method_defined?(:active_record)
alias_method :base_klass, :active_record
end
end
end
|
require 'facets/pathname'
module POM
# Release Notes file provides an interface to
# to the current release message.
#
# DEPRECATE: We will use improved History file instead.
class ReleaseNotes
DEFAULT_FILE = '{release,notes,news}{,.txt}'
attr :file
attr :notes
attr :changes
# New ReleaseNotes.
def initialize(root_directory)
@notes = ''
@changes = ''
@file = root_directory.glob(DEFAULT_FILE, :casefold).first
read
end
#
def read
if @file
text = File.read(file)
index = notes.index(/^(##|==)/m)
if index
@notes = notes[0...index]
@changes = notes[index..-1]
else
@notes = text
end
end
end
end #class ReleaseNotes
end #module POM
fixed up release.rb to be useful
require 'facets/pathname'
module POM
# = Release Notes
#
# This class provides the latest release notes for a project.
# These notes are either extracted from the latest entry in
# the +HISTORY+ file or taken from a +RELEASE+ file, if
# provided. The +RELEASE+ file can optionally be called +NEWS+,
# and have an extension.
#
# There are two part to release notes, the +notes+ and the
# list of +changes+.
class Release
DEFAULT_FILE = '{RELEASE,NEWS}{,.*}'
# Root directory of project.
attr :root
# Release file, if any.
attr :file
# Release notes.
attr :notes
# List of changes.
attr :changes
# New Release
def initialize(root)
@notes = ''
@changes = ''
@file = root.glob(DEFAULT_FILE, :casefold).first
if @file
read(@file)
else
rel = history.releases[0]
@notes = rel.notes
@changes = rel.notes
end
end
# TODO: Improve parsing to RELEASE file.
def read(file)
text = File.read(file)
index = notes.index(/^(##|==)/m)
if index
@notes = notes[0...index]
@changes = notes[index..-1]
else
@notes = text
end
end
# Access to HISTORY file.
def history
@history ||= History.new(root)
end
end #class ReleaseNotes
end #module POM
|
MESSAGE_DELAY = 0.5
GC_DELAY = 5
SELECT_DELAY = 0.5
@pin = ARGV[0]
@timeout = ARGV[1].to_i
@pin_file = File.open("/sys/class/gpio/gpio#{@pin}/value", "r")
@running = true
Signal.trap(:INT) { @running = false }
Signal.trap(:TERM) { @running = false }
Signal.trap(:QUIT) { @running = false }
$stdout.sync = true
@read_group = [@pin_file]
def read
@pin_file.rewind
@pin_file.read.to_i
end
def wait_for_tick
@prev_value = read
begin
ready = IO.select(nil, nil, @read_group, SELECT_DELAY)
if ready
val = read
ready = nil if @prev_value == val || val == 0
@prev_value = val
end
end while !ready && @running && (!block_given? || yield)
ready
end
def send_message
$stdout.puts "#{@pin},#{@first_tick},#{@last_tick},#{@ticks}"
$stdout.flush
@last_message = Time.now
end
GC.start
$stdout.puts "ready"
$stdout.flush
# Loop while we are running or a pour is in progress
while @running
# Wait for a pour to start
ticked = wait_for_tick
break if !@running
# Prevent GC from running during the pour
# GC.disable
# Rescue block so we always re-enable GC
begin
@now = Time.now
@first_tick = @last_tick = @now.to_f
@ticks = 1
send_message
while (@now.to_f - @last_tick) < @timeout
ticked = wait_for_tick do
now = Time.now
(now.to_f - @last_tick) < @timeout && (now - @last_message) < MESSAGE_DELAY
end
@now = Time.now
if ticked
@last_tick = @now.to_f
@ticks += 1
end
send_message if @now - @last_message > MESSAGE_DELAY
end
ensure
# GC.enable
GC.start
end
end
$stdout.puts "Done"
Setup the pin on load
MESSAGE_DELAY = 0.5
GC_DELAY = 5
SELECT_DELAY = 0.5
@pin = ARGV[0]
@timeout = ARGV[1].to_i
base_path = "/sys/class/gpio/gpio#{@pin}"
File.open("/sys/class/gpio/export", "w") {|f| f.write(@pin.to_s) } unless File.exist?(base_path)
File.open("#{base_path}/direction", "w") {|f| f.write("in") }
File.open("#{base_path}/edge", "w") {|f| f.write("both") }
@pin_file = File.open("#{base_path}/value", "r")
@running = true
Signal.trap(:INT) { @running = false }
Signal.trap(:TERM) { @running = false }
Signal.trap(:QUIT) { @running = false }
$stdout.sync = true
@read_group = [@pin_file]
def read
@pin_file.rewind
@pin_file.read.to_i
end
def wait_for_tick
@prev_value = read
begin
ready = IO.select(nil, nil, @read_group, SELECT_DELAY)
if ready
val = read
ready = nil if @prev_value == val || val == 0
@prev_value = val
end
end while !ready && @running && (!block_given? || yield)
ready
end
def send_message
$stdout.puts "#{@pin},#{@first_tick},#{@last_tick},#{@ticks}"
$stdout.flush
@last_message = Time.now
end
GC.start
$stdout.puts "ready"
$stdout.flush
# Loop while we are running or a pour is in progress
while @running
# Wait for a pour to start
ticked = wait_for_tick
break if !@running
# Prevent GC from running during the pour
# GC.disable
# Rescue block so we always re-enable GC
begin
@now = Time.now
@first_tick = @last_tick = @now.to_f
@ticks = 1
send_message
while (@now.to_f - @last_tick) < @timeout
ticked = wait_for_tick do
now = Time.now
(now.to_f - @last_tick) < @timeout && (now - @last_message) < MESSAGE_DELAY
end
@now = Time.now
if ticked
@last_tick = @now.to_f
@ticks += 1
end
send_message if @now - @last_message > MESSAGE_DELAY
end
ensure
# GC.enable
GC.start
end
end
$stdout.puts "Done"
|
module Prmd
class Schema
def [](key)
@data[key]
end
def []=(key, value)
@data[key] = value
end
def initialize(new_data = {})
convert_type_to_array = lambda do |datum|
case datum
when Array
datum.map { |element| convert_type_to_array.call(element) }
when Hash
if datum.has_key?('type') && datum['type'].is_a?(String)
datum['type'] = [*datum['type']]
end
datum.each { |k,v| datum[k] = convert_type_to_array.call(v) }
else
datum
end
end
@data = convert_type_to_array.call(new_data)
@schemata_examples = {}
end
def dereference(reference)
if reference.is_a?(Hash)
if reference.has_key?('$ref')
value = reference.dup
key = value.delete('$ref')
else
return [nil, reference] # no dereference needed
end
else
key, value = reference, {}
end
begin
datum = @data
key.gsub(%r{[^#]*#/}, '').split('/').each do |fragment|
datum = datum[fragment]
end
# last dereference will have nil key, so compact it out
# [-2..-1] should be the final key reached before deref
dereferenced_key, dereferenced_value = dereference(datum)
[
[key, dereferenced_key].compact.last,
[dereferenced_value, value].inject({}) { |composite, element| composite.merge(element) }
]
rescue => error
$stderr.puts("Failed to dereference `#{key}`")
raise(error)
end
end
def schemata_example(schemata_id)
_, definition = dereference("#/definitions/#{schemata_id}")
@schemata_examples[schemata_id] ||= begin
example = {}
if definition['properties']
definition['properties'].each do |key, value|
_, value = dereference(value)
if value.has_key?('properties')
example[key] = {}
value['properties'].each do |k,v|
example[key][k] = dereference(v).last['example']
end
else
example[key] = value['example']
end
end
else
example.merge!(definition['example'])
end
example
end
end
def href
(@data['links'].detect { |link| link['rel'] == 'self' } || {})['href']
end
def to_json
new_json = JSON.pretty_generate(@data)
# nuke empty lines
new_json = new_json.split("\n").delete_if {|line| line.empty?}.join("\n") + "\n"
new_json
end
def to_yaml
YAML.dump(@data)
end
def to_s
to_json
end
end
end
extract building example part of schemata_example() as build_example()
it might be useful describe some JSON example in render command (e.g. generate JSON request body by link['schema']['properties'] value)
module Prmd
class Schema
def [](key)
@data[key]
end
def []=(key, value)
@data[key] = value
end
def initialize(new_data = {})
convert_type_to_array = lambda do |datum|
case datum
when Array
datum.map { |element| convert_type_to_array.call(element) }
when Hash
if datum.has_key?('type') && datum['type'].is_a?(String)
datum['type'] = [*datum['type']]
end
datum.each { |k,v| datum[k] = convert_type_to_array.call(v) }
else
datum
end
end
@data = convert_type_to_array.call(new_data)
@schemata_examples = {}
end
def dereference(reference)
if reference.is_a?(Hash)
if reference.has_key?('$ref')
value = reference.dup
key = value.delete('$ref')
else
return [nil, reference] # no dereference needed
end
else
key, value = reference, {}
end
begin
datum = @data
key.gsub(%r{[^#]*#/}, '').split('/').each do |fragment|
datum = datum[fragment]
end
# last dereference will have nil key, so compact it out
# [-2..-1] should be the final key reached before deref
dereferenced_key, dereferenced_value = dereference(datum)
[
[key, dereferenced_key].compact.last,
[dereferenced_value, value].inject({}) { |composite, element| composite.merge(element) }
]
rescue => error
$stderr.puts("Failed to dereference `#{key}`")
raise(error)
end
end
def build_example(properties)
example = {}
properties.each do |key, value|
_, value = dereference(value)
if value.has_key?('properties')
example[key] = {}
value['properties'].each do |k,v|
example[key][k] = dereference(v).last['example']
end
else
example[key] = value['example']
end
end
return example
end
def schemata_example(schemata_id)
_, definition = dereference("#/definitions/#{schemata_id}")
@schemata_examples[schemata_id] ||= begin
example = {}
if definition['properties']
example = build_example(definition['properties'])
else
example.merge!(definition['example'])
end
example
end
end
def href
(@data['links'].detect { |link| link['rel'] == 'self' } || {})['href']
end
def to_json
new_json = JSON.pretty_generate(@data)
# nuke empty lines
new_json = new_json.split("\n").delete_if {|line| line.empty?}.join("\n") + "\n"
new_json
end
def to_yaml
YAML.dump(@data)
end
def to_s
to_json
end
end
end
|
require 'pronto'
require 'haml_lint'
module Pronto
class Haml < Runner
def initialize
@runner = ::HamlLint::Runner.new
end
def run(patches, _)
return [] unless patches
valid_patches = patches.select { |patch| patch.additions > 0 }
valid_patches.map { |patch| inspect(patch) }.flatten.compact
end
def inspect(patch)
lints = @runner.run(files: [patch.new_file_full_path]).lints
lints.map do |lint|
patch.added_lines.select { |line| line.new_lineno == lint.line }
.map { |line| new_message(lint, line) }
end
end
def new_message(lint, line)
path = line.patch.delta.new_file[:path]
Message.new(path, line, lint.severity, lint.message)
end
end
end
Convert Pathname to string before passing it to haml-lint
Was erroring with haml-lint-0.7.0 and ruby-2.1.1/2.1.2/2.1.3
Worked fine with ruby-2.1.4 and ruby-2.1.5.
Discovered via this issue:
https://github.com/mmozuras/pronto/issues/47
require 'pronto'
require 'haml_lint'
module Pronto
class Haml < Runner
def initialize
@runner = ::HamlLint::Runner.new
end
def run(patches, _)
return [] unless patches
valid_patches = patches.select { |patch| patch.additions > 0 }
valid_patches.map { |patch| inspect(patch) }.flatten.compact
end
def inspect(patch)
lints = @runner.run(files: [patch.new_file_full_path.to_s]).lints
lints.map do |lint|
patch.added_lines.select { |line| line.new_lineno == lint.line }
.map { |line| new_message(lint, line) }
end
end
def new_message(lint, line)
path = line.patch.delta.new_file[:path]
Message.new(path, line, lint.severity, lint.message)
end
end
end
|
############################################################
# This file is imported from a different project.
# DO NOT make modifications in this repo.
# File a patch instead and assign it to Ryan Davis
############################################################
$TESTING = true
begin
require 'mini/test'
rescue LoadError
require 'test/unit/testcase'
end
require 'sexp_processor' # for deep_clone
# key:
# wwtt = what were they thinking?
# TODO: <ko1_> 1.8.7 support {|&b|} syntax
class Examples
attr_reader :reader
attr_writer :writer
def a_method(x); x+1; end
alias an_alias a_method
define_method(:bmethod_noargs) do
x + 1
end
define_method(:unsplatted) do |x|
x + 1
end
define_method :splatted do |*args|
y = args.first
y + 42
end
define_method :dmethod_added, instance_method(:a_method) if
RUBY_VERSION < "1.9"
end
class ParseTreeTestCase < Test::Unit::TestCase
unless defined? Mini then
undef_method :default_test rescue nil
alias :refute_nil :assert_not_nil
end
attr_accessor :processor # to be defined by subclass
def setup
super
@processor = nil
end
def after_process_hook klass, node, data, input_name, output_name
end
def before_process_hook klass, node, data, input_name, output_name
end
def self.add_test name, data, klass = self.name[4..-1]
name = name.to_s
klass = klass.to_s
if testcases.has_key? name then
if testcases[name].has_key? klass then
warn "testcase #{klass}##{name} already has data"
else
testcases[name][klass] = data
end
else
warn "testcase #{name} does not exist"
end
end
def self.add_tests name, hash
name = name.to_s
hash.each do |klass, data|
warn "testcase #{klass}##{name} already has data" if
testcases[name].has_key? klass
testcases[name][klass] = data
end
end
def self.clone_same
@@testcases.each do |node, data|
data.each do |key, val|
if val == :same then
prev_key = self.previous(key)
data[key] = data[prev_key].deep_clone
end
end
end
end
def self.copy_test_case nonverbose, klass
verbose = nonverbose + "_mri_verbose_flag"
testcases[verbose][klass] = testcases[nonverbose][klass]
end
def self.generate_test klass, node, data, input_name, output_name
klass.send(:define_method, "test_#{node}".to_sym) do
flunk "Processor is nil" if processor.nil?
assert data.has_key?(input_name), "Unknown input data"
assert data.has_key?(output_name), "Missing test data"
$missing[node] << output_name unless data.has_key? output_name
input = data[input_name].deep_clone
expected = data[output_name].deep_clone
case expected
when :unsupported then
assert_raises(UnsupportedNodeError) do
processor.process(input)
end
else
extra_expected = []
extra_input = []
_, expected, extra_expected = *expected if
Array === expected and expected.first == :defx
_, input, extra_input = *input if
Array === input and input.first == :defx
# OMG... I can't believe I have to do this this way. these
# hooks are here instead of refactoring this define_method
# body into an assertion. It'll allow subclasses to hook in
# and add behavior before or after the processor does it's
# thing. If you go the body refactor route, some of the
# RawParseTree test casese fail for completely bogus reasons.
before_process_hook klass, node, data, input_name, output_name
refute_nil data[input_name], "testcase does not exist?"
@result = processor.process input
assert_equal(expected, @result,
"failed on input: #{data[input_name].inspect}")
after_process_hook klass, node, data, input_name, output_name
extra_input.each do |extra|
processor.process(extra)
end
extra = processor.extra_methods rescue []
assert_equal extra_expected, extra
end
end
end
def self.generate_tests klass
install_missing_reporter
clone_same
output_name = klass.name.to_s.sub(/^Test/, '')
input_name = self.previous(output_name)
@@testcases.each do |node, data|
next if [:skip, :unsupported].include? data[input_name]
next if data[output_name] == :skip
generate_test klass, node, data, input_name, output_name
end
end
def self.inherited klass
super
generate_tests klass unless klass.name =~ /TestCase/
end
def self.install_missing_reporter
unless defined? $missing then
$missing = Hash.new { |h,k| h[k] = [] }
at_exit {
at_exit {
warn ""
$missing.sort.each do |name, klasses|
warn "add_tests(#{name.inspect},"
klasses.map! { |klass| " #{klass.inspect} => :same" }
warn klasses.join("\n") + ")"
end
warn ""
}
}
end
end
def self.previous(key, extra=0) # FIX: remove R2C code
idx = @@testcase_order.index(key)
raise "Unknown class #{key} in @@testcase_order" if idx.nil?
case key
when "RubyToRubyC" then
idx -= 1
end
@@testcase_order[idx - 1 - extra]
end
def self.testcase_order; @@testcase_order; end
def self.testcases; @@testcases; end
def self.unsupported_tests *tests
tests.flatten.each do |name|
add_test name, :unsupported
end
end
############################################################
# Shared TestCases:
@@testcase_order = %w(Ruby RawParseTree ParseTree)
@@testcases = Hash.new { |h,k| h[k] = {} }
add_tests("alias",
"Ruby" => "class X\n alias :y :x\nend",
"RawParseTree" => [:class, :X, nil,
[:scope, [:alias, [:lit, :y], [:lit, :x]]]],
"ParseTree" => s(:class, :X, nil,
s(:scope, s(:alias, s(:lit, :y), s(:lit, :x)))),
"Ruby2Ruby" => "class X\n alias_method :y, :x\nend")
add_tests("alias_ugh",
"Ruby" => "class X\n alias y x\nend",
"RawParseTree" => [:class, :X, nil,
[:scope, [:alias, [:lit, :y], [:lit, :x]]]],
"ParseTree" => s(:class, :X, nil,
s(:scope, s(:alias, s(:lit, :y), s(:lit, :x)))),
"Ruby2Ruby" => "class X\n alias_method :y, :x\nend")
add_tests("and",
"Ruby" => "(a and b)",
"RawParseTree" => [:and, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:and,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("argscat_inside",
"Ruby" => "a = [b, *c]",
"RawParseTree" => [:lasgn, :a,
[:argscat,
[:array, [:vcall, :b]], [:vcall, :c]]],
"ParseTree" => s(:lasgn, :a,
s(:argscat,
s(:array, s(:call, nil, :b, s(:arglist))),
s(:call, nil, :c, s(:arglist)))),
"Ruby2Ruby" => "a = b, *c")
add_tests("argscat_svalue",
"Ruby" => "a = b, c, *d",
"RawParseTree" => [:lasgn, :a,
[:svalue,
[:argscat,
[:array, [:vcall, :b], [:vcall, :c]],
[:vcall, :d]]]],
"ParseTree" => s(:lasgn, :a,
s(:svalue,
s(:argscat,
s(:array,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :c, s(:arglist))),
s(:call, nil, :d, s(:arglist))))))
add_tests("argspush",
"Ruby" => "a[*b] = c",
"RawParseTree" => [:attrasgn,
[:vcall, :a],
:[]=,
[:argspush,
[:splat,
[:vcall, :b]],
[:vcall, :c]]],
"ParseTree" => s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:[]=,
s(:argspush,
s(:splat,
s(:call, nil, :b, s(:arglist))),
s(:call, nil, :c, s(:arglist)))))
add_tests("array",
"Ruby" => "[1, :b, \"c\"]",
"RawParseTree" => [:array, [:lit, 1], [:lit, :b], [:str, "c"]],
"ParseTree" => s(:array, s(:lit, 1), s(:lit, :b), s(:str, "c")))
add_tests("array_pct_W",
"Ruby" => "%W[a b c]",
"RawParseTree" => [:array, [:str, "a"], [:str, "b"], [:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"), s(:str, "b"), s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"b\", \"c\"]")
add_tests("array_pct_W_dstr",
"Ruby" => "%W[a #\{@b} c]",
"RawParseTree" => [:array,
[:str, "a"],
[:dstr, "", [:evstr, [:ivar, :@b]]],
[:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"),
s(:dstr, "", s(:evstr, s(:ivar, :@b))),
s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"#\{@b}\", \"c\"]")
add_tests("array_pct_w",
"Ruby" => "%w[a b c]",
"RawParseTree" => [:array, [:str, "a"], [:str, "b"], [:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"), s(:str, "b"), s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"b\", \"c\"]")
add_tests("array_pct_w_dstr",
"Ruby" => "%w[a #\{@b} c]",
"RawParseTree" => [:array,
[:str, "a"],
[:str, "#\{@b}"],
[:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"),
s(:str, "#\{@b}"),
s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"\\\#{@b}\", \"c\"]") # TODO: huh?
add_tests("attrasgn",
"Ruby" => "y = 0\n42.method = y\n",
"RawParseTree" => [:block,
[:lasgn, :y, [:lit, 0]],
[:attrasgn, [:lit, 42], :method=,
[:array, [:lvar, :y]]]],
"ParseTree" => s(:block,
s(:lasgn, :y, s(:lit, 0)),
s(:attrasgn, s(:lit, 42), :method=,
s(:arglist, s(:lvar, :y)))))
add_tests("attrasgn_index_equals",
"Ruby" => "a[42] = 24",
"RawParseTree" => [:attrasgn, [:vcall, :a], :[]=,
[:array, [:lit, 42], [:lit, 24]]],
"ParseTree" => s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:[]=,
s(:arglist, s(:lit, 42), s(:lit, 24))))
add_tests("attrasgn_index_equals_space",
"Ruby" => "a = []; a [42] = 24",
"RawParseTree" => [:block,
[:lasgn, :a, [:zarray]],
[:attrasgn, [:lvar, :a], :[]=,
[:array, [:lit, 42], [:lit, 24]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:attrasgn, s(:lvar, :a), :[]=,
s(:arglist, s(:lit, 42), s(:lit, 24)))),
"Ruby2Ruby" => "a = []\na[42] = 24\n")
add_tests("attrset",
"Ruby" => [Examples, :writer=],
"RawParseTree" => [:defn, :writer=, [:attrset, :@writer]],
"ParseTree" => s(:defn, :writer=,
s(:args, :arg),
s(:attrset, :@writer)),
"Ruby2Ruby" => "attr_writer :writer")
add_tests("back_ref",
"Ruby" => "[$&, $`, $', $+]",
"RawParseTree" => [:array,
[:back_ref, :&],
[:back_ref, :"`"],
[:back_ref, :"'"],
[:back_ref, :+]],
"ParseTree" => s(:array,
s(:back_ref, :&),
s(:back_ref, :"`"),
s(:back_ref, :"'"),
s(:back_ref, :+)))
add_tests("begin",
"Ruby" => "begin\n (1 + 1)\nend",
"RawParseTree" => [:begin,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))),
"Ruby2Ruby" => "(1 + 1)")
add_tests("begin_def",
"Ruby" => "def m\n begin\n\n end\nend",
"RawParseTree" => [:defn, :m, [:scope, [:block, [:args], [:nil]]]],
"ParseTree" => s(:defn, :m, s(:args),
s(:scope, s(:block, s(:nil)))),
"Ruby2Ruby" => "def m\n # do nothing\nend")
add_tests("begin_rescue_ensure",
"Ruby" => "begin\n a\nrescue\n # do nothing\nensure\n # do nothing\nend",
"RawParseTree" => [:begin,
[:ensure,
[:rescue,
[:vcall, :a],
[:resbody, nil]],
[:nil]]],
"ParseTree" => s(:ensure,
s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody, s(:array), nil)),
s(:nil)))
add_tests("begin_rescue_ensure_all_empty",
"Ruby" => "begin\n # do nothing\nrescue\n # do nothing\nensure\n # do nothing\nend",
"RawParseTree" => [:begin,
[:ensure,
[:rescue,
[:resbody, nil]],
[:nil]]],
"ParseTree" => s(:ensure,
s(:rescue,
s(:resbody, s(:array), nil)),
s(:nil)))
add_tests("begin_rescue_twice",
"Ruby" => "begin\n a\nrescue => mes\n # do nothing\nend\nbegin\n b\nrescue => mes\n # do nothing\nend\n",
"RawParseTree" => [:block,
[:begin,
[:rescue,
[:vcall, :a],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]]],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]]]],
"ParseTree" => s(:block,
s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody,
s(:array, s(:lasgn, :mes, s(:gvar, :$!))),
nil)),
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array,
s(:lasgn, :mes, s(:gvar, :$!))),
nil))))
add_tests("begin_rescue_twice_mri_verbose_flag",
"RawParseTree" => [:block,
[:rescue, # no begin
[:vcall, :a],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]]]])
copy_test_case "begin_rescue_twice", "Ruby"
copy_test_case "begin_rescue_twice", "ParseTree"
add_tests("block_attrasgn",
"Ruby" => "def self.setup(ctx)\n bind = allocate\n bind.context = ctx\n return bind\nend",
"RawParseTree" => [:defs, [:self], :setup,
[:scope,
[:block,
[:args, :ctx],
[:lasgn, :bind, [:vcall, :allocate]],
[:attrasgn, [:lvar, :bind], :context=,
[:array, [:lvar, :ctx]]],
[:return, [:lvar, :bind]]]]],
"ParseTree" => s(:defs, s(:self), :setup,
s(:args, :ctx),
s(:scope,
s(:block,
s(:lasgn, :bind,
s(:call, nil, :allocate, s(:arglist))),
s(:attrasgn, s(:lvar, :bind), :context=,
s(:arglist, s(:lvar, :ctx))),
s(:return, s(:lvar, :bind))))))
add_tests("block_lasgn",
"Ruby" => "x = (y = 1\n(y + 2))",
"RawParseTree" => [:lasgn, :x,
[:block,
[:lasgn, :y, [:lit, 1]],
[:call, [:lvar, :y], :+, [:array, [:lit, 2]]]]],
"ParseTree" => s(:lasgn, :x,
s(:block,
s(:lasgn, :y, s(:lit, 1)),
s(:call, s(:lvar, :y), :+,
s(:arglist, s(:lit, 2))))))
add_tests("block_mystery_block",
"Ruby" => "a(b) do\n if b then\n true\n else\n c = false\n d { |x| c = true }\n c\n end\nend",
"RawParseTree" => [:iter,
[:fcall, :a, [:array, [:vcall, :b]]],
nil,
[:if,
[:vcall, :b],
[:true],
[:block,
[:dasgn_curr, :c, [:false]],
[:iter,
[:fcall, :d],
[:dasgn_curr, :x],
[:dasgn, :c, [:true]]],
[:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a,
s(:arglist, s(:call, nil, :b, s(:arglist)))),
nil,
s(:if,
s(:call, nil, :b, s(:arglist)),
s(:true),
s(:block,
s(:lasgn, :c, s(:false)),
s(:iter,
s(:call, nil, :d, s(:arglist)),
s(:lasgn, :x),
s(:lasgn, :c, s(:true))),
s(:lvar, :c)))))
add_tests("block_pass_args_and_splat",
"Ruby" => "def blah(*args, &block)\n other(42, *args, &block)\nend",
"RawParseTree" => [:defn, :blah,
[:scope,
[:block,
[:args, :"*args"],
[:block_arg, :block],
[:block_pass,
[:lvar, :block],
[:fcall, :other,
[:argscat,
[:array, [:lit, 42]], [:lvar, :args]]]]]]],
"ParseTree" => s(:defn, :blah,
s(:args, :"*args", :"&block"),
s(:scope,
s(:block,
s(:block_pass,
s(:lvar, :block),
s(:call, nil, :other,
s(:argscat,
s(:array,
s(:lit, 42)), s(:lvar, :args))))))))
add_tests("block_pass_call_0",
"Ruby" => "a.b(&c)",
"RawParseTree" => [:block_pass,
[:vcall, :c], [:call, [:vcall, :a], :b]],
"ParseTree" => s(:block_pass,
s(:call, nil, :c, s(:arglist)),
s(:call,
s(:call, nil, :a, s(:arglist)),
:b,
s(:arglist))))
add_tests("block_pass_call_1",
"Ruby" => "a.b(4, &c)",
"RawParseTree" => [:block_pass,
[:vcall, :c],
[:call, [:vcall, :a], :b, [:array, [:lit, 4]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :c, s(:arglist)),
s(:call,
s(:call, nil, :a, s(:arglist)),
:b,
s(:arglist, s(:lit, 4)))))
add_tests("block_pass_call_n",
"Ruby" => "a.b(1, 2, 3, &c)",
"RawParseTree" => [:block_pass,
[:vcall, :c],
[:call, [:vcall, :a], :b,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :c, s(:arglist)),
s(:call,
s(:call, nil, :a, s(:arglist)),
:b,
s(:arglist,
s(:lit, 1), s(:lit, 2), s(:lit, 3)))))
add_tests("block_pass_fcall_0",
"Ruby" => "a(&b)",
"RawParseTree" => [:block_pass, [:vcall, :b], [:fcall, :a]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist))))
add_tests("block_pass_fcall_1",
"Ruby" => "a(4, &b)",
"RawParseTree" => [:block_pass,
[:vcall, :b],
[:fcall, :a, [:array, [:lit, 4]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist, s(:lit, 4)))))
add_tests("block_pass_fcall_n",
"Ruby" => "a(1, 2, 3, &b)",
"RawParseTree" => [:block_pass,
[:vcall, :b],
[:fcall, :a,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a,
s(:arglist,
s(:lit, 1), s(:lit, 2), s(:lit, 3)))))
add_tests("block_pass_omgwtf",
"Ruby" => "define_attr_method(:x, :sequence_name, &Proc.new { |*args| nil })",
"RawParseTree" => [:block_pass,
[:iter,
[:call, [:const, :Proc], :new],
[:masgn, [:dasgn_curr, :args]],
[:nil]],
[:fcall, :define_attr_method,
[:array, [:lit, :x], [:lit, :sequence_name]]]],
"ParseTree" => s(:block_pass,
s(:iter,
s(:call, s(:const, :Proc), :new, s(:arglist)),
s(:masgn, s(:lasgn, :args)),
s(:nil)),
s(:call, nil, :define_attr_method,
s(:arglist,
s(:lit, :x), s(:lit, :sequence_name)))))
add_tests("block_pass_splat",
"Ruby" => "def blah(*args, &block)\n other(*args, &block)\nend",
"RawParseTree" => [:defn, :blah,
[:scope,
[:block,
[:args, :"*args"],
[:block_arg, :block],
[:block_pass,
[:lvar, :block],
[:fcall, :other,
[:splat, [:lvar, :args]]]]]]],
"ParseTree" => s(:defn, :blah,
s(:args, :"*args", :"&block"),
s(:scope,
s(:block,
s(:block_pass,
s(:lvar, :block),
s(:call, nil, :other,
s(:splat, s(:lvar, :args))))))))
add_tests("block_pass_super",
"Ruby" => "super(&prc)",
"RawParseTree" => [:block_pass, [:vcall, :prc], [:super]],
"ParseTree" => s(:block_pass,
s(:call, nil, :prc, s(:arglist)),
s(:super)))
add_tests("block_pass_thingy",
"Ruby" => "r.read_body(dest, &block)",
"RawParseTree" => [:block_pass,
[:vcall, :block],
[:call, [:vcall, :r], :read_body,
[:array, [:vcall, :dest]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :block, s(:arglist)),
s(:call, s(:call, nil, :r, s(:arglist)),
:read_body,
s(:arglist,
s(:call, nil, :dest, s(:arglist))))))
add_tests("block_stmt_after",
"Ruby" => "def f\n begin\n b\n rescue\n c\n end\n\n d\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody, nil, [:vcall, :c]]]],
[:vcall, :d]]]],
"ParseTree" => s(:defn, :f,
s(:args),
s(:scope,
s(:block,
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array),
s(:call, nil, :c, s(:arglist)))),
s(:call, nil, :d, s(:arglist))))),
"Ruby2Ruby" => "def f\n b rescue c\n d\nend")
add_tests("block_stmt_after_mri_verbose_flag",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:rescue, # no begin
[:vcall, :b],
[:resbody, nil, [:vcall, :c]]],
[:vcall, :d]]]])
copy_test_case "block_stmt_after", "Ruby"
copy_test_case "block_stmt_after", "ParseTree"
copy_test_case "block_stmt_after", "Ruby2Ruby"
add_tests("block_stmt_before",
"Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:vcall, :a],
[:begin,
[:rescue, [:vcall, :b],
[:resbody, nil, [:vcall, :c]]]]]]],
"ParseTree" => s(:defn, :f,
s(:args),
s(:scope,
s(:block,
s(:call, nil, :a, s(:arglist)),
s(:rescue, s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array),
s(:call, nil, :c, s(:arglist))))))),
"Ruby2Ruby" => "def f\n a\n b rescue c\nend")
# oddly... this one doesn't HAVE any differences when verbose... new?
copy_test_case "block_stmt_before", "Ruby"
copy_test_case "block_stmt_before", "ParseTree"
copy_test_case "block_stmt_before", "RawParseTree"
copy_test_case "block_stmt_before", "Ruby2Ruby"
add_tests("block_stmt_both",
"Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\n d\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:vcall, :a],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody,
nil,
[:vcall, :c]]]],
[:vcall, :d]]]],
"ParseTree" => s(:defn, :f, s(:args),
s(:scope,
s(:block,
s(:call, nil, :a, s(:arglist)),
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array),
s(:call, nil, :c, s(:arglist)))),
s(:call, nil, :d, s(:arglist))))),
"Ruby2Ruby" => "def f\n a\n b rescue c\n d\nend")
add_tests("block_stmt_both_mri_verbose_flag",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:vcall, :a],
[:rescue, # no begin
[:vcall, :b],
[:resbody,
nil,
[:vcall, :c]]],
[:vcall, :d]]]])
copy_test_case "block_stmt_both", "Ruby"
copy_test_case "block_stmt_both", "ParseTree"
copy_test_case "block_stmt_both", "Ruby2Ruby"
add_tests("bmethod",
"Ruby" => [Examples, :unsplatted],
"RawParseTree" => [:defn, :unsplatted,
[:bmethod,
[:dasgn_curr, :x],
[:call, [:dvar, :x], :+, [:array, [:lit, 1]]]]],
"ParseTree" => s(:defn, :unsplatted,
s(:args, :x),
s(:scope,
s(:block,
s(:call,
s(:lvar, :x),
:+,
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def unsplatted(x)\n (x + 1)\nend")
add_tests("bmethod_noargs",
"Ruby" => [Examples, :bmethod_noargs],
"RawParseTree" => [:defn, :bmethod_noargs,
[:bmethod,
nil,
[:call,
[:vcall, :x], :"+", [:array, [:lit, 1]]]]],
"ParseTree" => s(:defn, :bmethod_noargs,
s(:args),
s(:scope,
s(:block,
s(:call,
s(:call, nil, :x, s(:arglist)),
:"+",
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def bmethod_noargs\n (x + 1)\nend")
add_tests("bmethod_splat",
"Ruby" => [Examples, :splatted],
"RawParseTree" => [:defn, :splatted,
[:bmethod,
[:masgn, [:dasgn_curr, :args]],
[:block,
[:dasgn_curr, :y,
[:call, [:dvar, :args], :first]],
[:call, [:dvar, :y], :+,
[:array, [:lit, 42]]]]]],
"ParseTree" => s(:defn, :splatted,
s(:args, :"*args"),
s(:scope,
s(:block,
s(:lasgn, :y,
s(:call, s(:lvar, :args), :first,
s(:arglist))),
s(:call, s(:lvar, :y), :+,
s(:arglist, s(:lit, 42)))))),
"Ruby2Ruby" => "def splatted(*args)\n y = args.first\n (y + 42)\nend")
add_tests("break",
"Ruby" => "loop { break if true }",
"RawParseTree" => [:iter,
[:fcall, :loop], nil,
[:if, [:true], [:break], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)), nil,
s(:if, s(:true), s(:break), nil)))
add_tests("break_arg",
"Ruby" => "loop { break 42 if true }",
"RawParseTree" => [:iter,
[:fcall, :loop], nil,
[:if, [:true], [:break, [:lit, 42]], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)), nil,
s(:if, s(:true), s(:break, s(:lit, 42)), nil)))
add_tests("call",
"Ruby" => "self.method",
"RawParseTree" => [:call, [:self], :method],
"ParseTree" => s(:call, s(:self), :method, s(:arglist)))
add_tests("call_arglist",
"Ruby" => "o.puts(42)",
"RawParseTree" => [:call, [:vcall, :o], :puts,
[:array, [:lit, 42]]],
"ParseTree" => s(:call, s(:call, nil, :o, s(:arglist)), :puts,
s(:arglist, s(:lit, 42))))
add_tests("call_arglist_hash",
"Ruby" => "o.m(:a => 1, :b => 2)",
"RawParseTree" => [:call,
[:vcall, :o], :m,
[:array,
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call,
s(:call, nil, :o, s(:arglist)), :m,
s(:arglist,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("call_arglist_norm_hash",
"Ruby" => "o.m(42, :a => 1, :b => 2)",
"RawParseTree" => [:call,
[:vcall, :o], :m,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call,
s(:call, nil, :o, s(:arglist)), :m,
s(:arglist,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("call_arglist_norm_hash_splat",
"Ruby" => "o.m(42, :a => 1, :b => 2, *c)",
"RawParseTree" => [:call,
[:vcall, :o], :m,
[:argscat,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]],
[:vcall, :c]]],
"ParseTree" => s(:call,
s(:call, nil, :o, s(:arglist)), :m,
s(:argscat,
s(:array,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))),
s(:call, nil, :c, s(:arglist)))))
add_tests("call_arglist_space",
"Ruby" => "a (1,2,3)",
"RawParseTree" => [:fcall, :a,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
"ParseTree" => s(:call, nil, :a,
s(:arglist,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
"Ruby2Ruby" => "a(1, 2, 3)")
add_tests("call_command",
"Ruby" => "1.b(c)",
"RawParseTree" => [:call, [:lit, 1], :b, [:array, [:vcall, :c]]],
"ParseTree" => s(:call,
s(:lit, 1),
:b,
s(:arglist, s(:call, nil, :c, s(:arglist)))))
add_tests("call_expr",
"Ruby" => "(v = (1 + 1)).zero?",
"RawParseTree" => [:call,
[:lasgn, :v,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
:zero?],
"ParseTree" => s(:call,
s(:lasgn, :v,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
:zero?, s(:arglist)))
add_tests("call_index",
"Ruby" => "a = []\na[42]\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:zarray]],
[:call, [:lvar, :a], :[], [:array, [:lit, 42]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lit, 42)))))
add_tests("call_index_no_args",
"Ruby" => "a[]",
"RawParseTree" => [:call, [:vcall, :a], :[]],
"ParseTree" => s(:call, s(:call, nil, :a, s(:arglist)),
:[], s(:arglist)))
add_tests("call_index_space",
"Ruby" => "a = []\na [42]\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:zarray]],
[:call, [:lvar, :a], :[], [:array, [:lit, 42]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lit, 42)))),
"Ruby2Ruby" => "a = []\na[42]\n")
add_tests("call_unary_neg",
"Ruby" => "-2**31",
"RawParseTree" => [:call,
[:call, [:lit, 2], :**, [:array, [:lit, 31]]],
:-@],
"ParseTree" => s(:call,
s(:call,
s(:lit, 2),
:**,
s(:arglist, s(:lit, 31))),
:-@, s(:arglist)),
"Ruby2Ruby" => "-(2 ** 31)")
add_tests("case",
"Ruby" => "var = 2\nresult = \"\"\ncase var\nwhen 1 then\n puts(\"something\")\n result = \"red\"\nwhen 2, 3 then\n result = \"yellow\"\nwhen 4 then\n # do nothing\nelse\n result = \"green\"\nend\ncase result\nwhen \"red\" then\n var = 1\nwhen \"yellow\" then\n var = 2\nwhen \"green\" then\n var = 3\nelse\n # do nothing\nend\n",
"RawParseTree" => [:block,
[:lasgn, :var, [:lit, 2]],
[:lasgn, :result, [:str, ""]],
[:case,
[:lvar, :var],
[:when,
[:array, [:lit, 1]],
[:block,
[:fcall, :puts,
[:array, [:str, "something"]]],
[:lasgn, :result, [:str, "red"]]]],
[:when,
[:array, [:lit, 2], [:lit, 3]],
[:lasgn, :result, [:str, "yellow"]]],
[:when, [:array, [:lit, 4]], nil],
[:lasgn, :result, [:str, "green"]]],
[:case,
[:lvar, :result],
[:when, [:array, [:str, "red"]],
[:lasgn, :var, [:lit, 1]]],
[:when, [:array, [:str, "yellow"]],
[:lasgn, :var, [:lit, 2]]],
[:when, [:array, [:str, "green"]],
[:lasgn, :var, [:lit, 3]]],
nil]],
"ParseTree" => s(:block,
s(:lasgn, :var, s(:lit, 2)),
s(:lasgn, :result, s(:str, "")),
s(:case,
s(:lvar, :var),
s(:when,
s(:array, s(:lit, 1)),
s(:block,
s(:call, nil, :puts,
s(:arglist, s(:str, "something"))),
s(:lasgn, :result, s(:str, "red")))),
s(:when,
s(:array, s(:lit, 2), s(:lit, 3)),
s(:lasgn, :result, s(:str, "yellow"))),
s(:when, s(:array, s(:lit, 4)), nil),
s(:lasgn, :result, s(:str, "green"))),
s(:case,
s(:lvar, :result),
s(:when, s(:array, s(:str, "red")),
s(:lasgn, :var, s(:lit, 1))),
s(:when, s(:array, s(:str, "yellow")),
s(:lasgn, :var, s(:lit, 2))),
s(:when, s(:array, s(:str, "green")),
s(:lasgn, :var, s(:lit, 3))),
nil)))
add_tests("case_nested",
"Ruby" => "var1 = 1\nvar2 = 2\nresult = nil\ncase var1\nwhen 1 then\n case var2\n when 1 then\n result = 1\n when 2 then\n result = 2\n else\n result = 3\n end\nwhen 2 then\n case var2\n when 1 then\n result = 4\n when 2 then\n result = 5\n else\n result = 6\n end\nelse\n result = 7\nend\n",
"RawParseTree" => [:block,
[:lasgn, :var1, [:lit, 1]],
[:lasgn, :var2, [:lit, 2]],
[:lasgn, :result, [:nil]],
[:case,
[:lvar, :var1],
[:when, [:array, [:lit, 1]],
[:case,
[:lvar, :var2],
[:when, [:array, [:lit, 1]],
[:lasgn, :result, [:lit, 1]]],
[:when, [:array, [:lit, 2]],
[:lasgn, :result, [:lit, 2]]],
[:lasgn, :result, [:lit, 3]]]],
[:when, [:array, [:lit, 2]],
[:case,
[:lvar, :var2],
[:when, [:array, [:lit, 1]],
[:lasgn, :result, [:lit, 4]]],
[:when, [:array, [:lit, 2]],
[:lasgn, :result, [:lit, 5]]],
[:lasgn, :result, [:lit, 6]]]],
[:lasgn, :result, [:lit, 7]]]],
"ParseTree" => s(:block,
s(:lasgn, :var1, s(:lit, 1)),
s(:lasgn, :var2, s(:lit, 2)),
s(:lasgn, :result, s(:nil)),
s(:case,
s(:lvar, :var1),
s(:when, s(:array, s(:lit, 1)),
s(:case,
s(:lvar, :var2),
s(:when, s(:array, s(:lit, 1)),
s(:lasgn, :result, s(:lit, 1))),
s(:when, s(:array, s(:lit, 2)),
s(:lasgn, :result, s(:lit, 2))),
s(:lasgn, :result, s(:lit, 3)))),
s(:when, s(:array, s(:lit, 2)),
s(:case,
s(:lvar, :var2),
s(:when, s(:array, s(:lit, 1)),
s(:lasgn, :result, s(:lit, 4))),
s(:when, s(:array, s(:lit, 2)),
s(:lasgn, :result, s(:lit, 5))),
s(:lasgn, :result, s(:lit, 6)))),
s(:lasgn, :result, s(:lit, 7)))))
add_tests("case_nested_inner_no_expr",
"Ruby" => "case a\nwhen b then\n case\n when (d and e) then\n f\n else\n # do nothing\n end\nelse\n # do nothing\nend",
"RawParseTree" => [:case, [:vcall, :a],
[:when, [:array, [:vcall, :b]],
[:case, nil,
[:when,
[:array, [:and, [:vcall, :d], [:vcall, :e]]],
[:vcall, :f]],
nil]],
nil],
"ParseTree" => s(:case, s(:call, nil, :a, s(:arglist)),
s(:when,
s(:array, s(:call, nil, :b, s(:arglist))),
s(:case, nil,
s(:when,
s(:array,
s(:and,
s(:call, nil, :d, s(:arglist)),
s(:call, nil, :e, s(:arglist)))),
s(:call, nil, :f, s(:arglist))),
nil)),
nil))
add_tests("case_no_expr",
"Ruby" => "case\nwhen (a == 1) then\n :a\nwhen (a == 2) then\n :b\nelse\n :c\nend",
"RawParseTree" => [:case, nil,
[:when,
[:array,
[:call, [:vcall, :a], :==,
[:array, [:lit, 1]]]],
[:lit, :a]],
[:when,
[:array,
[:call, [:vcall, :a], :==,
[:array, [:lit, 2]]]],
[:lit, :b]],
[:lit, :c]],
"ParseTree" => s(:case, nil,
s(:when,
s(:array,
s(:call,
s(:call, nil, :a, s(:arglist)),
:==,
s(:arglist, s(:lit, 1)))),
s(:lit, :a)),
s(:when,
s(:array,
s(:call,
s(:call, nil, :a, s(:arglist)),
:==,
s(:arglist, s(:lit, 2)))),
s(:lit, :b)),
s(:lit, :c)))
add_tests("case_splat",
"Ruby" => "case a\nwhen :b, *c then\n d\nelse\n e\nend",
"RawParseTree" => [:case, [:vcall, :a],
[:when,
[:array,
[:lit, :b], [:when, [:vcall, :c], nil]], # wtf?
[:vcall, :d]],
[:vcall, :e]],
"ParseTree" => s(:case, s(:call, nil, :a, s(:arglist)),
s(:when,
s(:array,
s(:lit, :b),
s(:when,
s(:call, nil, :c, s(:arglist)),
nil)), # wtf?
s(:call, nil, :d, s(:arglist))),
s(:call, nil, :e, s(:arglist))))
add_tests("cdecl",
"Ruby" => "X = 42",
"RawParseTree" => [:cdecl, :X, [:lit, 42]],
"ParseTree" => s(:cdecl, :X, s(:lit, 42)))
add_tests("class_plain",
"Ruby" => "class X\n puts((1 + 1))\n def blah\n puts(\"hello\")\n end\nend",
"RawParseTree" => [:class,
:X,
nil,
[:scope,
[:block,
[:fcall, :puts,
[:array,
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]]]],
[:defn, :blah,
[:scope,
[:block,
[:args],
[:fcall, :puts,
[:array, [:str, "hello"]]]]]]]]],
"ParseTree" => s(:class,
:X,
nil,
s(:scope,
s(:block,
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))))),
s(:defn, :blah,
s(:args),
s(:scope,
s(:block,
s(:call, nil, :puts,
s(:arglist,
s(:str, "hello"))))))))))
add_tests("class_scoped",
"Ruby" => "class X::Y\n c\nend",
"RawParseTree" => [:class, [:colon2, [:const, :X], :Y], nil,
[:scope, [:vcall, :c]]],
"ParseTree" => s(:class, s(:colon2, s(:const, :X), :Y), nil,
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("class_scoped3",
"Ruby" => "class ::Y\n c\nend",
"RawParseTree" => [:class, [:colon3, :Y], nil,
[:scope, [:vcall, :c]]],
"ParseTree" => s(:class, s(:colon3, :Y), nil,
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("class_super_array",
"Ruby" => "class X < Array\nend",
"RawParseTree" => [:class,
:X,
[:const, :Array],
[:scope]],
"ParseTree" => s(:class,
:X,
s(:const, :Array),
s(:scope)))
add_tests("class_super_expr",
"Ruby" => "class X < expr\nend",
"RawParseTree" => [:class,
:X,
[:vcall, :expr],
[:scope]],
"ParseTree" => s(:class,
:X,
s(:call, nil, :expr, s(:arglist)),
s(:scope)))
add_tests("class_super_object",
"Ruby" => "class X < Object\nend",
"RawParseTree" => [:class,
:X,
[:const, :Object],
[:scope]],
"ParseTree" => s(:class,
:X,
s(:const, :Object),
s(:scope)))
add_tests("colon2",
"Ruby" => "X::Y",
"RawParseTree" => [:colon2, [:const, :X], :Y],
"ParseTree" => s(:colon2, s(:const, :X), :Y))
add_tests("colon3",
"Ruby" => "::X",
"RawParseTree" => [:colon3, :X],
"ParseTree" => s(:colon3, :X))
add_tests("const",
"Ruby" => "X",
"RawParseTree" => [:const, :X],
"ParseTree" => s(:const, :X))
add_tests("constX",
"Ruby" => "X = 1",
"RawParseTree" => [:cdecl, :X, [:lit, 1]],
"ParseTree" => s(:cdecl, :X, s(:lit, 1)))
add_tests("constY",
"Ruby" => "::X = 1",
"RawParseTree" => [:cdecl, [:colon3, :X], [:lit, 1]],
"ParseTree" => s(:cdecl, s(:colon3, :X), s(:lit, 1)))
add_tests("constZ",
"Ruby" => "X::Y = 1",
"RawParseTree" => [:cdecl, [:colon2, [:const, :X], :Y], [:lit, 1]],
"ParseTree" => s(:cdecl,
s(:colon2, s(:const, :X), :Y),
s(:lit, 1)))
add_tests("cvar",
"Ruby" => "@@x",
"RawParseTree" => [:cvar, :@@x],
"ParseTree" => s(:cvar, :@@x))
add_tests("cvasgn",
"Ruby" => "def x\n @@blah = 1\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block, [:args],
[:cvasgn, :@@blah, [:lit, 1]]]]],
"ParseTree" => s(:defn, :x,
s(:args),
s(:scope,
s(:block,
s(:cvasgn, :@@blah, s(:lit, 1))))))
add_tests("cvasgn_cls_method",
"Ruby" => "def self.quiet_mode=(boolean)\n @@quiet_mode = boolean\nend",
"RawParseTree" => [:defs, [:self], :quiet_mode=,
[:scope,
[:block,
[:args, :boolean],
[:cvasgn, :@@quiet_mode, [:lvar, :boolean]]]]],
"ParseTree" => s(:defs, s(:self), :quiet_mode=,
s(:args, :boolean),
s(:scope,
s(:block,
s(:cvasgn, :@@quiet_mode,
s(:lvar, :boolean))))))
add_tests("cvdecl",
"Ruby" => "class X\n @@blah = 1\nend",
"RawParseTree" => [:class, :X, nil,
[:scope, [:cvdecl, :@@blah, [:lit, 1]]]],
"ParseTree" => s(:class, :X, nil,
s(:scope, s(:cvdecl, :@@blah, s(:lit, 1)))))
add_tests("dasgn_0",
"Ruby" => "a.each { |x| b.each { |y| x = (x + 1) } if true }",
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :each],
[:dasgn_curr, :x],
[:if, [:true],
[:iter,
[:call, [:vcall, :b], :each],
[:dasgn_curr, :y],
[:dasgn, :x,
[:call, [:dvar, :x], :+,
[:array, [:lit, 1]]]]],
nil]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a, s(:arglist)), :each,
s(:arglist)),
s(:lasgn, :x),
s(:if, s(:true),
s(:iter,
s(:call, s(:call, nil, :b, s(:arglist)),
:each,
s(:arglist)),
s(:lasgn, :y),
s(:lasgn, :x,
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1))))),
nil)))
add_tests("dasgn_1",
"Ruby" => "a.each { |x| b.each { |y| c = (c + 1) } if true }",
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :each],
[:dasgn_curr, :x],
[:if, [:true],
[:iter,
[:call, [:vcall, :b], :each],
[:dasgn_curr, :y],
[:dasgn_curr, :c,
[:call, [:dvar, :c], :+,
[:array, [:lit, 1]]]]],
nil]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a, s(:arglist)), :each,
s(:arglist)),
s(:lasgn, :x),
s(:if, s(:true),
s(:iter,
s(:call, s(:call, nil, :b, s(:arglist)),
:each,
s(:arglist)),
s(:lasgn, :y),
s(:lasgn, :c,
s(:call, s(:lvar, :c), :+,
s(:arglist, s(:lit, 1))))),
nil)))
add_tests("dasgn_2",
"Ruby" => "a.each do |x|\n if true then\n c = 0\n b.each { |y| c = (c + 1) }\n end\nend", # FIX: hate that extra newline!
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :each],
[:dasgn_curr, :x],
[:if, [:true],
[:block,
[:dasgn_curr, :c, [:lit, 0]],
[:iter,
[:call, [:vcall, :b], :each],
[:dasgn_curr, :y],
[:dasgn, :c,
[:call, [:dvar, :c], :+,
[:array, [:lit, 1]]]]]],
nil]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a, s(:arglist)), :each,
s(:arglist)),
s(:lasgn, :x),
s(:if, s(:true),
s(:block,
s(:lasgn, :c, s(:lit, 0)),
s(:iter,
s(:call, s(:call, nil, :b, s(:arglist)),
:each,
s(:arglist)),
s(:lasgn, :y),
s(:lasgn, :c,
s(:call, s(:lvar, :c), :+,
s(:arglist, s(:lit, 1)))))),
nil)))
add_tests("dasgn_curr",
"Ruby" => "data.each do |x, y|\n a = 1\n b = a\n b = a = x\nend",
"RawParseTree" => [:iter,
[:call, [:vcall, :data], :each],
[:masgn,
[:array, [:dasgn_curr, :x], [:dasgn_curr, :y]]],
[:block,
[:dasgn_curr, :a, [:lit, 1]],
[:dasgn_curr, :b, [:dvar, :a]],
[:dasgn_curr, :b,
[:dasgn_curr, :a, [:dvar, :x]]]]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :data,
s(:arglist)), :each, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :x), s(:lasgn, :y))),
s(:block,
s(:lasgn, :a, s(:lit, 1)),
s(:lasgn, :b, s(:lvar, :a)),
s(:lasgn, :b, s(:lasgn, :a, s(:lvar, :x))))))
add_tests("dasgn_icky",
"Ruby" => "a do\n v = nil\n assert_block(full_message) do\n begin\n yield\n rescue Exception => v\n break\n end\n end\nend",
"RawParseTree" => [:iter,
[:fcall, :a],
nil,
[:block,
[:dasgn_curr, :v, [:nil]],
[:iter,
[:fcall, :assert_block,
[:array, [:vcall, :full_message]]],
nil,
[:begin,
[:rescue,
[:yield],
[:resbody,
[:array, [:const, :Exception]],
[:block,
[:dasgn, :v,
[:gvar, :$!]], [:break]]]]]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
nil,
s(:block,
s(:lasgn, :v, s(:nil)),
s(:iter,
s(:call, nil, :assert_block,
s(:arglist,
s(:call, nil, :full_message,
s(:arglist)))),
nil,
s(:rescue,
s(:yield),
s(:resbody,
s(:array,
s(:const, :Exception),
s(:lasgn, :v, s(:gvar, :$!))),
s(:break)))))))
add_tests("dasgn_mixed",
"Ruby" => "t = 0\nns.each { |n| t += n }\n",
"RawParseTree" => [:block,
[:lasgn, :t, [:lit, 0]],
[:iter,
[:call, [:vcall, :ns], :each],
[:dasgn_curr, :n],
[:lasgn, :t,
[:call, [:lvar, :t], :+,
[:array, [:dvar, :n]]]]]],
"ParseTree" => s(:block,
s(:lasgn, :t, s(:lit, 0)),
s(:iter,
s(:call, s(:call, nil, :ns,
s(:arglist)), :each, s(:arglist)),
s(:lasgn, :n),
s(:lasgn, :t,
s(:call, s(:lvar, :t), :+,
s(:arglist, s(:lvar, :n)))))),
"Ruby2Ruby" => "t = 0\nns.each { |n| t = (t + n) }\n")
add_tests("defined",
"Ruby" => "defined? $x",
"RawParseTree" => [:defined, [:gvar, :$x]],
"ParseTree" => s(:defined, s(:gvar, :$x)))
# TODO: make all the defn_args* p their arglist
add_tests("defn_args_block",
"Ruby" => "def f(&block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :"&block"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand",
"Ruby" => "def f(mand)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_block",
"Ruby" => "def f(mand, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"&block"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt",
"Ruby" => "def f(mand, opt = 42)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt,
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_block",
"Ruby" => "def f(mand, opt = 42, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt, :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_splat",
"Ruby" => "def f(mand, opt = 42, *rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt, :"*rest",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_splat_block",
"Ruby" => "def f(mand, opt = 42, *rest, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt, :"*rest", :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_splat_no_name",
"Ruby" => "def x(a, b = 42, *)\n # do nothing\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :b, :"*",
[:block, [:lasgn, :b, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :b, :"*",
s(:block, s(:lasgn, :b, s(:lit, 42)))),
s(:scope,
s(:block,
s(:nil)))))
add_tests("defn_args_mand_splat",
"Ruby" => "def f(mand, *rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :"*rest"],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"*rest"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_splat_block",
"Ruby" => "def f(mand, *rest, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :"*rest"],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"*rest", :"&block"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_splat_no_name",
"Ruby" => "def x(a, *args)\n p(a, args)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :"*args"],
[:fcall, :p,
[:array, [:lvar, :a], [:lvar, :args]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :"*args"),
s(:scope,
s(:block,
s(:call, nil, :p,
s(:arglist, s(:lvar, :a), s(:lvar, :args)))))))
add_tests("defn_args_none",
"Ruby" => "def empty\n # do nothing\nend",
"RawParseTree" => [:defn, :empty,
[:scope, [:block, [:args], [:nil]]]],
"ParseTree" => s(:defn, :empty,
s(:args),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt",
"Ruby" => "def f(opt = 42)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt,
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_block",
"Ruby" => "def f(opt = 42, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt, :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_splat",
"Ruby" => "def f(opt = 42, *rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt, :"*rest",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_splat_block",
"Ruby" => "def f(opt = 42, *rest, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt, :"*rest", :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_splat_no_name",
"Ruby" => "def x(b = 42, *)\n # do nothing\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :b, :"*",
[:block, [:lasgn, :b, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :x,
s(:args, :b, :"*",
s(:block, s(:lasgn, :b, s(:lit, 42)))),
s(:scope,
s(:block,
s(:nil)))))
add_tests("defn_args_splat",
"Ruby" => "def f(*rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :"*rest"],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :"*rest"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_splat_no_name",
"Ruby" => "def x(*)\n # do nothing\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :"*"],
[:nil]]]],
"ParseTree" => s(:defn, :x,
s(:args, :"*"),
s(:scope,
s(:block,
s(:nil)))))
add_tests("defn_or",
"Ruby" => "def |(o)\n # do nothing\nend",
"RawParseTree" => [:defn, :|,
[:scope, [:block, [:args, :o], [:nil]]]],
"ParseTree" => s(:defn, :|,
s(:args, :o),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_rescue",
"Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend",
"RawParseTree" => [:defn, :eql?,
[:scope,
[:block,
[:args, :resource],
[:rescue,
[:call,
[:call, [:self], :uuid],
:==,
[:array,
[:call, [:lvar, :resource], :uuid]]],
[:resbody, nil, [:false]]]]]],
"ParseTree" => s(:defn, :eql?,
s(:args, :resource),
s(:scope,
s(:block,
s(:rescue,
s(:call,
s(:call, s(:self), :uuid, s(:arglist)),
:==,
s(:arglist,
s(:call, s(:lvar, :resource),
:uuid, s(:arglist)))),
s(:resbody, s(:array), s(:false)))))),
"Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend")
add_tests("defn_rescue_mri_verbose_flag",
"Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend",
"RawParseTree" => [:defn, :eql?,
[:scope,
[:block,
[:args, :resource],
[:rescue,
[:call,
[:call, [:self], :uuid],
:==,
[:array,
[:call, [:lvar, :resource], :uuid]]],
[:resbody, nil, [:false]]]]]],
"ParseTree" => s(:defn, :eql?,
s(:args, :resource),
s(:scope,
s(:block,
s(:rescue,
s(:call,
s(:call, s(:self), :uuid, s(:arglist)),
:==,
s(:arglist,
s(:call, s(:lvar, :resource),
:uuid, s(:arglist)))),
s(:resbody, s(:array), s(:false)))))),
"Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend")
add_tests("defn_something_eh",
"Ruby" => "def something?\n # do nothing\nend",
"RawParseTree" => [:defn, :something?,
[:scope, [:block, [:args], [:nil]]]],
"ParseTree" => s(:defn, :something?,
s(:args),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_splat_no_name",
"Ruby" => "def x(a, *)\n p(a)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :"*"],
[:fcall, :p,
[:array, [:lvar, :a]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :"*"),
s(:scope,
s(:block,
s(:call, nil, :p,
s(:arglist, s(:lvar, :a)))))))
add_tests("defn_zarray",
"Ruby" => "def zarray\n a = []\n return a\nend",
"RawParseTree" => [:defn, :zarray,
[:scope,
[:block, [:args],
[:lasgn, :a, [:zarray]],
[:return, [:lvar, :a]]]]],
"ParseTree" => s(:defn, :zarray,
s(:args),
s(:scope,
s(:block,
s(:lasgn, :a, s(:array)),
s(:return, s(:lvar, :a))))))
add_tests("defs",
"Ruby" => "def self.x(y)\n (y + 1)\nend",
"RawParseTree" => [:defs, [:self], :x,
[:scope,
[:block,
[:args, :y],
[:call, [:lvar, :y], :+,
[:array, [:lit, 1]]]]]],
"ParseTree" => s(:defs, s(:self), :x,
s(:args, :y),
s(:scope,
s(:block,
s(:call, s(:lvar, :y), :+,
s(:arglist, s(:lit, 1)))))))
add_tests("defs_empty",
"Ruby" => "def self.empty\n # do nothing\nend",
"RawParseTree" => [:defs, [:self], :empty,
[:scope, [:args]]],
"ParseTree" => s(:defs, s(:self), :empty,
s(:args),
s(:scope, s(:block))))
add_tests("defs_empty_args",
"Ruby" => "def self.empty(*)\n # do nothing\nend",
"RawParseTree" => [:defs, [:self], :empty,
[:scope, [:args, :*]]],
"ParseTree" => s(:defs, s(:self), :empty,
s(:args, :*),
s(:scope, s(:block))))
add_tests("dmethod",
"Ruby" => [Examples, :dmethod_added],
"RawParseTree" => [:defn, :dmethod_added,
[:dmethod,
:a_method,
[:scope,
[:block,
[:args, :x],
[:call, [:lvar, :x], :+,
[:array, [:lit, 1]]]]]]],
"ParseTree" => s(:defn, :dmethod_added,
s(:args, :x),
s(:scope,
s(:block,
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def dmethod_added(x)\n (x + 1)\nend")
add_tests("dot2",
"Ruby" => "(a..b)",
"RawParseTree" => [:dot2, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:dot2,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("dot3",
"Ruby" => "(a...b)",
"RawParseTree" => [:dot3, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:dot3,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("dregx",
"Ruby" => "/x#\{(1 + 1)}y/",
"RawParseTree" => [:dregx, "x",
[:evstr,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
[:str, "y"]],
"ParseTree" => s(:dregx, "x",
s(:evstr,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
s(:str, "y")))
add_tests("dregx_interp",
"Ruby" => "/#\{@rakefile}/",
"RawParseTree" => [:dregx, '', [:evstr, [:ivar, :@rakefile]]],
"ParseTree" => s(:dregx, '', s(:evstr, s(:ivar, :@rakefile))))
add_tests("dregx_interp_empty",
"Ruby" => "/a#\{}b/",
"RawParseTree" => [:dregx, 'a', [:evstr], [:str, "b"]],
"ParseTree" => s(:dregx, 'a', s(:evstr), s(:str, "b")))
add_tests("dregx_n",
"Ruby" => '/#{1}/n',
"RawParseTree" => [:dregx, '', [:evstr, [:lit, 1]], /x/n.options],
"ParseTree" => s(:dregx, '',
s(:evstr, s(:lit, 1)), /x/n.options),
"Ruby2Ruby" => "/#\{1}/") # HACK - need to support regexp flag
add_tests("dregx_once",
"Ruby" => "/x#\{(1 + 1)}y/o",
"RawParseTree" => [:dregx_once, "x",
[:evstr,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
[:str, "y"]],
"ParseTree" => s(:dregx_once, "x",
s(:evstr,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
s(:str, "y")))
add_tests("dregx_once_n_interp",
"Ruby" => "/#\{IAC}#\{SB}/no",
"RawParseTree" => [:dregx_once, '',
[:evstr, [:const, :IAC]],
[:evstr, [:const, :SB]], /x/n.options],
"ParseTree" => s(:dregx_once, '',
s(:evstr, s(:const, :IAC)),
s(:evstr, s(:const, :SB)), /x/n.options),
"Ruby2Ruby" => "/#\{IAC}#\{SB}/o") # HACK
add_tests("dstr",
"Ruby" => "argl = 1\n\"x#\{argl}y\"\n",
"RawParseTree" => [:block,
[:lasgn, :argl, [:lit, 1]],
[:dstr, "x", [:evstr, [:lvar, :argl]],
[:str, "y"]]],
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr, "x", s(:evstr, s(:lvar, :argl)),
s(:str, "y"))))
add_tests("dstr_2",
"Ruby" => "argl = 1\n\"x#\{(\"%.2f\" % 3.14159)}y\"\n",
"RawParseTree" => [:block,
[:lasgn, :argl, [:lit, 1]],
[:dstr,
"x",
[:evstr,
[:call, [:str, "%.2f"], :%,
[:array, [:lit, 3.14159]]]],
[:str, "y"]]],
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr,
"x",
s(:evstr,
s(:call, s(:str, "%.2f"), :%,
s(:arglist, s(:lit, 3.14159)))),
s(:str, "y"))))
add_tests("dstr_3",
"Ruby" => "max = 2\nargl = 1\n\"x#\{(\"%.#\{max}f\" % 3.14159)}y\"\n",
"RawParseTree" => [:block,
[:lasgn, :max, [:lit, 2]],
[:lasgn, :argl, [:lit, 1]],
[:dstr, "x",
[:evstr,
[:call,
[:dstr, "%.",
[:evstr, [:lvar, :max]],
[:str, "f"]],
:%,
[:array, [:lit, 3.14159]]]],
[:str, "y"]]],
"ParseTree" => s(:block,
s(:lasgn, :max, s(:lit, 2)),
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr, "x",
s(:evstr,
s(:call,
s(:dstr, "%.",
s(:evstr, s(:lvar, :max)),
s(:str, "f")),
:%,
s(:arglist, s(:lit, 3.14159)))),
s(:str, "y"))))
add_tests("dstr_concat",
"Ruby" => '"#{22}aa" "cd#{44}" "55" "#{66}"',
"RawParseTree" => [:dstr,
"",
[:evstr, [:lit, 22]],
[:str, "aa"],
[:str, "cd"],
[:evstr, [:lit, 44]],
[:str, "55"],
[:evstr, [:lit, 66]]],
"ParseTree" => s(:dstr,
"",
s(:evstr, s(:lit, 22)),
s(:str, "aa"),
s(:str, "cd"),
s(:evstr, s(:lit, 44)),
s(:str, "55"),
s(:evstr, s(:lit, 66))),
"Ruby2Ruby" => '"#{22}aacd#{44}55#{66}"')
add_tests("dstr_gross",
"Ruby" => '"a #$global b #@ivar c #@@cvar d"',
"RawParseTree" => [:dstr, "a ",
[:evstr, [:gvar, :$global]],
[:str, " b "],
[:evstr, [:ivar, :@ivar]],
[:str, " c "],
[:evstr, [:cvar, :@@cvar]],
[:str, " d"]],
"ParseTree" => s(:dstr, "a ",
s(:evstr, s(:gvar, :$global)),
s(:str, " b "),
s(:evstr, s(:ivar, :@ivar)),
s(:str, " c "),
s(:evstr, s(:cvar, :@@cvar)),
s(:str, " d")),
"Ruby2Ruby" => '"a #{$global} b #{@ivar} c #{@@cvar} d"')
add_tests("dstr_heredoc_expand",
"Ruby" => "<<EOM\n blah\n#\{1 + 1}blah\nEOM\n",
"RawParseTree" => [:dstr, " blah\n",
[:evstr, [:call, [:lit, 1], :+,
[:array, [:lit, 1]]]],
[:str, "blah\n"]],
"ParseTree" => s(:dstr, " blah\n",
s(:evstr, s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
s(:str, "blah\n")),
"Ruby2Ruby" => "\" blah\\n#\{(1 + 1)}blah\\n\"")
add_tests("dstr_heredoc_windoze_sucks",
"Ruby" => "<<-EOF\r\ndef test_#\{action}_valid_feed\r\n EOF\r\n",
"RawParseTree" => [:dstr,
'def test_',
[:evstr, [:vcall, :action]],
[:str, "_valid_feed\n"]],
"ParseTree" => s(:dstr,
'def test_',
s(:evstr, s(:call, nil, :action, s(:arglist))),
s(:str, "_valid_feed\n")),
"Ruby2Ruby" => "\"def test_#\{action}_valid_feed\\n\"")
add_tests("dstr_heredoc_yet_again",
"Ruby" => "<<-EOF\ns1 '#\{RUBY_PLATFORM}' s2\n#\{__FILE__}\n EOF\n",
"RawParseTree" => [:dstr, "s1 '",
[:evstr, [:const, :RUBY_PLATFORM]],
[:str, "' s2\n"],
[:str, "(string)"],
[:str, "\n"]],
"ParseTree" => s(:dstr, "s1 '",
s(:evstr, s(:const, :RUBY_PLATFORM)),
s(:str, "' s2\n"),
s(:str, "(string)"),
s(:str, "\n")),
"Ruby2Ruby" => "\"s1 '#\{RUBY_PLATFORM}' s2\\n(string)\\n\"")
add_tests("dstr_nest",
"Ruby" => "%Q[before [#\{nest}] after]",
"RawParseTree" => [:dstr, "before [",
[:evstr, [:vcall, :nest]], [:str, "] after"]],
"ParseTree" => s(:dstr, "before [",
s(:evstr, s(:call, nil, :nest, s(:arglist))),
s(:str, "] after")),
"Ruby2Ruby" => "\"before [#\{nest}] after\"")
add_tests("dstr_str_lit_start",
"Ruby" => '"#{"blah"}#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})"',
"RawParseTree" => [:dstr,
"blah(string):",
[:evstr, [:lit, 1]],
[:str, ": warning: "],
[:evstr, [:call, [:gvar, :$!], :message]],
[:str, " ("],
[:evstr, [:call, [:gvar, :$!], :class]],
[:str, ")"]],
"ParseTree" => s(:dstr,
"blah(string):",
s(:evstr, s(:lit, 1)),
s(:str, ": warning: "),
s(:evstr, s(:call, s(:gvar, :$!), :message,
s(:arglist))),
s(:str, " ("),
s(:evstr, s(:call, s(:gvar, :$!), :class,
s(:arglist))),
s(:str, ")")),
"Ruby2Ruby" => '"blah(string):#{1}: warning: #{$!.message} (#{$!.class})"')
add_tests("dstr_the_revenge",
"Ruby" => '"before #{from} middle #{to} (#{__FILE__}:#{__LINE__})"',
"RawParseTree" => [:dstr,
"before ",
[:evstr, [:vcall, :from]],
[:str, " middle "],
[:evstr, [:vcall, :to]],
[:str, " ("],
[:str, "(string)"],
[:str, ":"],
[:evstr, [:lit, 1]],
[:str, ")"]],
"ParseTree" => s(:dstr,
"before ",
s(:evstr, s(:call, nil, :from, s(:arglist))),
s(:str, " middle "),
s(:evstr, s(:call, nil, :to, s(:arglist))),
s(:str, " ("),
s(:str, "(string)"),
s(:str, ":"),
s(:evstr, s(:lit, 1)),
s(:str, ")")),
"Ruby2Ruby" => '"before #{from} middle #{to} ((string):#{1})"')
add_tests("dsym",
"Ruby" => ":\"x#\{(1 + 1)}y\"",
"RawParseTree" => [:dsym, "x",
[:evstr, [:call, [:lit, 1], :+,
[:array, [:lit, 1]]]], [:str, "y"]],
"ParseTree" => s(:dsym, "x",
s(:evstr, s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))), s(:str, "y")))
add_tests("dxstr",
"Ruby" => "t = 5\n`touch #\{t}`\n",
"RawParseTree" => [:block,
[:lasgn, :t, [:lit, 5]],
[:dxstr, 'touch ', [:evstr, [:lvar, :t]]]],
"ParseTree" => s(:block,
s(:lasgn, :t, s(:lit, 5)),
s(:dxstr, 'touch ', s(:evstr, s(:lvar, :t)))))
add_tests("ensure",
"Ruby" => "begin\n (1 + 1)\nrescue SyntaxError => e1\n 2\nrescue Exception => e2\n 3\nelse\n 4\nensure\n 5\nend",
"RawParseTree" => [:begin,
[:ensure,
[:rescue,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]],
[:resbody,
[:array, [:const, :SyntaxError]],
[:block,
[:lasgn, :e1, [:gvar, :$!]], [:lit, 2]],
[:resbody,
[:array, [:const, :Exception]],
[:block,
[:lasgn, :e2, [:gvar, :$!]], [:lit, 3]]]],
[:lit, 4]],
[:lit, 5]]],
"ParseTree" => s(:ensure,
s(:rescue,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))),
s(:resbody,
s(:array,
s(:const, :SyntaxError),
s(:lasgn, :e1, s(:gvar, :$!))),
s(:lit, 2)),
s(:resbody,
s(:array,
s(:const, :Exception),
s(:lasgn, :e2, s(:gvar, :$!))),
s(:lit, 3)),
s(:lit, 4)),
s(:lit, 5)))
add_tests("false",
"Ruby" => "false",
"RawParseTree" => [:false],
"ParseTree" => s(:false))
add_tests("fbody",
"Ruby" => [Examples, :an_alias],
"RawParseTree" => [:defn, :an_alias,
[:fbody,
[:scope,
[:block,
[:args, :x],
[:call, [:lvar, :x], :+,
[:array, [:lit, 1]]]]]]],
"ParseTree" => s(:defn, :an_alias,
s(:args, :x),
s(:scope,
s(:block,
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def an_alias(x)\n (x + 1)\nend")
add_tests("fcall_arglist",
"Ruby" => "m(42)",
"RawParseTree" => [:fcall, :m, [:array, [:lit, 42]]],
"ParseTree" => s(:call, nil, :m, s(:arglist, s(:lit, 42))))
add_tests("fcall_arglist_hash",
"Ruby" => "m(:a => 1, :b => 2)",
"RawParseTree" => [:fcall, :m,
[:array,
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call, nil, :m,
s(:arglist,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("fcall_arglist_norm_hash",
"Ruby" => "m(42, :a => 1, :b => 2)",
"RawParseTree" => [:fcall, :m,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call, nil, :m,
s(:arglist,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("fcall_arglist_norm_hash_splat",
"Ruby" => "m(42, :a => 1, :b => 2, *c)",
"RawParseTree" => [:fcall, :m,
[:argscat,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]],
[:vcall, :c]]],
"ParseTree" => s(:call, nil, :m,
s(:argscat,
s(:array,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))),
s(:call, nil, :c, s(:arglist)))))
add_tests("fcall_block",
"Ruby" => "a(:b) { :c }",
"RawParseTree" => [:iter,
[:fcall, :a, [:array, [:lit, :b]]], nil,
[:lit, :c]],
"ParseTree" => s(:iter,
s(:call, nil, :a,
s(:arglist, s(:lit, :b))), nil,
s(:lit, :c)))
add_tests("fcall_index_space",
"Ruby" => "a [42]",
"RawParseTree" => [:fcall, :a, [:array, [:array, [:lit, 42]]]],
"ParseTree" => s(:call, nil, :a,
s(:arglist, s(:array, s(:lit, 42)))),
"Ruby2Ruby" => "a([42])")
add_tests("fcall_keyword",
"Ruby" => "42 if block_given?",
"RawParseTree" => [:if, [:fcall, :block_given?], [:lit, 42], nil],
"ParseTree" => s(:if,
s(:call, nil, :block_given?, s(:arglist)),
s(:lit, 42), nil))
add_tests("flip2",
"Ruby" => "x = if ((i % 4) == 0)..((i % 3) == 0) then\n i\nelse\n nil\nend",
"RawParseTree" => [:lasgn,
:x,
[:if,
[:flip2,
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 4]]],
:==,
[:array, [:lit, 0]]],
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 3]]],
:==,
[:array, [:lit, 0]]]],
[:vcall, :i],
[:nil]]],
"ParseTree" => s(:lasgn,
:x,
s(:if,
s(:flip2,
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 4))),
:==,
s(:arglist, s(:lit, 0))),
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 3))),
:==,
s(:arglist, s(:lit, 0)))),
s(:call, nil, :i, s(:arglist)),
s(:nil))))
add_tests("flip2_method",
"Ruby" => "if 1..2.a?(b) then\n nil\nend",
"RawParseTree" => [:if,
[:flip2,
[:lit, 1],
[:call, [:lit, 2], :a?,
[:array, [:vcall, :b]]]],
[:nil],
nil],
"ParseTree" => s(:if,
s(:flip2,
s(:lit, 1),
s(:call, s(:lit, 2), :a?,
s(:arglist,
s(:call, nil, :b, s(:arglist))))),
s(:nil),
nil))
add_tests("flip3",
"Ruby" => "x = if ((i % 4) == 0)...((i % 3) == 0) then\n i\nelse\n nil\nend",
"RawParseTree" => [:lasgn,
:x,
[:if,
[:flip3,
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 4]]],
:==,
[:array, [:lit, 0]]],
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 3]]],
:==,
[:array, [:lit, 0]]]],
[:vcall, :i],
[:nil]]],
"ParseTree" => s(:lasgn,
:x,
s(:if,
s(:flip3,
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 4))),
:==,
s(:arglist, s(:lit, 0))),
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 3))),
:==,
s(:arglist, s(:lit, 0)))),
s(:call, nil, :i, s(:arglist)),
s(:nil))))
add_tests("for",
"Ruby" => "for o in ary do\n puts(o)\nend",
"RawParseTree" => [:for,
[:vcall, :ary],
[:lasgn, :o],
[:fcall, :puts, [:array, [:lvar, :o]]]],
"ParseTree" => s(:for,
s(:call, nil, :ary, s(:arglist)),
s(:lasgn, :o),
s(:call, nil, :puts,
s(:arglist, s(:lvar, :o)))))
add_tests("for_no_body",
"Ruby" => "for i in (0..max) do\n # do nothing\nend",
"RawParseTree" => [:for,
[:dot2, [:lit, 0], [:vcall, :max]],
[:lasgn, :i]],
"ParseTree" => s(:for,
s(:dot2,
s(:lit, 0),
s(:call, nil, :max, s(:arglist))),
s(:lasgn, :i)))
add_tests("gasgn",
"Ruby" => "$x = 42",
"RawParseTree" => [:gasgn, :$x, [:lit, 42]],
"ParseTree" => s(:gasgn, :$x, s(:lit, 42)))
add_tests("global",
"Ruby" => "$stderr",
"RawParseTree" => [:gvar, :$stderr],
"ParseTree" => s(:gvar, :$stderr))
add_tests("gvar",
"Ruby" => "$x",
"RawParseTree" => [:gvar, :$x],
"ParseTree" => s(:gvar, :$x))
add_tests("gvar_underscore",
"Ruby" => "$_",
"RawParseTree" => [:gvar, :$_],
"ParseTree" => s(:gvar, :$_))
add_tests("gvar_underscore_blah",
"Ruby" => "$__blah",
"RawParseTree" => [:gvar, :$__blah],
"ParseTree" => s(:gvar, :$__blah))
add_tests("hash",
"Ruby" => "{ 1 => 2, 3 => 4 }",
"RawParseTree" => [:hash,
[:lit, 1], [:lit, 2],
[:lit, 3], [:lit, 4]],
"ParseTree" => s(:hash,
s(:lit, 1), s(:lit, 2),
s(:lit, 3), s(:lit, 4)))
add_tests("hash_rescue",
"Ruby" => "{ 1 => (2 rescue 3) }",
"RawParseTree" => [:hash,
[:lit, 1],
[:rescue,
[:lit, 2],
[:resbody, nil, [:lit, 3]]]],
"ParseTree" => s(:hash,
s(:lit, 1),
s(:rescue,
s(:lit, 2),
s(:resbody, s(:array), s(:lit, 3)))))
add_tests("iasgn",
"Ruby" => "@a = 4",
"RawParseTree" => [:iasgn, :@a, [:lit, 4]],
"ParseTree" => s(:iasgn, :@a, s(:lit, 4)))
add_tests("if_block_condition",
"Ruby" => "if (x = 5\n(x + 1)) then\n nil\nend",
"RawParseTree" => [:if,
[:block,
[:lasgn, :x, [:lit, 5]],
[:call,
[:lvar, :x],
:+,
[:array, [:lit, 1]]]],
[:nil],
nil],
"ParseTree" => s(:if,
s(:block,
s(:lasgn, :x, s(:lit, 5)),
s(:call,
s(:lvar, :x),
:+,
s(:arglist, s(:lit, 1)))),
s(:nil),
nil))
add_tests("if_lasgn_short",
"Ruby" => "if x = obj.x then\n x.do_it\nend",
"RawParseTree" => [:if,
[:lasgn, :x,
[:call, [:vcall, :obj], :x]],
[:call,
[:lvar, :x], :do_it],
nil],
"ParseTree" => s(:if,
s(:lasgn, :x,
s(:call,
s(:call, nil, :obj, s(:arglist)),
:x, s(:arglist))),
s(:call, s(:lvar, :x), :do_it, s(:arglist)),
nil))
add_tests("if_nested",
"Ruby" => "return if false unless true",
"RawParseTree" => [:if, [:true], nil,
[:if, [:false], [:return], nil]],
"ParseTree" => s(:if, s(:true), nil,
s(:if, s(:false), s(:return), nil)))
add_tests("if_post",
"Ruby" => "a if b",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil))
add_tests("if_post_not",
"Ruby" => "a if not b",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))),
"Ruby2Ruby" => "a unless b")
add_tests("if_pre",
"Ruby" => "if b then a end",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil),
"Ruby2Ruby" => "a if b")
add_tests("if_pre_not",
"Ruby" => "if not b then a end",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))),
"Ruby2Ruby" => "a unless b")
add_tests("iter_call_arglist_space",
"Ruby" => "a (1) {|c|d}",
"RawParseTree" => [:iter,
[:fcall, :a, [:array, [:lit, 1]]],
[:dasgn_curr, :c],
[:vcall, :d]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist, s(:lit, 1))),
s(:lasgn, :c),
s(:call, nil, :d, s(:arglist))),
"Ruby2Ruby" => "a(1) { |c| d }")
add_tests("iter_dasgn_curr_dasgn_madness",
"Ruby" => "as.each { |a|\n b += a.b(false) }",
"RawParseTree" => [:iter,
[:call, [:vcall, :as], :each],
[:dasgn_curr, :a],
[:dasgn_curr,
:b,
[:call,
[:dvar, :b],
:+,
[:array,
[:call, [:dvar, :a], :b,
[:array, [:false]]]]]]],
"ParseTree" => s(:iter,
s(:call,
s(:call, nil, :as, s(:arglist)),
:each, s(:arglist)),
s(:lasgn, :a),
s(:lasgn, :b,
s(:call,
s(:lvar, :b),
:+,
s(:arglist,
s(:call, s(:lvar, :a), :b,
s(:arglist, s(:false))))))),
"Ruby2Ruby" => "as.each { |a| b = (b + a.b(false)) }")
add_tests("iter_downto",
"Ruby" => "3.downto(1) { |n| puts(n.to_s) }",
"RawParseTree" => [:iter,
[:call, [:lit, 3], :downto, [:array, [:lit, 1]]],
[:dasgn_curr, :n],
[:fcall, :puts,
[:array, [:call, [:dvar, :n], :to_s]]]],
"ParseTree" => s(:iter,
s(:call, s(:lit, 3), :downto,
s(:arglist, s(:lit, 1))),
s(:lasgn, :n),
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :n),
:to_s, s(:arglist))))))
add_tests("iter_each_lvar",
"Ruby" => "array = [1, 2, 3]\narray.each { |x| puts(x.to_s) }\n",
"RawParseTree" => [:block,
[:lasgn, :array,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
[:iter,
[:call, [:lvar, :array], :each],
[:dasgn_curr, :x],
[:fcall, :puts,
[:array, [:call, [:dvar, :x], :to_s]]]]],
"ParseTree" => s(:block,
s(:lasgn, :array,
s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
s(:iter,
s(:call, s(:lvar, :array), :each,
s(:arglist)),
s(:lasgn, :x),
s(:call, nil, :puts,
s(:arglist, s(:call, s(:lvar, :x),
:to_s, s(:arglist)))))))
add_tests("iter_each_nested",
"Ruby" => "array1 = [1, 2, 3]\narray2 = [4, 5, 6, 7]\narray1.each do |x|\n array2.each do |y|\n puts(x.to_s)\n puts(y.to_s)\n end\nend\n",
"RawParseTree" => [:block,
[:lasgn, :array1,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
[:lasgn, :array2,
[:array,
[:lit, 4], [:lit, 5], [:lit, 6], [:lit, 7]]],
[:iter,
[:call,
[:lvar, :array1], :each],
[:dasgn_curr, :x],
[:iter,
[:call,
[:lvar, :array2], :each],
[:dasgn_curr, :y],
[:block,
[:fcall, :puts,
[:array, [:call, [:dvar, :x], :to_s]]],
[:fcall, :puts,
[:array, [:call, [:dvar, :y], :to_s]]]]]]],
"ParseTree" => s(:block,
s(:lasgn, :array1,
s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
s(:lasgn, :array2,
s(:array,
s(:lit, 4), s(:lit, 5),
s(:lit, 6), s(:lit, 7))),
s(:iter,
s(:call,
s(:lvar, :array1), :each, s(:arglist)),
s(:lasgn, :x),
s(:iter,
s(:call,
s(:lvar, :array2), :each, s(:arglist)),
s(:lasgn, :y),
s(:block,
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :x),
:to_s, s(:arglist)))),
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :y),
:to_s, s(:arglist)))))))))
add_tests("iter_loop_empty",
"Ruby" => "loop { }",
"RawParseTree" => [:iter, [:fcall, :loop], nil],
"ParseTree" => s(:iter, s(:call, nil, :loop, s(:arglist)), nil))
add_tests("iter_masgn_2",
"Ruby" => "a { |b, c| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:array, [:dasgn_curr, :b], [:dasgn_curr, :c]]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :b), s(:lasgn, :c))),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_args_splat",
"Ruby" => "a { |b, c, *d| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:array, [:dasgn_curr, :b], [:dasgn_curr, :c]],
[:dasgn_curr, :d]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :b), s(:lasgn, :c)),
s(:lasgn, :d)),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_args_splat_no_name",
"Ruby" => "a { |b, c, *| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:array, [:dasgn_curr, :b], [:dasgn_curr, :c]],
[:splat]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :b), s(:lasgn, :c)),
s(:splat)),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_splat",
"Ruby" => "a { |*c| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn, [:dasgn_curr, :c]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn, s(:lasgn, :c)),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_splat_no_name",
"Ruby" => "a { |*| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:splat]],
[:fcall, :p, [:array, [:vcall, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:splat)),
s(:call, nil, :p,
s(:arglist, s(:call, nil, :c, s(:arglist))))))
add_tests("iter_shadowed_var",
"Ruby" => "a do |x|\n b do |x|\n puts x\n end\nend",
"RawParseTree" => [:iter,
[:fcall, :a],
[:dasgn_curr, :x],
[:iter,
[:fcall, :b],
[:dasgn, :x],
[:fcall, :puts, [:array, [:dvar, :x]]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:lasgn, :x),
s(:iter,
s(:call, nil, :b, s(:arglist)),
s(:lasgn, :x),
s(:call, nil, :puts,
s(:arglist, s(:lvar, :x))))),
"Ruby2Ruby" => "a { |x| b { |x| puts(x) } }")
add_tests("iter_upto",
"Ruby" => "1.upto(3) { |n| puts(n.to_s) }",
"RawParseTree" => [:iter,
[:call, [:lit, 1], :upto, [:array, [:lit, 3]]],
[:dasgn_curr, :n],
[:fcall, :puts,
[:array, [:call, [:dvar, :n], :to_s]]]],
"ParseTree" => s(:iter,
s(:call, s(:lit, 1), :upto,
s(:arglist, s(:lit, 3))),
s(:lasgn, :n),
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :n), :to_s,
s(:arglist))))))
add_tests("iter_while",
"Ruby" => "argl = 10\nwhile (argl >= 1) do\n puts(\"hello\")\n argl = (argl - 1)\nend\n",
"RawParseTree" => [:block,
[:lasgn, :argl, [:lit, 10]],
[:while,
[:call, [:lvar, :argl], :">=",
[:array, [:lit, 1]]],
[:block,
[:fcall, :puts, [:array, [:str, "hello"]]],
[:lasgn,
:argl,
[:call, [:lvar, :argl],
:"-", [:array, [:lit, 1]]]]], true]],
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 10)),
s(:while,
s(:call, s(:lvar, :argl), :">=",
s(:arglist, s(:lit, 1))),
s(:block,
s(:call, nil, :puts,
s(:arglist, s(:str, "hello"))),
s(:lasgn,
:argl,
s(:call, s(:lvar, :argl), :"-",
s(:arglist, s(:lit, 1))))), true)))
add_tests("ivar",
"Ruby" => [Examples, :reader],
"RawParseTree" => [:defn, :reader, [:ivar, :@reader]],
"ParseTree" => s(:defn, :reader, # FIX should be unified?
s(:args),
s(:ivar, :@reader)),
"Ruby2Ruby" => "attr_reader :reader")
add_tests("lasgn_array",
"Ruby" => "var = [\"foo\", \"bar\"]",
"RawParseTree" => [:lasgn, :var,
[:array,
[:str, "foo"],
[:str, "bar"]]],
"ParseTree" => s(:lasgn, :var,
s(:array,
s(:str, "foo"),
s(:str, "bar"))))
add_tests("lasgn_call",
"Ruby" => "c = (2 + 3)",
"RawParseTree" => [:lasgn, :c, [:call, [:lit, 2], :+,
[:array, [:lit, 3]]]],
"ParseTree" => s(:lasgn, :c, s(:call, s(:lit, 2), :+,
s(:arglist, s(:lit, 3)))))
add_tests("lit_bool_false",
"Ruby" => "false",
"RawParseTree" => [:false],
"ParseTree" => s(:false))
add_tests("lit_bool_true",
"Ruby" => "true",
"RawParseTree" => [:true],
"ParseTree" => s(:true))
add_tests("lit_float",
"Ruby" => "1.1",
"RawParseTree" => [:lit, 1.1],
"ParseTree" => s(:lit, 1.1))
add_tests("lit_long",
"Ruby" => "1",
"RawParseTree" => [:lit, 1],
"ParseTree" => s(:lit, 1))
add_tests("lit_long_negative",
"Ruby" => "-1",
"RawParseTree" => [:lit, -1],
"ParseTree" => s(:lit, -1))
add_tests("lit_range2",
"Ruby" => "(1..10)",
"RawParseTree" => [:lit, 1..10],
"ParseTree" => s(:lit, 1..10))
add_tests("lit_range3",
"Ruby" => "(1...10)",
"RawParseTree" => [:lit, 1...10],
"ParseTree" => s(:lit, 1...10))
# TODO: discuss and decide which lit we like
# it "converts a regexp to an sexp" do
# "/blah/".to_sexp.should == s(:regex, "blah", 0)
# "/blah/i".to_sexp.should == s(:regex, "blah", 1)
# "/blah/u".to_sexp.should == s(:regex, "blah", 64)
# end
add_tests("lit_regexp",
"Ruby" => "/x/",
"RawParseTree" => [:lit, /x/],
"ParseTree" => s(:lit, /x/))
add_tests("lit_regexp_i_wwtt",
"Ruby" => 'str.split(//i)',
"RawParseTree" => [:call, [:vcall, :str], :split,
[:array, [:lit, //i]]],
"ParseTree" => s(:call, s(:call, nil, :str, s(:arglist)), :split,
s(:arglist, s(:lit, //i))))
add_tests("lit_regexp_n",
"Ruby" => "/x/n", # HACK differs on 1.9 - this is easiest
"RawParseTree" => [:lit, /x/n],
"ParseTree" => s(:lit, /x/n),
"Ruby2Ruby" => /x/n.inspect)
add_tests("lit_regexp_once",
"Ruby" => "/x/o",
"RawParseTree" => [:lit, /x/],
"ParseTree" => s(:lit, /x/),
"Ruby2Ruby" => "/x/")
add_tests("lit_sym",
"Ruby" => ":x",
"RawParseTree" => [:lit, :x],
"ParseTree" => s(:lit, :x))
add_tests("lit_sym_splat",
"Ruby" => ":\"*args\"",
"RawParseTree" => [:lit, :"*args"],
"ParseTree" => s(:lit, :"*args"))
add_tests("lvar_def_boundary",
"Ruby" => "b = 42\ndef a\n c do\n begin\n do_stuff\n rescue RuntimeError => b\n puts(b)\n end\n end\nend\n",
"RawParseTree" => [:block,
[:lasgn, :b, [:lit, 42]],
[:defn, :a,
[:scope,
[:block,
[:args],
[:iter,
[:fcall, :c],
nil,
[:begin,
[:rescue,
[:vcall, :do_stuff],
[:resbody,
[:array, [:const, :RuntimeError]],
[:block,
[:dasgn_curr, :b, [:gvar, :$!]],
[:fcall, :puts,
[:array, [:dvar, :b]]]]]]]]]]]],
"ParseTree" => s(:block,
s(:lasgn, :b, s(:lit, 42)),
s(:defn, :a,
s(:args),
s(:scope,
s(:block,
s(:iter,
s(:call, nil, :c, s(:arglist)),
nil,
s(:rescue,
s(:call, nil, :do_stuff, s(:arglist)),
s(:resbody,
s(:array,
s(:const, :RuntimeError),
s(:lasgn, :b, s(:gvar, :$!))),
s(:call, nil, :puts,
s(:arglist,
s(:lvar, :b)))))))))))
add_tests("masgn",
"Ruby" => "a, b = c, d",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:array, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:array, s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))))
add_tests("masgn_argscat",
"Ruby" => "a, b, *c = 1, 2, *[3, 4]",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:argscat,
[:array, [:lit, 1], [:lit, 2]],
[:array, [:lit, 3], [:lit, 4]]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:argscat,
s(:array, s(:lit, 1), s(:lit, 2)),
s(:array, s(:lit, 3), s(:lit, 4)))))
add_tests("masgn_attrasgn",
"Ruby" => "a, b.c = d, e",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a],
[:attrasgn, [:vcall, :b], :c=]],
[:array, [:vcall, :d], [:vcall, :e]]],
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:attrasgn,
s(:call, nil, :b, s(:arglist)),
:c=, s(:arglist))),
s(:array,
s(:call, nil, :d, s(:arglist)),
s(:call, nil, :e, s(:arglist)))))
add_tests("masgn_attrasgn_array_rhs",
"Ruby" => "a.b, a.c, _ = q",
"RawParseTree" => [:masgn,
[:array,
[:attrasgn, [:vcall, :a], :b=],
[:attrasgn, [:vcall, :a], :c=],
[:lasgn, :_]],
[:to_ary, [:vcall, :q]]],
"ParseTree" => s(:masgn,
s(:array,
s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:b=, s(:arglist)),
s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:c=, s(:arglist)),
s(:lasgn, :_)),
s(:to_ary,
s(:call, nil, :q, s(:arglist)))))
add_tests("masgn_attrasgn_idx",
"Ruby" => "a, i, j = [], 1, 2\na[i], a[j] = a[j], a[i]\n",
"RawParseTree" => [:block,
[:masgn,
[:array,
[:lasgn, :a], [:lasgn, :i], [:lasgn, :j]],
[:array, [:zarray], [:lit, 1], [:lit, 2]]],
[:masgn,
[:array,
[:attrasgn,
[:lvar, :a], :[]=, [:array, [:lvar, :i]]],
[:attrasgn,
[:lvar, :a], :[]=, [:array, [:lvar, :j]]]],
[:array,
[:call, [:lvar, :a], :[],
[:array, [:lvar, :j]]],
[:call, [:lvar, :a], :[],
[:array, [:lvar, :i]]]]]],
"ParseTree" => s(:block,
s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :i), s(:lasgn, :j)),
s(:array, s(:array), s(:lit, 1), s(:lit, 2))),
s(:masgn,
s(:array,
s(:attrasgn, s(:lvar, :a), :[]=,
s(:arglist, s(:lvar, :i))),
s(:attrasgn, s(:lvar, :a), :[]=,
s(:arglist, s(:lvar, :j)))),
s(:array,
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lvar, :j))),
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lvar, :i)))))))
add_tests("masgn_cdecl",
"Ruby" => "A, B, C = 1, 2, 3",
"RawParseTree" => [:masgn,
[:array, [:cdecl, :A], [:cdecl, :B],
[:cdecl, :C]],
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
"ParseTree" => s(:masgn,
s(:array, s(:cdecl, :A), s(:cdecl, :B),
s(:cdecl, :C)),
s(:array, s(:lit, 1), s(:lit, 2), s(:lit, 3))))
add_tests("masgn_iasgn",
"Ruby" => "a, @b = c, d",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:iasgn, :"@b"]],
[:array, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:iasgn, :"@b")),
s(:array,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))))
add_tests("masgn_masgn",
"Ruby" => "a, (b, c) = [1, [2, 3]]",
"RawParseTree" => [:masgn,
[:array,
[:lasgn, :a],
[:masgn,
[:array,
[:lasgn, :b],
[:lasgn, :c]]]],
[:to_ary,
[:array,
[:lit, 1],
[:array,
[:lit, 2],
[:lit, 3]]]]],
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:masgn,
s(:array,
s(:lasgn, :b),
s(:lasgn, :c)))),
s(:to_ary,
s(:array,
s(:lit, 1),
s(:array,
s(:lit, 2),
s(:lit, 3))))))
add_tests("masgn_splat",
"Ruby" => "a, b, *c = d, e, f, g",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:array,
[:vcall, :d], [:vcall, :e],
[:vcall, :f], [:vcall, :g]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:array,
s(:call, nil, :d, s(:arglist)),
s(:call, nil, :e, s(:arglist)),
s(:call, nil, :f, s(:arglist)),
s(:call, nil, :g, s(:arglist)))))
add_tests("masgn_splat_no_name_to_ary",
"Ruby" => "a, b, * = c",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:splat],
[:to_ary, [:vcall, :c]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:splat),
s(:to_ary, s(:call, nil, :c, s(:arglist)))))
add_tests("masgn_splat_no_name_trailing",
"Ruby" => "a, b, = c",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:to_ary, [:vcall, :c]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:to_ary, s(:call, nil, :c, s(:arglist)))),
"Ruby2Ruby" => "a, b = c") # TODO: check this is right
add_tests("masgn_splat_to_ary",
"Ruby" => "a, b, *c = d",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:to_ary, [:vcall, :d]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:to_ary, s(:call, nil, :d, s(:arglist)))))
add_tests("masgn_splat_to_ary2",
"Ruby" => "a, b, *c = d.e(\"f\")",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:to_ary,
[:call, [:vcall, :d], :e,
[:array, [:str, 'f']]]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:to_ary,
s(:call,
s(:call, nil, :d, s(:arglist)),
:e,
s(:arglist, s(:str, 'f'))))))
add_tests("match",
"Ruby" => "1 if /x/",
"RawParseTree" => [:if, [:match, [:lit, /x/]], [:lit, 1], nil],
"ParseTree" => s(:if, s(:match, s(:lit, /x/)), s(:lit, 1), nil))
add_tests("match2",
"Ruby" => "/x/ =~ \"blah\"",
"RawParseTree" => [:match2, [:lit, /x/], [:str, "blah"]],
"ParseTree" => s(:match2, s(:lit, /x/), s(:str, "blah")))
add_tests("match3",
"Ruby" => "\"blah\" =~ /x/",
"RawParseTree" => [:match3, [:lit, /x/], [:str, "blah"]],
"ParseTree" => s(:match3, s(:lit, /x/), s(:str, "blah")))
add_tests("module",
"Ruby" => "module X\n def y\n # do nothing\n end\nend",
"RawParseTree" => [:module, :X,
[:scope,
[:defn, :y,
[:scope, [:block, [:args], [:nil]]]]]],
"ParseTree" => s(:module, :X,
s(:scope,
s(:defn, :y,
s(:args),
s(:scope, s(:block, s(:nil)))))))
add_tests("module_scoped",
"Ruby" => "module X::Y\n c\nend",
"RawParseTree" => [:module, [:colon2, [:const, :X], :Y],
[:scope, [:vcall, :c]]],
"ParseTree" => s(:module, s(:colon2, s(:const, :X), :Y),
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("module_scoped3",
"Ruby" => "module ::Y\n c\nend",
"RawParseTree" => [:module, [:colon3, :Y], [:scope, [:vcall, :c]]],
"ParseTree" => s(:module,
s(:colon3, :Y),
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("next",
"Ruby" => "loop { next if false }",
"RawParseTree" => [:iter,
[:fcall, :loop],
nil,
[:if, [:false], [:next], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)),
nil,
s(:if, s(:false), s(:next), nil)))
add_tests("next_arg",
"Ruby" => "loop { next 42 if false }",
"RawParseTree" => [:iter,
[:fcall, :loop],
nil,
[:if, [:false], [:next, [:lit, 42]], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)),
nil,
s(:if, s(:false), s(:next, s(:lit, 42)), nil)))
add_tests("not",
"Ruby" => "(not true)",
"RawParseTree" => [:not, [:true]],
"ParseTree" => s(:not, s(:true)))
add_tests("nth_ref",
"Ruby" => "$1",
"RawParseTree" => [:nth_ref, 1],
"ParseTree" => s(:nth_ref, 1))
add_tests("op_asgn1",
"Ruby" => "b = []\nb[1] ||= 10\nb[2] &&= 11\nb[3] += 12\n",
"RawParseTree" => [:block,
[:lasgn, :b, [:zarray]],
[:op_asgn1, [:lvar, :b],
[:array, [:lit, 1]], :"||", [:lit, 10]],
[:op_asgn1, [:lvar, :b],
[:array, [:lit, 2]], :"&&", [:lit, 11]],
[:op_asgn1, [:lvar, :b],
[:array, [:lit, 3]], :+, [:lit, 12]]],
"ParseTree" => s(:block,
s(:lasgn, :b, s(:array)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 3)), :+, s(:lit, 12))))
add_tests("op_asgn1_ivar",
"Ruby" => "@b = []\n@b[1] ||= 10\n@b[2] &&= 11\n@b[3] += 12\n",
"RawParseTree" => [:block,
[:iasgn, :@b, [:zarray]],
[:op_asgn1, [:ivar, :@b],
[:array, [:lit, 1]], :"||", [:lit, 10]],
[:op_asgn1, [:ivar, :@b],
[:array, [:lit, 2]], :"&&", [:lit, 11]],
[:op_asgn1, [:ivar, :@b],
[:array, [:lit, 3]], :+, [:lit, 12]]],
"ParseTree" => s(:block,
s(:iasgn, :@b, s(:array)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 3)), :+, s(:lit, 12))))
add_tests("op_asgn2",
"Ruby" => "s = Struct.new(:var)\nc = s.new(nil)\nc.var ||= 20\nc.var &&= 21\nc.var += 22\nc.d.e.f ||= 42\n",
"RawParseTree" => [:block,
[:lasgn, :s,
[:call, [:const, :Struct],
:new, [:array, [:lit, :var]]]],
[:lasgn, :c,
[:call, [:lvar, :s], :new, [:array, [:nil]]]],
[:op_asgn2, [:lvar, :c], :var=, :"||",
[:lit, 20]],
[:op_asgn2, [:lvar, :c], :var=, :"&&",
[:lit, 21]],
[:op_asgn2, [:lvar, :c], :var=, :+, [:lit, 22]],
[:op_asgn2,
[:call,
[:call, [:lvar, :c], :d], :e], :f=, :"||",
[:lit, 42]]],
"ParseTree" => s(:block,
s(:lasgn, :s,
s(:call, s(:const, :Struct),
:new, s(:arglist, s(:lit, :var)))),
s(:lasgn, :c,
s(:call, s(:lvar, :s),
:new, s(:arglist, s(:nil)))),
s(:op_asgn2, s(:lvar, :c),
:var=, :"||", s(:lit, 20)),
s(:op_asgn2, s(:lvar, :c),
:var=, :"&&", s(:lit, 21)),
s(:op_asgn2, s(:lvar, :c),
:var=, :+, s(:lit, 22)),
s(:op_asgn2,
s(:call,
s(:call, s(:lvar, :c), :d, s(:arglist)),
:e, s(:arglist)),
:f=, :"||", s(:lit, 42))))
add_tests("op_asgn2_self",
"Ruby" => "self.Bag ||= Bag.new",
"RawParseTree" => [:op_asgn2, [:self], :"Bag=", :"||",
[:call, [:const, :Bag], :new]],
"ParseTree" => s(:op_asgn2, s(:self), :"Bag=", :"||",
s(:call, s(:const, :Bag), :new, s(:arglist))))
add_tests("op_asgn_and",
"Ruby" => "a = 0\na &&= 2\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:lit, 0]],
[:op_asgn_and,
[:lvar, :a], [:lasgn, :a, [:lit, 2]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:lit, 0)),
s(:op_asgn_and,
s(:lvar, :a), s(:lasgn, :a, s(:lit, 2)))))
add_tests("op_asgn_and_ivar2",
"Ruby" => "@fetcher &&= new(Gem.configuration[:http_proxy])",
"RawParseTree" => [:op_asgn_and,
[:ivar, :@fetcher],
[:iasgn,
:@fetcher,
[:fcall,
:new,
[:array,
[:call,
[:call, [:const, :Gem], :configuration],
:[],
[:array, [:lit, :http_proxy]]]]]]],
"ParseTree" => s(:op_asgn_and,
s(:ivar, :@fetcher),
s(:iasgn,
:@fetcher,
s(:call, nil,
:new,
s(:arglist,
s(:call,
s(:call, s(:const, :Gem),
:configuration,
s(:arglist)),
:[],
s(:arglist, s(:lit, :http_proxy))))))))
add_tests("op_asgn_or",
"Ruby" => "a = 0\na ||= 1\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:lit, 0]],
[:op_asgn_or,
[:lvar, :a], [:lasgn, :a, [:lit, 1]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:lit, 0)),
s(:op_asgn_or,
s(:lvar, :a), s(:lasgn, :a, s(:lit, 1)))))
add_tests("op_asgn_or_block",
"Ruby" => "a ||= begin\n b\n rescue\n c\n end",
"RawParseTree" => [:op_asgn_or,
[:lvar, :a],
[:lasgn, :a,
[:rescue,
[:vcall, :b],
[:resbody, nil, [:vcall, :c]]]]],
"ParseTree" => s(:op_asgn_or,
s(:lvar, :a),
s(:lasgn, :a,
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody, s(:array),
s(:call, nil, :c, s(:arglist)))))),
"Ruby2Ruby" => "a ||= b rescue c")
add_tests("op_asgn_or_ivar",
"Ruby" => "@v ||= { }",
"RawParseTree" => [:op_asgn_or,
[:ivar, :@v],
[:iasgn, :@v, [:hash]]],
"ParseTree" => s(:op_asgn_or,
s(:ivar, :@v),
s(:iasgn, :@v, s(:hash))))
add_tests("op_asgn_or_ivar2",
"Ruby" => "@fetcher ||= new(Gem.configuration[:http_proxy])",
"RawParseTree" => [:op_asgn_or,
[:ivar, :@fetcher],
[:iasgn,
:@fetcher,
[:fcall,
:new,
[:array,
[:call,
[:call, [:const, :Gem], :configuration],
:[],
[:array, [:lit, :http_proxy]]]]]]],
"ParseTree" => s(:op_asgn_or,
s(:ivar, :@fetcher),
s(:iasgn,
:@fetcher,
s(:call, nil, :new,
s(:arglist,
s(:call,
s(:call, s(:const, :Gem),
:configuration,
s(:arglist)),
:[],
s(:arglist, s(:lit, :http_proxy))))))))
add_tests("or",
"Ruby" => "(a or b)",
"RawParseTree" => [:or, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:or,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("or_big",
"Ruby" => "((a or b) or (c and d))",
"RawParseTree" => [:or,
[:or, [:vcall, :a], [:vcall, :b]],
[:and, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:or,
s(:or,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))),
s(:and,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))))
add_tests("or_big2",
"Ruby" => "((a || b) || (c && d))",
"RawParseTree" => [:or,
[:or, [:vcall, :a], [:vcall, :b]],
[:and, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:or,
s(:or,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))),
s(:and,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))),
"Ruby2Ruby" => "((a or b) or (c and d))")
add_tests("parse_floats_as_args",
"Ruby" => "def x(a=0.0,b=0.0)\n a+b\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :b,
[:block,
[:lasgn, :a, [:lit, 0.0]],
[:lasgn, :b, [:lit, 0.0]]]],
[:call, [:lvar, :a], :+,
[:array, [:lvar, :b]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :b,
s(:block,
s(:lasgn, :a, s(:lit, 0.0)),
s(:lasgn, :b, s(:lit, 0.0)))),
s(:scope,
s(:block,
s(:call, s(:lvar, :a), :+,
s(:arglist, s(:lvar, :b)))))),
"Ruby2Ruby" => "def x(a = 0.0, b = 0.0)\n (a + b)\nend")
add_tests("postexe",
"Ruby" => "END { 1 }",
"RawParseTree" => [:iter, [:postexe], nil, [:lit, 1]],
"ParseTree" => s(:iter, s(:postexe), nil, s(:lit, 1)))
add_tests("proc_args_0",
"Ruby" => "proc { || (x + 1) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
0,
[:call, [:vcall, :x], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
0,
s(:call,
s(:call, nil, :x, s(:arglist)),
:+,
s(:arglist, s(:lit, 1)))))
add_tests("proc_args_1",
"Ruby" => "proc { |x| (x + 1) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
[:dasgn_curr, :x],
[:call, [:dvar, :x], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
s(:lasgn, :x),
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1)))))
add_tests("proc_args_2",
"Ruby" => "proc { |x, y| (x + y) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
[:masgn, [:array,
[:dasgn_curr, :x],
[:dasgn_curr, :y]]],
[:call, [:dvar, :x], :+, [:array, [:dvar, :y]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
s(:masgn,
s(:array,
s(:lasgn, :x),
s(:lasgn, :y))),
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lvar, :y)))))
add_tests("proc_args_no",
"Ruby" => "proc { (x + 1) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
nil,
[:call, [:vcall, :x], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:call, s(:call, nil, :x, s(:arglist)),
:+, s(:arglist, s(:lit, 1)))))
add_tests("redo",
"Ruby" => "loop { redo if false }",
"RawParseTree" => [:iter,
[:fcall, :loop], nil,
[:if, [:false], [:redo], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)),
nil,
s(:if, s(:false), s(:redo), nil)))
# TODO: need a resbody w/ multiple classes and a splat
add_tests("rescue",
"Ruby" => "blah rescue nil",
"RawParseTree" => [:rescue,
[:vcall, :blah], [:resbody, nil, [:nil]]],
"ParseTree" => s(:rescue,
s(:call, nil, :blah, s(:arglist)),
s(:resbody, s(:array), s(:nil))))
add_tests("rescue_block_body",
"Ruby" => "begin\n a\nrescue => e\n c\n d\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :a],
[:resbody, nil,
[:block,
[:lasgn, :e, [:gvar, :$!]],
[:vcall, :c],
[:vcall, :d]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
s(:block,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist))))))
add_tests("rescue_block_body_ivar",
"Ruby" => "begin\n a\nrescue => @e\n c\n d\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :a],
[:resbody, nil,
[:block,
[:iasgn, :@e, [:gvar, :$!]],
[:vcall, :c],
[:vcall, :d]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody,
s(:array, s(:iasgn, :@e, s(:gvar, :$!))),
s(:block,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist))))))
add_tests("rescue_block_body_3",
"Ruby" => "begin\n a\nrescue A\n b\nrescue B\n c\nrescue C\n d\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :a],
[:resbody, [:array, [:const, :A]],
[:vcall, :b],
[:resbody, [:array, [:const, :B]],
[:vcall, :c],
[:resbody, [:array, [:const, :C]],
[:vcall, :d]]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody, s(:array, s(:const, :A)),
s(:call, nil, :b, s(:arglist))),
s(:resbody, s(:array, s(:const, :B)),
s(:call, nil, :c, s(:arglist))),
s(:resbody, s(:array, s(:const, :C)),
s(:call, nil, :d, s(:arglist)))))
add_tests("rescue_block_nada",
"Ruby" => "begin\n blah\nrescue\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue, [:vcall, :blah], [:resbody, nil]]],
"ParseTree" => s(:rescue,
s(:call, nil, :blah, s(:arglist)),
s(:resbody, s(:array), nil)))
add_tests("rescue_exceptions",
"Ruby" => "begin\n blah\nrescue RuntimeError => r\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :blah],
[:resbody,
[:array, [:const, :RuntimeError]],
[:lasgn, :r, [:gvar, :$!]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :blah, s(:arglist)),
s(:resbody,
s(:array,
s(:const, :RuntimeError),
s(:lasgn, :r, s(:gvar, :$!))),
nil)))
add_tests("rescue_lasgn",
"Ruby" => "begin\n 1\nrescue\n var = 2\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil, [:lasgn, :var, [:lit, 2]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array),
s(:lasgn, :var, s(:lit, 2)))),
"Ruby2Ruby" => "1 rescue var = 2")
add_tests("rescue_lasgn_var",
"Ruby" => "begin\n 1\nrescue => e\n var = 2\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil,
[:block,
[:lasgn, :e, [:gvar, :$!]],
[:lasgn, :var, [:lit, 2]]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
s(:lasgn, :var, s(:lit, 2)))))
add_tests("rescue_lasgn_var_empty",
"Ruby" => "begin\n 1\nrescue => e\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil, [:lasgn, :e, [:gvar, :$!]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
nil)))
add_tests("rescue_iasgn_var_empty",
"Ruby" => "begin\n 1\nrescue => @e\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil, [:iasgn, :@e, [:gvar, :$!]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:iasgn, :@e, s(:gvar, :$!))),
nil)))
add_tests("retry",
"Ruby" => "retry",
"RawParseTree" => [:retry],
"ParseTree" => s(:retry))
add_tests("return_0",
"Ruby" => "return",
"RawParseTree" => [:return],
"ParseTree" => s(:return))
add_tests("return_1",
"Ruby" => "return 1",
"RawParseTree" => [:return, [:lit, 1]],
"ParseTree" => s(:return, s(:lit, 1)))
add_tests("return_n",
"Ruby" => "return 1, 2, 3",
"RawParseTree" => [:return, [:array,
[:lit, 1], [:lit, 2], [:lit, 3]]],
"ParseTree" => s(:return, s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
"Ruby2Ruby" => "return [1, 2, 3]")
add_tests("sclass",
"Ruby" => "class << self\n 42\nend",
"RawParseTree" => [:sclass, [:self], [:scope, [:lit, 42]]],
"ParseTree" => s(:sclass, s(:self), s(:scope, s(:lit, 42))))
add_tests("sclass_trailing_class",
"Ruby" => "class A\n class << self\n a\n end\n class B\n end\nend",
"RawParseTree" => [:class, :A, nil,
[:scope,
[:block,
[:sclass, [:self], [:scope, [:vcall, :a]]],
[:class, :B, nil, [:scope]]]]],
"ParseTree" => s(:class, :A, nil,
s(:scope,
s(:block,
s(:sclass, s(:self),
s(:scope,
s(:call, nil, :a, s(:arglist)))),
s(:class, :B, nil, s(:scope))))))
add_tests("splat",
"Ruby" => "def x(*b)\n a(*b)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :"*b"],
[:fcall, :a, [:splat, [:lvar, :b]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :"*b"),
s(:scope,
s(:block,
s(:call, nil, :a,
s(:splat, s(:lvar, :b)))))))
add_tests("str",
"Ruby" => '"x"',
"RawParseTree" => [:str, "x"],
"ParseTree" => s(:str, "x"))
add_tests("str_concat_newline", # FIX? make prettier? possible?
"Ruby" => '"before" \\
" after"',
"RawParseTree" => [:str, "before after"],
"ParseTree" => s(:str, "before after"),
"Ruby2Ruby" => '"before after"')
add_tests("str_concat_space",
"Ruby" => '"before" " after"',
"RawParseTree" => [:str, "before after"],
"ParseTree" => s(:str, "before after"),
"Ruby2Ruby" => '"before after"')
add_tests("str_heredoc",
"Ruby" => "<<'EOM'\n blah\nblah\nEOM",
"RawParseTree" => [:str, " blah\nblah\n"],
"ParseTree" => s(:str, " blah\nblah\n"),
"Ruby2Ruby" => "\" blah\\nblah\\n\"")
add_tests("str_heredoc_call",
"Ruby" => "<<'EOM'.strip\n blah\nblah\nEOM",
"RawParseTree" => [:call, [:str, " blah\nblah\n"], :strip],
"ParseTree" => s(:call, s(:str, " blah\nblah\n"),
:strip, s(:arglist)),
"Ruby2Ruby" => "\" blah\\nblah\\n\".strip")
add_tests("str_heredoc_double",
"Ruby" => "a += <<-H1 + b + <<-H2\n first\nH1\n second\nH2",
"RawParseTree" => [:lasgn, :a,
[:call,
[:lvar, :a],
:+,
[:array,
[:call,
[:call, [:str, " first\n"], :+,
[:array, [:vcall, :b]]],
:+,
[:array, [:str, " second\n"]]]]]],
"ParseTree" => s(:lasgn, :a,
s(:call,
s(:lvar, :a),
:+,
s(:arglist,
s(:call,
s(:call, s(:str, " first\n"), :+,
s(:arglist,
s(:call, nil, :b, s(:arglist)))),
:+,
s(:arglist, s(:str, " second\n")))))),
"Ruby2Ruby" => "a = (a + ((\" first\\n\" + b) + \" second\\n\"))")
add_tests("str_heredoc_indent",
"Ruby" => "<<-EOM\n blah\nblah\n\n EOM",
"RawParseTree" => [:str, " blah\nblah\n\n"],
"ParseTree" => s(:str, " blah\nblah\n\n"),
"Ruby2Ruby" => "\" blah\\nblah\\n\\n\"")
add_tests("str_interp_file",
"Ruby" => '"file = #{__FILE__}\n"',
"RawParseTree" => [:str, "file = (string)\n"],
"ParseTree" => s(:str, "file = (string)\n"),
"Ruby2Ruby" => '"file = (string)\\n"')
add_tests("structure_extra_block_for_dvar_scoping",
"Ruby" => "a.b do |c, d|\n unless e.f(c) then\n g = false\n d.h { |x, i| g = true }\n end\nend",
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :b],
[:masgn, [:array,
[:dasgn_curr, :c],
[:dasgn_curr, :d]]],
[:if,
[:call, [:vcall, :e], :f,
[:array, [:dvar, :c]]],
nil,
[:block,
[:dasgn_curr, :g, [:false]],
[:iter,
[:call, [:dvar, :d], :h],
[:masgn, [:array,
[:dasgn_curr, :x],
[:dasgn_curr, :i]]],
[:dasgn, :g, [:true]]]]]],
"ParseTree" => s(:iter,
s(:call,
s(:call, nil, :a, s(:arglist)),
:b, s(:arglist)),
s(:masgn, s(:array,
s(:lasgn, :c),
s(:lasgn, :d))),
s(:if,
s(:call, s(:call, nil, :e, s(:arglist)), :f,
s(:arglist, s(:lvar, :c))),
nil,
s(:block,
s(:lasgn, :g, s(:false)),
s(:iter,
s(:call, s(:lvar, :d), :h, s(:arglist)),
s(:masgn, s(:array,
s(:lasgn, :x),
s(:lasgn, :i))),
s(:lasgn, :g, s(:true)))))))
add_tests("structure_remove_begin_1",
"Ruby" => "a << begin\n b\n rescue\n c\n end",
"RawParseTree" => [:call, [:vcall, :a], :<<,
[:array, [:rescue, [:vcall, :b],
[:resbody, nil, [:vcall, :c]]]]],
"ParseTree" => s(:call, s(:call, nil, :a, s(:arglist)), :<<,
s(:arglist,
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody, s(:array),
s(:call, nil, :c, s(:arglist)))))),
"Ruby2Ruby" => "(a << b rescue c)")
add_tests("structure_remove_begin_2",
"Ruby" => "a = if c\n begin\n b\n rescue\n nil\n end\n end\na",
"RawParseTree" => [:block,
[:lasgn,
:a,
[:if, [:vcall, :c],
[:rescue,
[:vcall, :b],
[:resbody, nil, [:nil]]],
nil]],
[:lvar, :a]],
"ParseTree" => s(:block,
s(:lasgn,
:a,
s(:if, s(:call, nil, :c, s(:arglist)),
s(:rescue, s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array), s(:nil))),
nil)),
s(:lvar, :a)),
"Ruby2Ruby" => "a = b rescue nil if c\na\n") # OMG that's awesome
add_tests("structure_unused_literal_wwtt",
"Ruby" => "\"prevent the above from infecting rdoc\"\n\nmodule Graffle\nend",
"RawParseTree" => [:module, :Graffle, [:scope]],
"ParseTree" => s(:module, :Graffle, s(:scope)),
"Ruby2Ruby" => "module Graffle\nend")
add_tests("super",
"Ruby" => "def x\n super(4)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args],
[:super, [:array, [:lit, 4]]]]]],
"ParseTree" => s(:defn, :x,
s(:args),
s(:scope,
s(:block,
s(:super, s(:array, s(:lit, 4)))))))
add_tests("super_block_pass",
"Ruby" => "super(a, &b)",
"RawParseTree" => [:block_pass,
[:vcall, :b], [:super, [:array, [:vcall, :a]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:super,
s(:array, s(:call, nil, :a, s(:arglist))))))
add_tests("super_block_splat",
"Ruby" => "super(a, *b)",
"RawParseTree" => [:super,
[:argscat,
[:array, [:vcall, :a]],
[:vcall, :b]]],
"ParseTree" => s(:super,
s(:argscat,
s(:array, s(:call, nil, :a, s(:arglist))),
s(:call, nil, :b, s(:arglist)))))
add_tests("super_multi",
"Ruby" => "def x\n super(4, 2, 1)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args],
[:super,
[:array, [:lit, 4], [:lit, 2], [:lit, 1]]]]]],
"ParseTree" => s(:defn, :x,
s(:args),
s(:scope,
s(:block,
s(:super,
s(:array,
s(:lit, 4), s(:lit, 2), s(:lit, 1)))))))
add_tests("svalue",
"Ruby" => "a = *b",
"RawParseTree" => [:lasgn, :a, [:svalue, [:splat, [:vcall, :b]]]],
"ParseTree" => s(:lasgn, :a,
s(:svalue,
s(:splat, s(:call, nil, :b, s(:arglist))))))
add_tests("to_ary",
"Ruby" => "a, b = c",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:to_ary, [:vcall, :c]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:to_ary, s(:call, nil, :c, s(:arglist)))))
add_tests("true",
"Ruby" => "true",
"RawParseTree" => [:true],
"ParseTree" => s(:true))
add_tests("undef",
"Ruby" => "undef :x",
"RawParseTree" => [:undef, [:lit, :x]],
"ParseTree" => s(:undef, s(:lit, :x)))
add_tests("undef_2",
"Ruby" => "undef :x, :y",
"RawParseTree" => [:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]]],
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y))),
"Ruby2Ruby" => "undef :x\nundef :y\n")
add_tests("undef_3",
"Ruby" => "undef :x, :y, :z",
"RawParseTree" => [:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]]],
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z))),
"Ruby2Ruby" => "undef :x\nundef :y\nundef :z\n")
add_tests("undef_block_1",
"Ruby" => "f1\nundef :x\n", # TODO: don't like the extra return
"RawParseTree" => [:block,
[:vcall, :f1],
[:undef, [:lit, :x]]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:undef, s(:lit, :x))))
add_tests("undef_block_2",
"Ruby" => "f1\nundef :x, :y",
"RawParseTree" => [:block,
[:vcall, :f1],
[:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y)\n")
add_tests("undef_block_3",
"Ruby" => "f1\nundef :x, :y, :z",
"RawParseTree" => [:block,
[:vcall, :f1],
[:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]],
]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z)))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\n")
add_tests("undef_block_3_post",
"Ruby" => "undef :x, :y, :z\nf2",
"RawParseTree" => [:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]],
[:vcall, :f2]],
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z)),
s(:call, nil, :f2, s(:arglist))),
"Ruby2Ruby" => "undef :x\nundef :y\nundef :z\nf2\n")
add_tests("undef_block_wtf",
"Ruby" => "f1\nundef :x, :y, :z\nf2",
"RawParseTree" => [:block,
[:vcall, :f1],
[:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]]],
[:vcall, :f2]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z))),
s(:call, nil, :f2, s(:arglist))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\nf2\n")
add_tests("unless_post",
"Ruby" => "a unless b",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))))
add_tests("unless_post_not",
"Ruby" => "a unless not b",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil),
"Ruby2Ruby" => "a if b")
add_tests("unless_pre",
"Ruby" => "unless b then a end",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))),
"Ruby2Ruby" => "a unless b")
add_tests("unless_pre_not",
"Ruby" => "unless not b then a end",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil),
"Ruby2Ruby" => "a if b")
add_tests("until_post",
"Ruby" => "begin\n (1 + 1)\nend until false",
"RawParseTree" => [:until, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false))
add_tests("until_post_not",
"Ruby" => "begin\n (1 + 1)\nend until not true",
"RawParseTree" => [:while, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend while true")
add_tests("until_pre",
"Ruby" => "until false do\n (1 + 1)\nend",
"RawParseTree" => [:until, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true))
add_tests("until_pre_mod",
"Ruby" => "(1 + 1) until false",
"RawParseTree" => [:until, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "until false do\n (1 + 1)\nend")
add_tests("until_pre_not",
"Ruby" => "until not true do\n (1 + 1)\nend",
"RawParseTree" => [:while, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_tests("until_pre_not_mod",
"Ruby" => "(1 + 1) until not true",
"RawParseTree" => [:while, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_tests("valias",
"Ruby" => "alias $y $x",
"RawParseTree" => [:valias, :$y, :$x],
"ParseTree" => s(:valias, :$y, :$x))
add_tests("vcall",
"Ruby" => "method",
"RawParseTree" => [:vcall, :method],
"ParseTree" => s(:call, nil, :method, s(:arglist)))
add_tests("while_post",
"Ruby" => "begin\n (1 + 1)\nend while false",
"RawParseTree" => [:while, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false))
add_tests("while_post2",
"Ruby" => "begin\n (1 + 2)\n (3 + 4)\nend while false",
"RawParseTree" => [:while, [:false],
[:block,
[:call, [:lit, 1], :+, [:array, [:lit, 2]]],
[:call, [:lit, 3], :+, [:array, [:lit, 4]]]],
false],
"ParseTree" => s(:while, s(:false),
s(:block,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 2))),
s(:call, s(:lit, 3), :+,
s(:arglist, s(:lit, 4)))),
false))
add_tests("while_post_not",
"Ruby" => "begin\n (1 + 1)\nend while not true",
"RawParseTree" => [:until, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend until true")
add_tests("while_pre",
"Ruby" => "while false do\n (1 + 1)\nend",
"RawParseTree" => [:while, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true))
add_tests("while_pre_mod",
"Ruby" => "(1 + 1) while false",
"RawParseTree" => [:while, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "while false do\n (1 + 1)\nend") # FIX can be one liner
add_tests("while_pre_nil",
"Ruby" => "while false do\nend",
"RawParseTree" => [:while, [:false], nil, true],
"ParseTree" => s(:while, s(:false), nil, true))
add_tests("while_pre_not",
"Ruby" => "while not true do\n (1 + 1)\nend",
"RawParseTree" => [:until, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend")
add_tests("while_pre_not_mod",
"Ruby" => "(1 + 1) while not true",
"RawParseTree" => [:until, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend") # FIX
add_tests("xstr",
"Ruby" => "`touch 5`",
"RawParseTree" => [:xstr, 'touch 5'],
"ParseTree" => s(:xstr, 'touch 5'))
add_tests("yield_0",
"Ruby" => "yield",
"RawParseTree" => [:yield],
"ParseTree" => s(:yield))
add_tests("yield_1",
"Ruby" => "yield(42)",
"RawParseTree" => [:yield, [:lit, 42]],
"ParseTree" => s(:yield, s(:lit, 42)))
add_tests("yield_n",
"Ruby" => "yield(42, 24)",
"RawParseTree" => [:yield, [:array, [:lit, 42], [:lit, 24]]],
"ParseTree" => s(:yield, s(:array, s(:lit, 42), s(:lit, 24))))
add_tests("zarray",
"Ruby" => "a = []",
"RawParseTree" => [:lasgn, :a, [:zarray]],
"ParseTree" => s(:lasgn, :a, s(:array)))
add_tests("zsuper",
"Ruby" => "def x\n super\nend",
"RawParseTree" => [:defn, :x,
[:scope, [:block, [:args], [:zsuper]]]],
"ParseTree" => s(:defn, :x, s(:args),
s(:scope, s(:block, s(:zsuper)))))
end
stupid... we need to decide what to do about miniunit anyhow
############################################################
# This file is imported from a different project.
# DO NOT make modifications in this repo.
# File a patch instead and assign it to Ryan Davis
############################################################
$TESTING = true
require 'test/unit/testcase'
require 'sexp_processor' # for deep_clone
# key:
# wwtt = what were they thinking?
# TODO: <ko1_> 1.8.7 support {|&b|} syntax
class Examples
attr_reader :reader
attr_writer :writer
def a_method(x); x+1; end
alias an_alias a_method
define_method(:bmethod_noargs) do
x + 1
end
define_method(:unsplatted) do |x|
x + 1
end
define_method :splatted do |*args|
y = args.first
y + 42
end
define_method :dmethod_added, instance_method(:a_method) if
RUBY_VERSION < "1.9"
end
class ParseTreeTestCase < Test::Unit::TestCase
unless defined? Mini then
undef_method :default_test rescue nil
alias :refute_nil :assert_not_nil
end
attr_accessor :processor # to be defined by subclass
def setup
super
@processor = nil
end
def after_process_hook klass, node, data, input_name, output_name
end
def before_process_hook klass, node, data, input_name, output_name
end
def self.add_test name, data, klass = self.name[4..-1]
name = name.to_s
klass = klass.to_s
if testcases.has_key? name then
if testcases[name].has_key? klass then
warn "testcase #{klass}##{name} already has data"
else
testcases[name][klass] = data
end
else
warn "testcase #{name} does not exist"
end
end
def self.add_tests name, hash
name = name.to_s
hash.each do |klass, data|
warn "testcase #{klass}##{name} already has data" if
testcases[name].has_key? klass
testcases[name][klass] = data
end
end
def self.clone_same
@@testcases.each do |node, data|
data.each do |key, val|
if val == :same then
prev_key = self.previous(key)
data[key] = data[prev_key].deep_clone
end
end
end
end
def self.copy_test_case nonverbose, klass
verbose = nonverbose + "_mri_verbose_flag"
testcases[verbose][klass] = testcases[nonverbose][klass]
end
def self.generate_test klass, node, data, input_name, output_name
klass.send(:define_method, "test_#{node}".to_sym) do
flunk "Processor is nil" if processor.nil?
assert data.has_key?(input_name), "Unknown input data"
assert data.has_key?(output_name), "Missing test data"
$missing[node] << output_name unless data.has_key? output_name
input = data[input_name].deep_clone
expected = data[output_name].deep_clone
case expected
when :unsupported then
assert_raises(UnsupportedNodeError) do
processor.process(input)
end
else
extra_expected = []
extra_input = []
_, expected, extra_expected = *expected if
Array === expected and expected.first == :defx
_, input, extra_input = *input if
Array === input and input.first == :defx
# OMG... I can't believe I have to do this this way. these
# hooks are here instead of refactoring this define_method
# body into an assertion. It'll allow subclasses to hook in
# and add behavior before or after the processor does it's
# thing. If you go the body refactor route, some of the
# RawParseTree test casese fail for completely bogus reasons.
before_process_hook klass, node, data, input_name, output_name
refute_nil data[input_name], "testcase does not exist?"
@result = processor.process input
assert_equal(expected, @result,
"failed on input: #{data[input_name].inspect}")
after_process_hook klass, node, data, input_name, output_name
extra_input.each do |extra|
processor.process(extra)
end
extra = processor.extra_methods rescue []
assert_equal extra_expected, extra
end
end
end
def self.generate_tests klass
install_missing_reporter
clone_same
output_name = klass.name.to_s.sub(/^Test/, '')
input_name = self.previous(output_name)
@@testcases.each do |node, data|
next if [:skip, :unsupported].include? data[input_name]
next if data[output_name] == :skip
generate_test klass, node, data, input_name, output_name
end
end
def self.inherited klass
super
generate_tests klass unless klass.name =~ /TestCase/
end
def self.install_missing_reporter
unless defined? $missing then
$missing = Hash.new { |h,k| h[k] = [] }
at_exit {
at_exit {
warn ""
$missing.sort.each do |name, klasses|
warn "add_tests(#{name.inspect},"
klasses.map! { |klass| " #{klass.inspect} => :same" }
warn klasses.join("\n") + ")"
end
warn ""
}
}
end
end
def self.previous(key, extra=0) # FIX: remove R2C code
idx = @@testcase_order.index(key)
raise "Unknown class #{key} in @@testcase_order" if idx.nil?
case key
when "RubyToRubyC" then
idx -= 1
end
@@testcase_order[idx - 1 - extra]
end
def self.testcase_order; @@testcase_order; end
def self.testcases; @@testcases; end
def self.unsupported_tests *tests
tests.flatten.each do |name|
add_test name, :unsupported
end
end
############################################################
# Shared TestCases:
@@testcase_order = %w(Ruby RawParseTree ParseTree)
@@testcases = Hash.new { |h,k| h[k] = {} }
add_tests("alias",
"Ruby" => "class X\n alias :y :x\nend",
"RawParseTree" => [:class, :X, nil,
[:scope, [:alias, [:lit, :y], [:lit, :x]]]],
"ParseTree" => s(:class, :X, nil,
s(:scope, s(:alias, s(:lit, :y), s(:lit, :x)))),
"Ruby2Ruby" => "class X\n alias_method :y, :x\nend")
add_tests("alias_ugh",
"Ruby" => "class X\n alias y x\nend",
"RawParseTree" => [:class, :X, nil,
[:scope, [:alias, [:lit, :y], [:lit, :x]]]],
"ParseTree" => s(:class, :X, nil,
s(:scope, s(:alias, s(:lit, :y), s(:lit, :x)))),
"Ruby2Ruby" => "class X\n alias_method :y, :x\nend")
add_tests("and",
"Ruby" => "(a and b)",
"RawParseTree" => [:and, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:and,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("argscat_inside",
"Ruby" => "a = [b, *c]",
"RawParseTree" => [:lasgn, :a,
[:argscat,
[:array, [:vcall, :b]], [:vcall, :c]]],
"ParseTree" => s(:lasgn, :a,
s(:argscat,
s(:array, s(:call, nil, :b, s(:arglist))),
s(:call, nil, :c, s(:arglist)))),
"Ruby2Ruby" => "a = b, *c")
add_tests("argscat_svalue",
"Ruby" => "a = b, c, *d",
"RawParseTree" => [:lasgn, :a,
[:svalue,
[:argscat,
[:array, [:vcall, :b], [:vcall, :c]],
[:vcall, :d]]]],
"ParseTree" => s(:lasgn, :a,
s(:svalue,
s(:argscat,
s(:array,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :c, s(:arglist))),
s(:call, nil, :d, s(:arglist))))))
add_tests("argspush",
"Ruby" => "a[*b] = c",
"RawParseTree" => [:attrasgn,
[:vcall, :a],
:[]=,
[:argspush,
[:splat,
[:vcall, :b]],
[:vcall, :c]]],
"ParseTree" => s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:[]=,
s(:argspush,
s(:splat,
s(:call, nil, :b, s(:arglist))),
s(:call, nil, :c, s(:arglist)))))
add_tests("array",
"Ruby" => "[1, :b, \"c\"]",
"RawParseTree" => [:array, [:lit, 1], [:lit, :b], [:str, "c"]],
"ParseTree" => s(:array, s(:lit, 1), s(:lit, :b), s(:str, "c")))
add_tests("array_pct_W",
"Ruby" => "%W[a b c]",
"RawParseTree" => [:array, [:str, "a"], [:str, "b"], [:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"), s(:str, "b"), s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"b\", \"c\"]")
add_tests("array_pct_W_dstr",
"Ruby" => "%W[a #\{@b} c]",
"RawParseTree" => [:array,
[:str, "a"],
[:dstr, "", [:evstr, [:ivar, :@b]]],
[:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"),
s(:dstr, "", s(:evstr, s(:ivar, :@b))),
s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"#\{@b}\", \"c\"]")
add_tests("array_pct_w",
"Ruby" => "%w[a b c]",
"RawParseTree" => [:array, [:str, "a"], [:str, "b"], [:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"), s(:str, "b"), s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"b\", \"c\"]")
add_tests("array_pct_w_dstr",
"Ruby" => "%w[a #\{@b} c]",
"RawParseTree" => [:array,
[:str, "a"],
[:str, "#\{@b}"],
[:str, "c"]],
"ParseTree" => s(:array,
s(:str, "a"),
s(:str, "#\{@b}"),
s(:str, "c")),
"Ruby2Ruby" => "[\"a\", \"\\\#{@b}\", \"c\"]") # TODO: huh?
add_tests("attrasgn",
"Ruby" => "y = 0\n42.method = y\n",
"RawParseTree" => [:block,
[:lasgn, :y, [:lit, 0]],
[:attrasgn, [:lit, 42], :method=,
[:array, [:lvar, :y]]]],
"ParseTree" => s(:block,
s(:lasgn, :y, s(:lit, 0)),
s(:attrasgn, s(:lit, 42), :method=,
s(:arglist, s(:lvar, :y)))))
add_tests("attrasgn_index_equals",
"Ruby" => "a[42] = 24",
"RawParseTree" => [:attrasgn, [:vcall, :a], :[]=,
[:array, [:lit, 42], [:lit, 24]]],
"ParseTree" => s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:[]=,
s(:arglist, s(:lit, 42), s(:lit, 24))))
add_tests("attrasgn_index_equals_space",
"Ruby" => "a = []; a [42] = 24",
"RawParseTree" => [:block,
[:lasgn, :a, [:zarray]],
[:attrasgn, [:lvar, :a], :[]=,
[:array, [:lit, 42], [:lit, 24]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:attrasgn, s(:lvar, :a), :[]=,
s(:arglist, s(:lit, 42), s(:lit, 24)))),
"Ruby2Ruby" => "a = []\na[42] = 24\n")
add_tests("attrset",
"Ruby" => [Examples, :writer=],
"RawParseTree" => [:defn, :writer=, [:attrset, :@writer]],
"ParseTree" => s(:defn, :writer=,
s(:args, :arg),
s(:attrset, :@writer)),
"Ruby2Ruby" => "attr_writer :writer")
add_tests("back_ref",
"Ruby" => "[$&, $`, $', $+]",
"RawParseTree" => [:array,
[:back_ref, :&],
[:back_ref, :"`"],
[:back_ref, :"'"],
[:back_ref, :+]],
"ParseTree" => s(:array,
s(:back_ref, :&),
s(:back_ref, :"`"),
s(:back_ref, :"'"),
s(:back_ref, :+)))
add_tests("begin",
"Ruby" => "begin\n (1 + 1)\nend",
"RawParseTree" => [:begin,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))),
"Ruby2Ruby" => "(1 + 1)")
add_tests("begin_def",
"Ruby" => "def m\n begin\n\n end\nend",
"RawParseTree" => [:defn, :m, [:scope, [:block, [:args], [:nil]]]],
"ParseTree" => s(:defn, :m, s(:args),
s(:scope, s(:block, s(:nil)))),
"Ruby2Ruby" => "def m\n # do nothing\nend")
add_tests("begin_rescue_ensure",
"Ruby" => "begin\n a\nrescue\n # do nothing\nensure\n # do nothing\nend",
"RawParseTree" => [:begin,
[:ensure,
[:rescue,
[:vcall, :a],
[:resbody, nil]],
[:nil]]],
"ParseTree" => s(:ensure,
s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody, s(:array), nil)),
s(:nil)))
add_tests("begin_rescue_ensure_all_empty",
"Ruby" => "begin\n # do nothing\nrescue\n # do nothing\nensure\n # do nothing\nend",
"RawParseTree" => [:begin,
[:ensure,
[:rescue,
[:resbody, nil]],
[:nil]]],
"ParseTree" => s(:ensure,
s(:rescue,
s(:resbody, s(:array), nil)),
s(:nil)))
add_tests("begin_rescue_twice",
"Ruby" => "begin\n a\nrescue => mes\n # do nothing\nend\nbegin\n b\nrescue => mes\n # do nothing\nend\n",
"RawParseTree" => [:block,
[:begin,
[:rescue,
[:vcall, :a],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]]],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]]]],
"ParseTree" => s(:block,
s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody,
s(:array, s(:lasgn, :mes, s(:gvar, :$!))),
nil)),
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array,
s(:lasgn, :mes, s(:gvar, :$!))),
nil))))
add_tests("begin_rescue_twice_mri_verbose_flag",
"RawParseTree" => [:block,
[:rescue, # no begin
[:vcall, :a],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody, nil,
[:lasgn, :mes, [:gvar, :$!]]]]]])
copy_test_case "begin_rescue_twice", "Ruby"
copy_test_case "begin_rescue_twice", "ParseTree"
add_tests("block_attrasgn",
"Ruby" => "def self.setup(ctx)\n bind = allocate\n bind.context = ctx\n return bind\nend",
"RawParseTree" => [:defs, [:self], :setup,
[:scope,
[:block,
[:args, :ctx],
[:lasgn, :bind, [:vcall, :allocate]],
[:attrasgn, [:lvar, :bind], :context=,
[:array, [:lvar, :ctx]]],
[:return, [:lvar, :bind]]]]],
"ParseTree" => s(:defs, s(:self), :setup,
s(:args, :ctx),
s(:scope,
s(:block,
s(:lasgn, :bind,
s(:call, nil, :allocate, s(:arglist))),
s(:attrasgn, s(:lvar, :bind), :context=,
s(:arglist, s(:lvar, :ctx))),
s(:return, s(:lvar, :bind))))))
add_tests("block_lasgn",
"Ruby" => "x = (y = 1\n(y + 2))",
"RawParseTree" => [:lasgn, :x,
[:block,
[:lasgn, :y, [:lit, 1]],
[:call, [:lvar, :y], :+, [:array, [:lit, 2]]]]],
"ParseTree" => s(:lasgn, :x,
s(:block,
s(:lasgn, :y, s(:lit, 1)),
s(:call, s(:lvar, :y), :+,
s(:arglist, s(:lit, 2))))))
add_tests("block_mystery_block",
"Ruby" => "a(b) do\n if b then\n true\n else\n c = false\n d { |x| c = true }\n c\n end\nend",
"RawParseTree" => [:iter,
[:fcall, :a, [:array, [:vcall, :b]]],
nil,
[:if,
[:vcall, :b],
[:true],
[:block,
[:dasgn_curr, :c, [:false]],
[:iter,
[:fcall, :d],
[:dasgn_curr, :x],
[:dasgn, :c, [:true]]],
[:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a,
s(:arglist, s(:call, nil, :b, s(:arglist)))),
nil,
s(:if,
s(:call, nil, :b, s(:arglist)),
s(:true),
s(:block,
s(:lasgn, :c, s(:false)),
s(:iter,
s(:call, nil, :d, s(:arglist)),
s(:lasgn, :x),
s(:lasgn, :c, s(:true))),
s(:lvar, :c)))))
add_tests("block_pass_args_and_splat",
"Ruby" => "def blah(*args, &block)\n other(42, *args, &block)\nend",
"RawParseTree" => [:defn, :blah,
[:scope,
[:block,
[:args, :"*args"],
[:block_arg, :block],
[:block_pass,
[:lvar, :block],
[:fcall, :other,
[:argscat,
[:array, [:lit, 42]], [:lvar, :args]]]]]]],
"ParseTree" => s(:defn, :blah,
s(:args, :"*args", :"&block"),
s(:scope,
s(:block,
s(:block_pass,
s(:lvar, :block),
s(:call, nil, :other,
s(:argscat,
s(:array,
s(:lit, 42)), s(:lvar, :args))))))))
add_tests("block_pass_call_0",
"Ruby" => "a.b(&c)",
"RawParseTree" => [:block_pass,
[:vcall, :c], [:call, [:vcall, :a], :b]],
"ParseTree" => s(:block_pass,
s(:call, nil, :c, s(:arglist)),
s(:call,
s(:call, nil, :a, s(:arglist)),
:b,
s(:arglist))))
add_tests("block_pass_call_1",
"Ruby" => "a.b(4, &c)",
"RawParseTree" => [:block_pass,
[:vcall, :c],
[:call, [:vcall, :a], :b, [:array, [:lit, 4]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :c, s(:arglist)),
s(:call,
s(:call, nil, :a, s(:arglist)),
:b,
s(:arglist, s(:lit, 4)))))
add_tests("block_pass_call_n",
"Ruby" => "a.b(1, 2, 3, &c)",
"RawParseTree" => [:block_pass,
[:vcall, :c],
[:call, [:vcall, :a], :b,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :c, s(:arglist)),
s(:call,
s(:call, nil, :a, s(:arglist)),
:b,
s(:arglist,
s(:lit, 1), s(:lit, 2), s(:lit, 3)))))
add_tests("block_pass_fcall_0",
"Ruby" => "a(&b)",
"RawParseTree" => [:block_pass, [:vcall, :b], [:fcall, :a]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist))))
add_tests("block_pass_fcall_1",
"Ruby" => "a(4, &b)",
"RawParseTree" => [:block_pass,
[:vcall, :b],
[:fcall, :a, [:array, [:lit, 4]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist, s(:lit, 4)))))
add_tests("block_pass_fcall_n",
"Ruby" => "a(1, 2, 3, &b)",
"RawParseTree" => [:block_pass,
[:vcall, :b],
[:fcall, :a,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a,
s(:arglist,
s(:lit, 1), s(:lit, 2), s(:lit, 3)))))
add_tests("block_pass_omgwtf",
"Ruby" => "define_attr_method(:x, :sequence_name, &Proc.new { |*args| nil })",
"RawParseTree" => [:block_pass,
[:iter,
[:call, [:const, :Proc], :new],
[:masgn, [:dasgn_curr, :args]],
[:nil]],
[:fcall, :define_attr_method,
[:array, [:lit, :x], [:lit, :sequence_name]]]],
"ParseTree" => s(:block_pass,
s(:iter,
s(:call, s(:const, :Proc), :new, s(:arglist)),
s(:masgn, s(:lasgn, :args)),
s(:nil)),
s(:call, nil, :define_attr_method,
s(:arglist,
s(:lit, :x), s(:lit, :sequence_name)))))
add_tests("block_pass_splat",
"Ruby" => "def blah(*args, &block)\n other(*args, &block)\nend",
"RawParseTree" => [:defn, :blah,
[:scope,
[:block,
[:args, :"*args"],
[:block_arg, :block],
[:block_pass,
[:lvar, :block],
[:fcall, :other,
[:splat, [:lvar, :args]]]]]]],
"ParseTree" => s(:defn, :blah,
s(:args, :"*args", :"&block"),
s(:scope,
s(:block,
s(:block_pass,
s(:lvar, :block),
s(:call, nil, :other,
s(:splat, s(:lvar, :args))))))))
add_tests("block_pass_super",
"Ruby" => "super(&prc)",
"RawParseTree" => [:block_pass, [:vcall, :prc], [:super]],
"ParseTree" => s(:block_pass,
s(:call, nil, :prc, s(:arglist)),
s(:super)))
add_tests("block_pass_thingy",
"Ruby" => "r.read_body(dest, &block)",
"RawParseTree" => [:block_pass,
[:vcall, :block],
[:call, [:vcall, :r], :read_body,
[:array, [:vcall, :dest]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :block, s(:arglist)),
s(:call, s(:call, nil, :r, s(:arglist)),
:read_body,
s(:arglist,
s(:call, nil, :dest, s(:arglist))))))
add_tests("block_stmt_after",
"Ruby" => "def f\n begin\n b\n rescue\n c\n end\n\n d\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody, nil, [:vcall, :c]]]],
[:vcall, :d]]]],
"ParseTree" => s(:defn, :f,
s(:args),
s(:scope,
s(:block,
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array),
s(:call, nil, :c, s(:arglist)))),
s(:call, nil, :d, s(:arglist))))),
"Ruby2Ruby" => "def f\n b rescue c\n d\nend")
add_tests("block_stmt_after_mri_verbose_flag",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:rescue, # no begin
[:vcall, :b],
[:resbody, nil, [:vcall, :c]]],
[:vcall, :d]]]])
copy_test_case "block_stmt_after", "Ruby"
copy_test_case "block_stmt_after", "ParseTree"
copy_test_case "block_stmt_after", "Ruby2Ruby"
add_tests("block_stmt_before",
"Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:vcall, :a],
[:begin,
[:rescue, [:vcall, :b],
[:resbody, nil, [:vcall, :c]]]]]]],
"ParseTree" => s(:defn, :f,
s(:args),
s(:scope,
s(:block,
s(:call, nil, :a, s(:arglist)),
s(:rescue, s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array),
s(:call, nil, :c, s(:arglist))))))),
"Ruby2Ruby" => "def f\n a\n b rescue c\nend")
# oddly... this one doesn't HAVE any differences when verbose... new?
copy_test_case "block_stmt_before", "Ruby"
copy_test_case "block_stmt_before", "ParseTree"
copy_test_case "block_stmt_before", "RawParseTree"
copy_test_case "block_stmt_before", "Ruby2Ruby"
add_tests("block_stmt_both",
"Ruby" => "def f\n a\n begin\n b\n rescue\n c\n end\n d\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:vcall, :a],
[:begin,
[:rescue,
[:vcall, :b],
[:resbody,
nil,
[:vcall, :c]]]],
[:vcall, :d]]]],
"ParseTree" => s(:defn, :f, s(:args),
s(:scope,
s(:block,
s(:call, nil, :a, s(:arglist)),
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array),
s(:call, nil, :c, s(:arglist)))),
s(:call, nil, :d, s(:arglist))))),
"Ruby2Ruby" => "def f\n a\n b rescue c\n d\nend")
add_tests("block_stmt_both_mri_verbose_flag",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:vcall, :a],
[:rescue, # no begin
[:vcall, :b],
[:resbody,
nil,
[:vcall, :c]]],
[:vcall, :d]]]])
copy_test_case "block_stmt_both", "Ruby"
copy_test_case "block_stmt_both", "ParseTree"
copy_test_case "block_stmt_both", "Ruby2Ruby"
add_tests("bmethod",
"Ruby" => [Examples, :unsplatted],
"RawParseTree" => [:defn, :unsplatted,
[:bmethod,
[:dasgn_curr, :x],
[:call, [:dvar, :x], :+, [:array, [:lit, 1]]]]],
"ParseTree" => s(:defn, :unsplatted,
s(:args, :x),
s(:scope,
s(:block,
s(:call,
s(:lvar, :x),
:+,
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def unsplatted(x)\n (x + 1)\nend")
add_tests("bmethod_noargs",
"Ruby" => [Examples, :bmethod_noargs],
"RawParseTree" => [:defn, :bmethod_noargs,
[:bmethod,
nil,
[:call,
[:vcall, :x], :"+", [:array, [:lit, 1]]]]],
"ParseTree" => s(:defn, :bmethod_noargs,
s(:args),
s(:scope,
s(:block,
s(:call,
s(:call, nil, :x, s(:arglist)),
:"+",
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def bmethod_noargs\n (x + 1)\nend")
add_tests("bmethod_splat",
"Ruby" => [Examples, :splatted],
"RawParseTree" => [:defn, :splatted,
[:bmethod,
[:masgn, [:dasgn_curr, :args]],
[:block,
[:dasgn_curr, :y,
[:call, [:dvar, :args], :first]],
[:call, [:dvar, :y], :+,
[:array, [:lit, 42]]]]]],
"ParseTree" => s(:defn, :splatted,
s(:args, :"*args"),
s(:scope,
s(:block,
s(:lasgn, :y,
s(:call, s(:lvar, :args), :first,
s(:arglist))),
s(:call, s(:lvar, :y), :+,
s(:arglist, s(:lit, 42)))))),
"Ruby2Ruby" => "def splatted(*args)\n y = args.first\n (y + 42)\nend")
add_tests("break",
"Ruby" => "loop { break if true }",
"RawParseTree" => [:iter,
[:fcall, :loop], nil,
[:if, [:true], [:break], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)), nil,
s(:if, s(:true), s(:break), nil)))
add_tests("break_arg",
"Ruby" => "loop { break 42 if true }",
"RawParseTree" => [:iter,
[:fcall, :loop], nil,
[:if, [:true], [:break, [:lit, 42]], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)), nil,
s(:if, s(:true), s(:break, s(:lit, 42)), nil)))
add_tests("call",
"Ruby" => "self.method",
"RawParseTree" => [:call, [:self], :method],
"ParseTree" => s(:call, s(:self), :method, s(:arglist)))
add_tests("call_arglist",
"Ruby" => "o.puts(42)",
"RawParseTree" => [:call, [:vcall, :o], :puts,
[:array, [:lit, 42]]],
"ParseTree" => s(:call, s(:call, nil, :o, s(:arglist)), :puts,
s(:arglist, s(:lit, 42))))
add_tests("call_arglist_hash",
"Ruby" => "o.m(:a => 1, :b => 2)",
"RawParseTree" => [:call,
[:vcall, :o], :m,
[:array,
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call,
s(:call, nil, :o, s(:arglist)), :m,
s(:arglist,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("call_arglist_norm_hash",
"Ruby" => "o.m(42, :a => 1, :b => 2)",
"RawParseTree" => [:call,
[:vcall, :o], :m,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call,
s(:call, nil, :o, s(:arglist)), :m,
s(:arglist,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("call_arglist_norm_hash_splat",
"Ruby" => "o.m(42, :a => 1, :b => 2, *c)",
"RawParseTree" => [:call,
[:vcall, :o], :m,
[:argscat,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]],
[:vcall, :c]]],
"ParseTree" => s(:call,
s(:call, nil, :o, s(:arglist)), :m,
s(:argscat,
s(:array,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))),
s(:call, nil, :c, s(:arglist)))))
add_tests("call_arglist_space",
"Ruby" => "a (1,2,3)",
"RawParseTree" => [:fcall, :a,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
"ParseTree" => s(:call, nil, :a,
s(:arglist,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
"Ruby2Ruby" => "a(1, 2, 3)")
add_tests("call_command",
"Ruby" => "1.b(c)",
"RawParseTree" => [:call, [:lit, 1], :b, [:array, [:vcall, :c]]],
"ParseTree" => s(:call,
s(:lit, 1),
:b,
s(:arglist, s(:call, nil, :c, s(:arglist)))))
add_tests("call_expr",
"Ruby" => "(v = (1 + 1)).zero?",
"RawParseTree" => [:call,
[:lasgn, :v,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
:zero?],
"ParseTree" => s(:call,
s(:lasgn, :v,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
:zero?, s(:arglist)))
add_tests("call_index",
"Ruby" => "a = []\na[42]\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:zarray]],
[:call, [:lvar, :a], :[], [:array, [:lit, 42]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lit, 42)))))
add_tests("call_index_no_args",
"Ruby" => "a[]",
"RawParseTree" => [:call, [:vcall, :a], :[]],
"ParseTree" => s(:call, s(:call, nil, :a, s(:arglist)),
:[], s(:arglist)))
add_tests("call_index_space",
"Ruby" => "a = []\na [42]\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:zarray]],
[:call, [:lvar, :a], :[], [:array, [:lit, 42]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:array)),
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lit, 42)))),
"Ruby2Ruby" => "a = []\na[42]\n")
add_tests("call_unary_neg",
"Ruby" => "-2**31",
"RawParseTree" => [:call,
[:call, [:lit, 2], :**, [:array, [:lit, 31]]],
:-@],
"ParseTree" => s(:call,
s(:call,
s(:lit, 2),
:**,
s(:arglist, s(:lit, 31))),
:-@, s(:arglist)),
"Ruby2Ruby" => "-(2 ** 31)")
add_tests("case",
"Ruby" => "var = 2\nresult = \"\"\ncase var\nwhen 1 then\n puts(\"something\")\n result = \"red\"\nwhen 2, 3 then\n result = \"yellow\"\nwhen 4 then\n # do nothing\nelse\n result = \"green\"\nend\ncase result\nwhen \"red\" then\n var = 1\nwhen \"yellow\" then\n var = 2\nwhen \"green\" then\n var = 3\nelse\n # do nothing\nend\n",
"RawParseTree" => [:block,
[:lasgn, :var, [:lit, 2]],
[:lasgn, :result, [:str, ""]],
[:case,
[:lvar, :var],
[:when,
[:array, [:lit, 1]],
[:block,
[:fcall, :puts,
[:array, [:str, "something"]]],
[:lasgn, :result, [:str, "red"]]]],
[:when,
[:array, [:lit, 2], [:lit, 3]],
[:lasgn, :result, [:str, "yellow"]]],
[:when, [:array, [:lit, 4]], nil],
[:lasgn, :result, [:str, "green"]]],
[:case,
[:lvar, :result],
[:when, [:array, [:str, "red"]],
[:lasgn, :var, [:lit, 1]]],
[:when, [:array, [:str, "yellow"]],
[:lasgn, :var, [:lit, 2]]],
[:when, [:array, [:str, "green"]],
[:lasgn, :var, [:lit, 3]]],
nil]],
"ParseTree" => s(:block,
s(:lasgn, :var, s(:lit, 2)),
s(:lasgn, :result, s(:str, "")),
s(:case,
s(:lvar, :var),
s(:when,
s(:array, s(:lit, 1)),
s(:block,
s(:call, nil, :puts,
s(:arglist, s(:str, "something"))),
s(:lasgn, :result, s(:str, "red")))),
s(:when,
s(:array, s(:lit, 2), s(:lit, 3)),
s(:lasgn, :result, s(:str, "yellow"))),
s(:when, s(:array, s(:lit, 4)), nil),
s(:lasgn, :result, s(:str, "green"))),
s(:case,
s(:lvar, :result),
s(:when, s(:array, s(:str, "red")),
s(:lasgn, :var, s(:lit, 1))),
s(:when, s(:array, s(:str, "yellow")),
s(:lasgn, :var, s(:lit, 2))),
s(:when, s(:array, s(:str, "green")),
s(:lasgn, :var, s(:lit, 3))),
nil)))
add_tests("case_nested",
"Ruby" => "var1 = 1\nvar2 = 2\nresult = nil\ncase var1\nwhen 1 then\n case var2\n when 1 then\n result = 1\n when 2 then\n result = 2\n else\n result = 3\n end\nwhen 2 then\n case var2\n when 1 then\n result = 4\n when 2 then\n result = 5\n else\n result = 6\n end\nelse\n result = 7\nend\n",
"RawParseTree" => [:block,
[:lasgn, :var1, [:lit, 1]],
[:lasgn, :var2, [:lit, 2]],
[:lasgn, :result, [:nil]],
[:case,
[:lvar, :var1],
[:when, [:array, [:lit, 1]],
[:case,
[:lvar, :var2],
[:when, [:array, [:lit, 1]],
[:lasgn, :result, [:lit, 1]]],
[:when, [:array, [:lit, 2]],
[:lasgn, :result, [:lit, 2]]],
[:lasgn, :result, [:lit, 3]]]],
[:when, [:array, [:lit, 2]],
[:case,
[:lvar, :var2],
[:when, [:array, [:lit, 1]],
[:lasgn, :result, [:lit, 4]]],
[:when, [:array, [:lit, 2]],
[:lasgn, :result, [:lit, 5]]],
[:lasgn, :result, [:lit, 6]]]],
[:lasgn, :result, [:lit, 7]]]],
"ParseTree" => s(:block,
s(:lasgn, :var1, s(:lit, 1)),
s(:lasgn, :var2, s(:lit, 2)),
s(:lasgn, :result, s(:nil)),
s(:case,
s(:lvar, :var1),
s(:when, s(:array, s(:lit, 1)),
s(:case,
s(:lvar, :var2),
s(:when, s(:array, s(:lit, 1)),
s(:lasgn, :result, s(:lit, 1))),
s(:when, s(:array, s(:lit, 2)),
s(:lasgn, :result, s(:lit, 2))),
s(:lasgn, :result, s(:lit, 3)))),
s(:when, s(:array, s(:lit, 2)),
s(:case,
s(:lvar, :var2),
s(:when, s(:array, s(:lit, 1)),
s(:lasgn, :result, s(:lit, 4))),
s(:when, s(:array, s(:lit, 2)),
s(:lasgn, :result, s(:lit, 5))),
s(:lasgn, :result, s(:lit, 6)))),
s(:lasgn, :result, s(:lit, 7)))))
add_tests("case_nested_inner_no_expr",
"Ruby" => "case a\nwhen b then\n case\n when (d and e) then\n f\n else\n # do nothing\n end\nelse\n # do nothing\nend",
"RawParseTree" => [:case, [:vcall, :a],
[:when, [:array, [:vcall, :b]],
[:case, nil,
[:when,
[:array, [:and, [:vcall, :d], [:vcall, :e]]],
[:vcall, :f]],
nil]],
nil],
"ParseTree" => s(:case, s(:call, nil, :a, s(:arglist)),
s(:when,
s(:array, s(:call, nil, :b, s(:arglist))),
s(:case, nil,
s(:when,
s(:array,
s(:and,
s(:call, nil, :d, s(:arglist)),
s(:call, nil, :e, s(:arglist)))),
s(:call, nil, :f, s(:arglist))),
nil)),
nil))
add_tests("case_no_expr",
"Ruby" => "case\nwhen (a == 1) then\n :a\nwhen (a == 2) then\n :b\nelse\n :c\nend",
"RawParseTree" => [:case, nil,
[:when,
[:array,
[:call, [:vcall, :a], :==,
[:array, [:lit, 1]]]],
[:lit, :a]],
[:when,
[:array,
[:call, [:vcall, :a], :==,
[:array, [:lit, 2]]]],
[:lit, :b]],
[:lit, :c]],
"ParseTree" => s(:case, nil,
s(:when,
s(:array,
s(:call,
s(:call, nil, :a, s(:arglist)),
:==,
s(:arglist, s(:lit, 1)))),
s(:lit, :a)),
s(:when,
s(:array,
s(:call,
s(:call, nil, :a, s(:arglist)),
:==,
s(:arglist, s(:lit, 2)))),
s(:lit, :b)),
s(:lit, :c)))
add_tests("case_splat",
"Ruby" => "case a\nwhen :b, *c then\n d\nelse\n e\nend",
"RawParseTree" => [:case, [:vcall, :a],
[:when,
[:array,
[:lit, :b], [:when, [:vcall, :c], nil]], # wtf?
[:vcall, :d]],
[:vcall, :e]],
"ParseTree" => s(:case, s(:call, nil, :a, s(:arglist)),
s(:when,
s(:array,
s(:lit, :b),
s(:when,
s(:call, nil, :c, s(:arglist)),
nil)), # wtf?
s(:call, nil, :d, s(:arglist))),
s(:call, nil, :e, s(:arglist))))
add_tests("cdecl",
"Ruby" => "X = 42",
"RawParseTree" => [:cdecl, :X, [:lit, 42]],
"ParseTree" => s(:cdecl, :X, s(:lit, 42)))
add_tests("class_plain",
"Ruby" => "class X\n puts((1 + 1))\n def blah\n puts(\"hello\")\n end\nend",
"RawParseTree" => [:class,
:X,
nil,
[:scope,
[:block,
[:fcall, :puts,
[:array,
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]]]],
[:defn, :blah,
[:scope,
[:block,
[:args],
[:fcall, :puts,
[:array, [:str, "hello"]]]]]]]]],
"ParseTree" => s(:class,
:X,
nil,
s(:scope,
s(:block,
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))))),
s(:defn, :blah,
s(:args),
s(:scope,
s(:block,
s(:call, nil, :puts,
s(:arglist,
s(:str, "hello"))))))))))
add_tests("class_scoped",
"Ruby" => "class X::Y\n c\nend",
"RawParseTree" => [:class, [:colon2, [:const, :X], :Y], nil,
[:scope, [:vcall, :c]]],
"ParseTree" => s(:class, s(:colon2, s(:const, :X), :Y), nil,
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("class_scoped3",
"Ruby" => "class ::Y\n c\nend",
"RawParseTree" => [:class, [:colon3, :Y], nil,
[:scope, [:vcall, :c]]],
"ParseTree" => s(:class, s(:colon3, :Y), nil,
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("class_super_array",
"Ruby" => "class X < Array\nend",
"RawParseTree" => [:class,
:X,
[:const, :Array],
[:scope]],
"ParseTree" => s(:class,
:X,
s(:const, :Array),
s(:scope)))
add_tests("class_super_expr",
"Ruby" => "class X < expr\nend",
"RawParseTree" => [:class,
:X,
[:vcall, :expr],
[:scope]],
"ParseTree" => s(:class,
:X,
s(:call, nil, :expr, s(:arglist)),
s(:scope)))
add_tests("class_super_object",
"Ruby" => "class X < Object\nend",
"RawParseTree" => [:class,
:X,
[:const, :Object],
[:scope]],
"ParseTree" => s(:class,
:X,
s(:const, :Object),
s(:scope)))
add_tests("colon2",
"Ruby" => "X::Y",
"RawParseTree" => [:colon2, [:const, :X], :Y],
"ParseTree" => s(:colon2, s(:const, :X), :Y))
add_tests("colon3",
"Ruby" => "::X",
"RawParseTree" => [:colon3, :X],
"ParseTree" => s(:colon3, :X))
add_tests("const",
"Ruby" => "X",
"RawParseTree" => [:const, :X],
"ParseTree" => s(:const, :X))
add_tests("constX",
"Ruby" => "X = 1",
"RawParseTree" => [:cdecl, :X, [:lit, 1]],
"ParseTree" => s(:cdecl, :X, s(:lit, 1)))
add_tests("constY",
"Ruby" => "::X = 1",
"RawParseTree" => [:cdecl, [:colon3, :X], [:lit, 1]],
"ParseTree" => s(:cdecl, s(:colon3, :X), s(:lit, 1)))
add_tests("constZ",
"Ruby" => "X::Y = 1",
"RawParseTree" => [:cdecl, [:colon2, [:const, :X], :Y], [:lit, 1]],
"ParseTree" => s(:cdecl,
s(:colon2, s(:const, :X), :Y),
s(:lit, 1)))
add_tests("cvar",
"Ruby" => "@@x",
"RawParseTree" => [:cvar, :@@x],
"ParseTree" => s(:cvar, :@@x))
add_tests("cvasgn",
"Ruby" => "def x\n @@blah = 1\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block, [:args],
[:cvasgn, :@@blah, [:lit, 1]]]]],
"ParseTree" => s(:defn, :x,
s(:args),
s(:scope,
s(:block,
s(:cvasgn, :@@blah, s(:lit, 1))))))
add_tests("cvasgn_cls_method",
"Ruby" => "def self.quiet_mode=(boolean)\n @@quiet_mode = boolean\nend",
"RawParseTree" => [:defs, [:self], :quiet_mode=,
[:scope,
[:block,
[:args, :boolean],
[:cvasgn, :@@quiet_mode, [:lvar, :boolean]]]]],
"ParseTree" => s(:defs, s(:self), :quiet_mode=,
s(:args, :boolean),
s(:scope,
s(:block,
s(:cvasgn, :@@quiet_mode,
s(:lvar, :boolean))))))
add_tests("cvdecl",
"Ruby" => "class X\n @@blah = 1\nend",
"RawParseTree" => [:class, :X, nil,
[:scope, [:cvdecl, :@@blah, [:lit, 1]]]],
"ParseTree" => s(:class, :X, nil,
s(:scope, s(:cvdecl, :@@blah, s(:lit, 1)))))
add_tests("dasgn_0",
"Ruby" => "a.each { |x| b.each { |y| x = (x + 1) } if true }",
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :each],
[:dasgn_curr, :x],
[:if, [:true],
[:iter,
[:call, [:vcall, :b], :each],
[:dasgn_curr, :y],
[:dasgn, :x,
[:call, [:dvar, :x], :+,
[:array, [:lit, 1]]]]],
nil]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a, s(:arglist)), :each,
s(:arglist)),
s(:lasgn, :x),
s(:if, s(:true),
s(:iter,
s(:call, s(:call, nil, :b, s(:arglist)),
:each,
s(:arglist)),
s(:lasgn, :y),
s(:lasgn, :x,
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1))))),
nil)))
add_tests("dasgn_1",
"Ruby" => "a.each { |x| b.each { |y| c = (c + 1) } if true }",
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :each],
[:dasgn_curr, :x],
[:if, [:true],
[:iter,
[:call, [:vcall, :b], :each],
[:dasgn_curr, :y],
[:dasgn_curr, :c,
[:call, [:dvar, :c], :+,
[:array, [:lit, 1]]]]],
nil]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a, s(:arglist)), :each,
s(:arglist)),
s(:lasgn, :x),
s(:if, s(:true),
s(:iter,
s(:call, s(:call, nil, :b, s(:arglist)),
:each,
s(:arglist)),
s(:lasgn, :y),
s(:lasgn, :c,
s(:call, s(:lvar, :c), :+,
s(:arglist, s(:lit, 1))))),
nil)))
add_tests("dasgn_2",
"Ruby" => "a.each do |x|\n if true then\n c = 0\n b.each { |y| c = (c + 1) }\n end\nend", # FIX: hate that extra newline!
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :each],
[:dasgn_curr, :x],
[:if, [:true],
[:block,
[:dasgn_curr, :c, [:lit, 0]],
[:iter,
[:call, [:vcall, :b], :each],
[:dasgn_curr, :y],
[:dasgn, :c,
[:call, [:dvar, :c], :+,
[:array, [:lit, 1]]]]]],
nil]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :a, s(:arglist)), :each,
s(:arglist)),
s(:lasgn, :x),
s(:if, s(:true),
s(:block,
s(:lasgn, :c, s(:lit, 0)),
s(:iter,
s(:call, s(:call, nil, :b, s(:arglist)),
:each,
s(:arglist)),
s(:lasgn, :y),
s(:lasgn, :c,
s(:call, s(:lvar, :c), :+,
s(:arglist, s(:lit, 1)))))),
nil)))
add_tests("dasgn_curr",
"Ruby" => "data.each do |x, y|\n a = 1\n b = a\n b = a = x\nend",
"RawParseTree" => [:iter,
[:call, [:vcall, :data], :each],
[:masgn,
[:array, [:dasgn_curr, :x], [:dasgn_curr, :y]]],
[:block,
[:dasgn_curr, :a, [:lit, 1]],
[:dasgn_curr, :b, [:dvar, :a]],
[:dasgn_curr, :b,
[:dasgn_curr, :a, [:dvar, :x]]]]],
"ParseTree" => s(:iter,
s(:call, s(:call, nil, :data,
s(:arglist)), :each, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :x), s(:lasgn, :y))),
s(:block,
s(:lasgn, :a, s(:lit, 1)),
s(:lasgn, :b, s(:lvar, :a)),
s(:lasgn, :b, s(:lasgn, :a, s(:lvar, :x))))))
add_tests("dasgn_icky",
"Ruby" => "a do\n v = nil\n assert_block(full_message) do\n begin\n yield\n rescue Exception => v\n break\n end\n end\nend",
"RawParseTree" => [:iter,
[:fcall, :a],
nil,
[:block,
[:dasgn_curr, :v, [:nil]],
[:iter,
[:fcall, :assert_block,
[:array, [:vcall, :full_message]]],
nil,
[:begin,
[:rescue,
[:yield],
[:resbody,
[:array, [:const, :Exception]],
[:block,
[:dasgn, :v,
[:gvar, :$!]], [:break]]]]]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
nil,
s(:block,
s(:lasgn, :v, s(:nil)),
s(:iter,
s(:call, nil, :assert_block,
s(:arglist,
s(:call, nil, :full_message,
s(:arglist)))),
nil,
s(:rescue,
s(:yield),
s(:resbody,
s(:array,
s(:const, :Exception),
s(:lasgn, :v, s(:gvar, :$!))),
s(:break)))))))
add_tests("dasgn_mixed",
"Ruby" => "t = 0\nns.each { |n| t += n }\n",
"RawParseTree" => [:block,
[:lasgn, :t, [:lit, 0]],
[:iter,
[:call, [:vcall, :ns], :each],
[:dasgn_curr, :n],
[:lasgn, :t,
[:call, [:lvar, :t], :+,
[:array, [:dvar, :n]]]]]],
"ParseTree" => s(:block,
s(:lasgn, :t, s(:lit, 0)),
s(:iter,
s(:call, s(:call, nil, :ns,
s(:arglist)), :each, s(:arglist)),
s(:lasgn, :n),
s(:lasgn, :t,
s(:call, s(:lvar, :t), :+,
s(:arglist, s(:lvar, :n)))))),
"Ruby2Ruby" => "t = 0\nns.each { |n| t = (t + n) }\n")
add_tests("defined",
"Ruby" => "defined? $x",
"RawParseTree" => [:defined, [:gvar, :$x]],
"ParseTree" => s(:defined, s(:gvar, :$x)))
# TODO: make all the defn_args* p their arglist
add_tests("defn_args_block",
"Ruby" => "def f(&block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :"&block"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand",
"Ruby" => "def f(mand)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_block",
"Ruby" => "def f(mand, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"&block"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt",
"Ruby" => "def f(mand, opt = 42)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt,
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_block",
"Ruby" => "def f(mand, opt = 42, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt, :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_splat",
"Ruby" => "def f(mand, opt = 42, *rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt, :"*rest",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_splat_block",
"Ruby" => "def f(mand, opt = 42, *rest, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :opt, :"*rest", :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_opt_splat_no_name",
"Ruby" => "def x(a, b = 42, *)\n # do nothing\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :b, :"*",
[:block, [:lasgn, :b, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :b, :"*",
s(:block, s(:lasgn, :b, s(:lit, 42)))),
s(:scope,
s(:block,
s(:nil)))))
add_tests("defn_args_mand_splat",
"Ruby" => "def f(mand, *rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :"*rest"],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"*rest"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_splat_block",
"Ruby" => "def f(mand, *rest, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :mand, :"*rest"],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :mand, :"*rest", :"&block"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_mand_splat_no_name",
"Ruby" => "def x(a, *args)\n p(a, args)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :"*args"],
[:fcall, :p,
[:array, [:lvar, :a], [:lvar, :args]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :"*args"),
s(:scope,
s(:block,
s(:call, nil, :p,
s(:arglist, s(:lvar, :a), s(:lvar, :args)))))))
add_tests("defn_args_none",
"Ruby" => "def empty\n # do nothing\nend",
"RawParseTree" => [:defn, :empty,
[:scope, [:block, [:args], [:nil]]]],
"ParseTree" => s(:defn, :empty,
s(:args),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt",
"Ruby" => "def f(opt = 42)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt,
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_block",
"Ruby" => "def f(opt = 42, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt,
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt, :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_splat",
"Ruby" => "def f(opt = 42, *rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt, :"*rest",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_splat_block",
"Ruby" => "def f(opt = 42, *rest, &block)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :opt, :"*rest",
[:block,
[:lasgn, :opt, [:lit, 42]]]],
[:block_arg, :block],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :opt, :"*rest", :"&block",
s(:block,
s(:lasgn, :opt, s(:lit, 42)))),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_opt_splat_no_name",
"Ruby" => "def x(b = 42, *)\n # do nothing\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :b, :"*",
[:block, [:lasgn, :b, [:lit, 42]]]],
[:nil]]]],
"ParseTree" => s(:defn, :x,
s(:args, :b, :"*",
s(:block, s(:lasgn, :b, s(:lit, 42)))),
s(:scope,
s(:block,
s(:nil)))))
add_tests("defn_args_splat",
"Ruby" => "def f(*rest)\n # do nothing\nend",
"RawParseTree" => [:defn, :f,
[:scope,
[:block,
[:args, :"*rest"],
[:nil]]]],
"ParseTree" => s(:defn, :f,
s(:args, :"*rest"),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_args_splat_no_name",
"Ruby" => "def x(*)\n # do nothing\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :"*"],
[:nil]]]],
"ParseTree" => s(:defn, :x,
s(:args, :"*"),
s(:scope,
s(:block,
s(:nil)))))
add_tests("defn_or",
"Ruby" => "def |(o)\n # do nothing\nend",
"RawParseTree" => [:defn, :|,
[:scope, [:block, [:args, :o], [:nil]]]],
"ParseTree" => s(:defn, :|,
s(:args, :o),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_rescue",
"Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend",
"RawParseTree" => [:defn, :eql?,
[:scope,
[:block,
[:args, :resource],
[:rescue,
[:call,
[:call, [:self], :uuid],
:==,
[:array,
[:call, [:lvar, :resource], :uuid]]],
[:resbody, nil, [:false]]]]]],
"ParseTree" => s(:defn, :eql?,
s(:args, :resource),
s(:scope,
s(:block,
s(:rescue,
s(:call,
s(:call, s(:self), :uuid, s(:arglist)),
:==,
s(:arglist,
s(:call, s(:lvar, :resource),
:uuid, s(:arglist)))),
s(:resbody, s(:array), s(:false)))))),
"Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend")
add_tests("defn_rescue_mri_verbose_flag",
"Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid)\nrescue\n false\nend",
"RawParseTree" => [:defn, :eql?,
[:scope,
[:block,
[:args, :resource],
[:rescue,
[:call,
[:call, [:self], :uuid],
:==,
[:array,
[:call, [:lvar, :resource], :uuid]]],
[:resbody, nil, [:false]]]]]],
"ParseTree" => s(:defn, :eql?,
s(:args, :resource),
s(:scope,
s(:block,
s(:rescue,
s(:call,
s(:call, s(:self), :uuid, s(:arglist)),
:==,
s(:arglist,
s(:call, s(:lvar, :resource),
:uuid, s(:arglist)))),
s(:resbody, s(:array), s(:false)))))),
"Ruby2Ruby" => "def eql?(resource)\n (self.uuid == resource.uuid) rescue false\nend")
add_tests("defn_something_eh",
"Ruby" => "def something?\n # do nothing\nend",
"RawParseTree" => [:defn, :something?,
[:scope, [:block, [:args], [:nil]]]],
"ParseTree" => s(:defn, :something?,
s(:args),
s(:scope, s(:block, s(:nil)))))
add_tests("defn_splat_no_name",
"Ruby" => "def x(a, *)\n p(a)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :"*"],
[:fcall, :p,
[:array, [:lvar, :a]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :"*"),
s(:scope,
s(:block,
s(:call, nil, :p,
s(:arglist, s(:lvar, :a)))))))
add_tests("defn_zarray",
"Ruby" => "def zarray\n a = []\n return a\nend",
"RawParseTree" => [:defn, :zarray,
[:scope,
[:block, [:args],
[:lasgn, :a, [:zarray]],
[:return, [:lvar, :a]]]]],
"ParseTree" => s(:defn, :zarray,
s(:args),
s(:scope,
s(:block,
s(:lasgn, :a, s(:array)),
s(:return, s(:lvar, :a))))))
add_tests("defs",
"Ruby" => "def self.x(y)\n (y + 1)\nend",
"RawParseTree" => [:defs, [:self], :x,
[:scope,
[:block,
[:args, :y],
[:call, [:lvar, :y], :+,
[:array, [:lit, 1]]]]]],
"ParseTree" => s(:defs, s(:self), :x,
s(:args, :y),
s(:scope,
s(:block,
s(:call, s(:lvar, :y), :+,
s(:arglist, s(:lit, 1)))))))
add_tests("defs_empty",
"Ruby" => "def self.empty\n # do nothing\nend",
"RawParseTree" => [:defs, [:self], :empty,
[:scope, [:args]]],
"ParseTree" => s(:defs, s(:self), :empty,
s(:args),
s(:scope, s(:block))))
add_tests("defs_empty_args",
"Ruby" => "def self.empty(*)\n # do nothing\nend",
"RawParseTree" => [:defs, [:self], :empty,
[:scope, [:args, :*]]],
"ParseTree" => s(:defs, s(:self), :empty,
s(:args, :*),
s(:scope, s(:block))))
add_tests("dmethod",
"Ruby" => [Examples, :dmethod_added],
"RawParseTree" => [:defn, :dmethod_added,
[:dmethod,
:a_method,
[:scope,
[:block,
[:args, :x],
[:call, [:lvar, :x], :+,
[:array, [:lit, 1]]]]]]],
"ParseTree" => s(:defn, :dmethod_added,
s(:args, :x),
s(:scope,
s(:block,
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def dmethod_added(x)\n (x + 1)\nend")
add_tests("dot2",
"Ruby" => "(a..b)",
"RawParseTree" => [:dot2, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:dot2,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("dot3",
"Ruby" => "(a...b)",
"RawParseTree" => [:dot3, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:dot3,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("dregx",
"Ruby" => "/x#\{(1 + 1)}y/",
"RawParseTree" => [:dregx, "x",
[:evstr,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
[:str, "y"]],
"ParseTree" => s(:dregx, "x",
s(:evstr,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
s(:str, "y")))
add_tests("dregx_interp",
"Ruby" => "/#\{@rakefile}/",
"RawParseTree" => [:dregx, '', [:evstr, [:ivar, :@rakefile]]],
"ParseTree" => s(:dregx, '', s(:evstr, s(:ivar, :@rakefile))))
add_tests("dregx_interp_empty",
"Ruby" => "/a#\{}b/",
"RawParseTree" => [:dregx, 'a', [:evstr], [:str, "b"]],
"ParseTree" => s(:dregx, 'a', s(:evstr), s(:str, "b")))
add_tests("dregx_n",
"Ruby" => '/#{1}/n',
"RawParseTree" => [:dregx, '', [:evstr, [:lit, 1]], /x/n.options],
"ParseTree" => s(:dregx, '',
s(:evstr, s(:lit, 1)), /x/n.options),
"Ruby2Ruby" => "/#\{1}/") # HACK - need to support regexp flag
add_tests("dregx_once",
"Ruby" => "/x#\{(1 + 1)}y/o",
"RawParseTree" => [:dregx_once, "x",
[:evstr,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]]],
[:str, "y"]],
"ParseTree" => s(:dregx_once, "x",
s(:evstr,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
s(:str, "y")))
add_tests("dregx_once_n_interp",
"Ruby" => "/#\{IAC}#\{SB}/no",
"RawParseTree" => [:dregx_once, '',
[:evstr, [:const, :IAC]],
[:evstr, [:const, :SB]], /x/n.options],
"ParseTree" => s(:dregx_once, '',
s(:evstr, s(:const, :IAC)),
s(:evstr, s(:const, :SB)), /x/n.options),
"Ruby2Ruby" => "/#\{IAC}#\{SB}/o") # HACK
add_tests("dstr",
"Ruby" => "argl = 1\n\"x#\{argl}y\"\n",
"RawParseTree" => [:block,
[:lasgn, :argl, [:lit, 1]],
[:dstr, "x", [:evstr, [:lvar, :argl]],
[:str, "y"]]],
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr, "x", s(:evstr, s(:lvar, :argl)),
s(:str, "y"))))
add_tests("dstr_2",
"Ruby" => "argl = 1\n\"x#\{(\"%.2f\" % 3.14159)}y\"\n",
"RawParseTree" => [:block,
[:lasgn, :argl, [:lit, 1]],
[:dstr,
"x",
[:evstr,
[:call, [:str, "%.2f"], :%,
[:array, [:lit, 3.14159]]]],
[:str, "y"]]],
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr,
"x",
s(:evstr,
s(:call, s(:str, "%.2f"), :%,
s(:arglist, s(:lit, 3.14159)))),
s(:str, "y"))))
add_tests("dstr_3",
"Ruby" => "max = 2\nargl = 1\n\"x#\{(\"%.#\{max}f\" % 3.14159)}y\"\n",
"RawParseTree" => [:block,
[:lasgn, :max, [:lit, 2]],
[:lasgn, :argl, [:lit, 1]],
[:dstr, "x",
[:evstr,
[:call,
[:dstr, "%.",
[:evstr, [:lvar, :max]],
[:str, "f"]],
:%,
[:array, [:lit, 3.14159]]]],
[:str, "y"]]],
"ParseTree" => s(:block,
s(:lasgn, :max, s(:lit, 2)),
s(:lasgn, :argl, s(:lit, 1)),
s(:dstr, "x",
s(:evstr,
s(:call,
s(:dstr, "%.",
s(:evstr, s(:lvar, :max)),
s(:str, "f")),
:%,
s(:arglist, s(:lit, 3.14159)))),
s(:str, "y"))))
add_tests("dstr_concat",
"Ruby" => '"#{22}aa" "cd#{44}" "55" "#{66}"',
"RawParseTree" => [:dstr,
"",
[:evstr, [:lit, 22]],
[:str, "aa"],
[:str, "cd"],
[:evstr, [:lit, 44]],
[:str, "55"],
[:evstr, [:lit, 66]]],
"ParseTree" => s(:dstr,
"",
s(:evstr, s(:lit, 22)),
s(:str, "aa"),
s(:str, "cd"),
s(:evstr, s(:lit, 44)),
s(:str, "55"),
s(:evstr, s(:lit, 66))),
"Ruby2Ruby" => '"#{22}aacd#{44}55#{66}"')
add_tests("dstr_gross",
"Ruby" => '"a #$global b #@ivar c #@@cvar d"',
"RawParseTree" => [:dstr, "a ",
[:evstr, [:gvar, :$global]],
[:str, " b "],
[:evstr, [:ivar, :@ivar]],
[:str, " c "],
[:evstr, [:cvar, :@@cvar]],
[:str, " d"]],
"ParseTree" => s(:dstr, "a ",
s(:evstr, s(:gvar, :$global)),
s(:str, " b "),
s(:evstr, s(:ivar, :@ivar)),
s(:str, " c "),
s(:evstr, s(:cvar, :@@cvar)),
s(:str, " d")),
"Ruby2Ruby" => '"a #{$global} b #{@ivar} c #{@@cvar} d"')
add_tests("dstr_heredoc_expand",
"Ruby" => "<<EOM\n blah\n#\{1 + 1}blah\nEOM\n",
"RawParseTree" => [:dstr, " blah\n",
[:evstr, [:call, [:lit, 1], :+,
[:array, [:lit, 1]]]],
[:str, "blah\n"]],
"ParseTree" => s(:dstr, " blah\n",
s(:evstr, s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))),
s(:str, "blah\n")),
"Ruby2Ruby" => "\" blah\\n#\{(1 + 1)}blah\\n\"")
add_tests("dstr_heredoc_windoze_sucks",
"Ruby" => "<<-EOF\r\ndef test_#\{action}_valid_feed\r\n EOF\r\n",
"RawParseTree" => [:dstr,
'def test_',
[:evstr, [:vcall, :action]],
[:str, "_valid_feed\n"]],
"ParseTree" => s(:dstr,
'def test_',
s(:evstr, s(:call, nil, :action, s(:arglist))),
s(:str, "_valid_feed\n")),
"Ruby2Ruby" => "\"def test_#\{action}_valid_feed\\n\"")
add_tests("dstr_heredoc_yet_again",
"Ruby" => "<<-EOF\ns1 '#\{RUBY_PLATFORM}' s2\n#\{__FILE__}\n EOF\n",
"RawParseTree" => [:dstr, "s1 '",
[:evstr, [:const, :RUBY_PLATFORM]],
[:str, "' s2\n"],
[:str, "(string)"],
[:str, "\n"]],
"ParseTree" => s(:dstr, "s1 '",
s(:evstr, s(:const, :RUBY_PLATFORM)),
s(:str, "' s2\n"),
s(:str, "(string)"),
s(:str, "\n")),
"Ruby2Ruby" => "\"s1 '#\{RUBY_PLATFORM}' s2\\n(string)\\n\"")
add_tests("dstr_nest",
"Ruby" => "%Q[before [#\{nest}] after]",
"RawParseTree" => [:dstr, "before [",
[:evstr, [:vcall, :nest]], [:str, "] after"]],
"ParseTree" => s(:dstr, "before [",
s(:evstr, s(:call, nil, :nest, s(:arglist))),
s(:str, "] after")),
"Ruby2Ruby" => "\"before [#\{nest}] after\"")
add_tests("dstr_str_lit_start",
"Ruby" => '"#{"blah"}#{__FILE__}:#{__LINE__}: warning: #{$!.message} (#{$!.class})"',
"RawParseTree" => [:dstr,
"blah(string):",
[:evstr, [:lit, 1]],
[:str, ": warning: "],
[:evstr, [:call, [:gvar, :$!], :message]],
[:str, " ("],
[:evstr, [:call, [:gvar, :$!], :class]],
[:str, ")"]],
"ParseTree" => s(:dstr,
"blah(string):",
s(:evstr, s(:lit, 1)),
s(:str, ": warning: "),
s(:evstr, s(:call, s(:gvar, :$!), :message,
s(:arglist))),
s(:str, " ("),
s(:evstr, s(:call, s(:gvar, :$!), :class,
s(:arglist))),
s(:str, ")")),
"Ruby2Ruby" => '"blah(string):#{1}: warning: #{$!.message} (#{$!.class})"')
add_tests("dstr_the_revenge",
"Ruby" => '"before #{from} middle #{to} (#{__FILE__}:#{__LINE__})"',
"RawParseTree" => [:dstr,
"before ",
[:evstr, [:vcall, :from]],
[:str, " middle "],
[:evstr, [:vcall, :to]],
[:str, " ("],
[:str, "(string)"],
[:str, ":"],
[:evstr, [:lit, 1]],
[:str, ")"]],
"ParseTree" => s(:dstr,
"before ",
s(:evstr, s(:call, nil, :from, s(:arglist))),
s(:str, " middle "),
s(:evstr, s(:call, nil, :to, s(:arglist))),
s(:str, " ("),
s(:str, "(string)"),
s(:str, ":"),
s(:evstr, s(:lit, 1)),
s(:str, ")")),
"Ruby2Ruby" => '"before #{from} middle #{to} ((string):#{1})"')
add_tests("dsym",
"Ruby" => ":\"x#\{(1 + 1)}y\"",
"RawParseTree" => [:dsym, "x",
[:evstr, [:call, [:lit, 1], :+,
[:array, [:lit, 1]]]], [:str, "y"]],
"ParseTree" => s(:dsym, "x",
s(:evstr, s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1)))), s(:str, "y")))
add_tests("dxstr",
"Ruby" => "t = 5\n`touch #\{t}`\n",
"RawParseTree" => [:block,
[:lasgn, :t, [:lit, 5]],
[:dxstr, 'touch ', [:evstr, [:lvar, :t]]]],
"ParseTree" => s(:block,
s(:lasgn, :t, s(:lit, 5)),
s(:dxstr, 'touch ', s(:evstr, s(:lvar, :t)))))
add_tests("ensure",
"Ruby" => "begin\n (1 + 1)\nrescue SyntaxError => e1\n 2\nrescue Exception => e2\n 3\nelse\n 4\nensure\n 5\nend",
"RawParseTree" => [:begin,
[:ensure,
[:rescue,
[:call, [:lit, 1], :+, [:array, [:lit, 1]]],
[:resbody,
[:array, [:const, :SyntaxError]],
[:block,
[:lasgn, :e1, [:gvar, :$!]], [:lit, 2]],
[:resbody,
[:array, [:const, :Exception]],
[:block,
[:lasgn, :e2, [:gvar, :$!]], [:lit, 3]]]],
[:lit, 4]],
[:lit, 5]]],
"ParseTree" => s(:ensure,
s(:rescue,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))),
s(:resbody,
s(:array,
s(:const, :SyntaxError),
s(:lasgn, :e1, s(:gvar, :$!))),
s(:lit, 2)),
s(:resbody,
s(:array,
s(:const, :Exception),
s(:lasgn, :e2, s(:gvar, :$!))),
s(:lit, 3)),
s(:lit, 4)),
s(:lit, 5)))
add_tests("false",
"Ruby" => "false",
"RawParseTree" => [:false],
"ParseTree" => s(:false))
add_tests("fbody",
"Ruby" => [Examples, :an_alias],
"RawParseTree" => [:defn, :an_alias,
[:fbody,
[:scope,
[:block,
[:args, :x],
[:call, [:lvar, :x], :+,
[:array, [:lit, 1]]]]]]],
"ParseTree" => s(:defn, :an_alias,
s(:args, :x),
s(:scope,
s(:block,
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1)))))),
"Ruby2Ruby" => "def an_alias(x)\n (x + 1)\nend")
add_tests("fcall_arglist",
"Ruby" => "m(42)",
"RawParseTree" => [:fcall, :m, [:array, [:lit, 42]]],
"ParseTree" => s(:call, nil, :m, s(:arglist, s(:lit, 42))))
add_tests("fcall_arglist_hash",
"Ruby" => "m(:a => 1, :b => 2)",
"RawParseTree" => [:fcall, :m,
[:array,
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call, nil, :m,
s(:arglist,
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("fcall_arglist_norm_hash",
"Ruby" => "m(42, :a => 1, :b => 2)",
"RawParseTree" => [:fcall, :m,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]]],
"ParseTree" => s(:call, nil, :m,
s(:arglist,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2)))))
add_tests("fcall_arglist_norm_hash_splat",
"Ruby" => "m(42, :a => 1, :b => 2, *c)",
"RawParseTree" => [:fcall, :m,
[:argscat,
[:array,
[:lit, 42],
[:hash,
[:lit, :a], [:lit, 1],
[:lit, :b], [:lit, 2]]],
[:vcall, :c]]],
"ParseTree" => s(:call, nil, :m,
s(:argscat,
s(:array,
s(:lit, 42),
s(:hash,
s(:lit, :a), s(:lit, 1),
s(:lit, :b), s(:lit, 2))),
s(:call, nil, :c, s(:arglist)))))
add_tests("fcall_block",
"Ruby" => "a(:b) { :c }",
"RawParseTree" => [:iter,
[:fcall, :a, [:array, [:lit, :b]]], nil,
[:lit, :c]],
"ParseTree" => s(:iter,
s(:call, nil, :a,
s(:arglist, s(:lit, :b))), nil,
s(:lit, :c)))
add_tests("fcall_index_space",
"Ruby" => "a [42]",
"RawParseTree" => [:fcall, :a, [:array, [:array, [:lit, 42]]]],
"ParseTree" => s(:call, nil, :a,
s(:arglist, s(:array, s(:lit, 42)))),
"Ruby2Ruby" => "a([42])")
add_tests("fcall_keyword",
"Ruby" => "42 if block_given?",
"RawParseTree" => [:if, [:fcall, :block_given?], [:lit, 42], nil],
"ParseTree" => s(:if,
s(:call, nil, :block_given?, s(:arglist)),
s(:lit, 42), nil))
add_tests("flip2",
"Ruby" => "x = if ((i % 4) == 0)..((i % 3) == 0) then\n i\nelse\n nil\nend",
"RawParseTree" => [:lasgn,
:x,
[:if,
[:flip2,
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 4]]],
:==,
[:array, [:lit, 0]]],
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 3]]],
:==,
[:array, [:lit, 0]]]],
[:vcall, :i],
[:nil]]],
"ParseTree" => s(:lasgn,
:x,
s(:if,
s(:flip2,
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 4))),
:==,
s(:arglist, s(:lit, 0))),
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 3))),
:==,
s(:arglist, s(:lit, 0)))),
s(:call, nil, :i, s(:arglist)),
s(:nil))))
add_tests("flip2_method",
"Ruby" => "if 1..2.a?(b) then\n nil\nend",
"RawParseTree" => [:if,
[:flip2,
[:lit, 1],
[:call, [:lit, 2], :a?,
[:array, [:vcall, :b]]]],
[:nil],
nil],
"ParseTree" => s(:if,
s(:flip2,
s(:lit, 1),
s(:call, s(:lit, 2), :a?,
s(:arglist,
s(:call, nil, :b, s(:arglist))))),
s(:nil),
nil))
add_tests("flip3",
"Ruby" => "x = if ((i % 4) == 0)...((i % 3) == 0) then\n i\nelse\n nil\nend",
"RawParseTree" => [:lasgn,
:x,
[:if,
[:flip3,
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 4]]],
:==,
[:array, [:lit, 0]]],
[:call,
[:call, [:vcall, :i], :%,
[:array, [:lit, 3]]],
:==,
[:array, [:lit, 0]]]],
[:vcall, :i],
[:nil]]],
"ParseTree" => s(:lasgn,
:x,
s(:if,
s(:flip3,
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 4))),
:==,
s(:arglist, s(:lit, 0))),
s(:call,
s(:call, s(:call, nil, :i, s(:arglist)),
:%,
s(:arglist, s(:lit, 3))),
:==,
s(:arglist, s(:lit, 0)))),
s(:call, nil, :i, s(:arglist)),
s(:nil))))
add_tests("for",
"Ruby" => "for o in ary do\n puts(o)\nend",
"RawParseTree" => [:for,
[:vcall, :ary],
[:lasgn, :o],
[:fcall, :puts, [:array, [:lvar, :o]]]],
"ParseTree" => s(:for,
s(:call, nil, :ary, s(:arglist)),
s(:lasgn, :o),
s(:call, nil, :puts,
s(:arglist, s(:lvar, :o)))))
add_tests("for_no_body",
"Ruby" => "for i in (0..max) do\n # do nothing\nend",
"RawParseTree" => [:for,
[:dot2, [:lit, 0], [:vcall, :max]],
[:lasgn, :i]],
"ParseTree" => s(:for,
s(:dot2,
s(:lit, 0),
s(:call, nil, :max, s(:arglist))),
s(:lasgn, :i)))
add_tests("gasgn",
"Ruby" => "$x = 42",
"RawParseTree" => [:gasgn, :$x, [:lit, 42]],
"ParseTree" => s(:gasgn, :$x, s(:lit, 42)))
add_tests("global",
"Ruby" => "$stderr",
"RawParseTree" => [:gvar, :$stderr],
"ParseTree" => s(:gvar, :$stderr))
add_tests("gvar",
"Ruby" => "$x",
"RawParseTree" => [:gvar, :$x],
"ParseTree" => s(:gvar, :$x))
add_tests("gvar_underscore",
"Ruby" => "$_",
"RawParseTree" => [:gvar, :$_],
"ParseTree" => s(:gvar, :$_))
add_tests("gvar_underscore_blah",
"Ruby" => "$__blah",
"RawParseTree" => [:gvar, :$__blah],
"ParseTree" => s(:gvar, :$__blah))
add_tests("hash",
"Ruby" => "{ 1 => 2, 3 => 4 }",
"RawParseTree" => [:hash,
[:lit, 1], [:lit, 2],
[:lit, 3], [:lit, 4]],
"ParseTree" => s(:hash,
s(:lit, 1), s(:lit, 2),
s(:lit, 3), s(:lit, 4)))
add_tests("hash_rescue",
"Ruby" => "{ 1 => (2 rescue 3) }",
"RawParseTree" => [:hash,
[:lit, 1],
[:rescue,
[:lit, 2],
[:resbody, nil, [:lit, 3]]]],
"ParseTree" => s(:hash,
s(:lit, 1),
s(:rescue,
s(:lit, 2),
s(:resbody, s(:array), s(:lit, 3)))))
add_tests("iasgn",
"Ruby" => "@a = 4",
"RawParseTree" => [:iasgn, :@a, [:lit, 4]],
"ParseTree" => s(:iasgn, :@a, s(:lit, 4)))
add_tests("if_block_condition",
"Ruby" => "if (x = 5\n(x + 1)) then\n nil\nend",
"RawParseTree" => [:if,
[:block,
[:lasgn, :x, [:lit, 5]],
[:call,
[:lvar, :x],
:+,
[:array, [:lit, 1]]]],
[:nil],
nil],
"ParseTree" => s(:if,
s(:block,
s(:lasgn, :x, s(:lit, 5)),
s(:call,
s(:lvar, :x),
:+,
s(:arglist, s(:lit, 1)))),
s(:nil),
nil))
add_tests("if_lasgn_short",
"Ruby" => "if x = obj.x then\n x.do_it\nend",
"RawParseTree" => [:if,
[:lasgn, :x,
[:call, [:vcall, :obj], :x]],
[:call,
[:lvar, :x], :do_it],
nil],
"ParseTree" => s(:if,
s(:lasgn, :x,
s(:call,
s(:call, nil, :obj, s(:arglist)),
:x, s(:arglist))),
s(:call, s(:lvar, :x), :do_it, s(:arglist)),
nil))
add_tests("if_nested",
"Ruby" => "return if false unless true",
"RawParseTree" => [:if, [:true], nil,
[:if, [:false], [:return], nil]],
"ParseTree" => s(:if, s(:true), nil,
s(:if, s(:false), s(:return), nil)))
add_tests("if_post",
"Ruby" => "a if b",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil))
add_tests("if_post_not",
"Ruby" => "a if not b",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))),
"Ruby2Ruby" => "a unless b")
add_tests("if_pre",
"Ruby" => "if b then a end",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil),
"Ruby2Ruby" => "a if b")
add_tests("if_pre_not",
"Ruby" => "if not b then a end",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))),
"Ruby2Ruby" => "a unless b")
add_tests("iter_call_arglist_space",
"Ruby" => "a (1) {|c|d}",
"RawParseTree" => [:iter,
[:fcall, :a, [:array, [:lit, 1]]],
[:dasgn_curr, :c],
[:vcall, :d]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist, s(:lit, 1))),
s(:lasgn, :c),
s(:call, nil, :d, s(:arglist))),
"Ruby2Ruby" => "a(1) { |c| d }")
add_tests("iter_dasgn_curr_dasgn_madness",
"Ruby" => "as.each { |a|\n b += a.b(false) }",
"RawParseTree" => [:iter,
[:call, [:vcall, :as], :each],
[:dasgn_curr, :a],
[:dasgn_curr,
:b,
[:call,
[:dvar, :b],
:+,
[:array,
[:call, [:dvar, :a], :b,
[:array, [:false]]]]]]],
"ParseTree" => s(:iter,
s(:call,
s(:call, nil, :as, s(:arglist)),
:each, s(:arglist)),
s(:lasgn, :a),
s(:lasgn, :b,
s(:call,
s(:lvar, :b),
:+,
s(:arglist,
s(:call, s(:lvar, :a), :b,
s(:arglist, s(:false))))))),
"Ruby2Ruby" => "as.each { |a| b = (b + a.b(false)) }")
add_tests("iter_downto",
"Ruby" => "3.downto(1) { |n| puts(n.to_s) }",
"RawParseTree" => [:iter,
[:call, [:lit, 3], :downto, [:array, [:lit, 1]]],
[:dasgn_curr, :n],
[:fcall, :puts,
[:array, [:call, [:dvar, :n], :to_s]]]],
"ParseTree" => s(:iter,
s(:call, s(:lit, 3), :downto,
s(:arglist, s(:lit, 1))),
s(:lasgn, :n),
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :n),
:to_s, s(:arglist))))))
add_tests("iter_each_lvar",
"Ruby" => "array = [1, 2, 3]\narray.each { |x| puts(x.to_s) }\n",
"RawParseTree" => [:block,
[:lasgn, :array,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
[:iter,
[:call, [:lvar, :array], :each],
[:dasgn_curr, :x],
[:fcall, :puts,
[:array, [:call, [:dvar, :x], :to_s]]]]],
"ParseTree" => s(:block,
s(:lasgn, :array,
s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
s(:iter,
s(:call, s(:lvar, :array), :each,
s(:arglist)),
s(:lasgn, :x),
s(:call, nil, :puts,
s(:arglist, s(:call, s(:lvar, :x),
:to_s, s(:arglist)))))))
add_tests("iter_each_nested",
"Ruby" => "array1 = [1, 2, 3]\narray2 = [4, 5, 6, 7]\narray1.each do |x|\n array2.each do |y|\n puts(x.to_s)\n puts(y.to_s)\n end\nend\n",
"RawParseTree" => [:block,
[:lasgn, :array1,
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
[:lasgn, :array2,
[:array,
[:lit, 4], [:lit, 5], [:lit, 6], [:lit, 7]]],
[:iter,
[:call,
[:lvar, :array1], :each],
[:dasgn_curr, :x],
[:iter,
[:call,
[:lvar, :array2], :each],
[:dasgn_curr, :y],
[:block,
[:fcall, :puts,
[:array, [:call, [:dvar, :x], :to_s]]],
[:fcall, :puts,
[:array, [:call, [:dvar, :y], :to_s]]]]]]],
"ParseTree" => s(:block,
s(:lasgn, :array1,
s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
s(:lasgn, :array2,
s(:array,
s(:lit, 4), s(:lit, 5),
s(:lit, 6), s(:lit, 7))),
s(:iter,
s(:call,
s(:lvar, :array1), :each, s(:arglist)),
s(:lasgn, :x),
s(:iter,
s(:call,
s(:lvar, :array2), :each, s(:arglist)),
s(:lasgn, :y),
s(:block,
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :x),
:to_s, s(:arglist)))),
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :y),
:to_s, s(:arglist)))))))))
add_tests("iter_loop_empty",
"Ruby" => "loop { }",
"RawParseTree" => [:iter, [:fcall, :loop], nil],
"ParseTree" => s(:iter, s(:call, nil, :loop, s(:arglist)), nil))
add_tests("iter_masgn_2",
"Ruby" => "a { |b, c| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:array, [:dasgn_curr, :b], [:dasgn_curr, :c]]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :b), s(:lasgn, :c))),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_args_splat",
"Ruby" => "a { |b, c, *d| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:array, [:dasgn_curr, :b], [:dasgn_curr, :c]],
[:dasgn_curr, :d]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :b), s(:lasgn, :c)),
s(:lasgn, :d)),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_args_splat_no_name",
"Ruby" => "a { |b, c, *| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:array, [:dasgn_curr, :b], [:dasgn_curr, :c]],
[:splat]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:array, s(:lasgn, :b), s(:lasgn, :c)),
s(:splat)),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_splat",
"Ruby" => "a { |*c| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn, [:dasgn_curr, :c]],
[:fcall, :p, [:array, [:dvar, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn, s(:lasgn, :c)),
s(:call, nil, :p, s(:arglist, s(:lvar, :c)))))
add_tests("iter_masgn_splat_no_name",
"Ruby" => "a { |*| p(c) }",
"RawParseTree" => [:iter,
[:fcall, :a],
[:masgn,
[:splat]],
[:fcall, :p, [:array, [:vcall, :c]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:masgn,
s(:splat)),
s(:call, nil, :p,
s(:arglist, s(:call, nil, :c, s(:arglist))))))
add_tests("iter_shadowed_var",
"Ruby" => "a do |x|\n b do |x|\n puts x\n end\nend",
"RawParseTree" => [:iter,
[:fcall, :a],
[:dasgn_curr, :x],
[:iter,
[:fcall, :b],
[:dasgn, :x],
[:fcall, :puts, [:array, [:dvar, :x]]]]],
"ParseTree" => s(:iter,
s(:call, nil, :a, s(:arglist)),
s(:lasgn, :x),
s(:iter,
s(:call, nil, :b, s(:arglist)),
s(:lasgn, :x),
s(:call, nil, :puts,
s(:arglist, s(:lvar, :x))))),
"Ruby2Ruby" => "a { |x| b { |x| puts(x) } }")
add_tests("iter_upto",
"Ruby" => "1.upto(3) { |n| puts(n.to_s) }",
"RawParseTree" => [:iter,
[:call, [:lit, 1], :upto, [:array, [:lit, 3]]],
[:dasgn_curr, :n],
[:fcall, :puts,
[:array, [:call, [:dvar, :n], :to_s]]]],
"ParseTree" => s(:iter,
s(:call, s(:lit, 1), :upto,
s(:arglist, s(:lit, 3))),
s(:lasgn, :n),
s(:call, nil, :puts,
s(:arglist,
s(:call, s(:lvar, :n), :to_s,
s(:arglist))))))
add_tests("iter_while",
"Ruby" => "argl = 10\nwhile (argl >= 1) do\n puts(\"hello\")\n argl = (argl - 1)\nend\n",
"RawParseTree" => [:block,
[:lasgn, :argl, [:lit, 10]],
[:while,
[:call, [:lvar, :argl], :">=",
[:array, [:lit, 1]]],
[:block,
[:fcall, :puts, [:array, [:str, "hello"]]],
[:lasgn,
:argl,
[:call, [:lvar, :argl],
:"-", [:array, [:lit, 1]]]]], true]],
"ParseTree" => s(:block,
s(:lasgn, :argl, s(:lit, 10)),
s(:while,
s(:call, s(:lvar, :argl), :">=",
s(:arglist, s(:lit, 1))),
s(:block,
s(:call, nil, :puts,
s(:arglist, s(:str, "hello"))),
s(:lasgn,
:argl,
s(:call, s(:lvar, :argl), :"-",
s(:arglist, s(:lit, 1))))), true)))
add_tests("ivar",
"Ruby" => [Examples, :reader],
"RawParseTree" => [:defn, :reader, [:ivar, :@reader]],
"ParseTree" => s(:defn, :reader, # FIX should be unified?
s(:args),
s(:ivar, :@reader)),
"Ruby2Ruby" => "attr_reader :reader")
add_tests("lasgn_array",
"Ruby" => "var = [\"foo\", \"bar\"]",
"RawParseTree" => [:lasgn, :var,
[:array,
[:str, "foo"],
[:str, "bar"]]],
"ParseTree" => s(:lasgn, :var,
s(:array,
s(:str, "foo"),
s(:str, "bar"))))
add_tests("lasgn_call",
"Ruby" => "c = (2 + 3)",
"RawParseTree" => [:lasgn, :c, [:call, [:lit, 2], :+,
[:array, [:lit, 3]]]],
"ParseTree" => s(:lasgn, :c, s(:call, s(:lit, 2), :+,
s(:arglist, s(:lit, 3)))))
add_tests("lit_bool_false",
"Ruby" => "false",
"RawParseTree" => [:false],
"ParseTree" => s(:false))
add_tests("lit_bool_true",
"Ruby" => "true",
"RawParseTree" => [:true],
"ParseTree" => s(:true))
add_tests("lit_float",
"Ruby" => "1.1",
"RawParseTree" => [:lit, 1.1],
"ParseTree" => s(:lit, 1.1))
add_tests("lit_long",
"Ruby" => "1",
"RawParseTree" => [:lit, 1],
"ParseTree" => s(:lit, 1))
add_tests("lit_long_negative",
"Ruby" => "-1",
"RawParseTree" => [:lit, -1],
"ParseTree" => s(:lit, -1))
add_tests("lit_range2",
"Ruby" => "(1..10)",
"RawParseTree" => [:lit, 1..10],
"ParseTree" => s(:lit, 1..10))
add_tests("lit_range3",
"Ruby" => "(1...10)",
"RawParseTree" => [:lit, 1...10],
"ParseTree" => s(:lit, 1...10))
# TODO: discuss and decide which lit we like
# it "converts a regexp to an sexp" do
# "/blah/".to_sexp.should == s(:regex, "blah", 0)
# "/blah/i".to_sexp.should == s(:regex, "blah", 1)
# "/blah/u".to_sexp.should == s(:regex, "blah", 64)
# end
add_tests("lit_regexp",
"Ruby" => "/x/",
"RawParseTree" => [:lit, /x/],
"ParseTree" => s(:lit, /x/))
add_tests("lit_regexp_i_wwtt",
"Ruby" => 'str.split(//i)',
"RawParseTree" => [:call, [:vcall, :str], :split,
[:array, [:lit, //i]]],
"ParseTree" => s(:call, s(:call, nil, :str, s(:arglist)), :split,
s(:arglist, s(:lit, //i))))
add_tests("lit_regexp_n",
"Ruby" => "/x/n", # HACK differs on 1.9 - this is easiest
"RawParseTree" => [:lit, /x/n],
"ParseTree" => s(:lit, /x/n),
"Ruby2Ruby" => /x/n.inspect)
add_tests("lit_regexp_once",
"Ruby" => "/x/o",
"RawParseTree" => [:lit, /x/],
"ParseTree" => s(:lit, /x/),
"Ruby2Ruby" => "/x/")
add_tests("lit_sym",
"Ruby" => ":x",
"RawParseTree" => [:lit, :x],
"ParseTree" => s(:lit, :x))
add_tests("lit_sym_splat",
"Ruby" => ":\"*args\"",
"RawParseTree" => [:lit, :"*args"],
"ParseTree" => s(:lit, :"*args"))
add_tests("lvar_def_boundary",
"Ruby" => "b = 42\ndef a\n c do\n begin\n do_stuff\n rescue RuntimeError => b\n puts(b)\n end\n end\nend\n",
"RawParseTree" => [:block,
[:lasgn, :b, [:lit, 42]],
[:defn, :a,
[:scope,
[:block,
[:args],
[:iter,
[:fcall, :c],
nil,
[:begin,
[:rescue,
[:vcall, :do_stuff],
[:resbody,
[:array, [:const, :RuntimeError]],
[:block,
[:dasgn_curr, :b, [:gvar, :$!]],
[:fcall, :puts,
[:array, [:dvar, :b]]]]]]]]]]]],
"ParseTree" => s(:block,
s(:lasgn, :b, s(:lit, 42)),
s(:defn, :a,
s(:args),
s(:scope,
s(:block,
s(:iter,
s(:call, nil, :c, s(:arglist)),
nil,
s(:rescue,
s(:call, nil, :do_stuff, s(:arglist)),
s(:resbody,
s(:array,
s(:const, :RuntimeError),
s(:lasgn, :b, s(:gvar, :$!))),
s(:call, nil, :puts,
s(:arglist,
s(:lvar, :b)))))))))))
add_tests("masgn",
"Ruby" => "a, b = c, d",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:array, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:array, s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))))
add_tests("masgn_argscat",
"Ruby" => "a, b, *c = 1, 2, *[3, 4]",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:argscat,
[:array, [:lit, 1], [:lit, 2]],
[:array, [:lit, 3], [:lit, 4]]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:argscat,
s(:array, s(:lit, 1), s(:lit, 2)),
s(:array, s(:lit, 3), s(:lit, 4)))))
add_tests("masgn_attrasgn",
"Ruby" => "a, b.c = d, e",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a],
[:attrasgn, [:vcall, :b], :c=]],
[:array, [:vcall, :d], [:vcall, :e]]],
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:attrasgn,
s(:call, nil, :b, s(:arglist)),
:c=, s(:arglist))),
s(:array,
s(:call, nil, :d, s(:arglist)),
s(:call, nil, :e, s(:arglist)))))
add_tests("masgn_attrasgn_array_rhs",
"Ruby" => "a.b, a.c, _ = q",
"RawParseTree" => [:masgn,
[:array,
[:attrasgn, [:vcall, :a], :b=],
[:attrasgn, [:vcall, :a], :c=],
[:lasgn, :_]],
[:to_ary, [:vcall, :q]]],
"ParseTree" => s(:masgn,
s(:array,
s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:b=, s(:arglist)),
s(:attrasgn,
s(:call, nil, :a, s(:arglist)),
:c=, s(:arglist)),
s(:lasgn, :_)),
s(:to_ary,
s(:call, nil, :q, s(:arglist)))))
add_tests("masgn_attrasgn_idx",
"Ruby" => "a, i, j = [], 1, 2\na[i], a[j] = a[j], a[i]\n",
"RawParseTree" => [:block,
[:masgn,
[:array,
[:lasgn, :a], [:lasgn, :i], [:lasgn, :j]],
[:array, [:zarray], [:lit, 1], [:lit, 2]]],
[:masgn,
[:array,
[:attrasgn,
[:lvar, :a], :[]=, [:array, [:lvar, :i]]],
[:attrasgn,
[:lvar, :a], :[]=, [:array, [:lvar, :j]]]],
[:array,
[:call, [:lvar, :a], :[],
[:array, [:lvar, :j]]],
[:call, [:lvar, :a], :[],
[:array, [:lvar, :i]]]]]],
"ParseTree" => s(:block,
s(:masgn,
s(:array,
s(:lasgn, :a),
s(:lasgn, :i), s(:lasgn, :j)),
s(:array, s(:array), s(:lit, 1), s(:lit, 2))),
s(:masgn,
s(:array,
s(:attrasgn, s(:lvar, :a), :[]=,
s(:arglist, s(:lvar, :i))),
s(:attrasgn, s(:lvar, :a), :[]=,
s(:arglist, s(:lvar, :j)))),
s(:array,
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lvar, :j))),
s(:call, s(:lvar, :a), :[],
s(:arglist, s(:lvar, :i)))))))
add_tests("masgn_cdecl",
"Ruby" => "A, B, C = 1, 2, 3",
"RawParseTree" => [:masgn,
[:array, [:cdecl, :A], [:cdecl, :B],
[:cdecl, :C]],
[:array, [:lit, 1], [:lit, 2], [:lit, 3]]],
"ParseTree" => s(:masgn,
s(:array, s(:cdecl, :A), s(:cdecl, :B),
s(:cdecl, :C)),
s(:array, s(:lit, 1), s(:lit, 2), s(:lit, 3))))
add_tests("masgn_iasgn",
"Ruby" => "a, @b = c, d",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:iasgn, :"@b"]],
[:array, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:iasgn, :"@b")),
s(:array,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))))
add_tests("masgn_masgn",
"Ruby" => "a, (b, c) = [1, [2, 3]]",
"RawParseTree" => [:masgn,
[:array,
[:lasgn, :a],
[:masgn,
[:array,
[:lasgn, :b],
[:lasgn, :c]]]],
[:to_ary,
[:array,
[:lit, 1],
[:array,
[:lit, 2],
[:lit, 3]]]]],
"ParseTree" => s(:masgn,
s(:array,
s(:lasgn, :a),
s(:masgn,
s(:array,
s(:lasgn, :b),
s(:lasgn, :c)))),
s(:to_ary,
s(:array,
s(:lit, 1),
s(:array,
s(:lit, 2),
s(:lit, 3))))))
add_tests("masgn_splat",
"Ruby" => "a, b, *c = d, e, f, g",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:array,
[:vcall, :d], [:vcall, :e],
[:vcall, :f], [:vcall, :g]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:array,
s(:call, nil, :d, s(:arglist)),
s(:call, nil, :e, s(:arglist)),
s(:call, nil, :f, s(:arglist)),
s(:call, nil, :g, s(:arglist)))))
add_tests("masgn_splat_no_name_to_ary",
"Ruby" => "a, b, * = c",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:splat],
[:to_ary, [:vcall, :c]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:splat),
s(:to_ary, s(:call, nil, :c, s(:arglist)))))
add_tests("masgn_splat_no_name_trailing",
"Ruby" => "a, b, = c",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:to_ary, [:vcall, :c]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:to_ary, s(:call, nil, :c, s(:arglist)))),
"Ruby2Ruby" => "a, b = c") # TODO: check this is right
add_tests("masgn_splat_to_ary",
"Ruby" => "a, b, *c = d",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:to_ary, [:vcall, :d]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:to_ary, s(:call, nil, :d, s(:arglist)))))
add_tests("masgn_splat_to_ary2",
"Ruby" => "a, b, *c = d.e(\"f\")",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:lasgn, :c],
[:to_ary,
[:call, [:vcall, :d], :e,
[:array, [:str, 'f']]]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:lasgn, :c),
s(:to_ary,
s(:call,
s(:call, nil, :d, s(:arglist)),
:e,
s(:arglist, s(:str, 'f'))))))
add_tests("match",
"Ruby" => "1 if /x/",
"RawParseTree" => [:if, [:match, [:lit, /x/]], [:lit, 1], nil],
"ParseTree" => s(:if, s(:match, s(:lit, /x/)), s(:lit, 1), nil))
add_tests("match2",
"Ruby" => "/x/ =~ \"blah\"",
"RawParseTree" => [:match2, [:lit, /x/], [:str, "blah"]],
"ParseTree" => s(:match2, s(:lit, /x/), s(:str, "blah")))
add_tests("match3",
"Ruby" => "\"blah\" =~ /x/",
"RawParseTree" => [:match3, [:lit, /x/], [:str, "blah"]],
"ParseTree" => s(:match3, s(:lit, /x/), s(:str, "blah")))
add_tests("module",
"Ruby" => "module X\n def y\n # do nothing\n end\nend",
"RawParseTree" => [:module, :X,
[:scope,
[:defn, :y,
[:scope, [:block, [:args], [:nil]]]]]],
"ParseTree" => s(:module, :X,
s(:scope,
s(:defn, :y,
s(:args),
s(:scope, s(:block, s(:nil)))))))
add_tests("module_scoped",
"Ruby" => "module X::Y\n c\nend",
"RawParseTree" => [:module, [:colon2, [:const, :X], :Y],
[:scope, [:vcall, :c]]],
"ParseTree" => s(:module, s(:colon2, s(:const, :X), :Y),
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("module_scoped3",
"Ruby" => "module ::Y\n c\nend",
"RawParseTree" => [:module, [:colon3, :Y], [:scope, [:vcall, :c]]],
"ParseTree" => s(:module,
s(:colon3, :Y),
s(:scope, s(:call, nil, :c, s(:arglist)))))
add_tests("next",
"Ruby" => "loop { next if false }",
"RawParseTree" => [:iter,
[:fcall, :loop],
nil,
[:if, [:false], [:next], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)),
nil,
s(:if, s(:false), s(:next), nil)))
add_tests("next_arg",
"Ruby" => "loop { next 42 if false }",
"RawParseTree" => [:iter,
[:fcall, :loop],
nil,
[:if, [:false], [:next, [:lit, 42]], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)),
nil,
s(:if, s(:false), s(:next, s(:lit, 42)), nil)))
add_tests("not",
"Ruby" => "(not true)",
"RawParseTree" => [:not, [:true]],
"ParseTree" => s(:not, s(:true)))
add_tests("nth_ref",
"Ruby" => "$1",
"RawParseTree" => [:nth_ref, 1],
"ParseTree" => s(:nth_ref, 1))
add_tests("op_asgn1",
"Ruby" => "b = []\nb[1] ||= 10\nb[2] &&= 11\nb[3] += 12\n",
"RawParseTree" => [:block,
[:lasgn, :b, [:zarray]],
[:op_asgn1, [:lvar, :b],
[:array, [:lit, 1]], :"||", [:lit, 10]],
[:op_asgn1, [:lvar, :b],
[:array, [:lit, 2]], :"&&", [:lit, 11]],
[:op_asgn1, [:lvar, :b],
[:array, [:lit, 3]], :+, [:lit, 12]]],
"ParseTree" => s(:block,
s(:lasgn, :b, s(:array)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)),
s(:op_asgn1, s(:lvar, :b),
s(:arglist, s(:lit, 3)), :+, s(:lit, 12))))
add_tests("op_asgn1_ivar",
"Ruby" => "@b = []\n@b[1] ||= 10\n@b[2] &&= 11\n@b[3] += 12\n",
"RawParseTree" => [:block,
[:iasgn, :@b, [:zarray]],
[:op_asgn1, [:ivar, :@b],
[:array, [:lit, 1]], :"||", [:lit, 10]],
[:op_asgn1, [:ivar, :@b],
[:array, [:lit, 2]], :"&&", [:lit, 11]],
[:op_asgn1, [:ivar, :@b],
[:array, [:lit, 3]], :+, [:lit, 12]]],
"ParseTree" => s(:block,
s(:iasgn, :@b, s(:array)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 1)), :"||", s(:lit, 10)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 2)), :"&&", s(:lit, 11)),
s(:op_asgn1, s(:ivar, :@b),
s(:arglist, s(:lit, 3)), :+, s(:lit, 12))))
add_tests("op_asgn2",
"Ruby" => "s = Struct.new(:var)\nc = s.new(nil)\nc.var ||= 20\nc.var &&= 21\nc.var += 22\nc.d.e.f ||= 42\n",
"RawParseTree" => [:block,
[:lasgn, :s,
[:call, [:const, :Struct],
:new, [:array, [:lit, :var]]]],
[:lasgn, :c,
[:call, [:lvar, :s], :new, [:array, [:nil]]]],
[:op_asgn2, [:lvar, :c], :var=, :"||",
[:lit, 20]],
[:op_asgn2, [:lvar, :c], :var=, :"&&",
[:lit, 21]],
[:op_asgn2, [:lvar, :c], :var=, :+, [:lit, 22]],
[:op_asgn2,
[:call,
[:call, [:lvar, :c], :d], :e], :f=, :"||",
[:lit, 42]]],
"ParseTree" => s(:block,
s(:lasgn, :s,
s(:call, s(:const, :Struct),
:new, s(:arglist, s(:lit, :var)))),
s(:lasgn, :c,
s(:call, s(:lvar, :s),
:new, s(:arglist, s(:nil)))),
s(:op_asgn2, s(:lvar, :c),
:var=, :"||", s(:lit, 20)),
s(:op_asgn2, s(:lvar, :c),
:var=, :"&&", s(:lit, 21)),
s(:op_asgn2, s(:lvar, :c),
:var=, :+, s(:lit, 22)),
s(:op_asgn2,
s(:call,
s(:call, s(:lvar, :c), :d, s(:arglist)),
:e, s(:arglist)),
:f=, :"||", s(:lit, 42))))
add_tests("op_asgn2_self",
"Ruby" => "self.Bag ||= Bag.new",
"RawParseTree" => [:op_asgn2, [:self], :"Bag=", :"||",
[:call, [:const, :Bag], :new]],
"ParseTree" => s(:op_asgn2, s(:self), :"Bag=", :"||",
s(:call, s(:const, :Bag), :new, s(:arglist))))
add_tests("op_asgn_and",
"Ruby" => "a = 0\na &&= 2\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:lit, 0]],
[:op_asgn_and,
[:lvar, :a], [:lasgn, :a, [:lit, 2]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:lit, 0)),
s(:op_asgn_and,
s(:lvar, :a), s(:lasgn, :a, s(:lit, 2)))))
add_tests("op_asgn_and_ivar2",
"Ruby" => "@fetcher &&= new(Gem.configuration[:http_proxy])",
"RawParseTree" => [:op_asgn_and,
[:ivar, :@fetcher],
[:iasgn,
:@fetcher,
[:fcall,
:new,
[:array,
[:call,
[:call, [:const, :Gem], :configuration],
:[],
[:array, [:lit, :http_proxy]]]]]]],
"ParseTree" => s(:op_asgn_and,
s(:ivar, :@fetcher),
s(:iasgn,
:@fetcher,
s(:call, nil,
:new,
s(:arglist,
s(:call,
s(:call, s(:const, :Gem),
:configuration,
s(:arglist)),
:[],
s(:arglist, s(:lit, :http_proxy))))))))
add_tests("op_asgn_or",
"Ruby" => "a = 0\na ||= 1\n",
"RawParseTree" => [:block,
[:lasgn, :a, [:lit, 0]],
[:op_asgn_or,
[:lvar, :a], [:lasgn, :a, [:lit, 1]]]],
"ParseTree" => s(:block,
s(:lasgn, :a, s(:lit, 0)),
s(:op_asgn_or,
s(:lvar, :a), s(:lasgn, :a, s(:lit, 1)))))
add_tests("op_asgn_or_block",
"Ruby" => "a ||= begin\n b\n rescue\n c\n end",
"RawParseTree" => [:op_asgn_or,
[:lvar, :a],
[:lasgn, :a,
[:rescue,
[:vcall, :b],
[:resbody, nil, [:vcall, :c]]]]],
"ParseTree" => s(:op_asgn_or,
s(:lvar, :a),
s(:lasgn, :a,
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody, s(:array),
s(:call, nil, :c, s(:arglist)))))),
"Ruby2Ruby" => "a ||= b rescue c")
add_tests("op_asgn_or_ivar",
"Ruby" => "@v ||= { }",
"RawParseTree" => [:op_asgn_or,
[:ivar, :@v],
[:iasgn, :@v, [:hash]]],
"ParseTree" => s(:op_asgn_or,
s(:ivar, :@v),
s(:iasgn, :@v, s(:hash))))
add_tests("op_asgn_or_ivar2",
"Ruby" => "@fetcher ||= new(Gem.configuration[:http_proxy])",
"RawParseTree" => [:op_asgn_or,
[:ivar, :@fetcher],
[:iasgn,
:@fetcher,
[:fcall,
:new,
[:array,
[:call,
[:call, [:const, :Gem], :configuration],
:[],
[:array, [:lit, :http_proxy]]]]]]],
"ParseTree" => s(:op_asgn_or,
s(:ivar, :@fetcher),
s(:iasgn,
:@fetcher,
s(:call, nil, :new,
s(:arglist,
s(:call,
s(:call, s(:const, :Gem),
:configuration,
s(:arglist)),
:[],
s(:arglist, s(:lit, :http_proxy))))))))
add_tests("or",
"Ruby" => "(a or b)",
"RawParseTree" => [:or, [:vcall, :a], [:vcall, :b]],
"ParseTree" => s(:or,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))))
add_tests("or_big",
"Ruby" => "((a or b) or (c and d))",
"RawParseTree" => [:or,
[:or, [:vcall, :a], [:vcall, :b]],
[:and, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:or,
s(:or,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))),
s(:and,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))))
add_tests("or_big2",
"Ruby" => "((a || b) || (c && d))",
"RawParseTree" => [:or,
[:or, [:vcall, :a], [:vcall, :b]],
[:and, [:vcall, :c], [:vcall, :d]]],
"ParseTree" => s(:or,
s(:or,
s(:call, nil, :a, s(:arglist)),
s(:call, nil, :b, s(:arglist))),
s(:and,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist)))),
"Ruby2Ruby" => "((a or b) or (c and d))")
add_tests("parse_floats_as_args",
"Ruby" => "def x(a=0.0,b=0.0)\n a+b\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :a, :b,
[:block,
[:lasgn, :a, [:lit, 0.0]],
[:lasgn, :b, [:lit, 0.0]]]],
[:call, [:lvar, :a], :+,
[:array, [:lvar, :b]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :a, :b,
s(:block,
s(:lasgn, :a, s(:lit, 0.0)),
s(:lasgn, :b, s(:lit, 0.0)))),
s(:scope,
s(:block,
s(:call, s(:lvar, :a), :+,
s(:arglist, s(:lvar, :b)))))),
"Ruby2Ruby" => "def x(a = 0.0, b = 0.0)\n (a + b)\nend")
add_tests("postexe",
"Ruby" => "END { 1 }",
"RawParseTree" => [:iter, [:postexe], nil, [:lit, 1]],
"ParseTree" => s(:iter, s(:postexe), nil, s(:lit, 1)))
add_tests("proc_args_0",
"Ruby" => "proc { || (x + 1) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
0,
[:call, [:vcall, :x], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
0,
s(:call,
s(:call, nil, :x, s(:arglist)),
:+,
s(:arglist, s(:lit, 1)))))
add_tests("proc_args_1",
"Ruby" => "proc { |x| (x + 1) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
[:dasgn_curr, :x],
[:call, [:dvar, :x], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
s(:lasgn, :x),
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lit, 1)))))
add_tests("proc_args_2",
"Ruby" => "proc { |x, y| (x + y) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
[:masgn, [:array,
[:dasgn_curr, :x],
[:dasgn_curr, :y]]],
[:call, [:dvar, :x], :+, [:array, [:dvar, :y]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
s(:masgn,
s(:array,
s(:lasgn, :x),
s(:lasgn, :y))),
s(:call, s(:lvar, :x), :+,
s(:arglist, s(:lvar, :y)))))
add_tests("proc_args_no",
"Ruby" => "proc { (x + 1) }",
"RawParseTree" => [:iter,
[:fcall, :proc],
nil,
[:call, [:vcall, :x], :+, [:array, [:lit, 1]]]],
"ParseTree" => s(:iter,
s(:call, nil, :proc, s(:arglist)),
nil,
s(:call, s(:call, nil, :x, s(:arglist)),
:+, s(:arglist, s(:lit, 1)))))
add_tests("redo",
"Ruby" => "loop { redo if false }",
"RawParseTree" => [:iter,
[:fcall, :loop], nil,
[:if, [:false], [:redo], nil]],
"ParseTree" => s(:iter,
s(:call, nil, :loop, s(:arglist)),
nil,
s(:if, s(:false), s(:redo), nil)))
# TODO: need a resbody w/ multiple classes and a splat
add_tests("rescue",
"Ruby" => "blah rescue nil",
"RawParseTree" => [:rescue,
[:vcall, :blah], [:resbody, nil, [:nil]]],
"ParseTree" => s(:rescue,
s(:call, nil, :blah, s(:arglist)),
s(:resbody, s(:array), s(:nil))))
add_tests("rescue_block_body",
"Ruby" => "begin\n a\nrescue => e\n c\n d\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :a],
[:resbody, nil,
[:block,
[:lasgn, :e, [:gvar, :$!]],
[:vcall, :c],
[:vcall, :d]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
s(:block,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist))))))
add_tests("rescue_block_body_ivar",
"Ruby" => "begin\n a\nrescue => @e\n c\n d\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :a],
[:resbody, nil,
[:block,
[:iasgn, :@e, [:gvar, :$!]],
[:vcall, :c],
[:vcall, :d]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody,
s(:array, s(:iasgn, :@e, s(:gvar, :$!))),
s(:block,
s(:call, nil, :c, s(:arglist)),
s(:call, nil, :d, s(:arglist))))))
add_tests("rescue_block_body_3",
"Ruby" => "begin\n a\nrescue A\n b\nrescue B\n c\nrescue C\n d\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :a],
[:resbody, [:array, [:const, :A]],
[:vcall, :b],
[:resbody, [:array, [:const, :B]],
[:vcall, :c],
[:resbody, [:array, [:const, :C]],
[:vcall, :d]]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :a, s(:arglist)),
s(:resbody, s(:array, s(:const, :A)),
s(:call, nil, :b, s(:arglist))),
s(:resbody, s(:array, s(:const, :B)),
s(:call, nil, :c, s(:arglist))),
s(:resbody, s(:array, s(:const, :C)),
s(:call, nil, :d, s(:arglist)))))
add_tests("rescue_block_nada",
"Ruby" => "begin\n blah\nrescue\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue, [:vcall, :blah], [:resbody, nil]]],
"ParseTree" => s(:rescue,
s(:call, nil, :blah, s(:arglist)),
s(:resbody, s(:array), nil)))
add_tests("rescue_exceptions",
"Ruby" => "begin\n blah\nrescue RuntimeError => r\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue,
[:vcall, :blah],
[:resbody,
[:array, [:const, :RuntimeError]],
[:lasgn, :r, [:gvar, :$!]]]]],
"ParseTree" => s(:rescue,
s(:call, nil, :blah, s(:arglist)),
s(:resbody,
s(:array,
s(:const, :RuntimeError),
s(:lasgn, :r, s(:gvar, :$!))),
nil)))
add_tests("rescue_lasgn",
"Ruby" => "begin\n 1\nrescue\n var = 2\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil, [:lasgn, :var, [:lit, 2]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array),
s(:lasgn, :var, s(:lit, 2)))),
"Ruby2Ruby" => "1 rescue var = 2")
add_tests("rescue_lasgn_var",
"Ruby" => "begin\n 1\nrescue => e\n var = 2\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil,
[:block,
[:lasgn, :e, [:gvar, :$!]],
[:lasgn, :var, [:lit, 2]]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
s(:lasgn, :var, s(:lit, 2)))))
add_tests("rescue_lasgn_var_empty",
"Ruby" => "begin\n 1\nrescue => e\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil, [:lasgn, :e, [:gvar, :$!]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:lasgn, :e, s(:gvar, :$!))),
nil)))
add_tests("rescue_iasgn_var_empty",
"Ruby" => "begin\n 1\nrescue => @e\n # do nothing\nend",
"RawParseTree" => [:begin,
[:rescue,
[:lit, 1],
[:resbody, nil, [:iasgn, :@e, [:gvar, :$!]]]]],
"ParseTree" => s(:rescue,
s(:lit, 1),
s(:resbody,
s(:array, s(:iasgn, :@e, s(:gvar, :$!))),
nil)))
add_tests("retry",
"Ruby" => "retry",
"RawParseTree" => [:retry],
"ParseTree" => s(:retry))
add_tests("return_0",
"Ruby" => "return",
"RawParseTree" => [:return],
"ParseTree" => s(:return))
add_tests("return_1",
"Ruby" => "return 1",
"RawParseTree" => [:return, [:lit, 1]],
"ParseTree" => s(:return, s(:lit, 1)))
add_tests("return_n",
"Ruby" => "return 1, 2, 3",
"RawParseTree" => [:return, [:array,
[:lit, 1], [:lit, 2], [:lit, 3]]],
"ParseTree" => s(:return, s(:array,
s(:lit, 1), s(:lit, 2), s(:lit, 3))),
"Ruby2Ruby" => "return [1, 2, 3]")
add_tests("sclass",
"Ruby" => "class << self\n 42\nend",
"RawParseTree" => [:sclass, [:self], [:scope, [:lit, 42]]],
"ParseTree" => s(:sclass, s(:self), s(:scope, s(:lit, 42))))
add_tests("sclass_trailing_class",
"Ruby" => "class A\n class << self\n a\n end\n class B\n end\nend",
"RawParseTree" => [:class, :A, nil,
[:scope,
[:block,
[:sclass, [:self], [:scope, [:vcall, :a]]],
[:class, :B, nil, [:scope]]]]],
"ParseTree" => s(:class, :A, nil,
s(:scope,
s(:block,
s(:sclass, s(:self),
s(:scope,
s(:call, nil, :a, s(:arglist)))),
s(:class, :B, nil, s(:scope))))))
add_tests("splat",
"Ruby" => "def x(*b)\n a(*b)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args, :"*b"],
[:fcall, :a, [:splat, [:lvar, :b]]]]]],
"ParseTree" => s(:defn, :x,
s(:args, :"*b"),
s(:scope,
s(:block,
s(:call, nil, :a,
s(:splat, s(:lvar, :b)))))))
add_tests("str",
"Ruby" => '"x"',
"RawParseTree" => [:str, "x"],
"ParseTree" => s(:str, "x"))
add_tests("str_concat_newline", # FIX? make prettier? possible?
"Ruby" => '"before" \\
" after"',
"RawParseTree" => [:str, "before after"],
"ParseTree" => s(:str, "before after"),
"Ruby2Ruby" => '"before after"')
add_tests("str_concat_space",
"Ruby" => '"before" " after"',
"RawParseTree" => [:str, "before after"],
"ParseTree" => s(:str, "before after"),
"Ruby2Ruby" => '"before after"')
add_tests("str_heredoc",
"Ruby" => "<<'EOM'\n blah\nblah\nEOM",
"RawParseTree" => [:str, " blah\nblah\n"],
"ParseTree" => s(:str, " blah\nblah\n"),
"Ruby2Ruby" => "\" blah\\nblah\\n\"")
add_tests("str_heredoc_call",
"Ruby" => "<<'EOM'.strip\n blah\nblah\nEOM",
"RawParseTree" => [:call, [:str, " blah\nblah\n"], :strip],
"ParseTree" => s(:call, s(:str, " blah\nblah\n"),
:strip, s(:arglist)),
"Ruby2Ruby" => "\" blah\\nblah\\n\".strip")
add_tests("str_heredoc_double",
"Ruby" => "a += <<-H1 + b + <<-H2\n first\nH1\n second\nH2",
"RawParseTree" => [:lasgn, :a,
[:call,
[:lvar, :a],
:+,
[:array,
[:call,
[:call, [:str, " first\n"], :+,
[:array, [:vcall, :b]]],
:+,
[:array, [:str, " second\n"]]]]]],
"ParseTree" => s(:lasgn, :a,
s(:call,
s(:lvar, :a),
:+,
s(:arglist,
s(:call,
s(:call, s(:str, " first\n"), :+,
s(:arglist,
s(:call, nil, :b, s(:arglist)))),
:+,
s(:arglist, s(:str, " second\n")))))),
"Ruby2Ruby" => "a = (a + ((\" first\\n\" + b) + \" second\\n\"))")
add_tests("str_heredoc_indent",
"Ruby" => "<<-EOM\n blah\nblah\n\n EOM",
"RawParseTree" => [:str, " blah\nblah\n\n"],
"ParseTree" => s(:str, " blah\nblah\n\n"),
"Ruby2Ruby" => "\" blah\\nblah\\n\\n\"")
add_tests("str_interp_file",
"Ruby" => '"file = #{__FILE__}\n"',
"RawParseTree" => [:str, "file = (string)\n"],
"ParseTree" => s(:str, "file = (string)\n"),
"Ruby2Ruby" => '"file = (string)\\n"')
add_tests("structure_extra_block_for_dvar_scoping",
"Ruby" => "a.b do |c, d|\n unless e.f(c) then\n g = false\n d.h { |x, i| g = true }\n end\nend",
"RawParseTree" => [:iter,
[:call, [:vcall, :a], :b],
[:masgn, [:array,
[:dasgn_curr, :c],
[:dasgn_curr, :d]]],
[:if,
[:call, [:vcall, :e], :f,
[:array, [:dvar, :c]]],
nil,
[:block,
[:dasgn_curr, :g, [:false]],
[:iter,
[:call, [:dvar, :d], :h],
[:masgn, [:array,
[:dasgn_curr, :x],
[:dasgn_curr, :i]]],
[:dasgn, :g, [:true]]]]]],
"ParseTree" => s(:iter,
s(:call,
s(:call, nil, :a, s(:arglist)),
:b, s(:arglist)),
s(:masgn, s(:array,
s(:lasgn, :c),
s(:lasgn, :d))),
s(:if,
s(:call, s(:call, nil, :e, s(:arglist)), :f,
s(:arglist, s(:lvar, :c))),
nil,
s(:block,
s(:lasgn, :g, s(:false)),
s(:iter,
s(:call, s(:lvar, :d), :h, s(:arglist)),
s(:masgn, s(:array,
s(:lasgn, :x),
s(:lasgn, :i))),
s(:lasgn, :g, s(:true)))))))
add_tests("structure_remove_begin_1",
"Ruby" => "a << begin\n b\n rescue\n c\n end",
"RawParseTree" => [:call, [:vcall, :a], :<<,
[:array, [:rescue, [:vcall, :b],
[:resbody, nil, [:vcall, :c]]]]],
"ParseTree" => s(:call, s(:call, nil, :a, s(:arglist)), :<<,
s(:arglist,
s(:rescue,
s(:call, nil, :b, s(:arglist)),
s(:resbody, s(:array),
s(:call, nil, :c, s(:arglist)))))),
"Ruby2Ruby" => "(a << b rescue c)")
add_tests("structure_remove_begin_2",
"Ruby" => "a = if c\n begin\n b\n rescue\n nil\n end\n end\na",
"RawParseTree" => [:block,
[:lasgn,
:a,
[:if, [:vcall, :c],
[:rescue,
[:vcall, :b],
[:resbody, nil, [:nil]]],
nil]],
[:lvar, :a]],
"ParseTree" => s(:block,
s(:lasgn,
:a,
s(:if, s(:call, nil, :c, s(:arglist)),
s(:rescue, s(:call, nil, :b, s(:arglist)),
s(:resbody,
s(:array), s(:nil))),
nil)),
s(:lvar, :a)),
"Ruby2Ruby" => "a = b rescue nil if c\na\n") # OMG that's awesome
add_tests("structure_unused_literal_wwtt",
"Ruby" => "\"prevent the above from infecting rdoc\"\n\nmodule Graffle\nend",
"RawParseTree" => [:module, :Graffle, [:scope]],
"ParseTree" => s(:module, :Graffle, s(:scope)),
"Ruby2Ruby" => "module Graffle\nend")
add_tests("super",
"Ruby" => "def x\n super(4)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args],
[:super, [:array, [:lit, 4]]]]]],
"ParseTree" => s(:defn, :x,
s(:args),
s(:scope,
s(:block,
s(:super, s(:array, s(:lit, 4)))))))
add_tests("super_block_pass",
"Ruby" => "super(a, &b)",
"RawParseTree" => [:block_pass,
[:vcall, :b], [:super, [:array, [:vcall, :a]]]],
"ParseTree" => s(:block_pass,
s(:call, nil, :b, s(:arglist)),
s(:super,
s(:array, s(:call, nil, :a, s(:arglist))))))
add_tests("super_block_splat",
"Ruby" => "super(a, *b)",
"RawParseTree" => [:super,
[:argscat,
[:array, [:vcall, :a]],
[:vcall, :b]]],
"ParseTree" => s(:super,
s(:argscat,
s(:array, s(:call, nil, :a, s(:arglist))),
s(:call, nil, :b, s(:arglist)))))
add_tests("super_multi",
"Ruby" => "def x\n super(4, 2, 1)\nend",
"RawParseTree" => [:defn, :x,
[:scope,
[:block,
[:args],
[:super,
[:array, [:lit, 4], [:lit, 2], [:lit, 1]]]]]],
"ParseTree" => s(:defn, :x,
s(:args),
s(:scope,
s(:block,
s(:super,
s(:array,
s(:lit, 4), s(:lit, 2), s(:lit, 1)))))))
add_tests("svalue",
"Ruby" => "a = *b",
"RawParseTree" => [:lasgn, :a, [:svalue, [:splat, [:vcall, :b]]]],
"ParseTree" => s(:lasgn, :a,
s(:svalue,
s(:splat, s(:call, nil, :b, s(:arglist))))))
add_tests("to_ary",
"Ruby" => "a, b = c",
"RawParseTree" => [:masgn,
[:array, [:lasgn, :a], [:lasgn, :b]],
[:to_ary, [:vcall, :c]]],
"ParseTree" => s(:masgn,
s(:array, s(:lasgn, :a), s(:lasgn, :b)),
s(:to_ary, s(:call, nil, :c, s(:arglist)))))
add_tests("true",
"Ruby" => "true",
"RawParseTree" => [:true],
"ParseTree" => s(:true))
add_tests("undef",
"Ruby" => "undef :x",
"RawParseTree" => [:undef, [:lit, :x]],
"ParseTree" => s(:undef, s(:lit, :x)))
add_tests("undef_2",
"Ruby" => "undef :x, :y",
"RawParseTree" => [:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]]],
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y))),
"Ruby2Ruby" => "undef :x\nundef :y\n")
add_tests("undef_3",
"Ruby" => "undef :x, :y, :z",
"RawParseTree" => [:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]]],
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z))),
"Ruby2Ruby" => "undef :x\nundef :y\nundef :z\n")
add_tests("undef_block_1",
"Ruby" => "f1\nundef :x\n", # TODO: don't like the extra return
"RawParseTree" => [:block,
[:vcall, :f1],
[:undef, [:lit, :x]]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:undef, s(:lit, :x))))
add_tests("undef_block_2",
"Ruby" => "f1\nundef :x, :y",
"RawParseTree" => [:block,
[:vcall, :f1],
[:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y)\n")
add_tests("undef_block_3",
"Ruby" => "f1\nundef :x, :y, :z",
"RawParseTree" => [:block,
[:vcall, :f1],
[:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]],
]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z)))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\n")
add_tests("undef_block_3_post",
"Ruby" => "undef :x, :y, :z\nf2",
"RawParseTree" => [:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]],
[:vcall, :f2]],
"ParseTree" => s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z)),
s(:call, nil, :f2, s(:arglist))),
"Ruby2Ruby" => "undef :x\nundef :y\nundef :z\nf2\n")
add_tests("undef_block_wtf",
"Ruby" => "f1\nundef :x, :y, :z\nf2",
"RawParseTree" => [:block,
[:vcall, :f1],
[:block,
[:undef, [:lit, :x]],
[:undef, [:lit, :y]],
[:undef, [:lit, :z]]],
[:vcall, :f2]],
"ParseTree" => s(:block,
s(:call, nil, :f1, s(:arglist)),
s(:block,
s(:undef, s(:lit, :x)),
s(:undef, s(:lit, :y)),
s(:undef, s(:lit, :z))),
s(:call, nil, :f2, s(:arglist))),
"Ruby2Ruby" => "f1\n(undef :x\nundef :y\nundef :z)\nf2\n")
add_tests("unless_post",
"Ruby" => "a unless b",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))))
add_tests("unless_post_not",
"Ruby" => "a unless not b",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil),
"Ruby2Ruby" => "a if b")
add_tests("unless_pre",
"Ruby" => "unless b then a end",
"RawParseTree" => [:if, [:vcall, :b], nil, [:vcall, :a]],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)), nil,
s(:call, nil, :a, s(:arglist))),
"Ruby2Ruby" => "a unless b")
add_tests("unless_pre_not",
"Ruby" => "unless not b then a end",
"RawParseTree" => [:if, [:vcall, :b], [:vcall, :a], nil],
"ParseTree" => s(:if, s(:call, nil, :b, s(:arglist)),
s(:call, nil, :a, s(:arglist)), nil),
"Ruby2Ruby" => "a if b")
add_tests("until_post",
"Ruby" => "begin\n (1 + 1)\nend until false",
"RawParseTree" => [:until, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false))
add_tests("until_post_not",
"Ruby" => "begin\n (1 + 1)\nend until not true",
"RawParseTree" => [:while, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend while true")
add_tests("until_pre",
"Ruby" => "until false do\n (1 + 1)\nend",
"RawParseTree" => [:until, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true))
add_tests("until_pre_mod",
"Ruby" => "(1 + 1) until false",
"RawParseTree" => [:until, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "until false do\n (1 + 1)\nend")
add_tests("until_pre_not",
"Ruby" => "until not true do\n (1 + 1)\nend",
"RawParseTree" => [:while, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_tests("until_pre_not_mod",
"Ruby" => "(1 + 1) until not true",
"RawParseTree" => [:while, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "while true do\n (1 + 1)\nend")
add_tests("valias",
"Ruby" => "alias $y $x",
"RawParseTree" => [:valias, :$y, :$x],
"ParseTree" => s(:valias, :$y, :$x))
add_tests("vcall",
"Ruby" => "method",
"RawParseTree" => [:vcall, :method],
"ParseTree" => s(:call, nil, :method, s(:arglist)))
add_tests("while_post",
"Ruby" => "begin\n (1 + 1)\nend while false",
"RawParseTree" => [:while, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false))
add_tests("while_post2",
"Ruby" => "begin\n (1 + 2)\n (3 + 4)\nend while false",
"RawParseTree" => [:while, [:false],
[:block,
[:call, [:lit, 1], :+, [:array, [:lit, 2]]],
[:call, [:lit, 3], :+, [:array, [:lit, 4]]]],
false],
"ParseTree" => s(:while, s(:false),
s(:block,
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 2))),
s(:call, s(:lit, 3), :+,
s(:arglist, s(:lit, 4)))),
false))
add_tests("while_post_not",
"Ruby" => "begin\n (1 + 1)\nend while not true",
"RawParseTree" => [:until, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], false],
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), false),
"Ruby2Ruby" => "begin\n (1 + 1)\nend until true")
add_tests("while_pre",
"Ruby" => "while false do\n (1 + 1)\nend",
"RawParseTree" => [:while, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true))
add_tests("while_pre_mod",
"Ruby" => "(1 + 1) while false",
"RawParseTree" => [:while, [:false],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:while, s(:false),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "while false do\n (1 + 1)\nend") # FIX can be one liner
add_tests("while_pre_nil",
"Ruby" => "while false do\nend",
"RawParseTree" => [:while, [:false], nil, true],
"ParseTree" => s(:while, s(:false), nil, true))
add_tests("while_pre_not",
"Ruby" => "while not true do\n (1 + 1)\nend",
"RawParseTree" => [:until, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend")
add_tests("while_pre_not_mod",
"Ruby" => "(1 + 1) while not true",
"RawParseTree" => [:until, [:true],
[:call, [:lit, 1], :+,
[:array, [:lit, 1]]], true],
"ParseTree" => s(:until, s(:true),
s(:call, s(:lit, 1), :+,
s(:arglist, s(:lit, 1))), true),
"Ruby2Ruby" => "until true do\n (1 + 1)\nend") # FIX
add_tests("xstr",
"Ruby" => "`touch 5`",
"RawParseTree" => [:xstr, 'touch 5'],
"ParseTree" => s(:xstr, 'touch 5'))
add_tests("yield_0",
"Ruby" => "yield",
"RawParseTree" => [:yield],
"ParseTree" => s(:yield))
add_tests("yield_1",
"Ruby" => "yield(42)",
"RawParseTree" => [:yield, [:lit, 42]],
"ParseTree" => s(:yield, s(:lit, 42)))
add_tests("yield_n",
"Ruby" => "yield(42, 24)",
"RawParseTree" => [:yield, [:array, [:lit, 42], [:lit, 24]]],
"ParseTree" => s(:yield, s(:array, s(:lit, 42), s(:lit, 24))))
add_tests("zarray",
"Ruby" => "a = []",
"RawParseTree" => [:lasgn, :a, [:zarray]],
"ParseTree" => s(:lasgn, :a, s(:array)))
add_tests("zsuper",
"Ruby" => "def x\n super\nend",
"RawParseTree" => [:defn, :x,
[:scope, [:block, [:args], [:zsuper]]]],
"ParseTree" => s(:defn, :x, s(:args),
s(:scope, s(:block, s(:zsuper)))))
end
|
require 'puma/const'
module Puma
class Binder
include Puma::Const
def initialize(events)
@events = events
@listeners = []
@inherited_fds = {}
@unix_paths = []
@proto_env = {
"rack.version".freeze => Rack::VERSION,
"rack.errors".freeze => events.stderr,
"rack.multithread".freeze => true,
"rack.multiprocess".freeze => false,
"rack.run_once".freeze => false,
"SCRIPT_NAME".freeze => ENV['SCRIPT_NAME'] || "",
# Rack blows up if this is an empty string, and Rack::Lint
# blows up if it's nil. So 'text/plain' seems like the most
# sensible default value.
"CONTENT_TYPE".freeze => "text/plain",
"QUERY_STRING".freeze => "",
SERVER_PROTOCOL => HTTP_11,
SERVER_SOFTWARE => PUMA_VERSION,
GATEWAY_INTERFACE => CGI_VER
}
@envs = {}
@ios = []
end
attr_reader :listeners, :ios
def env(sock)
@envs.fetch(sock, @proto_env)
end
def close
@ios.each { |i| i.close }
@unix_paths.each { |i| File.unlink i }
end
def import_from_env
remove = []
ENV.each do |k,v|
if k =~ /PUMA_INHERIT_\d+/
fd, url = v.split(":", 2)
@inherited_fds[url] = fd.to_i
remove << k
end
if k =~ /LISTEN_FDS/ && ENV['LISTEN_PID'].to_i == $$
v.to_i.times do |num|
fd = num + 3
sock = TCPServer.for_fd(fd)
begin
url = "unix://" + Socket.unpack_sockaddr_un(sock.getsockname)
rescue ArgumentError
port, addr = Socket.unpack_sockaddr_in(sock.getsockname)
if addr =~ /\:/
addr = "[#{addr}]"
end
url = "tcp://#{addr}:#{port}"
end
@inherited_fds[url] = sock
end
ENV.delete k
ENV.delete 'LISTEN_PID'
end
end
remove.each do |k|
ENV.delete k
end
end
def parse(binds, logger)
binds.each do |str|
uri = URI.parse str
case uri.scheme
when "tcp"
if fd = @inherited_fds.delete(str)
logger.log "* Inherited #{str}"
io = inherit_tcp_listener uri.host, uri.port, fd
else
params = Rack::Utils.parse_query uri.query
opt = params.key?('low_latency')
bak = params.fetch('backlog', 1024).to_i
logger.log "* Listening on #{str}"
io = add_tcp_listener uri.host, uri.port, opt, bak
end
@listeners << [str, io]
when "unix"
path = "#{uri.host}#{uri.path}"
if fd = @inherited_fds.delete(str)
logger.log "* Inherited #{str}"
io = inherit_unix_listener path, fd
else
logger.log "* Listening on #{str}"
umask = nil
if uri.query
params = Rack::Utils.parse_query uri.query
if u = params['umask']
# Use Integer() to respect the 0 prefix as octal
umask = Integer(u)
end
end
io = add_unix_listener path, umask
end
@listeners << [str, io]
when "ssl"
params = Rack::Utils.parse_query uri.query
require 'puma/minissl'
ctx = MiniSSL::Context.new
if defined?(JRUBY_VERSION)
unless params['keystore']
@events.error "Please specify the Java keystore via 'keystore='"
end
ctx.keystore = params['keystore']
unless params['keystore-pass']
@events.error "Please specify the Java keystore password via 'keystore-pass='"
end
ctx.keystore_pass = params['keystore-pass']
else
unless params['key']
@events.error "Please specify the SSL key via 'key='"
end
ctx.key = params['key']
unless params['cert']
@events.error "Please specify the SSL cert via 'cert='"
end
ctx.cert = params['cert']
end
ctx.verify_mode = MiniSSL::VERIFY_NONE
if fd = @inherited_fds.delete(str)
logger.log "* Inherited #{str}"
io = inherited_ssl_listener fd, ctx
else
logger.log "* Listening on #{str}"
io = add_ssl_listener uri.host, uri.port, ctx
end
@listeners << [str, io]
else
logger.error "Invalid URI: #{str}"
end
end
# If we inherited fds but didn't use them (because of a
# configuration change), then be sure to close them.
@inherited_fds.each do |str, fd|
logger.log "* Closing unused inherited connection: #{str}"
begin
if fd.kind_of? TCPServer
fd.close
else
IO.for_fd(fd).close
end
rescue SystemCallError
end
# We have to unlink a unix socket path that's not being used
uri = URI.parse str
if uri.scheme == "unix"
path = "#{uri.host}#{uri.path}"
File.unlink path
end
end
end
# Tell the server to listen on host +host+, port +port+.
# If +optimize_for_latency+ is true (the default) then clients connecting
# will be optimized for latency over throughput.
#
# +backlog+ indicates how many unaccepted connections the kernel should
# allow to accumulate before returning connection refused.
#
def add_tcp_listener(host, port, optimize_for_latency=true, backlog=1024)
host = host[1..-2] if host[0..0] == '['
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
@ios << s
s
end
def inherit_tcp_listener(host, port, fd)
if fd.kind_of? TCPServer
s = fd
else
s = TCPServer.for_fd(fd)
end
@ios << s
s
end
def add_ssl_listener(host, port, ctx,
optimize_for_latency=true, backlog=1024)
require 'puma/minissl'
host = host[1..-2] if host[0..0] == '['
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
ssl = MiniSSL::Server.new s, ctx
env = @proto_env.dup
env[HTTPS_KEY] = HTTPS
@envs[ssl] = env
@ios << ssl
s
end
def inherited_ssl_listener(fd, ctx)
require 'puma/minissl'
s = TCPServer.for_fd(fd)
@ios << MiniSSL::Server.new(s, ctx)
s
end
# Tell the server to listen on +path+ as a UNIX domain socket.
#
def add_unix_listener(path, umask=nil)
@unix_paths << path
# Let anyone connect by default
umask ||= 0
begin
old_mask = File.umask(umask)
if File.exist? path
begin
old = UNIXSocket.new path
rescue SystemCallError, IOError
File.unlink path
else
old.close
raise "There is already a server bound to: #{path}"
end
end
s = UNIXServer.new(path)
@ios << s
ensure
File.umask old_mask
end
s
end
def inherit_unix_listener(path, fd)
@unix_paths << path
if fd.kind_of? TCPServer
s = fd
else
s = UNIXServer.for_fd fd
end
@ios << s
s
end
end
end
Add mode as an additional bind option to unix sockets. Fixes #630
require 'puma/const'
module Puma
class Binder
include Puma::Const
def initialize(events)
@events = events
@listeners = []
@inherited_fds = {}
@unix_paths = []
@proto_env = {
"rack.version".freeze => Rack::VERSION,
"rack.errors".freeze => events.stderr,
"rack.multithread".freeze => true,
"rack.multiprocess".freeze => false,
"rack.run_once".freeze => false,
"SCRIPT_NAME".freeze => ENV['SCRIPT_NAME'] || "",
# Rack blows up if this is an empty string, and Rack::Lint
# blows up if it's nil. So 'text/plain' seems like the most
# sensible default value.
"CONTENT_TYPE".freeze => "text/plain",
"QUERY_STRING".freeze => "",
SERVER_PROTOCOL => HTTP_11,
SERVER_SOFTWARE => PUMA_VERSION,
GATEWAY_INTERFACE => CGI_VER
}
@envs = {}
@ios = []
end
attr_reader :listeners, :ios
def env(sock)
@envs.fetch(sock, @proto_env)
end
def close
@ios.each { |i| i.close }
@unix_paths.each { |i| File.unlink i }
end
def import_from_env
remove = []
ENV.each do |k,v|
if k =~ /PUMA_INHERIT_\d+/
fd, url = v.split(":", 2)
@inherited_fds[url] = fd.to_i
remove << k
end
if k =~ /LISTEN_FDS/ && ENV['LISTEN_PID'].to_i == $$
v.to_i.times do |num|
fd = num + 3
sock = TCPServer.for_fd(fd)
begin
url = "unix://" + Socket.unpack_sockaddr_un(sock.getsockname)
rescue ArgumentError
port, addr = Socket.unpack_sockaddr_in(sock.getsockname)
if addr =~ /\:/
addr = "[#{addr}]"
end
url = "tcp://#{addr}:#{port}"
end
@inherited_fds[url] = sock
end
ENV.delete k
ENV.delete 'LISTEN_PID'
end
end
remove.each do |k|
ENV.delete k
end
end
def parse(binds, logger)
binds.each do |str|
uri = URI.parse str
case uri.scheme
when "tcp"
if fd = @inherited_fds.delete(str)
logger.log "* Inherited #{str}"
io = inherit_tcp_listener uri.host, uri.port, fd
else
params = Rack::Utils.parse_query uri.query
opt = params.key?('low_latency')
bak = params.fetch('backlog', 1024).to_i
logger.log "* Listening on #{str}"
io = add_tcp_listener uri.host, uri.port, opt, bak
end
@listeners << [str, io]
when "unix"
path = "#{uri.host}#{uri.path}"
if fd = @inherited_fds.delete(str)
logger.log "* Inherited #{str}"
io = inherit_unix_listener path, fd
else
logger.log "* Listening on #{str}"
umask = nil
mode = nil
if uri.query
params = Rack::Utils.parse_query uri.query
if u = params['umask']
# Use Integer() to respect the 0 prefix as octal
umask = Integer(u)
end
if u = params['mode']
mode = Integer('0'+u)
end
end
io = add_unix_listener path, umask, mode
end
@listeners << [str, io]
when "ssl"
params = Rack::Utils.parse_query uri.query
require 'puma/minissl'
ctx = MiniSSL::Context.new
if defined?(JRUBY_VERSION)
unless params['keystore']
@events.error "Please specify the Java keystore via 'keystore='"
end
ctx.keystore = params['keystore']
unless params['keystore-pass']
@events.error "Please specify the Java keystore password via 'keystore-pass='"
end
ctx.keystore_pass = params['keystore-pass']
else
unless params['key']
@events.error "Please specify the SSL key via 'key='"
end
ctx.key = params['key']
unless params['cert']
@events.error "Please specify the SSL cert via 'cert='"
end
ctx.cert = params['cert']
end
ctx.verify_mode = MiniSSL::VERIFY_NONE
if fd = @inherited_fds.delete(str)
logger.log "* Inherited #{str}"
io = inherited_ssl_listener fd, ctx
else
logger.log "* Listening on #{str}"
io = add_ssl_listener uri.host, uri.port, ctx
end
@listeners << [str, io]
else
logger.error "Invalid URI: #{str}"
end
end
# If we inherited fds but didn't use them (because of a
# configuration change), then be sure to close them.
@inherited_fds.each do |str, fd|
logger.log "* Closing unused inherited connection: #{str}"
begin
if fd.kind_of? TCPServer
fd.close
else
IO.for_fd(fd).close
end
rescue SystemCallError
end
# We have to unlink a unix socket path that's not being used
uri = URI.parse str
if uri.scheme == "unix"
path = "#{uri.host}#{uri.path}"
File.unlink path
end
end
end
# Tell the server to listen on host +host+, port +port+.
# If +optimize_for_latency+ is true (the default) then clients connecting
# will be optimized for latency over throughput.
#
# +backlog+ indicates how many unaccepted connections the kernel should
# allow to accumulate before returning connection refused.
#
def add_tcp_listener(host, port, optimize_for_latency=true, backlog=1024)
host = host[1..-2] if host[0..0] == '['
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
@ios << s
s
end
def inherit_tcp_listener(host, port, fd)
if fd.kind_of? TCPServer
s = fd
else
s = TCPServer.for_fd(fd)
end
@ios << s
s
end
def add_ssl_listener(host, port, ctx,
optimize_for_latency=true, backlog=1024)
require 'puma/minissl'
host = host[1..-2] if host[0..0] == '['
s = TCPServer.new(host, port)
if optimize_for_latency
s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
end
s.setsockopt(Socket::SOL_SOCKET,Socket::SO_REUSEADDR, true)
s.listen backlog
ssl = MiniSSL::Server.new s, ctx
env = @proto_env.dup
env[HTTPS_KEY] = HTTPS
@envs[ssl] = env
@ios << ssl
s
end
def inherited_ssl_listener(fd, ctx)
require 'puma/minissl'
s = TCPServer.for_fd(fd)
@ios << MiniSSL::Server.new(s, ctx)
s
end
# Tell the server to listen on +path+ as a UNIX domain socket.
#
def add_unix_listener(path, umask=nil, mode=nil)
@unix_paths << path
# Let anyone connect by default
umask ||= 0
begin
old_mask = File.umask(umask)
if File.exist? path
begin
old = UNIXSocket.new path
rescue SystemCallError, IOError
File.unlink path
else
old.close
raise "There is already a server bound to: #{path}"
end
end
s = UNIXServer.new(path)
@ios << s
ensure
File.umask old_mask
end
if mode
File.chmod mode, path
end
s
end
def inherit_unix_listener(path, fd)
@unix_paths << path
if fd.kind_of? TCPServer
s = fd
else
s = UNIXServer.for_fd fd
end
@ios << s
s
end
end
end
|
module Raev
class Author
def self.parse_from_rss_entry entry_author
if entry_author.nil?
return nil
else
# Strip whitespace
author = entry_author.strip
if author.empty?
return nil
end
# Ignore common strings that are not names of people
no_authors = ["admin", "blogs", "editor", "staff"]
if no_authors.include?(author.downcase)
return nil
end
end
# Parse notation "andreas@somedomain.com (Andreas)"
m = /\((.*)\)/.match(author)
unless m.nil?
author = m[1]
end
# Remove nickname quotes
author = author.gsub(/\"(.*)\"/, "").gsub(/\'(.*)\'/, "").gsub(" ", " ")
# Capitalize
return author.split(' ').map(&:capitalize).join(' ')
end
end
end
Renamed parse_from_rss_entry.
module Raev
class Author
def self.normalize_name entry_author
if entry_author.nil?
return nil
else
# Strip whitespace
author = entry_author.strip
if author.empty?
return nil
end
# Ignore common strings that are not names of people
no_authors = ["admin", "blogs", "editor", "staff"]
if no_authors.include?(author.downcase)
return nil
end
end
# Parse notation "andreas@somedomain.com (Andreas)"
m = /\((.*)\)/.match(author)
unless m.nil?
author = m[1]
end
# Remove nickname quotes
author = author.gsub(/\"(.*)\"/, "").gsub(/\'(.*)\'/, "").gsub(" ", " ")
# Capitalize
return author.split(' ').map(&:capitalize).join(' ')
end
end
end |
module Rdm
VERSION = "0.0.2"
end
bump version
module Rdm
VERSION = "0.0.3"
end
|
# encoding: UTF-8
require 'sys/proctable'
require 'colored'
class Restartable
def self.version
Gem.loaded_specs['restartable'].version.to_s rescue 'DEV'
end
WAIT_SIGNALS = [[1, 'INT'], [1, 'INT'], [1, 'INT'], [1, 'TERM'], [5, 'KILL']]
def initialize(options, &block)
@options, @block = options, block
@mutex = Mutex.new
synced_trap('INT'){ interrupt! }
synced_trap('TERM'){ no_restart!; interrupt! }
cycle
end
def interrupt!
unless @interrupted
@interrupted = true
Thread.list.each do |thread|
unless Thread.current == thread
thread.raise SignalException.new('INT')
end
end
else
no_restart!
end
end
def no_restart!
@stop = true
puts 'Don\'t restart!'.red.bold
end
def cycle
until @stop
@interrupted = false
puts '^C to restart, double ^C to stop'.green
begin
@block.call
sleep # wait ^C even if block finishes
rescue SignalException
unless children.empty?
puts 'Killing children…'.yellow.bold
ripper = Thread.new do
WAIT_SIGNALS.each do |time, signal|
sleep time
puts "…SIG#{signal}…".yellow
children.each do |child|
Process.kill(signal, child.pid)
end
end
end
Process.waitall
ripper.terminate
end
unless @stop
puts 'Waiting ^C 0.5 second than restart…'.yellow.bold
sleep 0.5
end
end
end
end
private
def synced_trap(signal, &block)
Signal.trap(signal) do
Thread.new do
@mutex.synchronize(&block)
end
end
end
def children
pid = Process.pid
Sys::ProcTable.ps.select{ |pe| pid == pe.ppid }
end
end
require thread for mutex in ruby1.8
# encoding: UTF-8
require 'sys/proctable'
require 'colored'
require 'thread'
class Restartable
def self.version
Gem.loaded_specs['restartable'].version.to_s rescue 'DEV'
end
WAIT_SIGNALS = [[1, 'INT'], [1, 'INT'], [1, 'INT'], [1, 'TERM'], [5, 'KILL']]
def initialize(options, &block)
@options, @block = options, block
@mutex = Mutex.new
synced_trap('INT'){ interrupt! }
synced_trap('TERM'){ no_restart!; interrupt! }
cycle
end
def interrupt!
unless @interrupted
@interrupted = true
Thread.list.each do |thread|
unless Thread.current == thread
thread.raise SignalException.new('INT')
end
end
else
no_restart!
end
end
def no_restart!
@stop = true
puts 'Don\'t restart!'.red.bold
end
def cycle
until @stop
@interrupted = false
puts '^C to restart, double ^C to stop'.green
begin
@block.call
sleep # wait ^C even if block finishes
rescue SignalException
unless children.empty?
puts 'Killing children…'.yellow.bold
ripper = Thread.new do
WAIT_SIGNALS.each do |time, signal|
sleep time
puts "…SIG#{signal}…".yellow
children.each do |child|
Process.kill(signal, child.pid)
end
end
end
Process.waitall
ripper.terminate
end
unless @stop
puts 'Waiting ^C 0.5 second than restart…'.yellow.bold
sleep 0.5
end
end
end
end
private
def synced_trap(signal, &block)
Signal.trap(signal) do
Thread.new do
@mutex.synchronize(&block)
end
end
end
def children
pid = Process.pid
Sys::ProcTable.ps.select{ |pe| pid == pe.ppid }
end
end
|
# encoding: utf-8
#
# Command: cron
#
# [:day, :hour, :minute, :month, :weekday, :path, :type, :action]
require 'ridoku/base'
module Ridoku
register :cron
class Cron < Base
attr_accessor :cron
def run
command = Base.config[:command]
sub_command = (command.length > 0 && command[1]) || nil
environment = load_environment
case sub_command
when 'list', nil
list
when 'set', 'add'
add
when 'delete', 'remove', 'rm'
delete
else
print_cron_help
end
end
protected
def load_environment
Base.fetch_stack
self.cron = (Base.custom_json['deploy'][Base.config[:app].downcase]['cron'] ||= {})
end
def print_cron_help
$stderr.puts <<-EOF
Command: cron
List/Modify the current app's associated cron.
cron[:list] lists the cron jobs associated with an application.
cron:add cron job, e.g., runner:scripts/runme.rb hour:0 minute:0
cron:delete delete this specific cron job
Columns Value (default: *) Label
M Minute 0-59 minute
H Hour 0-23 hour
DM Day of Month 0-30 day_of_month
MO Month 0-11 month
DW Day of Week 0-6 day_of_week
Example 'cron:list' output:
Type Scripts M H DM MO DW
runner scripts/runme.rb 0 0 * * *
The above list output indicates a DelayedJob cron and two separate
delayed_job processes. One processing 'mail'; the other processing 'sms'.
examples:
$ cron
No cron specified!
$ cron:add type:runner path:scripts/runme.rb hour:0 minute:0
$ cron:add type:runner path:scripts/runme_also.rb minute:*/5
$ cron:list
Type Scripts M H DM MO DW
runner scripts/runme.rb 0 0 * * *
runner scripts/runme_also.rb */5 * * * *
$ cron:delete path:scrips/runme_also.rb
Type Scripts M H DM MO DW
runner scripts/runme.rb 0 0 * * *
delete scripts/runme_also.rb - - - - -
EOF
end
def list
load_environment
if cron.length == 0
$stdout.puts 'No cron jobs specified!'
else
columns = {
type: 'Type',
path: 'Scripts',
minute: 'M',
hour: 'H',
day_of_month: 'DM',
month: 'MO',
day_of_week: 'DW'
}
offset = {}
cron.each do |cronjob|
columns.keys.each do |key|
cronjob[key.to_s] = '*' unless cronjob.key?(key.to_s)
offset[key] = cronjob[key.to_s].length + 2 if cronjob.key?(key.to_s) &&
cronjob[key.to_s].length + 2 > (offset[key] || 0)
end
end
columns.keys.each do |key|
offset[key] = columns[key].length if
columns[key].length > (offset[key] || 0)
end
print_line(offset, columns)
cron.each { |cr| print_line(offset, cr, columns.keys) }
end
rescue =>e
puts e.backtrace
puts e
end
def add
croninfo = {}
cronindex = 0
ARGV.each do |cron|
info = cron.split(':')
croninfo[info[0].to_sym] = info[1]
cronindex = get_path_index(info[1])
end
puts croninfo
puts cronindex
# list
# Base.save_stack
end
def delete
return print_cron_help unless ARGV.length > 0
cronindex = get_path_index(ARGV.first)
puts cron[cronindex] unless cronindex.nil?
puts cronindex
# list
# Base.save_stack
end
protected
def get_path_index(path)
cron.each_with_index do |cr, idx|
return idx if cr[:path] == path
end
return nil
end
def load_environment
Base.fetch_stack
self.cron = (Base.custom_json['deploy'][Base.config[:app].downcase]['cron'] ||= {})
end
def print_line(offset, columns, keys = nil)
keys ||= columns.keys
keys.each do |key|
skey = key.to_s
content = columns[key] || columns[skey]
$stdout.print content
$stdout.print ' '*(offset[key] - content.length)
end
$stdout.puts
end
end
end
Working cron helpers.
# encoding: utf-8
#
# Command: cron
#
# [:day, :hour, :minute, :month, :weekday, :path, :type, :action]
require 'ridoku/base'
module Ridoku
register :cron
class Cron < Base
attr_accessor :cron
def run
command = Base.config[:command]
sub_command = (command.length > 0 && command[1]) || nil
load_environment
case sub_command
when 'list', nil
list
when 'set', 'add', 'update'
add
when 'delete'
delete
when 'remove'
remove
else
print_cron_help
end
end
protected
def load_environment
Base.fetch_stack
Base.fetch_instance('workers')
@default_instance = Base.instances.first[:hostname]
self.cron = (Base.custom_json['deploy'][Base.config[:app].downcase]['cron'] ||= {})
end
def print_cron_help
$stderr.puts <<-EOF
Command: cron
List/Modify the current app's associated cron.
cron[:list] lists the cron jobs associated with an application.
cron:add cron job, e.g., runner:scripts/runme.rb hour:0 minute:0
cron:delete delete this specific cron job
cron:remove removes a cron from the list (run after a delete and push)
cron:push update running cron jobs
Columns Value (default: *) Label
M Minute 0-59 minute
H Hour 0-23 hour
DM Day of Month 0-30 day_of_month
MO Month 0-11 month
DW Day of Week 0-6 day_of_week
All cron jobs are run on the Workers layer or the AssetMaster on the
Rails Application layer if one is not set, unless otherwise specified.
Example 'cron:list' output:
Type Scripts M H DM MO DW
runner scripts/runme.rb 0 0 * * *
The above list output indicates a DelayedJob cron and two separate
delayed_job processes. One processing 'mail'; the other processing 'sms'.
examples:
$ cron
No cron specified!
$ cron:add type:runner path:scripts/runme.rb hour:0 minute:0
$ cron:add type:runner path:scripts/runme_also.rb minute:*/5 instance:mukujara
$ cron:list
Type Scripts M H DM MO DW Instance
runner scripts/runme.rb 0 0 * * * oiwa
runner scripts/runme_also.rb */5 * * * * mukujara
$ cron:delete scrips/runme_also.rb
Type Scripts M H DM MO DW
runner scripts/runme.rb 0 0 * * * oiwa
delete scripts/runme_also.rb - - - - - mukujara
EOF
end
def list
if cron.length == 0
$stdout.puts 'No cron jobs specified!'
else
columns = {
type: 'Type',
path: 'Scripts',
minute: 'M',
hour: 'H',
day_of_month: 'DM',
month: 'MO',
day_of_week: 'DW',
instance: 'Instance'
}
offset = {}
self.cron.each do |cr|
columns.keys.each do |key|
skey = key.to_s
cr[skey] = '*' unless cr.key?(skey)
val = cr[skey].length
offset[key] = val if cr.key?(skey) && val > (offset[key] || 0)
end
end
columns.keys.each do |key|
offset[key] = columns[key].length if
columns[key].length > (offset[key] || 0)
end
$stdout.puts $stdout.colorize(line(offset, columns), :bold)
self.cron.each { |cr| $stdout.puts line(offset, cr, columns.keys) }
end
rescue =>e
puts e.backtrace
puts e
end
def add
croninfo = {}
cronindex = nil
ARGV.each do |cron|
info = cron.split(':',2)
croninfo[info[0].to_s] = info[1]
cronindex = get_path_index(info[1]) if info[0] == 'path'
end
croninfo['instance'] = @default_instance unless croninfo.key?('instance')
if cronindex.nil?
self.cron << croninfo
else
self.cron[cronindex] = croninfo
end
list
Base.save_stack
end
def delete
return print_cron_help unless ARGV.length > 0
cronindex = get_path_index(ARGV.first)
if cronindex.nil?
$stdout.puts $stdout.colorize(
'Unable to find the specified script path in the cron list.', :red)
return list
end
cr = self.cron[cronindex]
cr['type'] = 'delete'
cr['minute'] = '-'
cr['hour'] = '-'
cr['day_of_month'] = '-'
cr['month'] = '-'
cr['day_of_week'] = '-'
list
Base.save_stack
end
def remove
return print_cron_help unless ARGV.length > 0
cronindex = get_path_index(ARGV.first)
if cronindex.nil?
$stdout.puts $stdout.colorize(
'Unable to find the specified script path in the cron list.', :red)
return list
end
self.cron.delete_at(cronindex)
list
Base.save_stack
end
protected
def get_path_index(path)
cron.each_with_index do |cr, idx|
return idx if cr['path'] == path
end
return nil
end
def line(offset, columns, keys = nil)
keys ||= columns.keys
output = ''
keys.each do |key|
skey = key.to_s
content = columns[key] || columns[skey]
if skey == 'type'
case content
when 'delete'
output += $stdout.colorize(content, :red)
when 'runner'
output += $stdout.colorize(content, :green)
else
output += $stdout.colorize(content, :yellow)
end
else
output += content
end
output += ' '*(offset[key] - content.length + 2)
end
output
end
end
end |
module Rr3
VERSION = "0.0.1"
end
bump version
module Rr3
VERSION = "0.1.1"
end
|
require 'rspec/mocks/framework'
require 'rspec/mocks/version'
module RSpec
module Mocks
class << self
attr_accessor :space
end
self.space = RSpec::Mocks::Space.new
def self.setup(host)
# Nothing to do for now
end
def self.verify
space.verify_all
end
def self.teardown
space.reset_all
end
def self.proxy_for(object)
space.proxy_for(object)
end
def self.proxies_of(klass)
space.proxies_of(klass)
end
def self.any_instance_recorder_for(klass)
space.any_instance_recorder_for(klass)
end
# Adds an allowance (stub) on `subject`
#
# @param subject the subject to which the message will be added
# @param message a symbol, representing the message that will be
# added.
# @param opts a hash of options, :expected_from is used to set the
# original call site
# @param block an optional implementation for the allowance
#
# @example Defines the implementation of `foo` on `bar`, using the passed block
# x = 0
# RSpec::Mocks.allow_message(bar, :foo) { x += 1 }
def self.allow_message(subject, message, opts={}, &block)
orig_caller = opts.fetch(:expected_from) {
CallerFilter.first_non_rspec_line
}
::RSpec::Mocks.proxy_for(subject).
add_stub(orig_caller, message, opts, &block)
end
# Sets a message expectation on `subject`.
# @param subject the subject on which the message will be expected
# @param message a symbol, representing the message that will be
# expected.
# @param opts a hash of options, :expected_from is used to set the
# original call site
# @param block an optional implementation for the expectation
#
# @example Expect the message `foo` to receive `bar`, then call it
# RSpec::Mocks.expect_message(bar, :foo)
# bar.foo
def self.expect_message(subject, message, opts={}, &block)
orig_caller = opts.fetch(:expected_from) {
CallerFilter.first_non_rspec_line
}
::RSpec::Mocks.proxy_for(subject).
add_message_expectation(orig_caller, message, opts, &block)
end
# @api private
KERNEL_METHOD_METHOD = ::Kernel.instance_method(:method)
# @api private
# Used internally to get a method handle for a particular object
# and method name.
#
# Includes handling for a few special cases:
#
# - Objects that redefine #method (e.g. an HTTPRequest struct)
# - BasicObject subclasses that mixin a Kernel dup (e.g. SimpleDelegator)
def self.method_handle_for(object, method_name)
if ::Kernel === object
KERNEL_METHOD_METHOD.bind(object).call(method_name)
else
object.method(method_name)
end
end
# @private
IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored'
end
end
Document the methods defined in RSpec::Mocks.
require 'rspec/mocks/framework'
require 'rspec/mocks/version'
module RSpec
# Contains top-level utility methods. While this contains a few
# public methods, these are not generally meant to be called from
# a test or example. They exist primarily for integration with
# test frameworks (such as rspec-core).
module Mocks
class << self
# Stores rspec-mocks' global state.
# @api private
attr_accessor :space
end
self.space = RSpec::Mocks::Space.new
# Performs per-test/example setup. This should be called before
# an test or example begins.
def self.setup(host)
# Nothing to do for now
end
# Verifies any message expectations that were set during the
# test or example. This should be called at the end of an example.
def self.verify
space.verify_all
end
# Cleans up all test double state (including any methods that were
# redefined on partial doubles). This _must_ be called after
# each example, even if an error was raised during the example.
def self.teardown
space.reset_all
end
# Adds an allowance (stub) on `subject`
#
# @param subject the subject to which the message will be added
# @param message a symbol, representing the message that will be
# added.
# @param opts a hash of options, :expected_from is used to set the
# original call site
# @param block an optional implementation for the allowance
#
# @example Defines the implementation of `foo` on `bar`, using the passed block
# x = 0
# RSpec::Mocks.allow_message(bar, :foo) { x += 1 }
def self.allow_message(subject, message, opts={}, &block)
orig_caller = opts.fetch(:expected_from) {
CallerFilter.first_non_rspec_line
}
::RSpec::Mocks.proxy_for(subject).
add_stub(orig_caller, message, opts, &block)
end
# Sets a message expectation on `subject`.
# @param subject the subject on which the message will be expected
# @param message a symbol, representing the message that will be
# expected.
# @param opts a hash of options, :expected_from is used to set the
# original call site
# @param block an optional implementation for the expectation
#
# @example Expect the message `foo` to receive `bar`, then call it
# RSpec::Mocks.expect_message(bar, :foo)
# bar.foo
def self.expect_message(subject, message, opts={}, &block)
orig_caller = opts.fetch(:expected_from) {
CallerFilter.first_non_rspec_line
}
::RSpec::Mocks.proxy_for(subject).
add_message_expectation(orig_caller, message, opts, &block)
end
# @api private
# Returns the mock proxy for the given object.
def self.proxy_for(object)
space.proxy_for(object)
end
# @api private
# Returns the mock proxies for instances of the given class.
def self.proxies_of(klass)
space.proxies_of(klass)
end
# @api private
# Returns the any instance recorder for the given class.
def self.any_instance_recorder_for(klass)
space.any_instance_recorder_for(klass)
end
# @api private
KERNEL_METHOD_METHOD = ::Kernel.instance_method(:method)
# @api private
# Used internally to get a method handle for a particular object
# and method name.
#
# Includes handling for a few special cases:
#
# - Objects that redefine #method (e.g. an HTTPRequest struct)
# - BasicObject subclasses that mixin a Kernel dup (e.g. SimpleDelegator)
def self.method_handle_for(object, method_name)
if ::Kernel === object
KERNEL_METHOD_METHOD.bind(object).call(method_name)
else
object.method(method_name)
end
end
# @private
IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored'
end
end
|
require 'tags/tags'
module RubyBBCode
include BBCode::Tags
@@to_sentence_bbcode_tags = {:words_connector => "], [",
:two_words_connector => "] and [",
:last_word_connector => "] and ["}
def self.to_html(text, escape_html = true, additional_tags = {}, method = :disable, *tags)
# We cannot convert to HTML if the BBCode is not valid!
text = text.clone
use_tags = @@tags.merge(additional_tags)
if method == :disable then
tags.each { |t| use_tags.delete(t) }
else
new_use_tags = {}
tags.each { |t| new_use_tags[t] = use_tags[t] if use_tags.key?(t) }
use_tags = new_use_tags
end
if escape_html
text.gsub!('<', '<')
text.gsub!('>', '>')
end
text.gsub!("\r\n", "\n")
text.gsub!("\n", "<br />\n")
valid = parse(text, use_tags)
raise valid.join(', ') if valid != true
bbtree_to_html(@bbtree[:nodes], use_tags)
end
def self.is_valid?(text, additional_tags = {})
parse(text, @@tags.merge(additional_tags));
end
def self.tag_list
@@tags
end
protected
def self.parse(text, tags = {})
tags = @@tags if tags == {}
tags_list = []
@bbtree = {:nodes => []}
bbtree_depth = 0
bbtree_current_node = @bbtree
text.scan(/((\[ (\/)? (\w+) ((=[^\[\]]+) | (\s\w+=\w+)* | ([^\]]*))? \]) | ([^\[]+))/ix) do |tag_info|
ti = find_tag_info(tag_info)
if ti[:is_tag] and !tags.include?(ti[:tag].to_sym)
# Handle as text from now on!
ti[:is_tag] = false
ti[:text] = ti[:complete_match]
end
if !ti[:is_tag] or !ti[:closing_tag]
if ti[:is_tag]
tag = tags[ti[:tag].to_sym]
unless tag[:only_in].nil? or (tags_list.length > 0 and tag[:only_in].include?(tags_list.last.to_sym))
# Tag does to be put in the last opened tag
err = "[#{ti[:tag]}] can only be used in [#{tag[:only_in].to_sentence(@@to_sentence_bbcode_tags)}]"
err += ", so using it in a [#{tags_list.last}] tag is not allowed" if tags_list.length > 0
return [err]
end
if tag[:allow_tag_param] and ti[:params][:tag_param] != nil
# Test if matches
return [tag[:tag_param_description].gsub('%param%', ti[:params][:tag_params])] if ti[:params][:tag_param].match(tag[:tag_param]).nil?
end
end
if tags_list.length > 0 and tags[tags_list.last.to_sym][:only_allow] != nil
# Check if the found tag is allowed
last_tag = tags[tags_list.last.to_sym]
allowed_tags = last_tag[:only_allow]
if (!ti[:is_tag] and last_tag[:require_between] != true) or (ti[:is_tag] and (allowed_tags.include?(ti[:tag].to_sym) == false))
# Last opened tag does not allow tag
err = "[#{tags_list.last}] can only contain [#{allowed_tags.to_sentence(@@to_sentence_bbcode_tags)}] tags, so "
err += "[#{ti[:tag]}]" if ti[:is_tag]
err += "\"#{ti[:text]}\"" unless ti[:is_tag]
err += ' is not allowed'
return [err]
end
end
# Validation of tag succeeded, add to tags_list and/or bbtree
if ti[:is_tag]
tag = tags[ti[:tag].to_sym]
tags_list.push ti[:tag]
element = {:is_tag => true, :tag => ti[:tag].to_sym, :nodes => [] }
element[:params] = {:tag_param => ti[:params][:tag_param]} if tag[:allow_tag_param] and ti[:params][:tag_param] != nil
else
element = {:is_tag => false, :text => ti[:text] }
if bbtree_depth > 0
tag = tags[bbtree_current_node[:tag]]
if tag[:require_between] == true
bbtree_current_node[:between] = ti[:text]
if tag[:allow_tag_param] and tag[:allow_tag_param_between] and (bbtree_current_node[:params] == nil or bbtree_current_node[:params][:tag_param] == nil)
# Did not specify tag_param, so use between.
# Check if valid
return [tag[:tag_param_description].gsub('%param%', ti[:text])] if ti[:text].match(tag[:tag_param]).nil?
# Store as tag_param
bbtree_current_node[:params] = {:tag_param => ti[:text]}
end
element = nil
end
end
end
bbtree_current_node[:nodes] << element unless element == nil
if ti[:is_tag]
# Advance to next level (the node we just added)
bbtree_current_node = element
bbtree_depth += 1
end
end
if ti[:is_tag] and ti[:closing_tag]
if ti[:is_tag]
tag = tags[ti[:tag].to_sym]
return ["Closing tag [/#{ti[:tag]}] does match [#{tags_list.last}]"] if tags_list.last != ti[:tag]
return ["No text between [#{ti[:tag]}] and [/#{ti[:tag]}] tags."] if tag[:require_between] == true and bbtree_current_node[:between].blank?
tags_list.pop
# Find parent node (kinda hard since no link to parent node is available...)
bbtree_depth -= 1
bbtree_current_node = @bbtree
bbtree_depth.times { bbtree_current_node = bbtree_current_node[:nodes].last }
end
end
end
return ["[#{tags_list.to_sentence((@@to_sentence_bbcode_tags))}] not closed"] if tags_list.length > 0
true
end
def self.find_tag_info(tag_info)
ti = {}
ti[:complete_match] = tag_info[0]
ti[:is_tag] = (tag_info[0].start_with? '[')
if ti[:is_tag]
ti[:closing_tag] = (tag_info[2] == '/')
ti[:tag] = tag_info[3]
ti[:params] = {}
if tag_info[4][0] == ?=
ti[:params][:tag_param] = tag_info[4][1..-1]
elsif tag_info[4][0] == ?\s
#TODO: Find params
end
else
# Plain text
ti[:text] = tag_info[8]
end
ti
end
def self.bbtree_to_html(node_list, tags = {})
tags = @@tags if tags == {}
text = ""
node_list.each do |node|
if node[:is_tag]
tag = tags[node[:tag]]
t = tag[:html_open].dup
t.gsub!('%between%', node[:between]) if tag[:require_between]
if tag[:allow_tag_param]
if node[:params] and !node[:params][:tag_param].blank?
match_array = node[:params][:tag_param].scan(tag[:tag_param])[0]
index = 0
match_array.each do |match|
if index < tag[:tag_param_tokens].length
t.gsub!("%#{tag[:tag_param_tokens][index][:token].to_s}%", tag[:tag_param_tokens][index][:prefix].to_s+match+tag[:tag_param_tokens][index][:postfix].to_s)
index += 1
end
end
else
# Remove unused tokens
tag[:tag_param_tokens].each do |token|
t.gsub!("%#{token[:token]}%", '')
end
end
end
text += t
text += bbtree_to_html(node[:nodes], tags) if node[:nodes].length > 0
t = tag[:html_close]
t.gsub!('%between%', node[:between]) if tag[:require_between]
text += t
else
text += node[:text] unless node[:text].nil?
end
end
text
end
end
String.class_eval do
# Convert a string with BBCode markup into its corresponding HTML markup
def bbcode_to_html(escape_html = true, additional_tags = {}, method = :disable, *tags)
RubyBBCode.to_html(self, escape_html, additional_tags, method, *tags)
end
# Replace the BBCode content of a string with its corresponding HTML markup
def bbcode_to_html!(escape_html = true, additional_tags = {}, method = :disable, *tags)
self.replace(RubyBBCode.to_html(self, escape_html, additional_tags, method, *tags))
end
# Check if string contains valid BBCode. Returns true when valid, else returns array with error(s)
def is_valid_bbcode?
RubyBBCode.is_valid?(self)
end
end
Fixed small problem while filling in the %param% part of the error description
require 'tags/tags'
module RubyBBCode
include BBCode::Tags
@@to_sentence_bbcode_tags = {:words_connector => "], [",
:two_words_connector => "] and [",
:last_word_connector => "] and ["}
def self.to_html(text, escape_html = true, additional_tags = {}, method = :disable, *tags)
# We cannot convert to HTML if the BBCode is not valid!
text = text.clone
use_tags = @@tags.merge(additional_tags)
if method == :disable then
tags.each { |t| use_tags.delete(t) }
else
new_use_tags = {}
tags.each { |t| new_use_tags[t] = use_tags[t] if use_tags.key?(t) }
use_tags = new_use_tags
end
if escape_html
text.gsub!('<', '<')
text.gsub!('>', '>')
end
text.gsub!("\r\n", "\n")
text.gsub!("\n", "<br />\n")
valid = parse(text, use_tags)
raise valid.join(', ') if valid != true
bbtree_to_html(@bbtree[:nodes], use_tags)
end
def self.is_valid?(text, additional_tags = {})
parse(text, @@tags.merge(additional_tags));
end
def self.tag_list
@@tags
end
protected
def self.parse(text, tags = {})
tags = @@tags if tags == {}
tags_list = []
@bbtree = {:nodes => []}
bbtree_depth = 0
bbtree_current_node = @bbtree
text.scan(/((\[ (\/)? (\w+) ((=[^\[\]]+) | (\s\w+=\w+)* | ([^\]]*))? \]) | ([^\[]+))/ix) do |tag_info|
ti = find_tag_info(tag_info)
if ti[:is_tag] and !tags.include?(ti[:tag].to_sym)
# Handle as text from now on!
ti[:is_tag] = false
ti[:text] = ti[:complete_match]
end
if !ti[:is_tag] or !ti[:closing_tag]
if ti[:is_tag]
tag = tags[ti[:tag].to_sym]
unless tag[:only_in].nil? or (tags_list.length > 0 and tag[:only_in].include?(tags_list.last.to_sym))
# Tag does to be put in the last opened tag
err = "[#{ti[:tag]}] can only be used in [#{tag[:only_in].to_sentence(@@to_sentence_bbcode_tags)}]"
err += ", so using it in a [#{tags_list.last}] tag is not allowed" if tags_list.length > 0
return [err]
end
if tag[:allow_tag_param] and ti[:params][:tag_param] != nil
# Test if matches
return [tag[:tag_param_description].gsub('%param%', ti[:params][:tag_param])] if ti[:params][:tag_param].match(tag[:tag_param]).nil?
end
end
if tags_list.length > 0 and tags[tags_list.last.to_sym][:only_allow] != nil
# Check if the found tag is allowed
last_tag = tags[tags_list.last.to_sym]
allowed_tags = last_tag[:only_allow]
if (!ti[:is_tag] and last_tag[:require_between] != true) or (ti[:is_tag] and (allowed_tags.include?(ti[:tag].to_sym) == false))
# Last opened tag does not allow tag
err = "[#{tags_list.last}] can only contain [#{allowed_tags.to_sentence(@@to_sentence_bbcode_tags)}] tags, so "
err += "[#{ti[:tag]}]" if ti[:is_tag]
err += "\"#{ti[:text]}\"" unless ti[:is_tag]
err += ' is not allowed'
return [err]
end
end
# Validation of tag succeeded, add to tags_list and/or bbtree
if ti[:is_tag]
tag = tags[ti[:tag].to_sym]
tags_list.push ti[:tag]
element = {:is_tag => true, :tag => ti[:tag].to_sym, :nodes => [] }
element[:params] = {:tag_param => ti[:params][:tag_param]} if tag[:allow_tag_param] and ti[:params][:tag_param] != nil
else
element = {:is_tag => false, :text => ti[:text] }
if bbtree_depth > 0
tag = tags[bbtree_current_node[:tag]]
if tag[:require_between] == true
bbtree_current_node[:between] = ti[:text]
if tag[:allow_tag_param] and tag[:allow_tag_param_between] and (bbtree_current_node[:params] == nil or bbtree_current_node[:params][:tag_param] == nil)
# Did not specify tag_param, so use between.
# Check if valid
return [tag[:tag_param_description].gsub('%param%', ti[:text])] if ti[:text].match(tag[:tag_param]).nil?
# Store as tag_param
bbtree_current_node[:params] = {:tag_param => ti[:text]}
end
element = nil
end
end
end
bbtree_current_node[:nodes] << element unless element == nil
if ti[:is_tag]
# Advance to next level (the node we just added)
bbtree_current_node = element
bbtree_depth += 1
end
end
if ti[:is_tag] and ti[:closing_tag]
if ti[:is_tag]
tag = tags[ti[:tag].to_sym]
return ["Closing tag [/#{ti[:tag]}] does match [#{tags_list.last}]"] if tags_list.last != ti[:tag]
return ["No text between [#{ti[:tag]}] and [/#{ti[:tag]}] tags."] if tag[:require_between] == true and bbtree_current_node[:between].blank?
tags_list.pop
# Find parent node (kinda hard since no link to parent node is available...)
bbtree_depth -= 1
bbtree_current_node = @bbtree
bbtree_depth.times { bbtree_current_node = bbtree_current_node[:nodes].last }
end
end
end
return ["[#{tags_list.to_sentence((@@to_sentence_bbcode_tags))}] not closed"] if tags_list.length > 0
true
end
def self.find_tag_info(tag_info)
ti = {}
ti[:complete_match] = tag_info[0]
ti[:is_tag] = (tag_info[0].start_with? '[')
if ti[:is_tag]
ti[:closing_tag] = (tag_info[2] == '/')
ti[:tag] = tag_info[3]
ti[:params] = {}
if tag_info[4][0] == ?=
ti[:params][:tag_param] = tag_info[4][1..-1]
elsif tag_info[4][0] == ?\s
#TODO: Find params
end
else
# Plain text
ti[:text] = tag_info[8]
end
ti
end
def self.bbtree_to_html(node_list, tags = {})
tags = @@tags if tags == {}
text = ""
node_list.each do |node|
if node[:is_tag]
tag = tags[node[:tag]]
t = tag[:html_open].dup
t.gsub!('%between%', node[:between]) if tag[:require_between]
if tag[:allow_tag_param]
if node[:params] and !node[:params][:tag_param].blank?
match_array = node[:params][:tag_param].scan(tag[:tag_param])[0]
index = 0
match_array.each do |match|
if index < tag[:tag_param_tokens].length
t.gsub!("%#{tag[:tag_param_tokens][index][:token].to_s}%", tag[:tag_param_tokens][index][:prefix].to_s+match+tag[:tag_param_tokens][index][:postfix].to_s)
index += 1
end
end
else
# Remove unused tokens
tag[:tag_param_tokens].each do |token|
t.gsub!("%#{token[:token]}%", '')
end
end
end
text += t
text += bbtree_to_html(node[:nodes], tags) if node[:nodes].length > 0
t = tag[:html_close]
t.gsub!('%between%', node[:between]) if tag[:require_between]
text += t
else
text += node[:text] unless node[:text].nil?
end
end
text
end
end
String.class_eval do
# Convert a string with BBCode markup into its corresponding HTML markup
def bbcode_to_html(escape_html = true, additional_tags = {}, method = :disable, *tags)
RubyBBCode.to_html(self, escape_html, additional_tags, method, *tags)
end
# Replace the BBCode content of a string with its corresponding HTML markup
def bbcode_to_html!(escape_html = true, additional_tags = {}, method = :disable, *tags)
self.replace(RubyBBCode.to_html(self, escape_html, additional_tags, method, *tags))
end
# Check if string contains valid BBCode. Returns true when valid, else returns array with error(s)
def is_valid_bbcode?
RubyBBCode.is_valid?(self)
end
end
|
require 'rubygems'
gem 'httparty'
require 'httparty'
class RedboxAPI
include HTTParty
base_uri "www.redbox.com"
class << self
def get_titles
url = URI.parse('http://www.redbox.com/api/product/js/titles')
response = Net::HTTP.start(url.host, url.port){|http| http.get(url.path)}
case response
when Net::HTTPSuccess, Net::HTTPRedirection
@titles = response.body[13..-1]
else
response.error
end
end
def find_nearest_kiosks(title_id, zip)
body = "{\"filters\":{\"proximity\":{\"lat\":39.3668174,\"lng\":-76.670948,\"radius\":50}},\"resultOptions\":{\"max\":50,\"profile\":true,\"status\":true,\"proximity\":true,\"user\":true,\"inventory\":true,\"inventoryProducts\":[\"#{title_id}\"]}}"
headers = {"Host" => "www.redbox.com", "Accept" => "application/json", "X-Requested-With" => "XMLHttpRequest", "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13", "cookie" => "rbuser=Validation=5u/UfKCJpwFUJOW0wYNsZrUJ/1Wc/yOL4HF3zhsxTC8=; RB_2.0=1; _json=%7B%22isBlurayWarningEnabled%22%3A%22true%22%2C%22isGamesWarningEnabled%22%3A%22true%22%2C%22locationSearchValue%22%3A%22%5C%2221209%5C%22%22%7D; s_vi=[CS]v1|268A179C851D2012-6000010160000D1E[CE]; ASP.NET_SessionId=oszj4v53yetgxjiiouic4cg4; LB=1518497546.0.0000; s_cc=true; c_m=undefinedDirect%20LoadDirect%20Load; s_sq=%5B%5BB%5D%5D", "__K" => "uFyVRI4STRLYVcsJY2zC92etFBe6N/ef19yTBpaRipY=", "Referer" => "http://www.redbox.com/"}
puts body.to_json
self.post("/api/Store/GetStores/", :body => body.to_json, :headers => headers)
end
end
end
Messing with Headers.
require 'rubygems'
gem 'httparty'
require 'httparty'
class RedboxAPI
include HTTParty
base_uri "www.redbox.com"
class << self
def get_titles
url = URI.parse('http://www.redbox.com/api/product/js/titles')
response = Net::HTTP.start(url.host, url.port){|http| http.get(url.path)}
case response
when Net::HTTPSuccess, Net::HTTPRedirection
@titles = response.body[13..-1]
else
response.error
end
end
def find_nearest_kiosks(title_id, zip)
body = "{\"filters\":{\"proximity\":{\"lat\":39.3668174,\"lng\":-76.670948,\"radius\":50}},\"resultOptions\":{\"max\":50,\"profile\":true,\"status\":true,\"proximity\":true,\"user\":true,\"inventory\":true,\"inventoryProducts\":[\"#{title_id}\"]}}"
headers = {"Host" => "www.redbox.com", "Accept" => "application/json, text/javascript, */*", "X-Requested-With" => "XMLHttpRequest", "User-Agent" => "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13", "Cookie" => "rbuser=Validation=5u/UfKCJpwFUJOW0wYNsZrUJ/1Wc/yOL4HF3zhsxTC8=; RB_2.0=1; _json=%7B%22isBlurayWarningEnabled%22%3A%22true%22%2C%22isGamesWarningEnabled%22%3A%22true%22%2C%22locationSearchValue%22%3A%22%5C%2221209%5C%22%22%7D; s_vi=[CS]v1|268A179C851D2012-6000010160000D1E[CE]; ASP.NET_SessionId=oszj4v53yetgxjiiouic4cg4; LB=1518497546.0.0000; s_cc=true; c_m=undefinedDirect%20LoadDirect%20Load; s_sq=%5B%5BB%5D%5D", "__K" => "uFyVRI4STRLYVcsJY2zC92etFBe6N/ef19yTBpaRipY="}
self.post("/api/Store/GetStores/", :body => body.to_json, :headers => headers)
end
end
end |
#!/usr/bin/ruby
module Rypple
require 'fileutils'
require 'ftools'
require 'yaml'
require "rubygems"
require 'dropbox_sdk'
require 'pathname'
DefaultConfiguration = {
:destinationDir => './test',
:dropbox => {
:root => '/',
:sync => ['**'],
:access_type => :app_folder,
}
}
DropboxKeyFile = "dropbox_session.yml"
RyppleConfigFile = "rypple.yml"
def Rypple.connectToDropbox(path)
dropConf = File.join(path, DropboxKeyFile)
#Load Dropbox API dropboxKeys from file, if applicable.
if File.exists?(dropConf)
dropboxKeys = YAML::load(File.read(dropConf))
else
puts "A Dropbox API key/secret is required for accessing your sync files."
puts "You can visit https://www.dropbox.com/developers/apps to generate these."
print "Please enter your Dropbox API key:"
dropboxKeys = {}
dropboxKeys[:key] = gets.chomp!
print "Please enter your Dropbox API secret:"
dropboxKeys[:secret] = gets.chomp!
print "Should this API access be used in sandbox mode? (Y/n):"
answer = gets.downcase.chomp
if !answer.empty? and answer == 'n'
dropboxKeys[:access_type]= :dropbox
end
end
session = nil
if dropboxKeys.has_key?(:session)
session = DropboxSession.deserialize(dropboxKeys[:session])
else
session = DropboxSession.new(dropboxKeys[:key], dropboxKeys[:secret])
session.get_request_token
authorize_url = session.get_authorize_url
puts "Visit #{authorize_url} to log in to Dropbox. Hit enter when you have done this."
gets
session.get_access_token
end
if session.nil?
return nil, nil, nil
end
if !dropboxKeys.has_key?(:session)
dropboxKeys[:session] = session.serialize()
end
client = DropboxClient.new(session, dropboxKeys[:access_type])
if client.nil?
return nil, nil, nil
else
return session, client, dropboxKeys
end
end
def Rypple.loadConfiguration(path)
conf = Rypple::DefaultConfiguration.dup
rypConf = File.join(path, RyppleConfigFile)
# Load configuration and override any values that differ from the default.
if File.exists?(rypConf)
loadedConf = YAML::load(File.read(rypConf))
conf.merge!(loadedConf)
end
conf[:destinationDir] = File.expand_path(conf[:destinationDir])
if !File.directory?(conf[:destinationDir])
begin
Dir.mkdir(conf[:destinationDir])
rescue SystemCallError
raise RuntimeError, "Destination doesn't exist and cannot be created."
end
end
return conf
end
def Rypple.saveDropbox(keys, path)
dropConfig = File.join(path, DropboxKeyFile)
File.open(dropConfig, 'w') do|file|
file.puts keys.to_yaml
end
end
def Rypple.saveConfig(conf, path)
ryppleConf = File.join(path, RyppleConfigFile)
File.open(ryppleConf, 'w') do |file|
file.puts conf.to_yaml
end
end
def Rypple.cleanup(conf, keys, path)
Rypple.saveConfig(conf, path)
Rypple.saveDropbox(keys, path)
end
# Iterates over dropbox directory, returing paths and state hash for each file
# oldFileState should be a hash of paths to state hashes, same as return values
def Rypple.walkDropbox(client, path, oldFileState)
#Here we need to actually sync newest files.
begin
useState = (!oldFileState.nil? and oldFileState.has_key?(path) and oldFileState[path]["path"] == path)
oldState = useState ? oldFileState[path]["hash"] : nil
states = client.metadata(path, 10000, true, oldState)
rescue DropboxNotModified
puts "Files have not changed."
return nil
end
files = {}
#State represents a folder
if states["is_dir"] and states.has_key?("contents")
states["contents"].each{ |xx|
useState = (!oldFileState.nil? and oldFileState.has_key?(xx["path"]))
old = (useState ? oldFileState[xx["path"]] : nil)
subs = Rypple.walkDropbox(client, xx["path"], old)
if !subs.nil?
files.merge!(subs)
end
}
else
files[states['path']] = states
end
return files
end
def Rypple.sync(path = "")
conf = Rypple.loadConfiguration(path)
begin
session, client, dropboxKeys = Rypple.connectToDropbox(path)
rescue DropboxAuthError
puts "Dropbox authorization failed."
Rypple.cleanup(conf, dropboxKeys, path)
return
rescue NameError
puts "Destination does not exist."
Rypple.cleanup(conf, dropboxKeys, path)
return
end
if session.nil?
puts "Could not connect to Dropbox."
Rypple.cleanup(conf, dropboxKeys, path)
return
end
destDir = conf[:destinationDir]
oldFileState = dropboxKeys[:files]
files = Rypple.walkDropbox(client, conf[:dropbox][:root], oldFileState)
rootLength = conf[:dropbox][:root].length
if !files.nil?
files.keys.each { |xx|
fileDest = xx[rootLength, xx.length]
matched = false
conf[:dropbox][:sync].each { |ii|
if File.fnmatch?(ii, xx, File::FNM_DOTMATCH)
matched = true
break
end
}
if matched
file = client.get_file(xx)
dest = File.join(destDir, fileDest)
File.makedirs(File.dirname(dest))
File.open(dest, 'w') {|f| f.puts file}
end
}
end
conf[:dropbox][:sync].each { |ii|
Dir.glob(File.join(destDir, ii)).each { |oo|
if !File.directory?(oo)
upName = Pathname.new(oo).relative_path_from(Pathname.new(destDir)).to_s
upName = File.join("", conf[:dropbox][:root], upName)
if files.nil? or !files.has_key?(upName)
File.open(oo) { |f| client.put_file(upName, f, true) }
end
end
}
}
dropboxKeys[:files] = Rypple.walkDropbox(client, conf[:dropbox][:root], {})
Rypple.cleanup(conf, dropboxKeys, path)
return true
end
end
Refactor of logging into Dropbox.
Fixing an issue in which the Dropbox access type was incorrectly set.
#!/usr/bin/ruby
module Rypple
require 'fileutils'
require 'ftools'
require 'yaml'
require "rubygems"
require 'dropbox_sdk'
require 'pathname'
DefaultConfiguration = {
:destinationDir => './test',
:dropbox => {
:root => '/',
:sync => ['**'],
}
}
DropboxKeyFile = "dropbox_session.yml"
RyppleConfigFile = "rypple.yml"
def Rypple.connectToDropbox(path)
session = nil
dropboxKeys = {:access_type => :app_folder}
dropConf = File.join(path, DropboxKeyFile)
#Load Dropbox API dropboxKeys from file, if applicable.
if File.exists?(dropConf)
dropboxKeys = YAML::load(File.read(dropConf))
end
if dropboxKeys.has_key?(:session)
session = DropboxSession.deserialize(dropboxKeys[:session])
else
dropboxKeys[:access], session = Rypple.buildLoginSession()
end
if session.nil?
return nil, nil, nil
end
if !dropboxKeys.has_key?(:session)
dropboxKeys[:session] = session.serialize()
end
client = DropboxClient.new(session, dropboxKeys[:access_type])
if client.nil?
return nil, nil, nil
else
return session, client, dropboxKeys
end
end
def Rypple.loadConfiguration(path)
conf = Rypple::DefaultConfiguration.dup
rypConf = File.join(path, RyppleConfigFile)
# Load configuration and override any values that differ from the default.
if File.exists?(rypConf)
loadedConf = YAML::load(File.read(rypConf))
conf.merge!(loadedConf)
end
conf[:destinationDir] = File.expand_path(conf[:destinationDir])
if !File.directory?(conf[:destinationDir])
begin
Dir.mkdir(conf[:destinationDir])
rescue SystemCallError
raise RuntimeError, "Destination doesn't exist and cannot be created."
end
end
return conf
end
def Rypple.buildLoginSession()
puts "A Dropbox API key/secret is required for accessing your sync files."
puts "You can visit https://www.dropbox.com/developers/apps to generate these."
print "Please enter your Dropbox API key:"
key = gets.chomp!
print "Please enter your Dropbox API secret:"
secret = gets.chomp!
access = :app_folder
print "Should this API access be used in sandbox mode? (Y/n):"
answer = gets.downcase.chomp
if !answer.empty? and answer == 'n'
access = :dropbox
end
session = DropboxSession.new(key, secret)
session.get_request_token
authorize_url = session.get_authorize_url
puts "Visit #{authorize_url} to log in to Dropbox. Hit enter when you have done this."
gets
session.get_access_token
return access, session
end
def Rypple.saveDropbox(keys, path)
dropConfig = File.join(path, DropboxKeyFile)
File.open(dropConfig, 'w') do|file|
file.puts keys.to_yaml
end
end
def Rypple.saveConfig(conf, path)
ryppleConf = File.join(path, RyppleConfigFile)
File.open(ryppleConf, 'w') do |file|
file.puts conf.to_yaml
end
end
def Rypple.cleanup(conf, keys, path)
Rypple.saveConfig(conf, path)
Rypple.saveDropbox(keys, path)
end
# Iterates over dropbox directory, returing paths and state hash for each file
# oldFileState should be a hash of paths to state hashes, same as return values
def Rypple.walkDropbox(client, path, oldFileState)
#Here we need to actually sync newest files.
begin
useState = (!oldFileState.nil? and oldFileState.has_key?(path) and oldFileState[path]["path"] == path)
oldState = useState ? oldFileState[path]["hash"] : nil
states = client.metadata(path, 10000, true, oldState)
rescue DropboxNotModified
puts "Files have not changed."
return nil
end
files = {}
#State represents a folder
if states["is_dir"] and states.has_key?("contents")
states["contents"].each{ |xx|
useState = (!oldFileState.nil? and oldFileState.has_key?(xx["path"]))
old = (useState ? oldFileState[xx["path"]] : nil)
subs = Rypple.walkDropbox(client, xx["path"], old)
if !subs.nil?
files.merge!(subs)
end
}
else
files[states['path']] = states
end
return files
end
def Rypple.sync(path = "")
conf = Rypple.loadConfiguration(path)
begin
session, client, dropboxKeys = Rypple.connectToDropbox(path)
rescue DropboxAuthError
puts "Dropbox authorization failed."
Rypple.cleanup(conf, dropboxKeys, path)
return
rescue NameError
puts "Destination does not exist."
Rypple.cleanup(conf, dropboxKeys, path)
return
end
if session.nil?
puts "Could not connect to Dropbox."
Rypple.cleanup(conf, dropboxKeys, path)
return
end
destDir = conf[:destinationDir]
oldFileState = dropboxKeys[:files]
files = Rypple.walkDropbox(client, conf[:dropbox][:root], oldFileState)
rootLength = conf[:dropbox][:root].length
if !files.nil?
files.keys.each { |xx|
fileDest = xx[rootLength, xx.length]
matched = false
conf[:dropbox][:sync].each { |ii|
if File.fnmatch?(ii, xx, File::FNM_DOTMATCH)
matched = true
break
end
}
if matched
file = client.get_file(xx)
dest = File.join(destDir, fileDest)
File.makedirs(File.dirname(dest))
File.open(dest, 'w') {|f| f.puts file}
end
}
end
conf[:dropbox][:sync].each { |ii|
Dir.glob(File.join(destDir, ii)).each { |oo|
if !File.directory?(oo)
upName = Pathname.new(oo).relative_path_from(Pathname.new(destDir)).to_s
upName = File.join("", conf[:dropbox][:root], upName)
if files.nil? or !files.has_key?(upName)
File.open(oo) { |f| client.put_file(upName, f, true) }
end
end
}
}
dropboxKeys[:files] = Rypple.walkDropbox(client, conf[:dropbox][:root], {})
Rypple.cleanup(conf, dropboxKeys, path)
return true
end
end
|
module RZMQMCompat
class ZMQError < RuntimeError; end
class ZMQOperationFailed < ZMQError; end
def self.included(klass)
klass.instance_eval do
%w(getsockopt recv).each do |m|
alias_method :"#{m}_without_raise", m.to_sym
alias_method m.to_sym, :"#{m}_with_raise"
end
end
end
def getsockopt_with_raise(opt, *args)
arity = method(:getsockopt_without_raise).arity
if args.empty?
case arity
when 1
getsockopt_without_raise(opt)
when 2
ret = []
rc = getsockopt_without_raise(opt, ret)
unless ZMQ::Util.resultcode_ok?(rc)
raise ZMQOperationFailed, "getsockopt: #{ZMQ.errno}"
end
(ret.size == 1) ? ret[0] : ret
else
raise "Unsupported version of ffi-rzmq, getsockopt takes #{arity} arguments"
end
else
# just pass the call to the original method
getsockopt_without_raise(opt, *args)
end
end
def recv_with_raise(msg, flags = 0)
recv_without_raise(msg, flags)
end
end
ZMQ::Socket.send(:include, RZMQCompat)
lib/rzmq_compat.rb
module RZMQCompat
class ZMQError < RuntimeError; end
class ZMQOperationFailed < ZMQError; end
def self.included(klass)
klass.instance_eval do
%w(getsockopt recv).each do |m|
alias_method :"#{m}_without_raise", m.to_sym
alias_method m.to_sym, :"#{m}_with_raise"
end
end
end
def getsockopt_with_raise(opt, *args)
arity = method(:getsockopt_without_raise).arity
if args.empty?
case arity
when 1
getsockopt_without_raise(opt)
when 2
ret = []
rc = getsockopt_without_raise(opt, ret)
unless ZMQ::Util.resultcode_ok?(rc)
raise ZMQOperationFailed, "getsockopt: #{ZMQ.errno}"
end
(ret.size == 1) ? ret[0] : ret
else
raise "Unsupported version of ffi-rzmq, getsockopt takes #{arity} arguments"
end
else
# just pass the call to the original method
getsockopt_without_raise(opt, *args)
end
end
def recv_with_raise(msg, flags = 0)
recv_without_raise(msg, flags)
end
end
ZMQ::Socket.send(:include, RZMQCompat)
|
$:.unshift(File.expand_path('..', __FILE__))
require 'rubygems'
require 'aws/s3'
require 'pp'
require 'builder'
module S3Uploader
CONFIG = YAML.load_file('./config/config.yml')
raise "Specify config.yml" unless CONFIG
class << self
def upload()
bucket = CONFIG[:s3][:bucket]
files = Dir.glob("#{Builder::DIST_DIR}/#{Builder.config["VERSION"]}/*")
target_dir = "#{Builder.config["VERSION"]}/"
AWS::S3::Base.establish_connection!(
:access_key_id => CONFIG[:s3][:access_key_id],
:secret_access_key => CONFIG[:s3][:secret_access_key]
)
files.each do |file|
file_name = File.basename(file)
p "Uploading ... AWS::S3::S3Object.store(#{target_dir + file_name}, open(#{file}), #{bucket}, :access => :public_read)"
AWS::S3::S3Object.store(target_dir + file_name, open(file), bucket, :access => :public_read)
end
end
end
end
Changed s3 uploader to upload both full version and major_minor version
$:.unshift(File.expand_path('..', __FILE__))
require 'rubygems'
require 'aws/s3'
require 'pp'
require 'builder'
module S3Uploader
CONFIG = YAML.load_file('./config/config.yml')
raise "Specify config.yml" unless CONFIG
class << self
def upload()
versions = [Builder.version.full, Builder.version.major_minor]
versions.each do |v|
bucket = CONFIG[:s3][:bucket]
files = Dir.glob("#{Builder::DIST_DIR}/#{v}/*")
target_dir = "#{v}/"
AWS::S3::Base.establish_connection!(
:access_key_id => CONFIG[:s3][:access_key_id],
:secret_access_key => CONFIG[:s3][:secret_access_key]
)
files.each do |file|
file_name = File.basename(file)
p "Uploading ... AWS::S3::S3Object.store(#{target_dir + file_name}, open(#{file}), #{bucket}, :access => :public_read)"
AWS::S3::S3Object.store(target_dir + file_name, open(file), bucket, :access => :public_read)
end
end
end
end
end
|
require 'pry'
module Samin
## Money class that implements required features for currency
## conversion
class Money
attr_writer :currency_ref_name, :currency_ref_conversion_rates
attr_reader :currency, :amount
def initialize(amount = 0, currency = 'CHF')
@amount = amount
@currency = currency
end
def inspect
"#{@amount} #{@currency}"
end
def convert_to(currency)
rate = @@currency_ref_conversion_rates[currency]
return nil if rate.nil?
Money.new((@amount*rate).to_f.round(2),currency)
end
def +(other)
sum = -1
if other.currency.eql? @currency
sum = @amount+other.amount
else
other_converted = other.convert_from(other.currency)
sum = other_converted.amount + @amount
end
Money.new(sum,@@currency_ref_name)
end
def -(other)
sub = -1
if other.currency.eql? @currency
sub = @amount-other.amount
else
other_converted = other.convert_from(other.currency)
sub = @amount - other_converted.amount
end
Money.new(sub,@@currency_ref_name)
end
def /(dividend)
Money.new((@amount/dividend).to_f,@currency)
end
def self.conversion_rates(currency_name = 'EUR', rates = {})
unless currency_name.nil? || rates.nil?
@@currency_ref_name ||= currency_name
@@currency_ref_conversion_rates ||= rates
return true
end
false
end
def convert_from(currency)
rate = @@currency_ref_conversion_rates[currency]
Money.new((@amount/rate).to_f.round(2),currency)
end
end
end
Implements #* operator
require 'pry'
module Samin
## Money class that implements required features for currency
## conversion
class Money
attr_writer :currency_ref_name, :currency_ref_conversion_rates
attr_reader :currency, :amount
def initialize(amount = 0, currency = 'CHF')
@amount = amount
@currency = currency
end
def inspect
"#{@amount} #{@currency}"
end
def convert_to(currency)
rate = @@currency_ref_conversion_rates[currency]
return nil if rate.nil?
Money.new((@amount*rate).to_f.round(2),currency)
end
def +(other)
sum = -1
if other.currency.eql? @currency
sum = @amount+other.amount
else
other_converted = other.convert_from(other.currency)
sum = other_converted.amount + @amount
end
Money.new(sum,@@currency_ref_name)
end
def -(other)
sub = -1
if other.currency.eql? @currency
sub = @amount-other.amount
else
other_converted = other.convert_from(other.currency)
sub = @amount - other_converted.amount
end
Money.new(sub,@@currency_ref_name)
end
def /(dividend)
Money.new((@amount/dividend).to_f,@currency)
end
def *(multiplicand)
Money.new((@amount*multiplicand).to_f,@currency)
end
def self.conversion_rates(currency_name = 'EUR', rates = {})
unless currency_name.nil? || rates.nil?
@@currency_ref_name ||= currency_name
@@currency_ref_conversion_rates ||= rates
return true
end
false
end
def convert_from(currency)
rate = @@currency_ref_conversion_rates[currency]
Money.new((@amount/rate).to_f.round(2),currency)
end
end
end
|
require 'strscan'
require 'sass/tree/node'
require 'sass/tree/rule_node'
require 'sass/tree/comment_node'
require 'sass/tree/attr_node'
require 'sass/tree/directive_node'
require 'sass/tree/variable_node'
require 'sass/tree/mixin_def_node'
require 'sass/tree/mixin_node'
require 'sass/tree/if_node'
require 'sass/tree/while_node'
require 'sass/tree/for_node'
require 'sass/tree/debug_node'
require 'sass/tree/file_node'
require 'sass/environment'
require 'sass/script'
require 'sass/error'
require 'haml/shared'
module Sass
# :stopdoc:
Mixin = Struct.new(:name, :args, :environment, :tree)
# :startdoc:
# This is the class where all the parsing and processing of the Sass
# template is done. It can be directly used by the user by creating a
# new instance and calling <tt>render</tt> to render the template. For example:
#
# template = File.load('stylesheets/sassy.sass')
# sass_engine = Sass::Engine.new(template)
# output = sass_engine.render
# puts output
class Engine
include Haml::Util
Line = Struct.new(:text, :tabs, :index, :offset, :filename, :children)
# The character that begins a CSS attribute.
ATTRIBUTE_CHAR = ?:
# The character that designates that
# an attribute should be assigned to a SassScript expression.
SCRIPT_CHAR = ?=
# The character that designates the beginning of a comment,
# either Sass or CSS.
COMMENT_CHAR = ?/
# The character that follows the general COMMENT_CHAR and designates a Sass comment,
# which is not output as a CSS comment.
SASS_COMMENT_CHAR = ?/
# The character that follows the general COMMENT_CHAR and designates a CSS comment,
# which is embedded in the CSS document.
CSS_COMMENT_CHAR = ?*
# The character used to denote a compiler directive.
DIRECTIVE_CHAR = ?@
# Designates a non-parsed rule.
ESCAPE_CHAR = ?\\
# Designates block as mixin definition rather than CSS rules to output
MIXIN_DEFINITION_CHAR = ?=
# Includes named mixin declared using MIXIN_DEFINITION_CHAR
MIXIN_INCLUDE_CHAR = ?+
# The regex that matches and extracts data from
# attributes of the form <tt>:name attr</tt>.
ATTRIBUTE = /^:([^\s=:"]+)\s*(=?)(?:\s+|$)(.*)/
# The regex that matches attributes of the form <tt>name: attr</tt>.
ATTRIBUTE_ALTERNATE_MATCHER = /^[^\s:"]+\s*[=:](\s|$)/
# The regex that matches and extracts data from
# attributes of the form <tt>name: attr</tt>.
ATTRIBUTE_ALTERNATE = /^([^\s=:"]+)(\s*=|:)(?:\s+|$)(.*)/
# Creates a new instace of Sass::Engine that will compile the given
# template string when <tt>render</tt> is called.
# See README.rdoc for available options.
#
#--
#
# TODO: Add current options to REFRENCE. Remember :filename!
#
# When adding options, remember to add information about them
# to README.rdoc!
#++
#
def initialize(template, options={})
@options = {
:style => :nested,
:load_paths => ['.']
}.merge! options
@template = template
@environment = Environment.new(nil, @options)
@environment.set_var("important", Script::String.new("!important"))
end
# Processes the template and returns the result as a string.
def render
begin
render_to_tree.perform(@environment).to_s
rescue SyntaxError => err
err.sass_line = @line unless err.sass_line
unless err.sass_filename
err.add_backtrace_entry(@options[:filename])
end
raise err
end
end
alias_method :to_css, :render
protected
def environment
@environment
end
def render_to_tree
root = Tree::Node.new(@options)
append_children(root, tree(tabulate(@template)).first, true)
root
end
private
def tabulate(string)
tab_str = nil
first = true
enum_with_index(string.gsub(/\r|\n|\r\n|\r\n/, "\n").scan(/^.*?$/)).map do |line, index|
index += (@options[:line] || 1)
next if line.strip.empty?
line_tab_str = line[/^\s*/]
unless line_tab_str.empty?
tab_str ||= line_tab_str
raise SyntaxError.new("Indenting at the beginning of the document is illegal.", index) if first
if tab_str.include?(?\s) && tab_str.include?(?\t)
raise SyntaxError.new("Indentation can't use both tabs and spaces.", index)
end
end
first &&= !tab_str.nil?
next Line.new(line.strip, 0, index, 0, @options[:filename], []) if tab_str.nil?
line_tabs = line_tab_str.scan(tab_str).size
raise SyntaxError.new(<<END.strip.gsub("\n", ' '), index) if tab_str * line_tabs != line_tab_str
Inconsistent indentation: #{Haml::Shared.human_indentation line_tab_str, true} used for indentation,
but the rest of the document was indented using #{Haml::Shared.human_indentation tab_str}.
END
Line.new(line.strip, line_tabs, index, tab_str.size, @options[:filename], [])
end.compact
end
def tree(arr, i = 0)
return [], i if arr[i].nil?
base = arr[i].tabs
nodes = []
while (line = arr[i]) && line.tabs >= base
if line.tabs > base
if line.tabs > base + 1
raise SyntaxError.new("The line was indented #{line.tabs - base} levels deeper than the previous line.", line.index)
end
nodes.last.children, i = tree(arr, i)
else
nodes << line
i += 1
end
end
return nodes, i
end
def build_tree(parent, line, root = false)
@line = line.index
node = parse_line(parent, line, root)
# Node is a symbol if it's non-outputting, like a variable assignment,
# or an array if it's a group of nodes to add
return node unless node.is_a? Tree::Node
node.line = line.index
node.filename = line.filename
if node.is_a?(Tree::CommentNode)
node.lines = line.children
else
append_children(node, line.children, false)
end
return node
end
def append_children(parent, children, root)
continued_rule = nil
children.each do |line|
child = build_tree(parent, line, root)
if child.is_a?(Tree::RuleNode) && child.continued?
raise SyntaxError.new("Rules can't end in commas.", child.line) unless child.children.empty?
if continued_rule
continued_rule.add_rules child
else
continued_rule = child
end
next
end
if continued_rule
raise SyntaxError.new("Rules can't end in commas.", continued_rule.line) unless child.is_a?(Tree::RuleNode)
continued_rule.add_rules child
continued_rule.children = child.children
continued_rule, child = nil, continued_rule
end
validate_and_append_child(parent, child, line, root)
end
raise SyntaxError.new("Rules can't end in commas.", continued_rule.line) if continued_rule
parent
end
def validate_and_append_child(parent, child, line, root)
unless root
case child
when Tree::MixinDefNode
raise SyntaxError.new("Mixins may only be defined at the root of a document.", line.index)
when Tree::DirectiveNode, Tree::FileNode
raise SyntaxError.new("Import directives may only be used at the root of a document.", line.index)
end
end
case child
when Array
child.each {|c| validate_and_append_child(parent, c, line, root)}
when Tree::Node
parent << child
end
end
def parse_line(parent, line, root)
case line.text[0]
when ATTRIBUTE_CHAR
if line.text[1] != ATTRIBUTE_CHAR
parse_attribute(line, ATTRIBUTE)
else
# Support CSS3-style pseudo-elements,
# which begin with ::
Tree::RuleNode.new(line.text, @options)
end
when Script::VARIABLE_CHAR
parse_variable(line)
when COMMENT_CHAR
parse_comment(line.text)
when DIRECTIVE_CHAR
parse_directive(parent, line, root)
when ESCAPE_CHAR
Tree::RuleNode.new(line.text[1..-1], @options)
when MIXIN_DEFINITION_CHAR
parse_mixin_definition(line)
when MIXIN_INCLUDE_CHAR
if line.text[1].nil?
Tree::RuleNode.new(line.text, @options)
else
parse_mixin_include(line, root)
end
else
if line.text =~ ATTRIBUTE_ALTERNATE_MATCHER
parse_attribute(line, ATTRIBUTE_ALTERNATE)
else
Tree::RuleNode.new(line.text, @options)
end
end
end
def parse_attribute(line, attribute_regx)
if @options[:attribute_syntax] == :normal &&
attribute_regx == ATTRIBUTE_ALTERNATE
raise SyntaxError.new("Illegal attribute syntax: can't use alternate syntax when :attribute_syntax => :normal is set.")
elsif @options[:attribute_syntax] == :alternate &&
attribute_regx == ATTRIBUTE
raise SyntaxError.new("Illegal attribute syntax: can't use normal syntax when :attribute_syntax => :alternate is set.")
end
name, eq, value = line.text.scan(attribute_regx)[0]
if name.nil? || value.nil?
raise SyntaxError.new("Invalid attribute: \"#{line.text}\".", @line)
end
expr = if (eq.strip[0] == SCRIPT_CHAR)
parse_script(value, :offset => line.offset + line.text.index(value))
else
value
end
Tree::AttrNode.new(name, expr, @options)
end
def parse_variable(line)
name, op, value = line.text.scan(Script::MATCH)[0]
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.", @line + 1) unless line.children.empty?
raise SyntaxError.new("Invalid variable: \"#{line.text}\".", @line) unless name && value
Tree::VariableNode.new(name, parse_script(value, :offset => line.offset + line.text.index(value)), op == '||=', @options)
end
def parse_comment(line)
if line[1] == CSS_COMMENT_CHAR || line[1] == SASS_COMMENT_CHAR
Tree::CommentNode.new(line, @options.merge(:silent => (line[1] == SASS_COMMENT_CHAR)))
else
Tree::RuleNode.new(line, @options)
end
end
def parse_directive(parent, line, root)
directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
offset = directive.size + whitespace.size + 1 if whitespace
# If value begins with url( or ",
# it's a CSS @import rule and we don't want to touch it.
if directive == "import" && value !~ /^(url\(|")/
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.", @line + 1) unless line.children.empty?
import(value)
elsif directive == "for"
parse_for(line, root, value)
elsif directive == "else"
parse_else(parent, line, value)
elsif directive == "while"
raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
Tree::WhileNode.new(parse_script(value, :offset => offset), @options)
elsif directive == "if"
raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
Tree::IfNode.new(parse_script(value, :offset => offset), @options)
elsif directive == "debug"
raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.", @line + 1) unless line.children.empty?
offset = line.offset + line.text.index(value).to_i
Tree::DebugNode.new(parse_script(value, :offset => offset), @options)
else
Tree::DirectiveNode.new(line.text, @options)
end
end
def parse_for(line, root, text)
var, from_expr, to_name, to_expr = text.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first
if var.nil? # scan failed, try to figure out why for error message
if text !~ /^[^\s]+/
expected = "variable name"
elsif text !~ /^[^\s]+\s+from\s+.+/
expected = "'from <expr>'"
else
expected = "'to <expr>' or 'through <expr>'"
end
raise SyntaxError.new("Invalid for directive '@for #{text}': expected #{expected}.", @line)
end
raise SyntaxError.new("Invalid variable \"#{var}\".", @line) unless var =~ Script::VALIDATE
parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
Tree::ForNode.new(var[1..-1], parsed_from, parsed_to, to_name == 'to', @options)
end
def parse_else(parent, line, text)
previous = parent.last
raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)
if text
if text !~ /^if\s+(.+)/
raise SyntaxError.new("Invalid else directive '@else #{text}': expected 'if <expr>'.", @line)
end
expr = parse_script($1, :offset => line.offset + line.text.index($1))
end
node = Tree::IfNode.new(expr, @options)
append_children(node, line.children, false)
previous.add_else node
nil
end
# parses out the arguments between the commas and cleans up the mixin arguments
# returns nil if it fails to parse, otherwise an array.
def parse_mixin_arguments(arg_string)
arg_string = arg_string.strip
return [] if arg_string.empty?
return nil unless (arg_string[0] == ?( && arg_string[-1] == ?))
arg_string = arg_string[1...-1]
arg_string.split(",", -1).map {|a| a.strip}
end
def parse_mixin_definition(line)
name, arg_string = line.text.scan(/^=\s*([^(]+)(.*)$/).first
args = parse_mixin_arguments(arg_string)
raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".", @line) if name.nil? || args.nil?
default_arg_found = false
required_arg_count = 0
args.map! do |arg|
raise SyntaxError.new("Mixin arguments can't be empty.", @line) if arg.empty? || arg == "!"
unless arg[0] == Script::VARIABLE_CHAR
raise SyntaxError.new("Mixin argument \"#{arg}\" must begin with an exclamation point (!).", @line)
end
arg, default = arg.split(/\s*=\s*/, 2)
required_arg_count += 1 unless default
default_arg_found ||= default
raise SyntaxError.new("Invalid variable \"#{arg}\".", @line) unless arg =~ Script::VALIDATE
raise SyntaxError.new("Required arguments must not follow optional arguments \"#{arg}\".", @line) if default_arg_found && !default
default = parse_script(default, :offset => line.offset + line.text.index(default)) if default
[arg[1..-1], default]
end
Tree::MixinDefNode.new(name, args, @options)
end
def parse_mixin_include(line, root)
name, arg_string = line.text.scan(/^\+\s*([^(]+)(.*)$/).first
args = parse_mixin_arguments(arg_string)
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath mixin directives.", @line + 1) unless line.children.empty?
raise SyntaxError.new("Invalid mixin include \"#{line.text}\".", @line) if name.nil? || args.nil?
args.each {|a| raise SyntaxError.new("Mixin arguments can't be empty.", @line) if a.empty?}
Tree::MixinNode.new(name, args.map {|s| parse_script(s, :offset => line.offset + line.text.index(s))}, @options)
end
def parse_script(script, options = {})
line = options[:line] || @line
offset = options[:offset] || 0
Script.parse(script, line, offset, @options[:filename])
end
def import_paths
paths = (@options[:load_paths] || []).dup
paths.unshift(File.dirname(@options[:filename])) if @options[:filename]
paths
end
def import(files)
files.split(/,\s*/).map do |filename|
engine = nil
begin
filename = self.class.find_file_to_import(filename, import_paths)
rescue Exception => e
raise SyntaxError.new(e.message, @line)
end
next Tree::DirectiveNode.new("@import url(#{filename})", @options) if filename =~ /\.css$/
File.open(filename) do |file|
new_options = @options.dup
new_options[:filename] = filename
engine = Sass::Engine.new(file.read, new_options)
end
begin
root = engine.render_to_tree
rescue Sass::SyntaxError => err
err.add_backtrace_entry(filename)
raise err
end
Tree::FileNode.new(filename, root.children, @options)
end.flatten
end
def self.find_file_to_import(filename, load_paths)
was_sass = false
original_filename = filename
if filename[-5..-1] == ".sass"
filename = filename[0...-5]
was_sass = true
elsif filename[-4..-1] == ".css"
return filename
end
new_filename = find_full_path("#{filename}.sass", load_paths)
return new_filename if new_filename
return filename + '.css' unless was_sass
raise SyntaxError.new("File to import not found or unreadable: #{original_filename}.", @line)
end
def self.find_full_path(filename, load_paths)
segments = filename.split(File::SEPARATOR)
segments.push "_#{segments.pop}"
partial_name = segments.join(File::SEPARATOR)
load_paths.each do |path|
[partial_name, filename].each do |name|
full_path = File.join(path, name)
if File.readable?(full_path)
return full_path
end
end
end
nil
end
end
end
[Sass] Get rid of the unused Engine#environment.
require 'strscan'
require 'sass/tree/node'
require 'sass/tree/rule_node'
require 'sass/tree/comment_node'
require 'sass/tree/attr_node'
require 'sass/tree/directive_node'
require 'sass/tree/variable_node'
require 'sass/tree/mixin_def_node'
require 'sass/tree/mixin_node'
require 'sass/tree/if_node'
require 'sass/tree/while_node'
require 'sass/tree/for_node'
require 'sass/tree/debug_node'
require 'sass/tree/file_node'
require 'sass/environment'
require 'sass/script'
require 'sass/error'
require 'haml/shared'
module Sass
# :stopdoc:
Mixin = Struct.new(:name, :args, :environment, :tree)
# :startdoc:
# This is the class where all the parsing and processing of the Sass
# template is done. It can be directly used by the user by creating a
# new instance and calling <tt>render</tt> to render the template. For example:
#
# template = File.load('stylesheets/sassy.sass')
# sass_engine = Sass::Engine.new(template)
# output = sass_engine.render
# puts output
class Engine
include Haml::Util
Line = Struct.new(:text, :tabs, :index, :offset, :filename, :children)
# The character that begins a CSS attribute.
ATTRIBUTE_CHAR = ?:
# The character that designates that
# an attribute should be assigned to a SassScript expression.
SCRIPT_CHAR = ?=
# The character that designates the beginning of a comment,
# either Sass or CSS.
COMMENT_CHAR = ?/
# The character that follows the general COMMENT_CHAR and designates a Sass comment,
# which is not output as a CSS comment.
SASS_COMMENT_CHAR = ?/
# The character that follows the general COMMENT_CHAR and designates a CSS comment,
# which is embedded in the CSS document.
CSS_COMMENT_CHAR = ?*
# The character used to denote a compiler directive.
DIRECTIVE_CHAR = ?@
# Designates a non-parsed rule.
ESCAPE_CHAR = ?\\
# Designates block as mixin definition rather than CSS rules to output
MIXIN_DEFINITION_CHAR = ?=
# Includes named mixin declared using MIXIN_DEFINITION_CHAR
MIXIN_INCLUDE_CHAR = ?+
# The regex that matches and extracts data from
# attributes of the form <tt>:name attr</tt>.
ATTRIBUTE = /^:([^\s=:"]+)\s*(=?)(?:\s+|$)(.*)/
# The regex that matches attributes of the form <tt>name: attr</tt>.
ATTRIBUTE_ALTERNATE_MATCHER = /^[^\s:"]+\s*[=:](\s|$)/
# The regex that matches and extracts data from
# attributes of the form <tt>name: attr</tt>.
ATTRIBUTE_ALTERNATE = /^([^\s=:"]+)(\s*=|:)(?:\s+|$)(.*)/
# Creates a new instace of Sass::Engine that will compile the given
# template string when <tt>render</tt> is called.
# See README.rdoc for available options.
#
#--
#
# TODO: Add current options to REFRENCE. Remember :filename!
#
# When adding options, remember to add information about them
# to README.rdoc!
#++
#
def initialize(template, options={})
@options = {
:style => :nested,
:load_paths => ['.']
}.merge! options
@template = template
@environment = Environment.new(nil, @options)
@environment.set_var("important", Script::String.new("!important"))
end
# Processes the template and returns the result as a string.
def render
begin
render_to_tree.perform(@environment).to_s
rescue SyntaxError => err
err.sass_line = @line unless err.sass_line
unless err.sass_filename
err.add_backtrace_entry(@options[:filename])
end
raise err
end
end
alias_method :to_css, :render
protected
def render_to_tree
root = Tree::Node.new(@options)
append_children(root, tree(tabulate(@template)).first, true)
root
end
private
def tabulate(string)
tab_str = nil
first = true
enum_with_index(string.gsub(/\r|\n|\r\n|\r\n/, "\n").scan(/^.*?$/)).map do |line, index|
index += (@options[:line] || 1)
next if line.strip.empty?
line_tab_str = line[/^\s*/]
unless line_tab_str.empty?
tab_str ||= line_tab_str
raise SyntaxError.new("Indenting at the beginning of the document is illegal.", index) if first
if tab_str.include?(?\s) && tab_str.include?(?\t)
raise SyntaxError.new("Indentation can't use both tabs and spaces.", index)
end
end
first &&= !tab_str.nil?
next Line.new(line.strip, 0, index, 0, @options[:filename], []) if tab_str.nil?
line_tabs = line_tab_str.scan(tab_str).size
raise SyntaxError.new(<<END.strip.gsub("\n", ' '), index) if tab_str * line_tabs != line_tab_str
Inconsistent indentation: #{Haml::Shared.human_indentation line_tab_str, true} used for indentation,
but the rest of the document was indented using #{Haml::Shared.human_indentation tab_str}.
END
Line.new(line.strip, line_tabs, index, tab_str.size, @options[:filename], [])
end.compact
end
def tree(arr, i = 0)
return [], i if arr[i].nil?
base = arr[i].tabs
nodes = []
while (line = arr[i]) && line.tabs >= base
if line.tabs > base
if line.tabs > base + 1
raise SyntaxError.new("The line was indented #{line.tabs - base} levels deeper than the previous line.", line.index)
end
nodes.last.children, i = tree(arr, i)
else
nodes << line
i += 1
end
end
return nodes, i
end
def build_tree(parent, line, root = false)
@line = line.index
node = parse_line(parent, line, root)
# Node is a symbol if it's non-outputting, like a variable assignment,
# or an array if it's a group of nodes to add
return node unless node.is_a? Tree::Node
node.line = line.index
node.filename = line.filename
if node.is_a?(Tree::CommentNode)
node.lines = line.children
else
append_children(node, line.children, false)
end
return node
end
def append_children(parent, children, root)
continued_rule = nil
children.each do |line|
child = build_tree(parent, line, root)
if child.is_a?(Tree::RuleNode) && child.continued?
raise SyntaxError.new("Rules can't end in commas.", child.line) unless child.children.empty?
if continued_rule
continued_rule.add_rules child
else
continued_rule = child
end
next
end
if continued_rule
raise SyntaxError.new("Rules can't end in commas.", continued_rule.line) unless child.is_a?(Tree::RuleNode)
continued_rule.add_rules child
continued_rule.children = child.children
continued_rule, child = nil, continued_rule
end
validate_and_append_child(parent, child, line, root)
end
raise SyntaxError.new("Rules can't end in commas.", continued_rule.line) if continued_rule
parent
end
def validate_and_append_child(parent, child, line, root)
unless root
case child
when Tree::MixinDefNode
raise SyntaxError.new("Mixins may only be defined at the root of a document.", line.index)
when Tree::DirectiveNode, Tree::FileNode
raise SyntaxError.new("Import directives may only be used at the root of a document.", line.index)
end
end
case child
when Array
child.each {|c| validate_and_append_child(parent, c, line, root)}
when Tree::Node
parent << child
end
end
def parse_line(parent, line, root)
case line.text[0]
when ATTRIBUTE_CHAR
if line.text[1] != ATTRIBUTE_CHAR
parse_attribute(line, ATTRIBUTE)
else
# Support CSS3-style pseudo-elements,
# which begin with ::
Tree::RuleNode.new(line.text, @options)
end
when Script::VARIABLE_CHAR
parse_variable(line)
when COMMENT_CHAR
parse_comment(line.text)
when DIRECTIVE_CHAR
parse_directive(parent, line, root)
when ESCAPE_CHAR
Tree::RuleNode.new(line.text[1..-1], @options)
when MIXIN_DEFINITION_CHAR
parse_mixin_definition(line)
when MIXIN_INCLUDE_CHAR
if line.text[1].nil?
Tree::RuleNode.new(line.text, @options)
else
parse_mixin_include(line, root)
end
else
if line.text =~ ATTRIBUTE_ALTERNATE_MATCHER
parse_attribute(line, ATTRIBUTE_ALTERNATE)
else
Tree::RuleNode.new(line.text, @options)
end
end
end
def parse_attribute(line, attribute_regx)
if @options[:attribute_syntax] == :normal &&
attribute_regx == ATTRIBUTE_ALTERNATE
raise SyntaxError.new("Illegal attribute syntax: can't use alternate syntax when :attribute_syntax => :normal is set.")
elsif @options[:attribute_syntax] == :alternate &&
attribute_regx == ATTRIBUTE
raise SyntaxError.new("Illegal attribute syntax: can't use normal syntax when :attribute_syntax => :alternate is set.")
end
name, eq, value = line.text.scan(attribute_regx)[0]
if name.nil? || value.nil?
raise SyntaxError.new("Invalid attribute: \"#{line.text}\".", @line)
end
expr = if (eq.strip[0] == SCRIPT_CHAR)
parse_script(value, :offset => line.offset + line.text.index(value))
else
value
end
Tree::AttrNode.new(name, expr, @options)
end
def parse_variable(line)
name, op, value = line.text.scan(Script::MATCH)[0]
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath variable declarations.", @line + 1) unless line.children.empty?
raise SyntaxError.new("Invalid variable: \"#{line.text}\".", @line) unless name && value
Tree::VariableNode.new(name, parse_script(value, :offset => line.offset + line.text.index(value)), op == '||=', @options)
end
def parse_comment(line)
if line[1] == CSS_COMMENT_CHAR || line[1] == SASS_COMMENT_CHAR
Tree::CommentNode.new(line, @options.merge(:silent => (line[1] == SASS_COMMENT_CHAR)))
else
Tree::RuleNode.new(line, @options)
end
end
def parse_directive(parent, line, root)
directive, whitespace, value = line.text[1..-1].split(/(\s+)/, 2)
offset = directive.size + whitespace.size + 1 if whitespace
# If value begins with url( or ",
# it's a CSS @import rule and we don't want to touch it.
if directive == "import" && value !~ /^(url\(|")/
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath import directives.", @line + 1) unless line.children.empty?
import(value)
elsif directive == "for"
parse_for(line, root, value)
elsif directive == "else"
parse_else(parent, line, value)
elsif directive == "while"
raise SyntaxError.new("Invalid while directive '@while': expected expression.") unless value
Tree::WhileNode.new(parse_script(value, :offset => offset), @options)
elsif directive == "if"
raise SyntaxError.new("Invalid if directive '@if': expected expression.") unless value
Tree::IfNode.new(parse_script(value, :offset => offset), @options)
elsif directive == "debug"
raise SyntaxError.new("Invalid debug directive '@debug': expected expression.") unless value
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath debug directives.", @line + 1) unless line.children.empty?
offset = line.offset + line.text.index(value).to_i
Tree::DebugNode.new(parse_script(value, :offset => offset), @options)
else
Tree::DirectiveNode.new(line.text, @options)
end
end
def parse_for(line, root, text)
var, from_expr, to_name, to_expr = text.scan(/^([^\s]+)\s+from\s+(.+)\s+(to|through)\s+(.+)$/).first
if var.nil? # scan failed, try to figure out why for error message
if text !~ /^[^\s]+/
expected = "variable name"
elsif text !~ /^[^\s]+\s+from\s+.+/
expected = "'from <expr>'"
else
expected = "'to <expr>' or 'through <expr>'"
end
raise SyntaxError.new("Invalid for directive '@for #{text}': expected #{expected}.", @line)
end
raise SyntaxError.new("Invalid variable \"#{var}\".", @line) unless var =~ Script::VALIDATE
parsed_from = parse_script(from_expr, :offset => line.offset + line.text.index(from_expr))
parsed_to = parse_script(to_expr, :offset => line.offset + line.text.index(to_expr))
Tree::ForNode.new(var[1..-1], parsed_from, parsed_to, to_name == 'to', @options)
end
def parse_else(parent, line, text)
previous = parent.last
raise SyntaxError.new("@else must come after @if.") unless previous.is_a?(Tree::IfNode)
if text
if text !~ /^if\s+(.+)/
raise SyntaxError.new("Invalid else directive '@else #{text}': expected 'if <expr>'.", @line)
end
expr = parse_script($1, :offset => line.offset + line.text.index($1))
end
node = Tree::IfNode.new(expr, @options)
append_children(node, line.children, false)
previous.add_else node
nil
end
# parses out the arguments between the commas and cleans up the mixin arguments
# returns nil if it fails to parse, otherwise an array.
def parse_mixin_arguments(arg_string)
arg_string = arg_string.strip
return [] if arg_string.empty?
return nil unless (arg_string[0] == ?( && arg_string[-1] == ?))
arg_string = arg_string[1...-1]
arg_string.split(",", -1).map {|a| a.strip}
end
def parse_mixin_definition(line)
name, arg_string = line.text.scan(/^=\s*([^(]+)(.*)$/).first
args = parse_mixin_arguments(arg_string)
raise SyntaxError.new("Invalid mixin \"#{line.text[1..-1]}\".", @line) if name.nil? || args.nil?
default_arg_found = false
required_arg_count = 0
args.map! do |arg|
raise SyntaxError.new("Mixin arguments can't be empty.", @line) if arg.empty? || arg == "!"
unless arg[0] == Script::VARIABLE_CHAR
raise SyntaxError.new("Mixin argument \"#{arg}\" must begin with an exclamation point (!).", @line)
end
arg, default = arg.split(/\s*=\s*/, 2)
required_arg_count += 1 unless default
default_arg_found ||= default
raise SyntaxError.new("Invalid variable \"#{arg}\".", @line) unless arg =~ Script::VALIDATE
raise SyntaxError.new("Required arguments must not follow optional arguments \"#{arg}\".", @line) if default_arg_found && !default
default = parse_script(default, :offset => line.offset + line.text.index(default)) if default
[arg[1..-1], default]
end
Tree::MixinDefNode.new(name, args, @options)
end
def parse_mixin_include(line, root)
name, arg_string = line.text.scan(/^\+\s*([^(]+)(.*)$/).first
args = parse_mixin_arguments(arg_string)
raise SyntaxError.new("Illegal nesting: Nothing may be nested beneath mixin directives.", @line + 1) unless line.children.empty?
raise SyntaxError.new("Invalid mixin include \"#{line.text}\".", @line) if name.nil? || args.nil?
args.each {|a| raise SyntaxError.new("Mixin arguments can't be empty.", @line) if a.empty?}
Tree::MixinNode.new(name, args.map {|s| parse_script(s, :offset => line.offset + line.text.index(s))}, @options)
end
def parse_script(script, options = {})
line = options[:line] || @line
offset = options[:offset] || 0
Script.parse(script, line, offset, @options[:filename])
end
def import_paths
paths = (@options[:load_paths] || []).dup
paths.unshift(File.dirname(@options[:filename])) if @options[:filename]
paths
end
def import(files)
files.split(/,\s*/).map do |filename|
engine = nil
begin
filename = self.class.find_file_to_import(filename, import_paths)
rescue Exception => e
raise SyntaxError.new(e.message, @line)
end
next Tree::DirectiveNode.new("@import url(#{filename})", @options) if filename =~ /\.css$/
File.open(filename) do |file|
new_options = @options.dup
new_options[:filename] = filename
engine = Sass::Engine.new(file.read, new_options)
end
begin
root = engine.render_to_tree
rescue Sass::SyntaxError => err
err.add_backtrace_entry(filename)
raise err
end
Tree::FileNode.new(filename, root.children, @options)
end.flatten
end
def self.find_file_to_import(filename, load_paths)
was_sass = false
original_filename = filename
if filename[-5..-1] == ".sass"
filename = filename[0...-5]
was_sass = true
elsif filename[-4..-1] == ".css"
return filename
end
new_filename = find_full_path("#{filename}.sass", load_paths)
return new_filename if new_filename
return filename + '.css' unless was_sass
raise SyntaxError.new("File to import not found or unreadable: #{original_filename}.", @line)
end
def self.find_full_path(filename, load_paths)
segments = filename.split(File::SEPARATOR)
segments.push "_#{segments.pop}"
partial_name = segments.join(File::SEPARATOR)
load_paths.each do |path|
[partial_name, filename].each do |name|
full_path = File.join(path, name)
if File.readable?(full_path)
return full_path
end
end
end
nil
end
end
end
|
require 'shin/ast'
require 'shin/mutator'
require 'shin/utils'
module Shin
class Parser
include Shin::Utils::LineColumn
include Shin::Utils::Snippet
include Shin::Utils::Mangler
include Shin::AST
class Error < StandardError; end
class EOF < Error; end
attr_reader :input
WS_RE = /[ \t\n,]/
OPEN_RE = /[(\[{]/
NUMBER_RE = /[0-9]+/
OPEN_MAP = {
'(' => List,
'[' => Vector,
'{' => Map,
}
CLOS_RE = /[)\]}]/
CLOS_REV_MAP = {
List => ')',
Vector => ']',
Map => '}',
Set => '}',
Closure => ')',
}
def self.parse(source)
# parse is a no-op if source is not a String.
# it might be a piece of already-parsed AST.
return source unless ::String === source
Shin::Parser.new(source).parse
end
def self.parse_file(path)
Shin::Parser.new(File.read(path), :file => path).parse
end
def initialize(input, options = {})
@options = options.dup
case
when input.respond_to?(:each_char)
@input = input.freeze
when input.respond_to?(:to_str)
require 'stringio' unless defined?(StringIO)
@input = input.to_str.freeze
else
raise ArgumentError, "expected an IO or String input stream, but got #{input.inspect}"
end
end
def parse
nodes = []
heap = [nodes]
state = [:expr]
@pos = 0
@input.each_char do |c|
if file.include?('test')
puts "#{c} at #{@pos}\t<- #{state}"
puts " \t<- [#{heap.join(", ")}]"
puts
end
case state.last
when :expr, :expr_one
state.pop if state.last == :expr_one
case c
when WS_RE
# muffin
when '@'
heap << Deref << token << []
state << :close_one << :expr_one
when '`'
heap << SyntaxQuote << token << []
state << :close_one << :expr_one
when "'"
heap << Quote << token << []
state << :close_one << :expr_one
when "~"
heap << Unquote << token << []
state << :close_one << :expr_one
when "^"
heap << MetaData << token << []
state << :close_one << :expr_one
when ';'
state << :comment
when '#'
state << :sharp
when ':'
state << :keyword
heap << token << ""
when '"'
state << :string
heap << token << ""
when OPEN_RE
heap << OPEN_MAP[c] << token << []
state << :expr
when CLOS_RE
state.pop # expr
els = heap.pop
tok = heap.pop
type = heap.pop
ex = CLOS_REV_MAP[type]
unless c === ex
ser!("Wrong closing delimiter. Expected '#{ex}' got '#{c}'")
end
heap.last << type.new(tok, els)
when SYM_START_REGEXP
state << :symbol
heap << token << ""
redo
when NUMBER_RE
state << :number
heap << token << ""
redo
else
ser!("Unexpected char: #{c}")
end
when :close_one
inner = heap.pop
tok = heap.pop
type = heap.pop
raise "Internal error" if inner.length != 1
heap.last << type.new(tok, inner[0])
state.pop
redo
when :comment
state.pop if c == "\n"
when :sharp
state.pop
case c
when '('
heap << Closure << token << [] << List << token << []
state << :close_one << :expr
when '{'
heap << Set << token << []
state << :expr
when '"'
heap << token << ""
state << :regexp
else
ser!("Unexpected char after #: #{c}")
end
when :string, :regexp
case c
when '"'
value = heap.pop
tok = heap.pop
case state.last
when :string
heap.last << String.new(tok, value)
when :regexp
heap.last << RegExp.new(tok, value)
else
raise "Internal error"
end
state.pop
else
heap.last << c
end
when :number
case c
when NUMBER_RE
heap.last << c
else
value = heap.pop
tok = heap.pop
heap.last << Number.new(tok, value.to_f)
state.pop
redo
end
when :symbol
case c
when SYM_INNER_REGEXP
heap.last << c
else
value = heap.pop
tok = heap.pop
heap.last << Symbol.new(tok, value)
state.pop
redo
end
when :keyword
case c
when SYM_INNER_REGEXP
heap.last << c
else
value = heap.pop
tok = heap.pop
heap.last << Keyword.new(tok, value)
state.pop
redo
end
else
raise "Inconsistent state: #{state.last}"
end # case state
@pos += 1
end # each_char
case state.last
when :number
value = heap.pop
tok = heap.pop
heap.last << Number.new(tok, value.to_f)
when :keyword
value = heap.pop
tok = heap.pop
heap.last << Keyword.new(tok, value)
when :symbol
value = heap.pop
tok = heap.pop
heap.last << Symbol.new(tok, value)
end
if heap.length > 1
heap.reverse_each do |type|
if Class === type
ser!("Unclosed #{type.name.split('::').last}")
break
end
end
end
nodes.map! do |node|
post_parse(node)
end
return nodes
end
def token
Token.new(file, @pos)
end
def file
@options[:file] || "<stdin>"
end
def ser!(msg, token = nil)
start = token ? token.start : @pos
length = token ? token.length : 1
line, column = line_column(@input, start)
snippet = snippet(@input, start, length)
raise Shin::SyntaxError, "#{msg} at #{file}:#{line}:#{column}\n\n#{snippet}\n\n"
end
# Post-parsing logic (auto-gensym, etc.)
def post_parse(node, trail = [])
case node
when Sequence
node = node.clone
_trail = trail + [node]
node.inner.map! do |child|
post_parse(child, _trail)
end
node
when SyntaxQuote
node = node.clone
candidate = LetCandidate.new(node)
_trail = trail + [node, candidate]
inner = post_parse(node.inner, _trail)
if candidate.useful?
candidate.let
else
SyntaxQuote.new(node.token, inner)
end
when Symbol
if node.value.end_with? '#'
t = node.token
candidate = nil
quote = nil
found = false
trail.reverse_each do |parent|
if SyntaxQuote === parent
found = true
quote = parent
break
end
candidate = parent
end
unless found
raise "auto-gensym used outside syntax quote: #{node}"
end
name = node.value[0..-2]
sym = candidate.lazy_make(name)
return Unquote.new(t, Symbol.new(t, sym))
end
node
else
node
end
end
end
class LetCandidate
include Shin::AST
attr_reader :t
attr_reader :let
def initialize(node)
@t = node.token
@let = List.new(t)
@let.inner << Symbol.new(t, "let")
@decls = Vector.new(t)
@let.inner << @decls
@let.inner << node
@cache = {}
end
def lazy_make(name)
sym = @cache[name]
unless sym
sym = "#{name}#{Shin::Mutator.fresh_sym}"
@cache[name] = sym
@decls.inner << Symbol.new(t, sym)
@decls.inner << List.new(t, [Symbol.new(t, "gensym"), String.new(t, name)])
end
sym
end
def to_s
"LetCandidate(#{@let}, cache = #{@cache})"
end
def useful?
!@decls.inner.empty?
end
end
end
Better token info, state-machine-based has feature-parity with old parser
require 'shin/ast'
require 'shin/mutator'
require 'shin/utils'
module Shin
class Parser
include Shin::Utils::LineColumn
include Shin::Utils::Snippet
include Shin::Utils::Mangler
include Shin::AST
class Error < StandardError; end
class EOF < Error; end
attr_reader :input
WS_RE = /[ \t\n,]/
OPEN_RE = /[(\[{]/
NUMBER_RE = /[0-9]+/
OPEN_MAP = {
'(' => List,
'[' => Vector,
'{' => Map,
}
CLOS_RE = /[)\]}]/
CLOS_REV_MAP = {
List => ')',
Vector => ']',
Map => '}',
Set => '}',
Closure => ')',
}
def self.parse(source)
# parse is a no-op if source is not a String.
# it might be a piece of already-parsed AST.
return source unless ::String === source
Shin::Parser.new(source).parse
end
def self.parse_file(path)
Shin::Parser.new(File.read(path), :file => path).parse
end
def initialize(input, options = {})
@options = options.dup
case
when input.respond_to?(:each_char)
@input = input.freeze
when input.respond_to?(:to_str)
require 'stringio' unless defined?(StringIO)
@input = input.to_str.freeze
else
raise ArgumentError, "expected an IO or String input stream, but got #{input.inspect}"
end
end
def parse
nodes = []
heap = [nodes]
state = [:expr]
@pos = 0
@input.each_char do |c|
if file.include?('test')
puts "#{c} at #{@pos}\t<- #{state}"
puts " \t<- [#{heap.join(", ")}]"
puts
end
case state.last
when :expr, :expr_one
state.pop if state.last == :expr_one
case c
when WS_RE
# muffin
when '@'
heap << Deref << token << []
state << :close_one << :expr_one
when '`'
heap << SyntaxQuote << token << []
state << :close_one << :expr_one
when "'"
heap << Quote << token << []
state << :close_one << :expr_one
when "~"
heap << Unquote << token << []
state << :close_one << :expr_one
when "^"
heap << MetaData << token << []
state << :close_one << :expr_one
when ';'
state << :comment
when '#'
state << :sharp
when ':'
state << :keyword
heap << token << ""
when '"'
state << :string
heap << token << ""
when OPEN_RE
heap << OPEN_MAP[c] << token << []
state << :expr
when CLOS_RE
state.pop # expr
els = heap.pop
tok = heap.pop
type = heap.pop
ex = CLOS_REV_MAP[type]
unless c === ex
ser!("Wrong closing delimiter. Expected '#{ex}' got '#{c}'")
end
heap.last << type.new(tok.extend!(@pos), els)
when SYM_START_REGEXP
state << :symbol
heap << token << ""
redo
when NUMBER_RE
state << :number
heap << token << ""
redo
else
ser!("Unexpected char: #{c}")
end
when :close_one
inner = heap.pop
tok = heap.pop
type = heap.pop
raise "Internal error" if inner.length != 1
heap.last << type.new(tok.extend!(@pos), inner[0])
state.pop
redo
when :comment
state.pop if c == "\n"
when :sharp
state.pop
case c
when '('
heap << Closure << token << [] << List << token << []
state << :close_one << :expr
when '{'
heap << Set << token << []
state << :expr
when '"'
heap << token << ""
state << :regexp
else
ser!("Unexpected char after #: #{c}")
end
when :string, :regexp
case c
when '"'
value = heap.pop
tok = heap.pop
case state.last
when :string
heap.last << String.new(tok.extend!(@pos), value)
when :regexp
heap.last << RegExp.new(tok.extend!(@pos), value)
else
raise "Internal error"
end
state.pop
else
heap.last << c
end
when :number
case c
when NUMBER_RE
heap.last << c
else
value = heap.pop
tok = heap.pop
heap.last << Number.new(tok.extend!(@pos), value.to_f)
state.pop
redo
end
when :symbol
case c
when SYM_INNER_REGEXP
heap.last << c
else
value = heap.pop
tok = heap.pop
heap.last << Symbol.new(tok.extend!(@pos), value)
state.pop
redo
end
when :keyword
case c
when SYM_INNER_REGEXP
heap.last << c
else
value = heap.pop
tok = heap.pop
heap.last << Keyword.new(tok.extend!(@pos), value)
state.pop
redo
end
else
raise "Inconsistent state: #{state.last}"
end # case state
@pos += 1
end # each_char
case state.last
when :number
value = heap.pop
tok = heap.pop
heap.last << Number.new(tok.extend!(@pos), value.to_f)
when :keyword
value = heap.pop
tok = heap.pop
heap.last << Keyword.new(tok.extend!(@pos), value)
when :symbol
value = heap.pop
tok = heap.pop
heap.last << Symbol.new(tok.extend!(@pos), value)
end
if heap.length > 1
heap.reverse_each do |type|
if Class === type
ser!("Unclosed #{type.name.split('::').last}")
break
end
end
end
nodes.map! do |node|
post_parse(node)
end
return nodes
end
def token
Token.new(file, @pos)
end
def file
@options[:file] || "<stdin>"
end
def ser!(msg, token = nil)
start = token ? token.start : @pos
length = token ? token.length : 1
line, column = line_column(@input, start)
snippet = snippet(@input, start, length)
raise Shin::SyntaxError, "#{msg} at #{file}:#{line}:#{column}\n\n#{snippet}\n\n"
end
# Post-parsing logic (auto-gensym, etc.)
def post_parse(node, trail = [])
case node
when Sequence
node = node.clone
_trail = trail + [node]
node.inner.map! do |child|
post_parse(child, _trail)
end
node
when SyntaxQuote
node = node.clone
candidate = LetCandidate.new(node)
_trail = trail + [node, candidate]
inner = post_parse(node.inner, _trail)
if candidate.useful?
candidate.let
else
SyntaxQuote.new(node.token, inner)
end
when Symbol
if node.value.end_with? '#'
t = node.token
candidate = nil
quote = nil
found = false
trail.reverse_each do |parent|
if SyntaxQuote === parent
found = true
quote = parent
break
end
candidate = parent
end
unless found
raise "auto-gensym used outside syntax quote: #{node}"
end
name = node.value[0..-2]
sym = candidate.lazy_make(name)
return Unquote.new(t, Symbol.new(t, sym))
end
node
else
node
end
end
end
class LetCandidate
include Shin::AST
attr_reader :t
attr_reader :let
def initialize(node)
@t = node.token
@let = List.new(t)
@let.inner << Symbol.new(t, "let")
@decls = Vector.new(t)
@let.inner << @decls
@let.inner << node
@cache = {}
end
def lazy_make(name)
sym = @cache[name]
unless sym
sym = "#{name}#{Shin::Mutator.fresh_sym}"
@cache[name] = sym
@decls.inner << Symbol.new(t, sym)
@decls.inner << List.new(t, [Symbol.new(t, "gensym"), String.new(t, name)])
end
sym
end
def to_s
"LetCandidate(#{@let}, cache = #{@cache})"
end
def useful?
!@decls.inner.empty?
end
end
end
|
require 'timeout'
require 'open3'
require 'rbconfig'
module Sicuro
# Ruby executable used.
RUBY_USED = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'])
# Sicuro::Eval is used to nicely handle stdout/stderr of evaluated code
class Eval
attr_accessor :out, :err
def initialize(out, err)
@out, @err = out, err.chomp
end
def to_s
if @err.empty? || @err == '""'
@out
else
@err
end
end
def inspect
if @err.empty? || @err == '""'
@out.inspect
else
@err.inspect
end
end
end
# Set the time and memory limits for Sicuro.eval.
#
# Passing nil (default) for the `memlimit` (second argument) will start at 5MB,
# and try to find the lowest multiple of 5MB that `puts 1` will run under.
# If it fails at `memlimit_upper_bound`, it prints an error and exits.
#
# This is needed because apparently some systems require *over 50MB* to run
# `puts 'hi'`, while others only require 5MB. I'm not quite sure what causes
# this. If you have any ideas, please open an issue on github and explain them!
# URL is: http://github.com/duckinator/sicuro/issues
#
# `memlimit_upper_bound` is the upper limit of memory detection, default is 100MB.
#
# `default_ruby` is the executable evaluated code should run as by default.
# This defaults to the ruby executable that was used to run.
def self.setup(timelimit=5, memlimit=nil, memlimit_upper_bound=nil, default_ruby=nil)
@@timelimit = timelimit
@@memlimit = memlimit
memlimit_upper_bound ||= 100
@@default_ruby = default_ruby || RUBY_USED
if @@memlimit.nil?
5.step(memlimit_upper_bound, 5) do |i|
if Sicuro.assert('print 1', '1', nil, nil, i)
@@memlimit = i
warn "[MEMLIMIT] Defaulting to #{i}MB" if $DEBUG
break
end
warn "[MEMLIMIT] Did not default to #{i}MB" if $DEBUG
end
if @@memlimit.nil?
fail "[MEMLIMIT] Could not run `print 1` in #{memlimit_upper_bound}MB RAM or less."
end
end
end
# This appends the code that actually makes the evaluation safe.
# Odds are, you don't want this unless you're debugging Sicuro.
def self._code_prefix(code, libs = nil, precode = nil, memlimit = nil, identifier = nil)
memlimit ||= @@memlimit
libs ||= []
precode ||= ''
identifier += '; ' if identifier
prefix = ''
current_time = Time.now.strftime("%I:%M:%S %p")
unless $DEBUG
# The following makes it use "sicuro ([identifier; ]current_time)" as the
# process name. Likely only actually does anything on *nix systems.
prefix = "$0 = 'sicuro (#{identifier}#{current_time})';"
end
prefix += <<-EOF
#{libs.inspect}.map {|x| require x }
require #{__FILE__.inspect}
Sicuro.setup(#{@@timelimit.inspect}, #{memlimit.inspect})
#{precode}
print Sicuro._safe_eval(#{code.inspect}, #{memlimit.inspect})
EOF
end
# Runs the specified code, returns STDOUT and STDERR as a single string.
# Automatically runs Sicuro.setup if needed.
#
# `code` is the code to run.
#
# `libs` is an array of libraries to include before setting up the safe eval process (BE CAREFUL!),
#
# `precode` is code ran before setting up the safe eval process (BE INCREDIBLY CAREFUL!).
#
# `memlimit` is the memory limit for this specific code. Default is `@@memlimit`
# as determined by Sicuro.setup
#
# `ruby_executable` is the exaecutable to use. Default is `@@default_ruby`, as
# determined by Sicuro.setup
#
# `identifier` is a unique identifier for this code (ie, if used an irc bot,
# the person's nickname). When specified, it tries setting the process name to
# "sicuro (#{identifier}, #{current_time})", otherwise it tries setting it to
# "sicuro (#{current_time})"
#
def self.eval(code, libs = nil, precode = nil, memlimit = nil, ruby_executable = nil, identifier = nil)
ruby_executable ||= @@default_ruby
i, o, e, t, pid = nil
Timeout.timeout(@@timelimit) do
i, o, e, t = Open3.popen3(ruby_executable)
pid = t.pid
out_reader = Thread.new { o.read }
err_reader = Thread.new { e.read }
i.write _code_prefix(code, libs, precode, memlimit, identifier)
i.close
Eval.new(out_reader.value, err_reader.value)
end
rescue Timeout::Error
Eval.new('', '<timeout hit>')
rescue NameError
Sicuro.setup
retry
ensure
i.close unless i.closed?
o.close unless o.closed?
e.close unless e.closed?
t.kill if t.alive?
Process.kill('KILL', pid) rescue nil # TODO: Handle this correctly
end
# Same as eval, but get only stdout
def self.eval_out(*args)
self.eval(*args).out
end
# Same as eval, but get only stderr
def self.eval_err(*args)
self.eval(*args).err
end
# Simple testing abilities.
#
# >> Sicuro.assert("print 'hi'", "hi")
# => true
#
def self.assert(code, output, *args)
Sicuro.eval(code, *args).out == output
end
# Use Sicuro.eval instead. This does not provide a strict time limit or call Sicuro.setup.
# Used internally by Sicuro.eval
def self._safe_eval(code, memlimit)
# RAM limit
Process.setrlimit(Process::RLIMIT_AS, memlimit*1024*1024)
# CPU time limit. 5s means 5s of CPU time.
Process.setrlimit(Process::RLIMIT_CPU, @@timelimit)
# Things we want, or need to have, available in eval
require 'stringio'
require 'pp'
# fakefs goes last, because I don't think `require` will work after it
begin
require 'fakefs'
rescue LoadError
require 'rubygems'
retry
end
# Undefine FakeFS
[:FakeFS, :RealFile, :RealFileTest, :RealFileUtils, :RealDir].each do |x|
Object.instance_eval{ remove_const x }
end
out_io, err_io, result, error = nil
begin
out_io = $stdout = StringIO.new
err_io = $stderr = StringIO.new
code = '$SAFE = 3; BEGIN { $SAFE=3 };' + code
result = ::Kernel.eval(code, TOPLEVEL_BINDING)
rescue Exception => e
error = "#{e.class}: #{e.message}"
ensure
$stdout = STDOUT
$stderr = STDERR
end
output = out_io.string
error ||= err_io.string
if output.empty?
print result.inspect
else
print output
end
warn error
end
end
Moar cleanup
require 'timeout'
require 'open3'
require 'rbconfig'
module Sicuro
# Ruby executable used.
RUBY_USED = File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + RbConfig::CONFIG['EXEEXT'])
# Sicuro::Eval is used to nicely handle stdout/stderr of evaluated code
class Eval
attr_accessor :out, :err
def initialize(out, err)
@out, @err = out, err.chomp
end
def to_s
if @err.empty? || @err == '""'
@out
else
@err
end
end
def inspect
if @err.empty? || @err == '""'
@out.inspect
else
@err.inspect
end
end
end
# Set the time and memory limits for Sicuro.eval.
#
# Passing nil (default) for the `memlimit` (second argument) will start at 5MB,
# and try to find the lowest multiple of 5MB that `puts 1` will run under.
# If it fails at `memlimit_upper_bound`, it prints an error and exits.
#
# This is needed because apparently some systems require *over 50MB* to run
# `puts 'hi'`, while others only require 5MB. I'm not quite sure what causes
# this. If you have any ideas, please open an issue on github and explain them!
# URL is: http://github.com/duckinator/sicuro/issues
#
# `memlimit_upper_bound` is the upper limit of memory detection, default is 100MB.
#
# `default_ruby` is the executable evaluated code should run as by default.
# This defaults to the ruby executable that was used to run.
def self.setup(timelimit=5, memlimit=nil, memlimit_upper_bound=nil, default_ruby=nil)
@@timelimit = timelimit
@@memlimit = memlimit
memlimit_upper_bound ||= 100
@@default_ruby = default_ruby || RUBY_USED
if @@memlimit.nil?
5.step(memlimit_upper_bound, 5) do |i|
if Sicuro.assert('print 1', '1', nil, nil, i)
@@memlimit = i
warn "[MEMLIMIT] Defaulting to #{i}MB" if $DEBUG
break
end
warn "[MEMLIMIT] Did not default to #{i}MB" if $DEBUG
end
if @@memlimit.nil?
fail "[MEMLIMIT] Could not run `print 1` in #{memlimit_upper_bound}MB RAM or less."
end
end
end
# This appends the code that actually makes the evaluation safe.
# Odds are, you don't want this unless you're debugging Sicuro.
def self._code_prefix(code, libs = nil, precode = nil, memlimit = nil, identifier = nil)
memlimit ||= @@memlimit
libs ||= []
precode ||= ''
identifier += '; ' if identifier
prefix = ''
current_time = Time.now.strftime("%I:%M:%S %p")
unless $DEBUG
# The following makes it use "sicuro ([identifier; ]current_time)" as the
# process name. Likely only actually does anything on *nix systems.
prefix = "$0 = 'sicuro (#{identifier}#{current_time})';"
end
prefix += <<-EOF
#{libs.inspect}.map {|x| require x }
require #{__FILE__.inspect}
Sicuro.setup(#{@@timelimit.inspect}, #{memlimit.inspect})
#{precode}
print Sicuro._safe_eval(#{code.inspect}, #{memlimit.inspect})
EOF
end
# Runs the specified code, returns STDOUT and STDERR as a single string.
# Automatically runs Sicuro.setup if needed.
#
# `code` is the code to run.
#
# `libs` is an array of libraries to include before setting up the safe eval process (BE CAREFUL!),
#
# `precode` is code ran before setting up the safe eval process (BE INCREDIBLY CAREFUL!).
#
# `memlimit` is the memory limit for this specific code. Default is `@@memlimit`
# as determined by Sicuro.setup
#
# `ruby_executable` is the exaecutable to use. Default is `@@default_ruby`, as
# determined by Sicuro.setup
#
# `identifier` is a unique identifier for this code (ie, if used an irc bot,
# the person's nickname). When specified, it tries setting the process name to
# "sicuro (#{identifier}, #{current_time})", otherwise it tries setting it to
# "sicuro (#{current_time})"
#
def self.eval(code, libs = nil, precode = nil, memlimit = nil, ruby_executable = nil, identifier = nil)
ruby_executable ||= @@default_ruby
i, o, e, t, pid = nil
Timeout.timeout(@@timelimit) do
i, o, e, t = Open3.popen3(ruby_executable)
pid = t.pid
out_reader = Thread.new { o.read }
err_reader = Thread.new { e.read }
i.write _code_prefix(code, libs, precode, memlimit, identifier)
i.close
Eval.new(out_reader.value, err_reader.value)
end
rescue Timeout::Error
Eval.new('', '<timeout hit>')
rescue NameError
Sicuro.setup
retry
ensure
i.close unless i.closed?
o.close unless o.closed?
e.close unless e.closed?
t.kill if t.alive?
Process.kill('KILL', pid) rescue nil # TODO: Handle this correctly
end
# Same as eval, but get only stdout
def self.eval_out(*args)
self.eval(*args).out
end
# Same as eval, but get only stderr
def self.eval_err(*args)
self.eval(*args).err
end
# Simple testing abilities.
#
# >> Sicuro.assert("print 'hi'", "hi")
# => true
#
def self.assert(code, output, *args)
Sicuro.eval(code, *args).out == output
end
# stdout, stderr, and exception catching for unsafe Kernel#eval
# Used internally by Sicuro._safe_eval
def self._unsafe_eval(code, binding)
out_io, err_io, result, error, exception = nil
begin
out_io = $stdout = StringIO.new
err_io = $stderr = StringIO.new
code = '$SAFE = 3; BEGIN { $SAFE=3 };' + code
result = ::Kernel.eval(code, binding)
rescue Exception => e
exception = "#{e.class}: #{e.message}"
ensure
$stdout = STDOUT
$stderr = STDERR
end
[out_io.string, result, err_io.string, exception]
end
# Use Sicuro.eval instead. This does not provide a strict time limit or call Sicuro.setup.
# Used internally by Sicuro.eval
def self._safe_eval(code, memlimit)
# RAM limit
Process.setrlimit(Process::RLIMIT_AS, memlimit*1024*1024)
# CPU time limit. 5s means 5s of CPU time.
Process.setrlimit(Process::RLIMIT_CPU, @@timelimit)
# Things we want, or need to have, available in eval
require 'stringio'
require 'pp'
# fakefs goes last, because I don't think `require` will work after it
begin
require 'fakefs'
rescue LoadError
require 'rubygems'
retry
end
# Undefine FakeFS
[:FakeFS, :RealFile, :RealFileTest, :RealFileUtils, :RealDir].each do |x|
Object.instance_eval{ remove_const x }
end
=begin
out_io, err_io, result, error = nil
begin
out_io = $stdout = StringIO.new
err_io = $stderr = StringIO.new
code = '$SAFE = 3; BEGIN { $SAFE=3 };' + code
result = ::Kernel.eval(code, TOPLEVEL_BINDING)
rescue Exception => e
error = "#{e.class}: #{e.message}"
ensure
$stdout = STDOUT
$stderr = STDERR
end
output = out_io.string
error ||= err_io.string
=end
output, result, error, exception = self._unsafe_eval(code, TOPLEVEL_BINDING)
output = result.inspect if output.empty?
error ||= exception
print output
warn error
end
end
|
require 'action_view'
require 'simple_form/action_view_extensions/form_helper'
require 'simple_form/action_view_extensions/builder'
module SimpleForm
autoload :Components, 'simple_form/components'
autoload :ErrorNotification, 'simple_form/error_notification'
autoload :FormBuilder, 'simple_form/form_builder'
autoload :Helpers, 'simple_form/helpers'
autoload :I18nCache, 'simple_form/i18n_cache'
autoload :Inputs, 'simple_form/inputs'
autoload :MapType, 'simple_form/map_type'
autoload :Wrappers, 'simple_form/wrappers'
## CONFIGURATION OPTIONS
# Method used to tidy up errors.
mattr_accessor :error_method
@@error_method = :first
# Default tag used for error notification helper.
mattr_accessor :error_notification_tag
@@error_notification_tag = :p
# CSS class to add for error notification helper.
mattr_accessor :error_notification_class
@@error_notification_class = :error_notification
# ID to add for error notification helper.
mattr_accessor :error_notification_id
@@error_notification_id = nil
# Series of attemps to detect a default label method for collection.
mattr_accessor :collection_label_methods
@@collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attemps to detect a default value method for collection.
mattr_accessor :collection_value_methods
@@collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
mattr_accessor :collection_wrapper_tag
@@collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
mattr_accessor :collection_wrapper_class
@@collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag, defaulting to none.
mattr_accessor :item_wrapper_tag
@@item_wrapper_tag = :span
# How the label text should be generated altogether with the required text.
mattr_accessor :label_text
@@label_text = lambda { |label, required| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
mattr_accessor :label_class
@@label_class = nil
# You can define the class to use on all forms. Default is simple_form.
mattr_accessor :form_class
@@form_class = :simple_form
# Whether attributes are required by default (or not).
mattr_accessor :required_by_default
@@required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
mattr_accessor :browser_validations
@@browser_validations = true
# Collection of methods to detect if a file type was given.
mattr_accessor :file_methods
@@file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value, such as { /count/ => :integer }.
mattr_accessor :input_mappings
@@input_mappings = nil
# Default priority for time_zone inputs.
mattr_accessor :time_zone_priority
@@time_zone_priority = nil
# Default priority for country inputs.
mattr_accessor :country_priority
@@country_priority = nil
# Maximum size allowed for inputs.
mattr_accessor :default_input_size
@@default_input_size = 50
# When off, do not use translations in labels. Disabling translation in
# hints and placeholders can be done manually in the wrapper API.
mattr_accessor :translate_labels
@@translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
mattr_accessor :inputs_discovery
@@inputs_discovery = true
# Cache simple form inputs discovery
mattr_accessor :cache_discovery
@@cache_discovery = !Rails.env.development?
# Adds a class to each generated button, mostly for compatiblity
mattr_accessor :button_class
@@button_class = 'button'
## WRAPPER CONFIGURATION
@@wrappers = {}
# Retrieves a given wrapper
def self.wrapper(name)
@@wrappers[name.to_sym] or raise WrapperNotFound, "Couldn't find wrapper with name #{name}"
end
# Raised when fails to find a given wrapper name
class WrapperNotFound < StandardError
end
# Define a new wrapper using SimpleForm::Wrappers::Builder
# and store it in the given name.
def self.wrappers(*args, &block)
if block_given?
options = args.extract_options!
name = args.first || :default
@@wrappers[name.to_sym] = build(options, &block)
else
@@wrappers
end
end
# Builds a new wrapper using SimpleForm::Wrappers::Builder.
def self.build(options={})
options[:tag] = :div if options[:tag].nil?
builder = SimpleForm::Wrappers::Builder.new
yield builder
SimpleForm::Wrappers::Root.new(builder.to_a, options)
end
wrappers :class => :input, :error_class => :field_with_errors do |b|
b.use :html5
b.use :min_max
b.use :maxlength
b.use :placeholder
b.use :pattern
b.use :readonly
b.use :label_input
b.use :hint, :tag => :span, :class => :hint
b.use :error, :tag => :span, :class => :error
end
## SETUP
DEPRECATED = %w(hint_tag hint_class error_tag error_class wrapper_tag wrapper_class wrapper_error_class components html5)
@@deprecated = false
DEPRECATED.each do |method|
class_eval "def self.#{method}=(*); @@deprecated = true; end"
class_eval "def self.#{method}; ActiveSupport::Deprecation.warn 'SimpleForm.#{method} is deprecated and has no effect'; end"
end
def self.translate=(value)
ActiveSupport::Deprecation.warn "SimpleForm.translate= is disabled in favor of translate_labels="
self.translate_labels = value
end
def self.translate
ActiveSupport::Deprecation.warn "SimpleForm.translate is disabled in favor of translate_labels"
self.translate_labels
end
# Default way to setup SimpleForm. Run rails generate simple_form:install
# to create a fresh initializer with all configuration values.
def self.setup
yield self
if @@deprecated
raise "[SIMPLE FORM] Your simple form initializer file is using an outdated configuration API. " <<
"Updating to the new API is easy and fast. Check for more info here: https://github.com/plataformatec/simple_form/wiki/Upgrading-to-Simple-Form-2.0"
end
end
end
Require AS dependencies.
require 'action_view'
require 'simple_form/action_view_extensions/form_helper'
require 'simple_form/action_view_extensions/builder'
require 'active_support/core_ext/hash/slice'
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/hash/reverse_merge'
module SimpleForm
autoload :Components, 'simple_form/components'
autoload :ErrorNotification, 'simple_form/error_notification'
autoload :FormBuilder, 'simple_form/form_builder'
autoload :Helpers, 'simple_form/helpers'
autoload :I18nCache, 'simple_form/i18n_cache'
autoload :Inputs, 'simple_form/inputs'
autoload :MapType, 'simple_form/map_type'
autoload :Wrappers, 'simple_form/wrappers'
## CONFIGURATION OPTIONS
# Method used to tidy up errors.
mattr_accessor :error_method
@@error_method = :first
# Default tag used for error notification helper.
mattr_accessor :error_notification_tag
@@error_notification_tag = :p
# CSS class to add for error notification helper.
mattr_accessor :error_notification_class
@@error_notification_class = :error_notification
# ID to add for error notification helper.
mattr_accessor :error_notification_id
@@error_notification_id = nil
# Series of attemps to detect a default label method for collection.
mattr_accessor :collection_label_methods
@@collection_label_methods = [ :to_label, :name, :title, :to_s ]
# Series of attemps to detect a default value method for collection.
mattr_accessor :collection_value_methods
@@collection_value_methods = [ :id, :to_s ]
# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
mattr_accessor :collection_wrapper_tag
@@collection_wrapper_tag = nil
# You can define the class to use on all collection wrappers. Defaulting to none.
mattr_accessor :collection_wrapper_class
@@collection_wrapper_class = nil
# You can wrap each item in a collection of radio/check boxes with a tag, defaulting to none.
mattr_accessor :item_wrapper_tag
@@item_wrapper_tag = :span
# How the label text should be generated altogether with the required text.
mattr_accessor :label_text
@@label_text = lambda { |label, required| "#{required} #{label}" }
# You can define the class to use on all labels. Default is nil.
mattr_accessor :label_class
@@label_class = nil
# You can define the class to use on all forms. Default is simple_form.
mattr_accessor :form_class
@@form_class = :simple_form
# Whether attributes are required by default (or not).
mattr_accessor :required_by_default
@@required_by_default = true
# Tell browsers whether to use default HTML5 validations (novalidate option).
mattr_accessor :browser_validations
@@browser_validations = true
# Collection of methods to detect if a file type was given.
mattr_accessor :file_methods
@@file_methods = [ :mounted_as, :file?, :public_filename ]
# Custom mappings for input types. This should be a hash containing a regexp
# to match as key, and the input type that will be used when the field name
# matches the regexp as value, such as { /count/ => :integer }.
mattr_accessor :input_mappings
@@input_mappings = nil
# Default priority for time_zone inputs.
mattr_accessor :time_zone_priority
@@time_zone_priority = nil
# Default priority for country inputs.
mattr_accessor :country_priority
@@country_priority = nil
# Maximum size allowed for inputs.
mattr_accessor :default_input_size
@@default_input_size = 50
# When off, do not use translations in labels. Disabling translation in
# hints and placeholders can be done manually in the wrapper API.
mattr_accessor :translate_labels
@@translate_labels = true
# Automatically discover new inputs in Rails' autoload path.
mattr_accessor :inputs_discovery
@@inputs_discovery = true
# Cache simple form inputs discovery
mattr_accessor :cache_discovery
@@cache_discovery = !Rails.env.development?
# Adds a class to each generated button, mostly for compatiblity
mattr_accessor :button_class
@@button_class = 'button'
## WRAPPER CONFIGURATION
@@wrappers = {}
# Retrieves a given wrapper
def self.wrapper(name)
@@wrappers[name.to_sym] or raise WrapperNotFound, "Couldn't find wrapper with name #{name}"
end
# Raised when fails to find a given wrapper name
class WrapperNotFound < StandardError
end
# Define a new wrapper using SimpleForm::Wrappers::Builder
# and store it in the given name.
def self.wrappers(*args, &block)
if block_given?
options = args.extract_options!
name = args.first || :default
@@wrappers[name.to_sym] = build(options, &block)
else
@@wrappers
end
end
# Builds a new wrapper using SimpleForm::Wrappers::Builder.
def self.build(options={})
options[:tag] = :div if options[:tag].nil?
builder = SimpleForm::Wrappers::Builder.new
yield builder
SimpleForm::Wrappers::Root.new(builder.to_a, options)
end
wrappers :class => :input, :error_class => :field_with_errors do |b|
b.use :html5
b.use :min_max
b.use :maxlength
b.use :placeholder
b.use :pattern
b.use :readonly
b.use :label_input
b.use :hint, :tag => :span, :class => :hint
b.use :error, :tag => :span, :class => :error
end
## SETUP
DEPRECATED = %w(hint_tag hint_class error_tag error_class wrapper_tag wrapper_class wrapper_error_class components html5)
@@deprecated = false
DEPRECATED.each do |method|
class_eval "def self.#{method}=(*); @@deprecated = true; end"
class_eval "def self.#{method}; ActiveSupport::Deprecation.warn 'SimpleForm.#{method} is deprecated and has no effect'; end"
end
def self.translate=(value)
ActiveSupport::Deprecation.warn "SimpleForm.translate= is disabled in favor of translate_labels="
self.translate_labels = value
end
def self.translate
ActiveSupport::Deprecation.warn "SimpleForm.translate is disabled in favor of translate_labels"
self.translate_labels
end
# Default way to setup SimpleForm. Run rails generate simple_form:install
# to create a fresh initializer with all configuration values.
def self.setup
yield self
if @@deprecated
raise "[SIMPLE FORM] Your simple form initializer file is using an outdated configuration API. " <<
"Updating to the new API is easy and fast. Check for more info here: https://github.com/plataformatec/simple_form/wiki/Upgrading-to-Simple-Form-2.0"
end
end
end
|
require 'erb'
require 'json'
require 'rest-client'
require 'colorize'
require 'yaml'
module Singularity
class Request
attr_accessor :release, :cpus, :mem, :envs, :schedule, :cmd, :arguments, :request_id, :repo, :release_string, :release_id_string
def get_binding
binding()
end
end
class Deployer
def initialize(uri, file, release)
@uri = uri
@file = file
@release = release
@config = ERB.new(open(file).read)
@r = Request.new
@r.release = @release
@data = JSON.parse(@config.result(@r.get_binding))
print @data['id']
end
def is_paused
begin
resp = RestClient.get "#{@uri}/api/requests/request/#{@data['id']}"
JSON.parse(resp)['state'] == 'PAUSED'
rescue
print " CREATING...".blue
false
end
end
def deploy
begin
if is_paused()
puts " PAUSED, SKIPPING".yellow
return
else
# create or update the request
resp = RestClient.post "#{@uri}/api/requests", @data.to_json, :content_type => :json
end
# deploy the request
@data['requestId'] = @data['id']
@data['id'] = "#{@release}.#{Time.now.to_i}"
deploy = {
'deploy' => @data,
'user' => `whoami`.chomp,
'unpauseOnSuccessfulDeploy' => false
}
resp = RestClient.post "#{@uri}/api/deploys", deploy.to_json, :content_type => :json
puts " DEPLOYED".green
rescue Exception => e
puts " #{e.response}".red
end
end
end
class Deleter
def initialize(uri, file)
@uri = uri
@file = file
end
# Deleter.delete -- arguments are <uri>, <file>
def delete
begin
task_id = "#{@file}".gsub(/\.\/singularity\//, "").gsub(/\.json/, "")
# delete the request
RestClient.delete "#{@uri}/api/requests/request/#{task_id}"
puts "#{task_id} DELETED"
rescue
puts "#{task_id} #{$!.response}"
end
end
end
class Runner
def initialize(script)
#########################################################
# TODO
# check to see that .mescal.json and mesos-deploy.yml exist
#########################################################
@script = script
# read .mescal.json for ssh command, image, release number, cpus, mem
@configData = JSON.parse(ERB.new(open(File.join(Dir.pwd, ".mescal.json")).read).result(Request.new.get_binding))
@sshCmd = @configData['sshCmd']
@image = @configData['image'].split(':')[0]
@release = @configData['image'].split(':')[1]
# read mesos-deploy.yml for singularity url
@mesosDeployConfig = YAML.load_file(File.join(Dir.pwd, "mesos-deploy.yml"))
@uri = @mesosDeployConfig['singularity_url']
# create request/deploy json data
@data = {
'command' => "/sbin/my_init",
'resources' => {
'memoryMb' => @configData['mem'],
'cpus' => @configData['cpus'],
'numPorts' => 1
},
'env' => {
'APPLICATION_ENV' => "production"
},
'requestType' => "RUN_ONCE",
'containerInfo' => {
'type' => "DOCKER",
'docker' => {
'image' => @configData['image'],
'network' => "BRIDGE",
'portMappings' => [{
'containerPortType': "LITERAL",
'containerPort': 22,
'hostPortType': "FROM_OFFER",
'hostPort': 0
}]
}
}
}
# either we typed 'singularity ssh'
if @script == "ssh"
@data['id'] = Dir.pwd.split('/').last + "_SSH"
@data['command'] = "#{@sshCmd}"
# or we passed a script/commands to 'singularity run'
else
# if we passed "runx", then skip use of /sbin/my_init
if @script[0] == "runx"
@data['arguments'] = [] # don't use "--" as first argument
@data['command'] = @script[1] #remove "runx" from commands
@script.shift
@data['id'] = @script.join("-").tr('@/\*?% []#$', '_')
@data['id'][0] = ''
@script.shift
# else join /sbin/my_init with your commands
else
@data['arguments'] = ["--"]
@data['id'] = @script.join("-").tr('@/\*?% []#$', '_')
@data['id'][0] = ''
end
@script.each { |i| @data['arguments'].push i }
end
end
def is_paused
begin
resp = RestClient.get "#{@uri}/api/requests/request/#{@data['id']}"
JSON.parse(resp)['state'] == 'PAUSED'
rescue
print " Deploying request...".light_blue
false
end
end
def runner
begin
if is_paused()
puts " PAUSED, SKIPPING.".yellow
return
else
# create or update the request
RestClient.post "#{@uri}/api/requests", @data.to_json, :content_type => :json
end
# deploy the request
@data['requestId'] = @data['id']
@data['id'] = "#{@release}.#{Time.now.to_i}"
@deploy = {
'deploy' => @data,
'user' => `whoami`.chomp,
'unpauseOnSuccessfulDeploy' => false
}
RestClient.post "#{@uri}/api/deploys", @deploy.to_json, :content_type => :json
# wait until deployment completes and succeeds
begin
@deployState = RestClient.get "#{@uri}/api/requests/request/#{@data['requestId']}", :content_type => :json
@deployState = JSON.parse(@deployState)
end until @deployState['pendingDeployState']['currentDeployState'] != "SUCCEEDED"
puts " Deploy succeeded.".green
if @script == "ssh"
where = Dir.pwd.split('/').last
puts " Opening a shell to #{where}, please wait a moment...".light_blue
# get active tasks until ours shows up so we can get IP/PORT
begin
@thisTask = ''
@tasks = RestClient.get "#{@uri}/api/tasks/active", :content_type => :json
@tasks = JSON.parse(@tasks)
@tasks.each do |entry|
if entry['taskRequest']['request']['id'] == @data['requestId']
@thisTask = entry
end
end
end until @thisTask != ''
@ip = @thisTask['offer']['url']['address']['ip']
@port = @thisTask['mesosTask']['container']['docker']['portMappings'][0]['hostPort']
# SSH into the machine
# uses "begin end until" because "system" will keep returning "false" unless the command exits with success
# this makes sure that the docker image has completely started and the SSH command succeeds
begin end until system "ssh -o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@#{@ip} -p #{@port}"
else
puts " Deployed and running #{@data['command']} #{@data['arguments']}".green
end
# finally, delete the request (which also deletes the corresponding task)
RestClient.delete "#{@uri}/api/requests/request/#{@data['requestId']}"
rescue Exception => e
puts " #{e.response}".red
end
end
end
end
updates
require 'erb'
require 'json'
require 'rest-client'
require 'colorize'
require 'yaml'
module Singularity
class Request
attr_accessor :release, :cpus, :mem, :envs, :schedule, :cmd, :arguments, :request_id, :repo, :release_string, :release_id_string
def get_binding
binding()
end
end
class Deployer
def initialize(uri, file, release)
@uri = uri
@file = file
@release = release
@config = ERB.new(open(file).read)
@r = Request.new
@r.release = @release
@data = JSON.parse(@config.result(@r.get_binding))
print @data['id']
end
def is_paused
begin
resp = RestClient.get "#{@uri}/api/requests/request/#{@data['id']}"
JSON.parse(resp)['state'] == 'PAUSED'
rescue
print " CREATING...".blue
false
end
end
def deploy
begin
if is_paused()
puts " PAUSED, SKIPPING".yellow
return
else
# create or update the request
resp = RestClient.post "#{@uri}/api/requests", @data.to_json, :content_type => :json
end
# deploy the request
@data['requestId'] = @data['id']
@data['id'] = "#{@release}.#{Time.now.to_i}"
deploy = {
'deploy' => @data,
'user' => `whoami`.chomp,
'unpauseOnSuccessfulDeploy' => false
}
resp = RestClient.post "#{@uri}/api/deploys", deploy.to_json, :content_type => :json
puts " DEPLOYED".green
rescue Exception => e
puts " #{e.response}".red
end
end
end
class Deleter
def initialize(uri, file)
@uri = uri
@file = file
end
# Deleter.delete -- arguments are <uri>, <file>
def delete
begin
task_id = "#{@file}".gsub(/\.\/singularity\//, "").gsub(/\.json/, "")
# delete the request
RestClient.delete "#{@uri}/api/requests/request/#{task_id}"
puts "#{task_id} DELETED"
rescue
puts "#{task_id} #{$!.response}"
end
end
end
class Runner
def initialize(script)
#########################################################
# TODO
# check to see that .mescal.json and mesos-deploy.yml exist
#########################################################
@script = script
# read .mescal.json for ssh command, image, release number, cpus, mem
@configData = JSON.parse(ERB.new(open(File.join(Dir.pwd, ".mescal.json")).read).result(Request.new.get_binding))
@sshCmd = @configData['sshCmd']
@image = @configData['image'].split(':')[0]
@release = @configData['image'].split(':')[1]
# read mesos-deploy.yml for singularity url
@mesosDeployConfig = YAML.load_file(File.join(Dir.pwd, "mesos-deploy.yml"))
@uri = @mesosDeployConfig['singularity_url']
# create request/deploy json data
@data = {
'command' => "/sbin/my_init",
'resources' => {
'memoryMb' => @configData['mem'],
'cpus' => @configData['cpus'],
'numPorts' => 1
},
'env' => {
'APPLICATION_ENV' => "production"
},
'requestType' => "RUN_ONCE",
'containerInfo' => {
'type' => "DOCKER",
'docker' => {
'image' => @configData['image'],
'network' => "BRIDGE",
'portMappings' => [{
'containerPortType': "LITERAL",
'containerPort': 22,
'hostPortType': "FROM_OFFER",
'hostPort': 0
}]
}
}
}
# either we typed 'singularity ssh'
if @script == "ssh"
@data['id'] = Dir.pwd.split('/').last + "_SSH"
@data['command'] = "#{@sshCmd}"
# or we passed a script/commands to 'singularity run'
else
# if we passed "runx", then skip use of /sbin/my_init
if @script[0] == "runx"
@data['arguments'] = [] # don't use "--" as first argument
@data['command'] = @script[1] #remove "runx" from commands
@script.shift
@data['id'] = @script.join("-").tr('@/\*?% []#$', '_')
@data['id'][0] = ''
@script.shift
# else join /sbin/my_init with your commands
else
@data['arguments'] = ["--"]
@data['id'] = @script.join("-").tr('@/\*?% []#$', '_')
@data['id'][0] = ''
end
@script.each { |i| @data['arguments'].push i }
end
end
def is_paused
begin
resp = RestClient.get "#{@uri}/api/requests/request/#{@data['id']}"
JSON.parse(resp)['state'] == 'PAUSED'
rescue
print " Deploying request...".light_blue
false
end
end
def runner
begin
if is_paused()
puts " PAUSED, SKIPPING.".yellow
return
else
# create or update the request
RestClient.post "#{@uri}/api/requests", @data.to_json, :content_type => :json
end
# deploy the request
@data['requestId'] = @data['id']
@data['id'] = "#{@release}.#{Time.now.to_i}"
@deploy = {
'deploy' => @data,
'user' => `whoami`.chomp,
'unpauseOnSuccessfulDeploy' => false
}
RestClient.post "#{@uri}/api/deploys", @deploy.to_json, :content_type => :json
# wait until deployment completes and succeeds
begin
@deployState = RestClient.get "#{@uri}/api/requests/request/#{@data['requestId']}", :content_type => :json
@deployState = JSON.parse(@deployState)
end until @deployState['pendingDeployState']['currentDeployState'] != "SUCCEEDED"
puts " Deploy succeeded.".green
# get active tasks until ours shows up so we can get IP/PORT
begin
@thisTask = ''
@tasks = RestClient.get "#{@uri}/api/tasks/active", :content_type => :json
@tasks = JSON.parse(@tasks)
@tasks.each do |entry|
if entry['taskRequest']['request']['id'] == @data['requestId']
@thisTask = entry
end
end
end until @thisTask != ''
@ip = @thisTask['offer']['url']['address']['ip']
@port = @thisTask['mesosTask']['container']['docker']['portMappings'][0]['hostPort']
if @script == "ssh"
# SSH into the machine
# uses "begin end until" because "system" will keep returning "false" unless the command exits with success
# this makes sure that the docker image has completely started and the SSH command succeeds
where = Dir.pwd.split('/').last
puts " Opening a shell to #{where}, please wait a moment...".light_blue
begin end until system "ssh -o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no root@#{@ip} -p #{@port}"
else
puts " Deployed and running #{@data['command']} #{@data['arguments']}".green
end
# need to wait for "task_finished" or something similar before asking for this sandbox info for non-ssh commands
# need to duplicate this for stderr
sandbox = RestClient.get "#{@uri}/api/sandbox/#{@thisTask['taskId']['id']}/read", {params: {path: "stdout", length: 30000, offset: 0}}
sandbox = JSON.parse(sandbox)
puts "stdout: ".green
puts sandbox['data']
# finally, delete the request (which also deletes the corresponding task)
RestClient.delete "#{@uri}/api/requests/request/#{@data['requestId']}"
rescue Exception => e
puts " #{e.response}".red
end
end
end
end
|
module Slim
# Parses Slim code and transforms it to a Temple expression
# @api private
class Parser
include Temple::Mixins::Options
set_default_options :tabsize => 4,
:encoding => 'utf-8',
:shortcut => {
'#' => 'id',
'.' => 'class'
}
class SyntaxError < StandardError
attr_reader :error, :file, :line, :lineno, :column
def initialize(error, file, line, lineno, column)
@error = error
@file = file || '(__TEMPLATE__)'
@line = line.to_s
@lineno = lineno
@column = column
end
def to_s
line = @line.strip
column = @column + line.size - @line.size
%{#{error}
#{file}, Line #{lineno}
#{line}
#{' ' * column}^
}
end
end
def initialize(options = {})
super
@tab = ' ' * @options[:tabsize]
@shortcut = {}
@options[:shortcut].each do |k,v|
@shortcut[k] = if v =~ /\A([^\s]+)\s+([^\s]+)\Z/
[$1, $2]
else
[@options[:default_tag], v]
end
end
shortcut = "[#{Regexp.escape @shortcut.keys.join}]"
@shortcut_regex = /\A(#{shortcut})(\w[\w-]*\w|\w+)/
@tag_regex = /\A(?:#{shortcut}|\*(?=[^\s]+)|(\w[\w:-]*\w|\w+))/
end
# Compile string to Temple expression
#
# @param [String] str Slim code
# @return [Array] Temple expression representing the code]]
def call(str)
# Set string encoding if option is set
if options[:encoding] && str.respond_to?(:encoding)
old_enc = str.encoding
str = str.dup if str.frozen?
str.force_encoding(options[:encoding])
# Fall back to old encoding if new encoding is invalid
str.force_encoding(old_enc) unless str.valid_encoding?
end
result = [:multi]
reset(str.split(/\r?\n/), [result])
parse_line while next_line
reset
result
end
private
DELIMITERS = {
'(' => ')',
'[' => ']',
'{' => '}',
}.freeze
DELIMITER_REGEX = /\A[#{Regexp.escape DELIMITERS.keys.join}]/
ATTR_NAME = '\A\s*(\w[:\w-]*)'
QUOTED_ATTR_REGEX = /#{ATTR_NAME}=("|')/
CODE_ATTR_REGEX = /#{ATTR_NAME}=/
def reset(lines = nil, stacks = nil)
# Since you can indent however you like in Slim, we need to keep a list
# of how deeply indented you are. For instance, in a template like this:
#
# doctype # 0 spaces
# html # 0 spaces
# head # 1 space
# title # 4 spaces
#
# indents will then contain [0, 1, 4] (when it's processing the last line.)
#
# We uses this information to figure out how many steps we must "jump"
# out when we see an de-indented line.
@indents = [0]
# Whenever we want to output something, we'll *always* output it to the
# last stack in this array. So when there's a line that expects
# indentation, we simply push a new stack onto this array. When it
# processes the next line, the content will then be outputted into that
# stack.
@stacks = stacks
@lineno = 0
@lines = lines
@line = @orig_line = nil
end
def next_line
if @lines.empty?
@orig_line = @line = nil
else
@orig_line = @lines.shift
@lineno += 1
@line = @orig_line.dup
end
end
def get_indent(line)
# Figure out the indentation. Kinda ugly/slow way to support tabs,
# but remember that this is only done at parsing time.
line[/\A[ \t]*/].gsub("\t", @tab).size
end
def parse_line
if @line =~ /\A\s*\Z/
@stacks.last << [:newline]
return
end
indent = get_indent(@line)
# Remove the indentation
@line.lstrip!
# If there's more stacks than indents, it means that the previous
# line is expecting this line to be indented.
expecting_indentation = @stacks.size > @indents.size
if indent > @indents.last
# This line was actually indented, so we'll have to check if it was
# supposed to be indented or not.
syntax_error!('Unexpected indentation') unless expecting_indentation
@indents << indent
else
# This line was *not* indented more than the line before,
# so we'll just forget about the stack that the previous line pushed.
@stacks.pop if expecting_indentation
# This line was deindented.
# Now we're have to go through the all the indents and figure out
# how many levels we've deindented.
while indent < @indents.last
@indents.pop
@stacks.pop
end
# This line's indentation happens lie "between" two other line's
# indentation:
#
# hello
# world
# this # <- This should not be possible!
syntax_error!('Malformed indentation') if indent != @indents.last
end
parse_line_indicators
end
def parse_line_indicators
case @line
when /\A\//
# Found a comment block.
if @line =~ %r{\A/!( ?)(.*)\Z}
# HTML comment
@stacks.last << [:html, :comment, [:slim, :text, parse_text_block($2, @indents.last + $1.size + 2)]]
elsif @line =~ %r{\A/\[\s*(.*?)\s*\]\s*\Z}
# HTML conditional comment
block = [:multi]
@stacks.last << [:html, :condcomment, $1, block]
@stacks << block
else
# Slim comment
parse_comment_block
end
when /\A([\|'])( ?)(.*)\Z/
# Found a text block.
trailing_ws = $1 == "'"
@stacks.last << [:slim, :text, parse_text_block($3, @indents.last + $2.size + 1)]
@stacks.last << [:static, ' '] if trailing_ws
when /\A-/
# Found a code block.
# We expect the line to be broken or the next line to be indented.
block = [:multi]
@line.slice!(0)
@stacks.last << [:slim, :control, parse_broken_line, block]
@stacks << block
when /\A=/
# Found an output block.
# We expect the line to be broken or the next line to be indented.
@line =~ /\A=(=?)('?)/
@line = $'
block = [:multi]
@stacks.last << [:slim, :output, $1.empty?, parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A(\w+):\s*\Z/
# Embedded template detected. It is treated as block.
@stacks.last << [:slim, :embedded, $1, parse_text_block]
when /\Adoctype\s+/i
# Found doctype declaration
@stacks.last << [:html, :doctype, $'.strip]
when @tag_regex
# Found a HTML tag.
@line = $' if $1
parse_tag($&)
else
syntax_error! 'Unknown line indicator'
end
@stacks.last << [:newline]
end
def parse_comment_block
while !@lines.empty? && (@lines.first =~ /\A\s*\Z/ || get_indent(@lines.first) > @indents.last)
next_line
@stacks.last << [:newline]
end
end
def parse_text_block(first_line = nil, text_indent = nil, in_tag = false)
result = [:multi]
if !first_line || first_line.empty?
text_indent = nil
else
result << [:slim, :interpolate, first_line]
end
empty_lines = 0
until @lines.empty?
if @lines.first =~ /\A\s*\Z/
next_line
result << [:newline]
empty_lines += 1 if text_indent
else
indent = get_indent(@lines.first)
break if indent <= @indents.last
if empty_lines > 0
result << [:slim, :interpolate, "\n" * empty_lines]
empty_lines = 0
end
next_line
@line.lstrip!
# The text block lines must be at least indented
# as deep as the first line.
offset = text_indent ? indent - text_indent : 0
if offset < 0
syntax_error!("Text line not indented deep enough.\n" +
"The first text line defines the necessary text indentation." +
(in_tag ? "\nAre you trying to nest a child tag in a tag containing text? Use | for the text block!" : ''))
end
result << [:newline] << [:slim, :interpolate, (text_indent ? "\n" : '') + (' ' * offset) + @line]
# The indentation of first line of the text block
# determines the text base indentation.
text_indent ||= indent
end
end
result
end
def parse_broken_line
broken_line = @line.strip
while broken_line =~ /[,\\]\Z/
next_line || syntax_error!('Unexpected end of file')
broken_line << "\n" << @line.strip
end
broken_line
end
def parse_tag(tag)
tag = [:slim, :tag, @shortcut[tag] ? @shortcut[tag][0] : tag, parse_attributes]
@stacks.last << tag
case @line
when /\A\s*:\s*/
# Block expansion
@line = $'
(@line =~ @tag_regex) || syntax_error!('Expected tag')
@line = $' if $1
content = [:multi]
tag << content
i = @stacks.size
@stacks << content
parse_tag($&)
@stacks.delete_at(i)
when /\A\s*=(=?)('?)/
# Handle output code
block = [:multi]
@line = $'
content = [:slim, :output, $1 != '=', parse_broken_line, block]
tag << content
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A\s*\//
# Closed tag. Do nothing
when /\A\s*\Z/
# Empty content
content = [:multi]
tag << content
@stacks << content
when /\A( ?)(.*)\Z/
# Text content
tag << [:slim, :text, parse_text_block($2, @orig_line.size - @line.size + $1.size, true)]
end
end
def parse_attributes
attributes = [:slim, :attrs]
attribute = nil
# Find any shortcut attributes
while @line =~ @shortcut_regex
# The class/id attribute is :static instead of :slim :text,
# because we don't want text interpolation in .class or #id shortcut
attributes << [:html, :attr, @shortcut[$1][1], [:static, $2]]
@line = $'
end
# Check to see if there is a delimiter right after the tag name
delimiter = nil
if @line =~ DELIMITER_REGEX
delimiter = DELIMITERS[$&]
@line.slice!(0)
end
if delimiter
boolean_attr_regex = /#{ATTR_NAME}(?=(\s|#{Regexp.escape delimiter}))/
end_regex = /\A\s*#{Regexp.escape delimiter}/
end
while true
case @line
when /\A\s*\*(?=[^\s]+)/
# Splat attribute
@line = $'
attributes << [:slim, :splat, parse_ruby_code(delimiter)]
when QUOTED_ATTR_REGEX
# Value is quoted (static)
@line = $'
attributes << [:html, :attr, $1, [:slim, :interpolate, parse_quoted_attribute($2)]]
when CODE_ATTR_REGEX
# Value is ruby code
@line = $'
escape = @line[0] != ?=
@line.slice!(0) unless escape
name = $1
value = parse_ruby_code(delimiter)
# Remove attribute wrapper which doesn't belong to the ruby code
# e.g id=[hash[:a] + hash[:b]]
value = value[1..-2] if value =~ DELIMITER_REGEX &&
DELIMITERS[$&] == value[-1, 1]
syntax_error!('Invalid empty attribute') if value.empty?
attributes << [:slim, :attr, name, escape, value]
else
break unless delimiter
case @line
when boolean_attr_regex
# Boolean attribute
@line = $'
attributes << [:slim, :attr, $1, false, 'true']
when end_regex
# Find ending delimiter
@line = $'
break
else
# Found something where an attribute should be
@line.lstrip!
syntax_error!('Expected attribute') unless @line.empty?
# Attributes span multiple lines
@stacks.last << [:newline]
orig_line, lineno = @orig_line, @lineno
next_line || syntax_error!("Expected closing delimiter #{delimiter}",
:orig_line => orig_line,
:lineno => lineno,
:column => orig_line.size)
end
end
end
attributes
end
def parse_ruby_code(outer_delimiter)
code, count, delimiter, close_delimiter = '', 0, nil, nil
# Attribute ends with space or attribute delimiter
end_regex = /\A[\s#{Regexp.escape outer_delimiter.to_s}]/
until @line.empty? || (count == 0 && @line =~ end_regex)
if count > 0
if @line[0] == delimiter[0]
count += 1
elsif @line[0] == close_delimiter[0]
count -= 1
end
elsif @line =~ DELIMITER_REGEX
count = 1
delimiter, close_delimiter = $&, DELIMITERS[$&]
end
code << @line.slice!(0)
end
syntax_error!("Expected closing delimiter #{close_delimiter}") if count != 0
code
end
def parse_quoted_attribute(quote)
value, count = '', 0
until @line.empty? || (count == 0 && @line[0] == quote[0])
if count > 0
if @line[0] == ?{
count += 1
elsif @line[0] == ?}
count -= 1
end
elsif @line =~ /\A#\{/
value << @line.slice!(0)
count = 1
end
value << @line.slice!(0)
end
syntax_error!("Expected closing brace }") if count != 0
@line.slice!(0)
value
end
# Helper for raising exceptions
def syntax_error!(message, args = {})
args[:orig_line] ||= @orig_line
args[:line] ||= @line
args[:lineno] ||= @lineno
args[:column] ||= args[:orig_line] && args[:line] ?
args[:orig_line].size - args[:line].size : 0
raise SyntaxError.new(message, options[:file],
args[:orig_line], args[:lineno], args[:column])
end
end
end
parser: minor cleanup
module Slim
# Parses Slim code and transforms it to a Temple expression
# @api private
class Parser
include Temple::Mixins::Options
set_default_options :tabsize => 4,
:encoding => 'utf-8',
:shortcut => {
'#' => 'id',
'.' => 'class'
}
class SyntaxError < StandardError
attr_reader :error, :file, :line, :lineno, :column
def initialize(error, file, line, lineno, column)
@error = error
@file = file || '(__TEMPLATE__)'
@line = line.to_s
@lineno = lineno
@column = column
end
def to_s
line = @line.strip
column = @column + line.size - @line.size
%{#{error}
#{file}, Line #{lineno}
#{line}
#{' ' * column}^
}
end
end
def initialize(options = {})
super
@tab = ' ' * @options[:tabsize]
@shortcut = {}
@options[:shortcut].each do |k,v|
@shortcut[k] = if v =~ /\A([^\s]+)\s+([^\s]+)\Z/
[$1, $2]
else
[@options[:default_tag], v]
end
end
shortcut = "[#{Regexp.escape @shortcut.keys.join}]"
@shortcut_regex = /\A(#{shortcut})(\w[\w-]*\w|\w+)/
@tag_regex = /\A(?:#{shortcut}|\*(?=[^\s]+)|(\w[\w:-]*\w|\w+))/
end
# Compile string to Temple expression
#
# @param [String] str Slim code
# @return [Array] Temple expression representing the code]]
def call(str)
# Set string encoding if option is set
if options[:encoding] && str.respond_to?(:encoding)
old_enc = str.encoding
str = str.dup if str.frozen?
str.force_encoding(options[:encoding])
# Fall back to old encoding if new encoding is invalid
str.force_encoding(old_enc) unless str.valid_encoding?
end
result = [:multi]
reset(str.split(/\r?\n/), [result])
parse_line while next_line
reset
result
end
private
DELIMITERS = {
'(' => ')',
'[' => ']',
'{' => '}',
}.freeze
DELIMITER_REGEX = /\A[#{Regexp.escape DELIMITERS.keys.join}]/
ATTR_NAME = '\A\s*(\w[:\w-]*)'
QUOTED_ATTR_REGEX = /#{ATTR_NAME}=("|')/
CODE_ATTR_REGEX = /#{ATTR_NAME}=/
def reset(lines = nil, stacks = nil)
# Since you can indent however you like in Slim, we need to keep a list
# of how deeply indented you are. For instance, in a template like this:
#
# doctype # 0 spaces
# html # 0 spaces
# head # 1 space
# title # 4 spaces
#
# indents will then contain [0, 1, 4] (when it's processing the last line.)
#
# We uses this information to figure out how many steps we must "jump"
# out when we see an de-indented line.
@indents = [0]
# Whenever we want to output something, we'll *always* output it to the
# last stack in this array. So when there's a line that expects
# indentation, we simply push a new stack onto this array. When it
# processes the next line, the content will then be outputted into that
# stack.
@stacks = stacks
@lineno = 0
@lines = lines
@line = @orig_line = nil
end
def next_line
if @lines.empty?
@orig_line = @line = nil
else
@orig_line = @lines.shift
@lineno += 1
@line = @orig_line.dup
end
end
def get_indent(line)
# Figure out the indentation. Kinda ugly/slow way to support tabs,
# but remember that this is only done at parsing time.
line[/\A[ \t]*/].gsub("\t", @tab).size
end
def parse_line
if @line =~ /\A\s*\Z/
@stacks.last << [:newline]
return
end
indent = get_indent(@line)
# Remove the indentation
@line.lstrip!
# If there's more stacks than indents, it means that the previous
# line is expecting this line to be indented.
expecting_indentation = @stacks.size > @indents.size
if indent > @indents.last
# This line was actually indented, so we'll have to check if it was
# supposed to be indented or not.
syntax_error!('Unexpected indentation') unless expecting_indentation
@indents << indent
else
# This line was *not* indented more than the line before,
# so we'll just forget about the stack that the previous line pushed.
@stacks.pop if expecting_indentation
# This line was deindented.
# Now we're have to go through the all the indents and figure out
# how many levels we've deindented.
while indent < @indents.last
@indents.pop
@stacks.pop
end
# This line's indentation happens lie "between" two other line's
# indentation:
#
# hello
# world
# this # <- This should not be possible!
syntax_error!('Malformed indentation') if indent != @indents.last
end
parse_line_indicators
end
def parse_line_indicators
case @line
when /\A\//
# Found a comment block.
if @line =~ %r{\A/!( ?)(.*)\Z}
# HTML comment
@stacks.last << [:html, :comment, [:slim, :text, parse_text_block($2, @indents.last + $1.size + 2)]]
elsif @line =~ %r{\A/\[\s*(.*?)\s*\]\s*\Z}
# HTML conditional comment
block = [:multi]
@stacks.last << [:html, :condcomment, $1, block]
@stacks << block
else
# Slim comment
parse_comment_block
end
when /\A([\|'])( ?)(.*)\Z/
# Found a text block.
trailing_ws = $1 == "'"
@stacks.last << [:slim, :text, parse_text_block($3, @indents.last + $2.size + 1)]
@stacks.last << [:static, ' '] if trailing_ws
when /\A-/
# Found a code block.
# We expect the line to be broken or the next line to be indented.
@line.slice!(0)
block = [:multi]
@stacks.last << [:slim, :control, parse_broken_line, block]
@stacks << block
when /\A=/
# Found an output block.
# We expect the line to be broken or the next line to be indented.
@line =~ /\A=(=?)('?)/
@line = $'
block = [:multi]
@stacks.last << [:slim, :output, $1.empty?, parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A(\w+):\s*\Z/
# Embedded template detected. It is treated as block.
@stacks.last << [:slim, :embedded, $1, parse_text_block]
when /\Adoctype\s+/i
# Found doctype declaration
@stacks.last << [:html, :doctype, $'.strip]
when @tag_regex
# Found a HTML tag.
@line = $' if $1
parse_tag($&)
else
syntax_error! 'Unknown line indicator'
end
@stacks.last << [:newline]
end
def parse_comment_block
while !@lines.empty? && (@lines.first =~ /\A\s*\Z/ || get_indent(@lines.first) > @indents.last)
next_line
@stacks.last << [:newline]
end
end
def parse_text_block(first_line = nil, text_indent = nil, in_tag = false)
result = [:multi]
if !first_line || first_line.empty?
text_indent = nil
else
result << [:slim, :interpolate, first_line]
end
empty_lines = 0
until @lines.empty?
if @lines.first =~ /\A\s*\Z/
next_line
result << [:newline]
empty_lines += 1 if text_indent
else
indent = get_indent(@lines.first)
break if indent <= @indents.last
if empty_lines > 0
result << [:slim, :interpolate, "\n" * empty_lines]
empty_lines = 0
end
next_line
@line.lstrip!
# The text block lines must be at least indented
# as deep as the first line.
offset = text_indent ? indent - text_indent : 0
if offset < 0
syntax_error!("Text line not indented deep enough.\n" +
"The first text line defines the necessary text indentation." +
(in_tag ? "\nAre you trying to nest a child tag in a tag containing text? Use | for the text block!" : ''))
end
result << [:newline] << [:slim, :interpolate, (text_indent ? "\n" : '') + (' ' * offset) + @line]
# The indentation of first line of the text block
# determines the text base indentation.
text_indent ||= indent
end
end
result
end
def parse_broken_line
broken_line = @line.strip
while broken_line =~ /[,\\]\Z/
next_line || syntax_error!('Unexpected end of file')
broken_line << "\n" << @line.strip
end
broken_line
end
def parse_tag(tag)
tag = [:slim, :tag, @shortcut[tag] ? @shortcut[tag][0] : tag, parse_attributes]
@stacks.last << tag
case @line
when /\A\s*:\s*/
# Block expansion
@line = $'
(@line =~ @tag_regex) || syntax_error!('Expected tag')
@line = $' if $1
content = [:multi]
tag << content
i = @stacks.size
@stacks << content
parse_tag($&)
@stacks.delete_at(i)
when /\A\s*=(=?)('?)/
# Handle output code
@line = $'
block = [:multi]
tag << [:slim, :output, $1 != '=', parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A\s*\//
# Closed tag. Do nothing
when /\A\s*\Z/
# Empty content
content = [:multi]
tag << content
@stacks << content
when /\A( ?)(.*)\Z/
# Text content
tag << [:slim, :text, parse_text_block($2, @orig_line.size - @line.size + $1.size, true)]
end
end
def parse_attributes
attributes = [:slim, :attrs]
# Find any shortcut attributes
while @line =~ @shortcut_regex
# The class/id attribute is :static instead of :slim :interpolate,
# because we don't want text interpolation in .class or #id shortcut
attributes << [:html, :attr, @shortcut[$1][1], [:static, $2]]
@line = $'
end
# Check to see if there is a delimiter right after the tag name
delimiter = nil
if @line =~ DELIMITER_REGEX
delimiter = DELIMITERS[$&]
@line.slice!(0)
end
if delimiter
boolean_attr_regex = /#{ATTR_NAME}(?=(\s|#{Regexp.escape delimiter}))/
end_regex = /\A\s*#{Regexp.escape delimiter}/
end
while true
case @line
when /\A\s*\*(?=[^\s]+)/
# Splat attribute
@line = $'
attributes << [:slim, :splat, parse_ruby_code(delimiter)]
when QUOTED_ATTR_REGEX
# Value is quoted (static)
@line = $'
attributes << [:html, :attr, $1, [:slim, :interpolate, parse_quoted_attribute($2)]]
when CODE_ATTR_REGEX
# Value is ruby code
@line = $'
escape = @line[0] != ?=
@line.slice!(0) unless escape
name = $1
value = parse_ruby_code(delimiter)
# Remove attribute wrapper which doesn't belong to the ruby code
# e.g id=[hash[:a] + hash[:b]]
value = value[1..-2] if value =~ DELIMITER_REGEX &&
DELIMITERS[$&] == value[-1, 1]
syntax_error!('Invalid empty attribute') if value.empty?
attributes << [:slim, :attr, name, escape, value]
else
break unless delimiter
case @line
when boolean_attr_regex
# Boolean attribute
@line = $'
attributes << [:slim, :attr, $1, false, 'true']
when end_regex
# Find ending delimiter
@line = $'
break
else
# Found something where an attribute should be
@line.lstrip!
syntax_error!('Expected attribute') unless @line.empty?
# Attributes span multiple lines
@stacks.last << [:newline]
orig_line, lineno = @orig_line, @lineno
next_line || syntax_error!("Expected closing delimiter #{delimiter}",
:orig_line => orig_line,
:lineno => lineno,
:column => orig_line.size)
end
end
end
attributes
end
def parse_ruby_code(outer_delimiter)
code, count, delimiter, close_delimiter = '', 0, nil, nil
# Attribute ends with space or attribute delimiter
end_regex = /\A[\s#{Regexp.escape outer_delimiter.to_s}]/
until @line.empty? || (count == 0 && @line =~ end_regex)
if count > 0
if @line[0] == delimiter[0]
count += 1
elsif @line[0] == close_delimiter[0]
count -= 1
end
elsif @line =~ DELIMITER_REGEX
count = 1
delimiter, close_delimiter = $&, DELIMITERS[$&]
end
code << @line.slice!(0)
end
syntax_error!("Expected closing delimiter #{close_delimiter}") if count != 0
code
end
def parse_quoted_attribute(quote)
value, count = '', 0
until @line.empty? || (count == 0 && @line[0] == quote[0])
if count > 0
if @line[0] == ?{
count += 1
elsif @line[0] == ?}
count -= 1
end
elsif @line =~ /\A#\{/
value << @line.slice!(0)
count = 1
end
value << @line.slice!(0)
end
syntax_error!("Expected closing brace }") if count != 0
@line.slice!(0)
value
end
# Helper for raising exceptions
def syntax_error!(message, args = {})
args[:orig_line] ||= @orig_line
args[:line] ||= @line
args[:lineno] ||= @lineno
args[:column] ||= args[:orig_line] && args[:line] ?
args[:orig_line].size - args[:line].size : 0
raise SyntaxError.new(message, options[:file],
args[:orig_line], args[:lineno], args[:column])
end
end
end
|
module Slim
# Parses Slim code and transforms it to a Temple expression
# @api private
class Parser < Temple::Parser
define_options :file,
:default_tag,
:escape_quoted_attrs => false,
:tabsize => 4,
:encoding => 'utf-8',
:shortcut => {
'#' => { :attr => 'id' },
'.' => { :attr => 'class' }
}
class SyntaxError < StandardError
attr_reader :error, :file, :line, :lineno, :column
def initialize(error, file, line, lineno, column)
@error = error
@file = file || '(__TEMPLATE__)'
@line = line.to_s
@lineno = lineno
@column = column
end
def to_s
line = @line.strip
column = @column + line.size - @line.size
%{#{error}
#{file}, Line #{lineno}, Column #{@column}
#{line}
#{' ' * column}^
}
end
end
def initialize(opts = {})
super
@tab = ' ' * options[:tabsize]
@tag_shortcut, @attr_shortcut = {}, {}
options[:shortcut].each do |k,v|
v = deprecated_shortcut(v) if String === v
raise ArgumentError, 'Shortcut requires :tag and/or :attr' unless (v[:attr] || v[:tag]) && (v.keys - [:attr, :tag]).empty?
@tag_shortcut[k] = v[:tag] || options[:default_tag]
if v.include?(:attr)
@attr_shortcut[k] = v[:attr]
raise ArgumentError, 'You can only use special characters for attribute shortcuts' if k =~ /(?:\w|-)/
end
end
@attr_shortcut_regex = /\A(#{shortcut_regex @attr_shortcut})(\w(?:\w|-)*\w|\w+)/
@tag_regex = /\A(?:#{shortcut_regex @tag_shortcut}|\*(?=[^\s]+)|(\w(?:\w|:|-)*\w|\w+))/
end
# Compile string to Temple expression
#
# @param [String] str Slim code
# @return [Array] Temple expression representing the code]]
def call(str)
str = remove_bom(set_encoding(str))
result = [:multi]
reset(str.split(/\r?\n/), [result])
parse_line while next_line
reset
result
end
protected
DELIMITERS = {
'(' => ')',
'[' => ']',
'{' => '}',
}.freeze
DELIMITER_REGEX = /\A[#{Regexp.escape DELIMITERS.keys.join}]/
ATTR_NAME = '\A\s*(\w(?:\w|:|-)*)'
QUOTED_ATTR_REGEX = /#{ATTR_NAME}=(=?)("|')/
CODE_ATTR_REGEX = /#{ATTR_NAME}=(=?)/
# Convert deprecated string shortcut to hash
def deprecated_shortcut(v)
warn "Slim :shortcut string values are deprecated, use hash like { '#' => { :tag => 'div', :attr => 'id' } }"
if v =~ /\A([^\s]+)\s+([^\s]+)\Z/
{ :tag => $1, :attr => $2 }
else
{ :attr => v }
end
end
# Compile shortcut regular expression
def shortcut_regex(shortcut)
shortcut.map { |k,v| Regexp.escape(k) }.join('|')
end
# Set string encoding if option is set
def set_encoding(s)
if options[:encoding] && s.respond_to?(:encoding)
old_enc = s.encoding
s = s.dup if s.frozen?
s.force_encoding(options[:encoding])
# Fall back to old encoding if new encoding is invalid
s.force_encoding(old_enc) unless s.valid_encoding?
end
s
end
# Remove unicode byte order mark from string
def remove_bom(s)
if s.respond_to?(:encoding)
if s.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?/
s.gsub(Regexp.new("\\A\uFEFF".encode(s.encoding.name)), '')
else
s
end
else
s.gsub(/\A\xEF\xBB\xBF/, '')
end
end
def reset(lines = nil, stacks = nil)
# Since you can indent however you like in Slim, we need to keep a list
# of how deeply indented you are. For instance, in a template like this:
#
# doctype # 0 spaces
# html # 0 spaces
# head # 1 space
# title # 4 spaces
#
# indents will then contain [0, 1, 4] (when it's processing the last line.)
#
# We uses this information to figure out how many steps we must "jump"
# out when we see an de-indented line.
@indents = [0]
# Whenever we want to output something, we'll *always* output it to the
# last stack in this array. So when there's a line that expects
# indentation, we simply push a new stack onto this array. When it
# processes the next line, the content will then be outputted into that
# stack.
@stacks = stacks
@lineno = 0
@lines = lines
@line = @orig_line = nil
end
def next_line
if @lines.empty?
@orig_line = @line = nil
else
@orig_line = @lines.shift
@lineno += 1
@line = @orig_line.dup
end
end
def get_indent(line)
# Figure out the indentation. Kinda ugly/slow way to support tabs,
# but remember that this is only done at parsing time.
line[/\A[ \t]*/].gsub("\t", @tab).size
end
def parse_line
if @line =~ /\A\s*\Z/
@stacks.last << [:newline]
return
end
indent = get_indent(@line)
# Remove the indentation
@line.lstrip!
# If there's more stacks than indents, it means that the previous
# line is expecting this line to be indented.
expecting_indentation = @stacks.size > @indents.size
if indent > @indents.last
# This line was actually indented, so we'll have to check if it was
# supposed to be indented or not.
syntax_error!('Unexpected indentation') unless expecting_indentation
@indents << indent
else
# This line was *not* indented more than the line before,
# so we'll just forget about the stack that the previous line pushed.
@stacks.pop if expecting_indentation
# This line was deindented.
# Now we're have to go through the all the indents and figure out
# how many levels we've deindented.
while indent < @indents.last
@indents.pop
@stacks.pop
end
# This line's indentation happens lie "between" two other line's
# indentation:
#
# hello
# world
# this # <- This should not be possible!
syntax_error!('Malformed indentation') if indent != @indents.last
end
parse_line_indicators
end
def parse_line_indicators
case @line
when /\A\/!( ?)/
# HTML comment
@stacks.last << [:html, :comment, [:slim, :text, parse_text_block($', @indents.last + $1.size + 2)]]
when /\A\/\[\s*(.*?)\s*\]\s*\Z/
# HTML conditional comment
block = [:multi]
@stacks.last << [:html, :condcomment, $1, block]
@stacks << block
when /\A\//
# Slim comment
parse_comment_block
when /\A([\|'])( ?)/
# Found a text block.
trailing_ws = $1 == "'"
@stacks.last << [:slim, :text, parse_text_block($', @indents.last + $2.size + 1)]
@stacks.last << [:static, ' '] if trailing_ws
when /\A</
# Inline html
# @stacks.last << parse_text_block(@line, @indents.last + 1)
block = [:multi]
@stacks.last << [:multi, [:slim, :interpolate, @line], block]
@stacks << block
when /\A-/
# Found a code block.
# We expect the line to be broken or the next line to be indented.
@line.slice!(0)
block = [:multi]
@stacks.last << [:slim, :control, parse_broken_line, block]
@stacks << block
when /\A=/
# Found an output block.
# We expect the line to be broken or the next line to be indented.
@line =~ /\A=(=?)('?)/
@line = $'
block = [:multi]
@stacks.last << [:slim, :output, $1.empty?, parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A(\w+):\s*\Z/
# Embedded template detected. It is treated as block.
@stacks.last << [:slim, :embedded, $1, parse_text_block]
when /\Adoctype\s+/i
# Found doctype declaration
@stacks.last << [:html, :doctype, $'.strip]
when @tag_regex
# Found a HTML tag.
@line = $' if $1
parse_tag($&)
else
syntax_error! 'Unknown line indicator'
end
@stacks.last << [:newline]
end
def parse_comment_block
while !@lines.empty? && (@lines.first =~ /\A\s*\Z/ || get_indent(@lines.first) > @indents.last)
next_line
@stacks.last << [:newline]
end
end
def parse_text_block(first_line = nil, text_indent = nil, in_tag = false)
result = [:multi]
if !first_line || first_line.empty?
text_indent = nil
else
result << [:slim, :interpolate, first_line]
end
empty_lines = 0
until @lines.empty?
if @lines.first =~ /\A\s*\Z/
next_line
result << [:newline]
empty_lines += 1 if text_indent
else
indent = get_indent(@lines.first)
break if indent <= @indents.last
if empty_lines > 0
result << [:slim, :interpolate, "\n" * empty_lines]
empty_lines = 0
end
next_line
@line.lstrip!
# The text block lines must be at least indented
# as deep as the first line.
offset = text_indent ? indent - text_indent : 0
if offset < 0
syntax_error!("Text line not indented deep enough.\n" +
"The first text line defines the necessary text indentation." +
(in_tag ? "\nAre you trying to nest a child tag in a tag containing text? Use | for the text block!" : ''))
end
result << [:newline] << [:slim, :interpolate, (text_indent ? "\n" : '') + (' ' * offset) + @line]
# The indentation of first line of the text block
# determines the text base indentation.
text_indent ||= indent
end
end
result
end
def parse_broken_line
broken_line = @line.strip
while broken_line =~ /[,\\]\Z/
expect_next_line
broken_line << "\n" << @line
end
broken_line
end
def parse_tag(tag)
if @tag_shortcut[tag]
@line.slice!(0, tag.size) unless @attr_shortcut[tag]
tag = @tag_shortcut[tag]
end
tag = [:html, :tag, tag, parse_attributes]
@stacks.last << tag
case @line
when /\A\s*:\s*/
# Block expansion
@line = $'
(@line =~ @tag_regex) || syntax_error!('Expected tag')
@line = $' if $1
content = [:multi]
tag << content
i = @stacks.size
@stacks << content
parse_tag($&)
@stacks.delete_at(i)
when /\A\s*=(=?)('?)/
# Handle output code
@line = $'
block = [:multi]
tag << [:slim, :output, $1 != '=', parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A\s*\//
# Closed tag. Do nothing
when /\A\s*\Z/
# Empty content
content = [:multi]
tag << content
@stacks << content
when /\A( ?)(.*)\Z/
# Text content
tag << [:slim, :text, parse_text_block($2, @orig_line.size - @line.size + $1.size, true)]
end
end
def parse_attributes
attributes = [:html, :attrs]
# Find any shortcut attributes
while @line =~ @attr_shortcut_regex
# The class/id attribute is :static instead of :slim :interpolate,
# because we don't want text interpolation in .class or #id shortcut
attributes << [:html, :attr, @attr_shortcut[$1], [:static, $2]]
@line = $'
end
# Check to see if there is a delimiter right after the tag name
delimiter = nil
if @line =~ DELIMITER_REGEX
delimiter = DELIMITERS[$&]
@line.slice!(0)
end
if delimiter
boolean_attr_regex = /#{ATTR_NAME}(?=(\s|#{Regexp.escape delimiter}|\Z))/
end_regex = /\A\s*#{Regexp.escape delimiter}/
end
while true
case @line
when /\A\s*\*(?=[^\s]+)/
# Splat attribute
@line = $'
attributes << [:slim, :splat, parse_ruby_code(delimiter)]
when QUOTED_ATTR_REGEX
# Value is quoted (static)
@line = $'
attributes << [:html, :attr, $1,
[:escape, options[:escape_quoted_attrs] && $2.empty?,
[:slim, :interpolate, parse_quoted_attribute($3)]]]
when CODE_ATTR_REGEX
# Value is ruby code
@line = $'
name = $1
escape = $2.empty?
value = parse_ruby_code(delimiter)
# Remove attribute wrapper which doesn't belong to the ruby code
# e.g id=[hash[:a] + hash[:b]]
value = value[1..-2] if value =~ DELIMITER_REGEX &&
DELIMITERS[$&] == value[-1, 1]
syntax_error!('Invalid empty attribute') if value.empty?
attributes << [:html, :attr, name, [:slim, :attrvalue, escape, value]]
else
break unless delimiter
case @line
when boolean_attr_regex
# Boolean attribute
@line = $'
attributes << [:html, :attr, $1, [:slim, :attrvalue, false, 'true']]
when end_regex
# Find ending delimiter
@line = $'
break
else
# Found something where an attribute should be
@line.lstrip!
syntax_error!('Expected attribute') unless @line.empty?
# Attributes span multiple lines
@stacks.last << [:newline]
syntax_error!("Expected closing delimiter #{delimiter}") if @lines.empty?
next_line
end
end
end
attributes
end
def parse_ruby_code(outer_delimiter)
code, count, delimiter, close_delimiter = '', 0, nil, nil
# Attribute ends with space or attribute delimiter
end_regex = /\A[\s#{Regexp.escape outer_delimiter.to_s}]/
until @line.empty? || (count == 0 && @line =~ end_regex)
if @line =~ /\A[,\\]\Z/
code << @line << "\n"
expect_next_line
else
if count > 0
if @line[0] == delimiter[0]
count += 1
elsif @line[0] == close_delimiter[0]
count -= 1
end
elsif @line =~ DELIMITER_REGEX
count = 1
delimiter, close_delimiter = $&, DELIMITERS[$&]
end
code << @line.slice!(0)
end
end
syntax_error!("Expected closing delimiter #{close_delimiter}") if count != 0
code
end
def parse_quoted_attribute(quote)
value, count = '', 0
until @line.empty? || (count == 0 && @line[0] == quote[0])
if @line =~ /\A\\\Z/
value << ' '
expect_next_line
else
if count > 0
if @line[0] == ?{
count += 1
elsif @line[0] == ?}
count -= 1
end
elsif @line =~ /\A#\{/
value << @line.slice!(0)
count = 1
end
value << @line.slice!(0)
end
end
syntax_error!("Expected closing brace }") if count != 0
syntax_error!("Expected closing quote #{quote}") if @line[0] != quote[0]
@line.slice!(0)
value
end
# Helper for raising exceptions
def syntax_error!(message)
raise SyntaxError.new(message, options[:file], @orig_line, @lineno,
@orig_line && @line ? @orig_line.size - @line.size : 0)
end
def expect_next_line
next_line || syntax_error!('Unexpected end of file')
@line.strip!
end
end
end
Parser: use \p{Word} to support unicode (Issue #212)
# coding: utf-8
module Slim
# Parses Slim code and transforms it to a Temple expression
# @api private
class Parser < Temple::Parser
define_options :file,
:default_tag,
:escape_quoted_attrs => false,
:tabsize => 4,
:encoding => 'utf-8',
:shortcut => {
'#' => { :attr => 'id' },
'.' => { :attr => 'class' }
}
class SyntaxError < StandardError
attr_reader :error, :file, :line, :lineno, :column
def initialize(error, file, line, lineno, column)
@error = error
@file = file || '(__TEMPLATE__)'
@line = line.to_s
@lineno = lineno
@column = column
end
def to_s
line = @line.strip
column = @column + line.size - @line.size
%{#{error}
#{file}, Line #{lineno}, Column #{@column}
#{line}
#{' ' * column}^
}
end
end
def initialize(opts = {})
super
@tab = ' ' * options[:tabsize]
@tag_shortcut, @attr_shortcut = {}, {}
options[:shortcut].each do |k,v|
v = deprecated_shortcut(v) if String === v
raise ArgumentError, 'Shortcut requires :tag and/or :attr' unless (v[:attr] || v[:tag]) && (v.keys - [:attr, :tag]).empty?
@tag_shortcut[k] = v[:tag] || options[:default_tag]
if v.include?(:attr)
@attr_shortcut[k] = v[:attr]
raise ArgumentError, 'You can only use special characters for attribute shortcuts' if k =~ /(#{WORD_RE}|-)/
end
end
@attr_shortcut_re = /\A(#{shortcut_re @attr_shortcut})(#{WORD_RE}(?:#{WORD_RE}|-)*#{WORD_RE}|#{WORD_RE}+)/
@tag_re = /\A(?:#{shortcut_re @tag_shortcut}|\*(?=[^\s]+)|(#{WORD_RE}(?:#{WORD_RE}|:|-)*#{WORD_RE}|#{WORD_RE}+))/
end
# Compile string to Temple expression
#
# @param [String] str Slim code
# @return [Array] Temple expression representing the code]]
def call(str)
str = remove_bom(set_encoding(str))
result = [:multi]
reset(str.split(/\r?\n/), [result])
parse_line while next_line
reset
result
end
protected
DELIMITERS = {
'(' => ')',
'[' => ']',
'{' => '}',
}.freeze
WORD_RE = ''.respond_to?(:encoding) ? '\p{Word}' : '\w'
DELIMITER_RE = /\A[#{Regexp.escape DELIMITERS.keys.join}]/
ATTR_NAME = "\\A\\s*(#{WORD_RE}(?:#{WORD_RE}|:|-)*)"
QUOTED_ATTR_RE = /#{ATTR_NAME}=(=?)("|')/
CODE_ATTR_RE = /#{ATTR_NAME}=(=?)/
# Convert deprecated string shortcut to hash
def deprecated_shortcut(v)
warn "Slim :shortcut string values are deprecated, use hash like { '#' => { :tag => 'div', :attr => 'id' } }"
if v =~ /\A([^\s]+)\s+([^\s]+)\Z/
{ :tag => $1, :attr => $2 }
else
{ :attr => v }
end
end
# Compile shortcut regular expression
def shortcut_re(shortcut)
shortcut.map { |k,v| Regexp.escape(k) }.join('|')
end
# Set string encoding if option is set
def set_encoding(s)
if options[:encoding] && s.respond_to?(:encoding)
old_enc = s.encoding
s = s.dup if s.frozen?
s.force_encoding(options[:encoding])
# Fall back to old encoding if new encoding is invalid
s.force_encoding(old_enc) unless s.valid_encoding?
end
s
end
# Remove unicode byte order mark from string
def remove_bom(s)
if s.respond_to?(:encoding)
if s.encoding.name =~ /^UTF-(8|16|32)(BE|LE)?/
s.gsub(Regexp.new("\\A\uFEFF".encode(s.encoding.name)), '')
else
s
end
else
s.gsub(/\A\xEF\xBB\xBF/, '')
end
end
def reset(lines = nil, stacks = nil)
# Since you can indent however you like in Slim, we need to keep a list
# of how deeply indented you are. For instance, in a template like this:
#
# doctype # 0 spaces
# html # 0 spaces
# head # 1 space
# title # 4 spaces
#
# indents will then contain [0, 1, 4] (when it's processing the last line.)
#
# We uses this information to figure out how many steps we must "jump"
# out when we see an de-indented line.
@indents = [0]
# Whenever we want to output something, we'll *always* output it to the
# last stack in this array. So when there's a line that expects
# indentation, we simply push a new stack onto this array. When it
# processes the next line, the content will then be outputted into that
# stack.
@stacks = stacks
@lineno = 0
@lines = lines
@line = @orig_line = nil
end
def next_line
if @lines.empty?
@orig_line = @line = nil
else
@orig_line = @lines.shift
@lineno += 1
@line = @orig_line.dup
end
end
def get_indent(line)
# Figure out the indentation. Kinda ugly/slow way to support tabs,
# but remember that this is only done at parsing time.
line[/\A[ \t]*/].gsub("\t", @tab).size
end
def parse_line
if @line =~ /\A\s*\Z/
@stacks.last << [:newline]
return
end
indent = get_indent(@line)
# Remove the indentation
@line.lstrip!
# If there's more stacks than indents, it means that the previous
# line is expecting this line to be indented.
expecting_indentation = @stacks.size > @indents.size
if indent > @indents.last
# This line was actually indented, so we'll have to check if it was
# supposed to be indented or not.
syntax_error!('Unexpected indentation') unless expecting_indentation
@indents << indent
else
# This line was *not* indented more than the line before,
# so we'll just forget about the stack that the previous line pushed.
@stacks.pop if expecting_indentation
# This line was deindented.
# Now we're have to go through the all the indents and figure out
# how many levels we've deindented.
while indent < @indents.last
@indents.pop
@stacks.pop
end
# This line's indentation happens lie "between" two other line's
# indentation:
#
# hello
# world
# this # <- This should not be possible!
syntax_error!('Malformed indentation') if indent != @indents.last
end
parse_line_indicators
end
def parse_line_indicators
case @line
when /\A\/!( ?)/
# HTML comment
@stacks.last << [:html, :comment, [:slim, :text, parse_text_block($', @indents.last + $1.size + 2)]]
when /\A\/\[\s*(.*?)\s*\]\s*\Z/
# HTML conditional comment
block = [:multi]
@stacks.last << [:html, :condcomment, $1, block]
@stacks << block
when /\A\//
# Slim comment
parse_comment_block
when /\A([\|'])( ?)/
# Found a text block.
trailing_ws = $1 == "'"
@stacks.last << [:slim, :text, parse_text_block($', @indents.last + $2.size + 1)]
@stacks.last << [:static, ' '] if trailing_ws
when /\A</
# Inline html
# @stacks.last << parse_text_block(@line, @indents.last + 1)
block = [:multi]
@stacks.last << [:multi, [:slim, :interpolate, @line], block]
@stacks << block
when /\A-/
# Found a code block.
# We expect the line to be broken or the next line to be indented.
@line.slice!(0)
block = [:multi]
@stacks.last << [:slim, :control, parse_broken_line, block]
@stacks << block
when /\A=/
# Found an output block.
# We expect the line to be broken or the next line to be indented.
@line =~ /\A=(=?)('?)/
@line = $'
block = [:multi]
@stacks.last << [:slim, :output, $1.empty?, parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A(\w+):\s*\Z/
# Embedded template detected. It is treated as block.
@stacks.last << [:slim, :embedded, $1, parse_text_block]
when /\Adoctype\s+/i
# Found doctype declaration
@stacks.last << [:html, :doctype, $'.strip]
when @tag_re
# Found a HTML tag.
@line = $' if $1
parse_tag($&)
else
syntax_error! 'Unknown line indicator'
end
@stacks.last << [:newline]
end
def parse_comment_block
while !@lines.empty? && (@lines.first =~ /\A\s*\Z/ || get_indent(@lines.first) > @indents.last)
next_line
@stacks.last << [:newline]
end
end
def parse_text_block(first_line = nil, text_indent = nil, in_tag = false)
result = [:multi]
if !first_line || first_line.empty?
text_indent = nil
else
result << [:slim, :interpolate, first_line]
end
empty_lines = 0
until @lines.empty?
if @lines.first =~ /\A\s*\Z/
next_line
result << [:newline]
empty_lines += 1 if text_indent
else
indent = get_indent(@lines.first)
break if indent <= @indents.last
if empty_lines > 0
result << [:slim, :interpolate, "\n" * empty_lines]
empty_lines = 0
end
next_line
@line.lstrip!
# The text block lines must be at least indented
# as deep as the first line.
offset = text_indent ? indent - text_indent : 0
if offset < 0
syntax_error!("Text line not indented deep enough.\n" +
"The first text line defines the necessary text indentation." +
(in_tag ? "\nAre you trying to nest a child tag in a tag containing text? Use | for the text block!" : ''))
end
result << [:newline] << [:slim, :interpolate, (text_indent ? "\n" : '') + (' ' * offset) + @line]
# The indentation of first line of the text block
# determines the text base indentation.
text_indent ||= indent
end
end
result
end
def parse_broken_line
broken_line = @line.strip
while broken_line =~ /[,\\]\Z/
expect_next_line
broken_line << "\n" << @line
end
broken_line
end
def parse_tag(tag)
if @tag_shortcut[tag]
@line.slice!(0, tag.size) unless @attr_shortcut[tag]
tag = @tag_shortcut[tag]
end
tag = [:html, :tag, tag, parse_attributes]
@stacks.last << tag
case @line
when /\A\s*:\s*/
# Block expansion
@line = $'
(@line =~ @tag_re) || syntax_error!('Expected tag')
@line = $' if $1
content = [:multi]
tag << content
i = @stacks.size
@stacks << content
parse_tag($&)
@stacks.delete_at(i)
when /\A\s*=(=?)('?)/
# Handle output code
@line = $'
block = [:multi]
tag << [:slim, :output, $1 != '=', parse_broken_line, block]
@stacks.last << [:static, ' '] unless $2.empty?
@stacks << block
when /\A\s*\//
# Closed tag. Do nothing
when /\A\s*\Z/
# Empty content
content = [:multi]
tag << content
@stacks << content
when /\A( ?)(.*)\Z/
# Text content
tag << [:slim, :text, parse_text_block($2, @orig_line.size - @line.size + $1.size, true)]
end
end
def parse_attributes
attributes = [:html, :attrs]
# Find any shortcut attributes
while @line =~ @attr_shortcut_re
# The class/id attribute is :static instead of :slim :interpolate,
# because we don't want text interpolation in .class or #id shortcut
attributes << [:html, :attr, @attr_shortcut[$1], [:static, $2]]
@line = $'
end
# Check to see if there is a delimiter right after the tag name
delimiter = nil
if @line =~ DELIMITER_RE
delimiter = DELIMITERS[$&]
@line.slice!(0)
end
if delimiter
boolean_attr_re = /#{ATTR_NAME}(?=(\s|#{Regexp.escape delimiter}|\Z))/
end_re = /\A\s*#{Regexp.escape delimiter}/
end
while true
case @line
when /\A\s*\*(?=[^\s]+)/
# Splat attribute
@line = $'
attributes << [:slim, :splat, parse_ruby_code(delimiter)]
when QUOTED_ATTR_RE
# Value is quoted (static)
@line = $'
attributes << [:html, :attr, $1,
[:escape, options[:escape_quoted_attrs] && $2.empty?,
[:slim, :interpolate, parse_quoted_attribute($3)]]]
when CODE_ATTR_RE
# Value is ruby code
@line = $'
name = $1
escape = $2.empty?
value = parse_ruby_code(delimiter)
# Remove attribute wrapper which doesn't belong to the ruby code
# e.g id=[hash[:a] + hash[:b]]
value = value[1..-2] if value =~ DELIMITER_RE &&
DELIMITERS[$&] == value[-1, 1]
syntax_error!('Invalid empty attribute') if value.empty?
attributes << [:html, :attr, name, [:slim, :attrvalue, escape, value]]
else
break unless delimiter
case @line
when boolean_attr_re
# Boolean attribute
@line = $'
attributes << [:html, :attr, $1, [:slim, :attrvalue, false, 'true']]
when end_re
# Find ending delimiter
@line = $'
break
else
# Found something where an attribute should be
@line.lstrip!
syntax_error!('Expected attribute') unless @line.empty?
# Attributes span multiple lines
@stacks.last << [:newline]
syntax_error!("Expected closing delimiter #{delimiter}") if @lines.empty?
next_line
end
end
end
attributes
end
def parse_ruby_code(outer_delimiter)
code, count, delimiter, close_delimiter = '', 0, nil, nil
# Attribute ends with space or attribute delimiter
end_re = /\A[\s#{Regexp.escape outer_delimiter.to_s}]/
until @line.empty? || (count == 0 && @line =~ end_re)
if @line =~ /\A[,\\]\Z/
code << @line << "\n"
expect_next_line
else
if count > 0
if @line[0] == delimiter[0]
count += 1
elsif @line[0] == close_delimiter[0]
count -= 1
end
elsif @line =~ DELIMITER_RE
count = 1
delimiter, close_delimiter = $&, DELIMITERS[$&]
end
code << @line.slice!(0)
end
end
syntax_error!("Expected closing delimiter #{close_delimiter}") if count != 0
code
end
def parse_quoted_attribute(quote)
value, count = '', 0
until @line.empty? || (count == 0 && @line[0] == quote[0])
if @line =~ /\A\\\Z/
value << ' '
expect_next_line
else
if count > 0
if @line[0] == ?{
count += 1
elsif @line[0] == ?}
count -= 1
end
elsif @line =~ /\A#\{/
value << @line.slice!(0)
count = 1
end
value << @line.slice!(0)
end
end
syntax_error!("Expected closing brace }") if count != 0
syntax_error!("Expected closing quote #{quote}") if @line[0] != quote[0]
@line.slice!(0)
value
end
# Helper for raising exceptions
def syntax_error!(message)
raise SyntaxError.new(message, options[:file], @orig_line, @lineno,
@orig_line && @line ? @orig_line.size - @line.size : 0)
end
def expect_next_line
next_line || syntax_error!('Unexpected end of file')
@line.strip!
end
end
end
|
class Sliver::Path
def initialize(http_method, string)
@http_method = http_method.to_s.upcase
@string = normalised_path string
end
def matches?(environment)
method = environment['REQUEST_METHOD']
path = normalised_path environment['PATH_INFO']
http_method == method && path[string_to_regexp]
end
def to_params(environment)
return {} unless matches?(environment)
path = normalised_path environment['PATH_INFO']
keys = string.to_s.scan(/:([\w-]+)/i).flatten
values = path.scan(string_to_regexp).flatten
hash = {}
keys.each_with_index { |key, index| hash[key] = values[index] }
hash
end
private
attr_reader :http_method, :string
def normalised_path(string)
string == '' ? '/' : string
end
def string_to_regexp
@string_to_regexp ||= Regexp.new(
"\\A" + string.to_s.gsub(/:[\w-]+/, "([\\w-]+)") + "\\z"
)
end
end
Smarter, cleaner implementation of path params.
class Sliver::Path
def initialize(http_method, string)
@http_method = http_method.to_s.upcase
@string = normalised_path string
end
def matches?(environment)
method = environment['REQUEST_METHOD']
path = normalised_path environment['PATH_INFO']
http_method == method && path[string_to_regexp]
end
def to_params(environment)
return {} unless matches?(environment)
path = normalised_path environment['PATH_INFO']
values = path.scan(string_to_regexp).flatten
string_keys.each_with_index.inject({}) do |hash, (key, index)|
hash[key] = values[index]
hash
end
end
private
attr_reader :http_method, :string
def normalised_path(string)
string == '' ? '/' : string
end
def string_keys
@string_keys ||= string.to_s.scan(/:([\w-]+)/i).flatten
end
def string_to_regexp
@string_to_regexp ||= Regexp.new(
"\\A" + string.to_s.gsub(/:[\w-]+/, "([\\w-]+)") + "\\z"
)
end
end
|
require 'str_dn_2030/version'
require 'str_dn_2030/input'
require 'socket'
require 'thread'
module StrDn2030
class ArefProxy
def initialize(parent, name)
@parent = parent
@set = :"#{name}_set"
@get = :"#{name}_get"
end
def [](*args)
@parent.__send__ @get, *args
end
def []=(*args)
@parent.__send__ @set, *args
end
end
class Remote
VOLUME_STATUS_REGEXP = /\x02\x06\xA8\x92(?<zone>.)(?<type>.)(?<volume>..)./nm
STATUS_REGEXP = /\x02\x07\xA8\x82(?<zone>.)(?<ch>.)(?<ch2>.)(?<flag1>.)(?<unused>.)./nm
INPUT_REGEXP = /(?<index>.)(?<audio>.)(?<video>.)(?<icon>.)(?<preset_name>.{8})(?<name>.{8})(?<skip>.)/mn
INPUTLIST_REGEXP = Regexp.new(
'\x02\xD7\xA8\x8B(?<zone>.)' \
"(?<inputs>(?:#{INPUT_REGEXP}){10})" \
'\x00\x00.',
Regexp::MULTILINE,
'n'
)
def initialize(host, port = 33335)
@host, @port = host, port
@socket = nil
@receiver_thread = nil
@lock = Mutex.new
@hook = nil
@listeners = {}
@listeners_lock = Mutex.new
@inputs = {}
@volumes_proxy = ArefProxy.new(self, 'volume')
@active_inputs_proxy = ArefProxy.new(self, 'active_input')
end
attr_reader :inputs, :host, :port
def inspect
"#<#{self.class.name}: #{@host}:#{@port}>"
end
def hook(&block)
if block_given?
@hook = block
else
@hook
end
end
def listen(type, filter = nil)
Thread.current[:strdn2030_filter] = filter
@listeners_lock.synchronize {
@listeners[type] ||= []
@listeners[type] << Thread.current
}
sleep
data = Thread.current[:strdn2030_data]
Thread.current[:strdn2030_data] = nil
data
end
def connected?
!!@socket
end
def connect
disconnect if connected?
@lock.synchronize do
@socket = TCPSocket.open(@host, @port)
@receiver_thread = Thread.new(@socket, &method(:receiver))
@receiver_thread.abort_on_exception = true
reload_input
self
end
end
def disconnect
@lock.synchronize do
return unless @socket
@socket.close unless @socket.closed?
@receiver_thread.kill if @receiver_thread.alive?
@socket = nil
@receiver_thread = nil
end
end
def status(zone_id = 0)
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x03\xA0\x82".b + zone + "\x00".b
listen(:status, zone_id)
end
def volume_get(zone_id, type = "\x03".b)
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x04\xa0\x92".b + zone + type + "\x00".b
listen(:volume, zone_id)
end
def volume_set(zone_id, other, type = "\x03".b)
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x06\xa0\x52" + zone + type + [other.to_i].pack('s>') + "\x00".b
listen(:success)
other
end
def volume
volume_get(0)
end
def volume=(other)
volume_set(0, other)
end
def volumes
@volumes_proxy
end
def active_input_get(zone_id)
current = status(zone_id)[:ch][:video]
inputs[zone_id][current] || self.reload_input.inputs[zone_id][current]
end
def active_input_set(zone_id, other)
new_input = if other.is_a?(Input)
other
else
inputs[zone_id][other] || self.reload_input.inputs[zone_id][other]
end
raise ArgumentError, "#{other.inspect} not exists" unless new_input
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x04\xa0\x42".b + zone + new_input.video + "\x00".b
listen(:success)
other
end
def active_inputs
@active_inputs_proxy
end
def active_input
active_input_get(0)
end
def active_input=(other)
active_input_set(0, other)
end
def reload_input
@inputs = {}
get_input_list(0, 0)
listen(:input_list, 0)
get_input_list(0, 1)
listen(:input_list, 0)
get_input_list(1, 0)
listen(:input_list, 1)
get_input_list(1, 1)
listen(:input_list, 1)
self
end
private
def get_input_list(zone_id, page = 0)
send("\x02\x04\xa0\x8b".b + zone_id.chr('ASCII-8BIT') + page.chr('ASCII-8BIT') + "\x00".b)
end
def send(str)
debug [:send, str]
@socket.write str
end
def receiver(socket)
buffer = "".b
hit = false
handle = lambda do |pattern, &handler|
if m = buffer.match(pattern)
hit = true
buffer.replace(m.pre_match + m.post_match)
handler[m]
end
end
while chunk = socket.read(1)
hit = false
buffer << chunk.b
handle.(STATUS_REGEXP, &method(:handle_status))
handle.(VOLUME_STATUS_REGEXP, &method(:handle_volume_status))
handle.(INPUTLIST_REGEXP, &method(:handle_input_list))
handle.(/\A\xFD/n) { delegate(:success) }
handle.(/\A\xFE/n) { delegate(:error) }
debug([:buffer_ramain, buffer]) if hit && !buffer.empty?
end
end
def delegate(name, subtype = nil, *args)
wake_listener name, subtype, *args
@hook.call(name, *args) if @hook
end
def wake_listener(type, subtype, data = nil)
@listeners_lock.synchronize do
@listeners[type] ||= []
@listeners[type].each do |th|
next if th[:strdn2030_filter] && !(th[:strdn2030_filter] === subtype)
th[:strdn2030_data] = data
th.wakeup
end
@listeners[type].clear
end
end
def handle_status(m)
flag1 = m['flag1'].ord
flags = {
raw: [m['flag1']].map{ |_| _.ord.to_s(2).rjust(8,' ') },
power: flag1[0] == 1,
mute: flag1[1] == 1,
headphone: flag1[2] == 1,
unknown_6: flag1[5],
}
data = {zone: m['zone'], ch: {audio: m['ch'], video: m['ch2']}, flags: flags}
delegate(:status, m['zone'].ord, data)
end
def handle_volume_status(m)
data = {zone: m['zone'], type: m['type'], volume: m['volume'].unpack('s>').first}
delegate(:volume, m['zone'].ord, data)
end
def handle_input_list(m)
#p m
inputs = {}
zone = m['zone'].ord
m['inputs'].scan(INPUT_REGEXP).each do |input_line|
idx, audio, video, icon, preset_name, name, skip_flags = input_line
input = inputs[audio] = inputs[video] = Input.new(
self,
zone,
idx,
audio,
video,
icon,
preset_name,
name,
skip_flags,
)
inputs[input.name] = input
end
(@inputs[zone] ||= {}).merge! inputs
delegate :input_list, zone, inputs
end
def debug(*args)
p(*args) if ENV["STR_DN_2030_DEBUG"]
end
end
end
Cache status
require 'str_dn_2030/version'
require 'str_dn_2030/input'
require 'socket'
require 'thread'
module StrDn2030
class ArefProxy
def initialize(parent, name)
@parent = parent
@set = :"#{name}_set"
@get = :"#{name}_get"
end
def [](*args)
@parent.__send__ @get, *args
end
def []=(*args)
@parent.__send__ @set, *args
end
end
class Remote
VOLUME_STATUS_REGEXP = /\x02\x06\xA8\x92(?<zone>.)(?<type>.)(?<volume>..)./nm
STATUS_REGEXP = /\x02\x07\xA8\x82(?<zone>.)(?<ch>.)(?<ch2>.)(?<flag1>.)(?<unused>.)./nm
INPUT_REGEXP = /(?<index>.)(?<audio>.)(?<video>.)(?<icon>.)(?<preset_name>.{8})(?<name>.{8})(?<skip>.)/mn
INPUTLIST_REGEXP = Regexp.new(
'\x02\xD7\xA8\x8B(?<zone>.)' \
"(?<inputs>(?:#{INPUT_REGEXP}){10})" \
'\x00\x00.',
Regexp::MULTILINE,
'n'
)
def initialize(host, port = 33335)
@host, @port = host, port
@socket = nil
@receiver_thread = nil
@lock = Mutex.new
@hook = nil
@listeners = {}
@listeners_lock = Mutex.new
@inputs = {}
@statuses = {}
@volumes_proxy = ArefProxy.new(self, 'volume')
@active_inputs_proxy = ArefProxy.new(self, 'active_input')
end
attr_reader :inputs, :host, :port
def inspect
"#<#{self.class.name}: #{@host}:#{@port}>"
end
def hook(&block)
if block_given?
@hook = block
else
@hook
end
end
def listen(type, filter = nil)
Thread.current[:strdn2030_filter] = filter
@listeners_lock.synchronize {
@listeners[type] ||= []
@listeners[type] << Thread.current
}
sleep
data = Thread.current[:strdn2030_data]
Thread.current[:strdn2030_data] = nil
data
end
def connected?
!!@socket
end
def connect
disconnect if connected?
@lock.synchronize do
@socket = TCPSocket.open(@host, @port)
@receiver_thread = Thread.new(@socket, &method(:receiver))
@receiver_thread.abort_on_exception = true
reload_input
self
end
end
def disconnect
@lock.synchronize do
return unless @socket
@socket.close unless @socket.closed?
@receiver_thread.kill if @receiver_thread.alive?
@socket = nil
@receiver_thread = nil
end
end
def reload
reload_input
@statuses = {}
self
end
def status(zone_id = 0)
@statuses[zone_id] || begin
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x03\xA0\x82".b + zone + "\x00".b
listen(:status, zone_id)
end
end
def volume_get(zone_id, type = "\x03".b)
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x04\xa0\x92".b + zone + type + "\x00".b
listen(:volume, zone_id)
end
def volume_set(zone_id, other, type = "\x03".b)
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x06\xa0\x52" + zone + type + [other.to_i].pack('s>') + "\x00".b
listen(:success)
other
end
def volume
volume_get(0)
end
def volume=(other)
volume_set(0, other)
end
def volumes
@volumes_proxy
end
def active_input_get(zone_id)
current = status(zone_id)[:ch][:video]
inputs[zone_id][current] || self.reload_input.inputs[zone_id][current]
end
def active_input_set(zone_id, other)
new_input = if other.is_a?(Input)
other
else
inputs[zone_id][other] || self.reload_input.inputs[zone_id][other]
end
raise ArgumentError, "#{other.inspect} not exists" unless new_input
zone = zone_id.chr('ASCII-8BIT')
send "\x02\x04\xa0\x42".b + zone + new_input.video + "\x00".b
listen(:success)
other
end
def active_inputs
@active_inputs_proxy
end
def active_input
active_input_get(0)
end
def active_input=(other)
active_input_set(0, other)
end
def reload_input
@inputs = {}
get_input_list(0, 0)
listen(:input_list, 0)
get_input_list(0, 1)
listen(:input_list, 0)
get_input_list(1, 0)
listen(:input_list, 1)
get_input_list(1, 1)
listen(:input_list, 1)
self
end
private
def get_input_list(zone_id, page = 0)
send("\x02\x04\xa0\x8b".b + zone_id.chr('ASCII-8BIT') + page.chr('ASCII-8BIT') + "\x00".b)
end
def send(str)
debug [:send, str]
@socket.write str
end
def receiver(socket)
buffer = "".b
hit = false
handle = lambda do |pattern, &handler|
if m = buffer.match(pattern)
hit = true
buffer.replace(m.pre_match + m.post_match)
handler[m]
end
end
while chunk = socket.read(1)
hit = false
buffer << chunk.b
handle.(STATUS_REGEXP, &method(:handle_status))
handle.(VOLUME_STATUS_REGEXP, &method(:handle_volume_status))
handle.(INPUTLIST_REGEXP, &method(:handle_input_list))
handle.(/\A\xFD/n) { delegate(:success) }
handle.(/\A\xFE/n) { delegate(:error) }
debug([:buffer_ramain, buffer]) if hit && !buffer.empty?
end
end
def delegate(name, subtype = nil, *args)
wake_listener name, subtype, *args
@hook.call(name, *args) if @hook
end
def wake_listener(type, subtype, data = nil)
@listeners_lock.synchronize do
@listeners[type] ||= []
@listeners[type].each do |th|
next if th[:strdn2030_filter] && !(th[:strdn2030_filter] === subtype)
th[:strdn2030_data] = data
th.wakeup
end
@listeners[type].clear
end
end
def handle_status(m)
flag1 = m['flag1'].ord
flags = {
raw: [m['flag1']].map{ |_| _.ord.to_s(2).rjust(8,' ') },
power: flag1[0] == 1,
mute: flag1[1] == 1,
headphone: flag1[2] == 1,
unknown_6: flag1[5],
}
data = @statuses[m['zone'].ord] = {
zone: m['zone'], ch: {audio: m['ch'], video: m['ch2']}, flags: flags
}
delegate(:status, m['zone'].ord, data)
end
def handle_volume_status(m)
data = {zone: m['zone'], type: m['type'], volume: m['volume'].unpack('s>').first}
delegate(:volume, m['zone'].ord, data)
end
def handle_input_list(m)
#p m
inputs = {}
zone = m['zone'].ord
m['inputs'].scan(INPUT_REGEXP).each do |input_line|
idx, audio, video, icon, preset_name, name, skip_flags = input_line
input = inputs[audio] = inputs[video] = Input.new(
self,
zone,
idx,
audio,
video,
icon,
preset_name,
name,
skip_flags,
)
inputs[input.name] = input
end
(@inputs[zone] ||= {}).merge! inputs
delegate :input_list, zone, inputs
end
def debug(*args)
p(*args) if ENV["STR_DN_2030_DEBUG"]
end
end
end
|
require 'openssl' # for decryption
require 'zlib' # for decompression
require 'base64' # for decoding
require 'rubygems' if defined?RUBY_VERSION && RUBY_VERSION =~ /^1.8/ # for requiring gem dependency in Ruby 1.8
require 'nokogiri' # for xml parsing
require 'strongboxio/version'
class Strongboxio
STRONGBOX_VERSION = 3
VERSION_LENGTH = 1
SALT_LENGTH = 64
IV_LENGTH = 16
KEY_LENGTH = 32
RANDOM_VALUE_LENGTH = 64
CIPHER = 'AES-256-CBC'
PAYLOAD_SCHEMA_VERSION = '2.4'
UNIX_EPOCH_IN_100NS_INTERVALS = 621355968000000000 # .NET time format: number of 100-nanosecond intervals since .NET epoch: January 1, 0001 at 00:00:00.000 (midnight)
attr_accessor :sbox
def self.decrypt(sbox_filename, password)
# open the xml file
f = File.open(sbox_filename)
data = Nokogiri::XML(f)
f.close
# extract the Data node
data = data.xpath('//Data').text
base64_error_msg = 'expected Base64 encoded byte string from the StrongBox.Payload.Data element of the xml of a Strongbox file'
raise "#{base64_error_msg}, but got nothing" if data.length == 0
raise "#{base64_error_msg}, but it does not resemble Base64" unless self.resembles_base64?(data)
data = Base64.decode64(data)
#version = data.getbyte(0) # ruby 1.9
version = data.bytes.to_a[0] # ruby 1.8 friendly
raise "expected version number #{STRONGBOX_VERSION}, but got #{version}" unless version == STRONGBOX_VERSION
salt = data.slice(1, SALT_LENGTH)
raise "expected salt length #{SALT_LENGTH}, but got #{salt.length}" unless salt.length == SALT_LENGTH
iv = data.bytes.to_a.slice((1+64), IV_LENGTH).pack('C*')
raise "expected iv length #{IV_LENGTH}, but got #{iv.length}" unless iv.length == IV_LENGTH
key = Digest::SHA256.digest(salt + password)
raise "expected key length #{KEY_LENGTH}, but got #{key.length}" unless key.length == KEY_LENGTH
# prepare for decryption
d = OpenSSL::Cipher.new(CIPHER)
d.decrypt
d.key = key
d.iv = iv
# decrypt the portion beyond the header
begin
data = '' << d.update(data.slice((VERSION_LENGTH+SALT_LENGTH+IV_LENGTH)..-1)) << d.final
rescue => e
raise "Error decrypting. You probably entered the password incorrectly. Specific error: #{e}"
end
# decompress the portion beyond the random value
#z = Zlib::Inflate.new
#z = Zlib::Inflate.new(-Zlib::BEST_COMPRESSION) # works for Strongbox
z = Zlib::Inflate.new(-Zlib::MAX_WBITS) # works for Strongbox!
#z = Zlib::Inflate.new(Zlib::MAX_WBITS) # works for roundtrip
data = z.inflate(data.slice(RANDOM_VALUE_LENGTH..-1))
z.finish
z.close
data
end
def self.render(decrypted_sbox, continue_despite_unexpected_payload_schema_version=false)
data = Nokogiri::XML(decrypted_sbox)
payload_schema_version = data.xpath('//Payload').xpath('SchemaVersion').text
unless payload_schema_version == PAYLOAD_SCHEMA_VERSION
raise "expected schema version #{PAYLOAD_SCHEMA_VERSION}, but got #{payload_schema_version}" unless continue_despite_unexpected_payload_schema_version
end
puts data.xpath('//Payload').xpath('PayloadInfo').xpath('MT').text
data.xpath('//PayloadData').each { |payload_data|
payload_data.xpath('//SBE').each { |entity|
puts
name = entity.xpath('N').text
puts "#{name}" if name.length > 0
description = entity.xpath('D').text
puts "#{description}" if description.length > 0
tags = entity.xpath('T').text
puts "#{tags}" if tags.length > 0
ce = entity.xpath('CE')
ce.xpath('TFE').each { |tfe|
name = tfe.xpath('N').text
puts "#{name}:" if name.length > 0
content = tfe.xpath('C').text
puts "#{content}" if content.length > 0
}
}
}
0
end
def initialize(decrypted_sbox, continue_despite_unexpected_payload_schema_version=false)
super()
data = Nokogiri::XML(decrypted_sbox)
payload_schema_version = data.xpath('//Payload').xpath('SchemaVersion').text
unless payload_schema_version == PAYLOAD_SCHEMA_VERSION
raise "expected schema version #{PAYLOAD_SCHEMA_VERSION}, but got #{payload_schema_version}" unless continue_despite_unexpected_payload_schema_version
end
@sbox = {}
mt = data.xpath('//Payload').xpath('PayloadInfo').xpath('MT').text
@sbox['MT'] = mt
data.xpath('//PayloadData').each { |payload_data|
@sbox['PayloadData'] = []
payload_data.xpath('//SBE').each_with_index { |strongbox_entity, sbe_index|
@sbox['PayloadData'][sbe_index] = {}
sbe_mt = strongbox_entity.attr('MT') # ModifiedTimestamp.Ticks
@sbox['PayloadData'][sbe_index]['MT'] = sbe_mt if sbe_mt.length > 0
sbe_ct = strongbox_entity.attr('CT') # CreatedTimestamp.Ticks
@sbox['PayloadData'][sbe_index]['CT'] = sbe_ct if sbe_ct.length > 0
sbe_ac = strongbox_entity.attr('AC') # accessCount
@sbox['PayloadData'][sbe_index]['AC'] = sbe_ac if sbe_ac.length > 0
sbe_name = strongbox_entity.xpath('N').text
@sbox['PayloadData'][sbe_index]['N'] = sbe_name if sbe_name.length > 0
sbe_description = strongbox_entity.xpath('D').text
@sbox['PayloadData'][sbe_index]['D'] = sbe_description if sbe_description.length > 0
sbe_tags = strongbox_entity.xpath('T').text
@sbox['PayloadData'][sbe_index]['T'] = sbe_tags if sbe_tags.length > 0
child_entity = strongbox_entity.xpath('CE')
if child_entity.length > 0
@sbox['PayloadData'][sbe_index]['CE'] = []
child_entity.xpath('TFE').each_with_index { |text_field_entity, ce_index|
@sbox['PayloadData'][sbe_index]['CE'][ce_index] = {}
tfe_name = text_field_entity.xpath('N').text
@sbox['PayloadData'][sbe_index]['CE'][ce_index]['N'] = tfe_name if tfe_name.length > 0
tfe_content = text_field_entity.xpath('C').text
@sbox['PayloadData'][sbe_index]['CE'][ce_index]['C'] = tfe_content if tfe_content.length > 0
}
end
}
}
end
def render(verbose=false)
puts sbox['MT']
sbox['PayloadData'].each { |payload_data|
puts
puts payload_data['N'] unless payload_data['N'].nil?
puts payload_data['D'] unless payload_data['D'].nil?
puts payload_data['T'] unless payload_data['T'].nil?
payload_data['CE'].each { |strongbox_entity|
puts strongbox_entity['N'] + ': ' unless strongbox_entity['N'].nil?
puts strongbox_entity['C'] unless strongbox_entity['C'].nil?
}
puts "Access Count: #{payload_data['AC']}" if !payload_data['AC'].nil? && verbose
puts "#{convert_time_from_dot_net_epoch(payload_data['MT'].to_i)} (modify time)" if !payload_data['MT'].nil? && verbose
puts "#{convert_time_from_dot_net_epoch(payload_data['CT'].to_i)} (create time)" if !payload_data['CT'].nil? && verbose
}
0
end
private
def self.resembles_base64?(string)
string.length % 4 == 0 && string =~ /^[A-Za-z0-9+\/=]+\Z/
end
def convert_time_from_dot_net_epoch(t)
Time.at((t-UNIX_EPOCH_IN_100NS_INTERVALS)*1e-7).utc.getlocal
end
end
#class String
# def resembles_base64?
# self.length % 4 == 0 && self =~ /^[A-Za-z0-9+\/=]+\Z/
# end
#end
added check for variable definition before length check
require 'openssl' # for decryption
require 'zlib' # for decompression
require 'base64' # for decoding
require 'rubygems' if defined?RUBY_VERSION && RUBY_VERSION =~ /^1.8/ # for requiring gem dependency in Ruby 1.8
require 'nokogiri' # for xml parsing
require 'strongboxio/version'
class Strongboxio
STRONGBOX_VERSION = 3
VERSION_LENGTH = 1
SALT_LENGTH = 64
IV_LENGTH = 16
KEY_LENGTH = 32
RANDOM_VALUE_LENGTH = 64
CIPHER = 'AES-256-CBC'
PAYLOAD_SCHEMA_VERSION = '2.4'
UNIX_EPOCH_IN_100NS_INTERVALS = 621355968000000000 # .NET time format: number of 100-nanosecond intervals since .NET epoch: January 1, 0001 at 00:00:00.000 (midnight)
attr_accessor :sbox
def self.decrypt(sbox_filename, password)
# open the xml file
f = File.open(sbox_filename)
data = Nokogiri::XML(f)
f.close
# extract the Data node
data = data.xpath('//Data').text
base64_error_msg = 'expected Base64 encoded byte string from the StrongBox.Payload.Data element of the xml of a Strongbox file'
raise "#{base64_error_msg}, but got nothing" if data.length == 0
raise "#{base64_error_msg}, but it does not resemble Base64" unless self.resembles_base64?(data)
data = Base64.decode64(data)
#version = data.getbyte(0) # ruby 1.9
version = data.bytes.to_a[0] # ruby 1.8 friendly
raise "expected version number #{STRONGBOX_VERSION}, but got #{version}" unless version == STRONGBOX_VERSION
salt = data.slice(1, SALT_LENGTH)
raise "expected salt length #{SALT_LENGTH}, but got #{salt.length}" unless salt.length == SALT_LENGTH
iv = data.bytes.to_a.slice((1+64), IV_LENGTH).pack('C*')
raise "expected iv length #{IV_LENGTH}, but got #{iv.length}" unless iv.length == IV_LENGTH
key = Digest::SHA256.digest(salt + password)
raise "expected key length #{KEY_LENGTH}, but got #{key.length}" unless key.length == KEY_LENGTH
# prepare for decryption
d = OpenSSL::Cipher.new(CIPHER)
d.decrypt
d.key = key
d.iv = iv
# decrypt the portion beyond the header
begin
data = '' << d.update(data.slice((VERSION_LENGTH+SALT_LENGTH+IV_LENGTH)..-1)) << d.final
rescue => e
raise "Error decrypting. You probably entered the password incorrectly. Specific error: #{e}"
end
# decompress the portion beyond the random value
#z = Zlib::Inflate.new
#z = Zlib::Inflate.new(-Zlib::BEST_COMPRESSION) # works for Strongbox
z = Zlib::Inflate.new(-Zlib::MAX_WBITS) # works for Strongbox!
#z = Zlib::Inflate.new(Zlib::MAX_WBITS) # works for roundtrip
data = z.inflate(data.slice(RANDOM_VALUE_LENGTH..-1))
z.finish
z.close
data
end
def self.render(decrypted_sbox, continue_despite_unexpected_payload_schema_version=false)
data = Nokogiri::XML(decrypted_sbox)
payload_schema_version = data.xpath('//Payload').xpath('SchemaVersion').text
unless payload_schema_version == PAYLOAD_SCHEMA_VERSION
raise "expected schema version #{PAYLOAD_SCHEMA_VERSION}, but got #{payload_schema_version}" unless continue_despite_unexpected_payload_schema_version
end
puts data.xpath('//Payload').xpath('PayloadInfo').xpath('MT').text
data.xpath('//PayloadData').each { |payload_data|
payload_data.xpath('//SBE').each { |entity|
puts
name = entity.xpath('N').text
puts "#{name}" if name.length > 0
description = entity.xpath('D').text
puts "#{description}" if description.length > 0
tags = entity.xpath('T').text
puts "#{tags}" if tags.length > 0
ce = entity.xpath('CE')
ce.xpath('TFE').each { |tfe|
name = tfe.xpath('N').text
puts "#{name}:" if name.length > 0
content = tfe.xpath('C').text
puts "#{content}" if content.length > 0
}
}
}
0
end
def initialize(decrypted_sbox, continue_despite_unexpected_payload_schema_version=false)
super()
data = Nokogiri::XML(decrypted_sbox)
payload_schema_version = data.xpath('//Payload').xpath('SchemaVersion').text
unless payload_schema_version == PAYLOAD_SCHEMA_VERSION
raise "expected schema version #{PAYLOAD_SCHEMA_VERSION}, but got #{payload_schema_version}" unless continue_despite_unexpected_payload_schema_version
end
@sbox = {}
mt = data.xpath('//Payload').xpath('PayloadInfo').xpath('MT').text
@sbox['MT'] = mt
data.xpath('//PayloadData').each { |payload_data|
@sbox['PayloadData'] = []
payload_data.xpath('//SBE').each_with_index { |strongbox_entity, sbe_index|
@sbox['PayloadData'][sbe_index] = {}
sbe_mt = strongbox_entity.attr('MT') # ModifiedTimestamp.Ticks
@sbox['PayloadData'][sbe_index]['MT'] = sbe_mt if sbe_mt.length > 0
sbe_ct = strongbox_entity.attr('CT') # CreatedTimestamp.Ticks
@sbox['PayloadData'][sbe_index]['CT'] = sbe_ct if sbe_ct.length > 0
sbe_ac = strongbox_entity.attr('AC') # accessCount
@sbox['PayloadData'][sbe_index]['AC'] = sbe_ac if defined?sbe_ac && sbe_ac.length > 0
sbe_name = strongbox_entity.xpath('N').text
@sbox['PayloadData'][sbe_index]['N'] = sbe_name if sbe_name.length > 0
sbe_description = strongbox_entity.xpath('D').text
@sbox['PayloadData'][sbe_index]['D'] = sbe_description if sbe_description.length > 0
sbe_tags = strongbox_entity.xpath('T').text
@sbox['PayloadData'][sbe_index]['T'] = sbe_tags if sbe_tags.length > 0
child_entity = strongbox_entity.xpath('CE')
if child_entity.length > 0
@sbox['PayloadData'][sbe_index]['CE'] = []
child_entity.xpath('TFE').each_with_index { |text_field_entity, ce_index|
@sbox['PayloadData'][sbe_index]['CE'][ce_index] = {}
tfe_name = text_field_entity.xpath('N').text
@sbox['PayloadData'][sbe_index]['CE'][ce_index]['N'] = tfe_name if tfe_name.length > 0
tfe_content = text_field_entity.xpath('C').text
@sbox['PayloadData'][sbe_index]['CE'][ce_index]['C'] = tfe_content if tfe_content.length > 0
}
end
}
}
end
def render(verbose=false)
puts sbox['MT']
sbox['PayloadData'].each { |payload_data|
puts
puts payload_data['N'] unless payload_data['N'].nil?
puts payload_data['D'] unless payload_data['D'].nil?
puts payload_data['T'] unless payload_data['T'].nil?
payload_data['CE'].each { |strongbox_entity|
puts strongbox_entity['N'] + ': ' unless strongbox_entity['N'].nil?
puts strongbox_entity['C'] unless strongbox_entity['C'].nil?
}
puts "Access Count: #{payload_data['AC']}" if !payload_data['AC'].nil? && verbose
puts "#{convert_time_from_dot_net_epoch(payload_data['MT'].to_i)} (modify time)" if !payload_data['MT'].nil? && verbose
puts "#{convert_time_from_dot_net_epoch(payload_data['CT'].to_i)} (create time)" if !payload_data['CT'].nil? && verbose
}
0
end
private
def self.resembles_base64?(string)
string.length % 4 == 0 && string =~ /^[A-Za-z0-9+\/=]+\Z/
end
def convert_time_from_dot_net_epoch(t)
Time.at((t-UNIX_EPOCH_IN_100NS_INTERVALS)*1e-7).utc.getlocal
end
end
#class String
# def resembles_base64?
# self.length % 4 == 0 && self =~ /^[A-Za-z0-9+\/=]+\Z/
# end
#end
|
require 'tilt'
require 'tilt/template'
module Tilt
# Stylus template implementation. See:
# http://learnboost.github.com/stylus/
#
# Stylus templates do not support object scopes, locals, or yield.
class StylusTemplate < Template
self.default_mime_type = 'text/css'
def prepare
end
def evaluate(scope, locals, &block)
Stylus.compile(data, options)
end
end
end
Tilt.register Tilt::StylusTemplate, 'styl'
whitespace
require 'tilt'
require 'tilt/template'
module Tilt
# Stylus template implementation. See:
# http://learnboost.github.com/stylus/
#
# Stylus templates do not support object scopes, locals, or yield.
class StylusTemplate < Template
self.default_mime_type = 'text/css'
def prepare
end
def evaluate(scope, locals, &block)
Stylus.compile(data, options)
end
end
end
Tilt.register Tilt::StylusTemplate, 'styl' |
# Going to make an `update` AND `upgrade` task that do the same thing
def same_thing
sh "git pull https://github.com/FarmBot/Farmbot-Web-App.git master"
sh "sudo docker-compose run web bundle install"
sh "sudo docker-compose run web npm install"
sh "sudo docker-compose run web rails db:migrate"
end
def check_for_digests
Log
.where(sent_at: nil, created_at: 1.day.ago...Time.now)
.where(Log::IS_EMAIL_ISH)
.where
.not(Log::IS_FATAL_EMAIL)
.pluck(:device_id)
.uniq
.map do |id|
device = Device.find(id)
puts "Sending log digest to device \##{id} (#{device.name})"
LogDeliveryMailer.log_digest(device).deliver
end
sleep 10.minutes
end
class V7Migration
BIG_WARNING = <<~END
░██████░░███████░░█████░░░██████░░ You have recently upgraded your server
░██░░░░░░░░██░░░░██░░░██░░██░░░██░ from version 6 to version 7.
░██████░░░░██░░░░██░░░██░░██████░░ This requires action on your part.
░░░░░██░░░░██░░░░██░░░██░░██░░░░░░ Please read the instructions below
░██████░░░░██░░░░░████░░░░██░░░░░░ carefully.
The biggest change from version 6 to version 7 is the addition of Docker for
managing services. This simplifies server setup because all software runs
inside of a container (no need to install Postgres or Ruby on your local
machine). Unfortunately, this change required a number of non-compatible
changes to the codebase, particularly related to the database and
configuration management.
The biggest changes for v7:
* Use a `.env` file instead of `application.yml`
* The database runs in a container
* The `mqtt/` directory was renamed `docker_configs/` (this directory
contains passwords which were previously `gitignore`ed)
Please perform the following steps to upgrade:
1. Follow v7 installation steps found in "ubuntu_example.sh". You will need
to skip certain steps. The skipable steps are listed in the instructions.
2. Stop using `rails api:start` and `rails mqtt:start` commands. The new
startup command is `sudo docker-compose up` See "ubuntu_example.sh" for
details. All services run in a single command now.
3. If you wish to continue using your current database:
a. To keep using the old database (v6) database, set the `DATABASE_URL`
ENV var to match the following format:
`postgres://username:password@host_name:5432/database_name`
b. Migrate the database to the new container-based DB manually:
https://stackoverflow.com/questions/1237725/copying-postgresql-database-to-another-server
(NOTE: We do not provide database migration support- consult
StackOverflow and the PostgreSQL docs)
c. Start a fresh database by following directions in `ubuntu_setup.sh`.
Old data will be lost.
4. Update database.yml to match https://github.com/FarmBot/Farmbot-Web-App/blob/staging/config/database.yml
5. Migrate the contents of `config/application.yml` to `.env`. Ensure you
have removed "quotation marks" and that all entries are `key=value` pairs.
See `example.env` for a properly formatted example.
6. (SECURITY CRITICAL) delete `mqtt/`
END
end
def hard_reset_api
sh "sudo docker stop $(sudo docker ps -a -q)"
sh "sudo docker rm $(sudo docker ps -a -q)"
sh "sudo rm -rf docker_volumes/"
rescue => exception
puts exception.message
puts "Reset failed. Was there nothing to destroy?"
end
def rebuild_deps
sh "sudo docker-compose run web bundle install"
sh "sudo docker-compose run web npm install"
sh "sudo docker-compose run web bundle exec rails db:setup"
sh "sudo docker-compose run web rake keys:generate"
sh "sudo docker-compose run web npm run build"
end
def user_typed?(word)
STDOUT.flush
STDIN.gets.chomp.downcase.include?(word.downcase)
end
namespace :api do
desc "Runs pending email digests. "\
"Use the `FOREVER` ENV var to continually check."
task log_digest: :environment do
ENV["FOREVER"] ? loop { check_for_digests } : check_for_digests
end
# TODO: Remove in dec 2018
desc "Deprecated. Will be removed in December of 2018"
task(:start) { puts V7Migration::BIG_WARNING }
desc "Run Rails _ONLY_. No Webpack."
task only: :environment do
sh "sudo docker-compose up --scale webpack=0"
end
desc "Pull the latest Farmbot API version"
task(update: :environment) { same_thing }
desc "Pull the latest Farmbot API version"
task(upgrade: :environment) { same_thing }
desc "Reset _everything_, including your database"
task :reset do
puts "This is going to destroy _ALL_ of your local Farmbot SQL data and "\
"configs. Type 'destroy' to continue, enter to abort."
if user_typed?("destroy")
hard_reset_api
puts "Done. Type 'build' to re-install dependencies, enter to abort."
rebuild_deps if user_typed?("build")
end
end
end
Its done, but needs a gentler version
# Going to make an `update` AND `upgrade` task that do the same thing
def same_thing
sh "git pull https://github.com/FarmBot/Farmbot-Web-App.git master"
sh "sudo docker-compose run web bundle install"
sh "sudo docker-compose run web npm install"
sh "sudo docker-compose run web rails db:migrate"
end
def check_for_digests
Log
.where(sent_at: nil, created_at: 1.day.ago...Time.now)
.where(Log::IS_EMAIL_ISH)
.where
.not(Log::IS_FATAL_EMAIL)
.pluck(:device_id)
.uniq
.map do |id|
device = Device.find(id)
puts "Sending log digest to device \##{id} (#{device.name})"
LogDeliveryMailer.log_digest(device).deliver
end
sleep 10.minutes
end
class V7Migration
BIG_WARNING = <<~END
░██████░░███████░░█████░░░██████░░ You have recently upgraded your server
░██░░░░░░░░██░░░░██░░░██░░██░░░██░ from version 6 to version 7.
░██████░░░░██░░░░██░░░██░░██████░░ This requires action on your part.
░░░░░██░░░░██░░░░██░░░██░░██░░░░░░ Please read the instructions below
░██████░░░░██░░░░░████░░░░██░░░░░░ carefully.
The biggest change from version 6 to version 7 is the addition of Docker for
managing services. This simplifies server setup because all software runs
inside of a container (no need to install Postgres or Ruby on your local
machine). Unfortunately, this change required a number of non-compatible
changes to the codebase, particularly related to the database and
configuration management.
The biggest changes for v7:
* Use a `.env` file instead of `application.yml`
* The database runs in a container
* The `mqtt/` directory was renamed `docker_configs/` (this directory
contains passwords which were previously `gitignore`ed)
Please perform the following steps to upgrade:
1. Follow v7 installation steps found in "ubuntu_example.sh". You will need
to skip certain steps. The skipable steps are listed in the instructions.
2. Stop using `rails api:start` and `rails mqtt:start` commands. The new
startup command is `sudo docker-compose up` See "ubuntu_example.sh" for
details. All services run in a single command now.
3. If you wish to continue using your current database:
a. To keep using the old database (v6) database, set the `DATABASE_URL`
ENV var to match the following format:
`postgres://username:password@host_name:5432/database_name`
b. Migrate the database to the new container-based DB manually:
https://stackoverflow.com/questions/1237725/copying-postgresql-database-to-another-server
(NOTE: We do not provide database migration support- consult
StackOverflow and the PostgreSQL docs)
c. Start a fresh database by following directions in `ubuntu_setup.sh`.
Old data will be lost.
4. Update database.yml to match https://github.com/FarmBot/Farmbot-Web-App/blob/staging/config/database.yml
5. Migrate the contents of `config/application.yml` to `.env`. Ensure you
have removed "quotation marks" and that all entries are `key=value` pairs.
See `example.env` for a properly formatted example.
6. (SECURITY CRITICAL) delete `mqtt/`
END
end
def hard_reset_api
sh "sudo docker stop $(sudo docker ps -a -q)"
sh "sudo docker rm $(sudo docker ps -a -q)"
sh "sudo rm -rf docker_volumes/"
rescue => exception
puts exception.message
puts "Reset failed. Was there nothing to destroy?"
end
def rebuild_deps
sh "sudo docker-compose run web bundle install"
sh "sudo docker-compose run web npm install"
sh "sudo docker-compose run web bundle exec rails db:setup"
sh "sudo docker-compose run web rake keys:generate"
sh "sudo docker-compose run web npm run build"
end
def user_typed?(word)
STDOUT.flush
STDIN.gets.chomp.downcase.include?(word.downcase)
end
namespace :api do
desc "Runs pending email digests. "\
"Use the `FOREVER` ENV var to continually check."
task log_digest: :environment do
ENV["FOREVER"] ? loop { check_for_digests } : check_for_digests
end
# TODO: Remove in dec 2018
desc "Deprecated. Will be removed in December of 2018"
task(:start) { puts V7Migration::BIG_WARNING }
desc "Run Rails _ONLY_. No Webpack."
task only: :environment do
sh "sudo docker-compose up --scale webpack=0"
end
desc "Pull the latest Farmbot API version"
task(update: :environment) { same_thing }
desc "Pull the latest Farmbot API version"
task(upgrade: :environment) { same_thing }
desc "Reset _everything_, including your database"
task :reset do
puts "This is going to destroy _ALL_ of your local Farmbot SQL data and "\
"configs. Type 'destroy' to continue, enter to abort."
if user_typed?("destroy")
hard_reset_api
puts "Done. Type 'build' to re-install dependencies, enter to abort."
rebuild_deps if user_typed?("build")
end
end
VERSION = "tag_name"
TIMESTAMP = "created_at"
desc "Update GlobalConfig to deprecate old FBOS versions"
task deprecate: :environment do
# Get current version
version_str = GlobalConfig.dump.fetch("MINIMUM_FBOS_VERSION")
# Convert it to Gem::Version for easy comparisons (>, <, ==, etc)
current_version = Gem::Version::new(version_str)
# 60 days is the current policy.
cutoff = 60.days.ago
# Download release data from github
stringio = open("https://api.github.com/repos/farmbot/farmbot_os/releases")
string = stringio.read
data = JSON
.parse(string)
.map { |x| x.slice(VERSION, TIMESTAMP) } # Only grab keys that matter
.reject { |x| x.fetch(VERSION).include?("-") } # Remove RC/Beta releases
.map do |x|
# Convert string-y version/timestamps to Real ObjectsTM
version = Gem::Version::new(x.fetch(VERSION).gsub("v", ""))
time = DateTime.parse(x.fetch(TIMESTAMP))
Pair.new(version, time)
end
.select do |pair|
# Grab versions that are > current version and outside of cutoff window
(pair.head > current_version) && (pair.tail < cutoff)
end
.sort_by { |p| p.tail } # Sort by release date
.last(2) # Grab 2 latest versions (closest to cuttof)
.first # Give 'em some leeway, grabbing the 2nd most outdated version.
.try(:head) # We might already be up-to-date?
if data # ...or not
puts "Setting new support target to #{data.to_s}"
GlobalConfig # Set the new oldest support version.
.find_by(key: "MINIMUM_FBOS_VERSION")
.update_attributes!(value: data.to_is)
end
end
end
|
rake task to make a CSV file of language properties
desc "This task creates a csv file of languages and their properties"
task :make_csv => :environment do
def get_value(x,y)
x.each do |prop|
if prop.property_id == y
return prop.value
end
end
return "ns"
end
file = File.open("languages.csv", "w")
all_properties = Property.all
file.write("Language")
all_properties.each do |prop|
file.write(", " + prop.name)
end
file.write("\n")
Ling.all.each do |ling|
string = ling.name
all_properties.each do |prop|
string += ", " + get_value(ling.lings_properties, prop.id)
end
file.write(string + "\n")
puts string
end
file.close unless file == nil
end |
#--
# Webyast Webservice framework
#
# Copyright (C) 2009, 2010 Novell, Inc.
# This library is free software; you can redistribute it and/or modify
# it only under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#++
require 'rake'
require "tempfile"
namespace :osc do
def obs_project
Packaging::Configuration.instance.obs_project
end
def obs_sr_project
Packaging::Configuration.instance.obs_sr_project
end
def package_name
Packaging::Configuration.instance.package_name
end
def package_dir
Packaging::Configuration.instance.package_dir
end
def build_dist
Packaging::Configuration.instance.obs_target
end
def cleaning
rm_rf obs_project
puts "cleaning" if verbose
end
def obs_api
Packaging::Configuration.instance.obs_api
end
def checkout
sh "osc -A '#{obs_api}' --traceback --verbose checkout '#{obs_project}' #{package_name}"
end
def osc_checkout_dir
File.join(Dir.pwd, obs_project, package_name)
end
def copy_sources
# clean project to easily add/remove new/old ones
Dir["#{osc_checkout_dir}/*"].each do |d|
rm d
end
# copy new
Dir["#{package_dir}/*"].each do |f|
cp f, osc_checkout_dir
end
Dir.chdir(osc_checkout_dir) do
sh "osc -A '#{obs_api}' addremove"
end
end
def version_from_spec spec_glob
version = `grep '^Version:' #{spec_glob}`
version.sub!(/^Version:\s*/, "")
version.sub!(/#.*$/, "")
version.strip!
version
end
desc "Build package locally"
task :build, [:osc_options] => ["check:osc", "package"] do |t, args|
args.with_defaults = { :osc_options => "" }
raise "Missing information about your Build service project" if !build_dist || !obs_project || !package_name
begin
checkout
copy_sources
puts "Building package #{package_name} from project #{obs_project}" if verbose
pkg_dir = File.join("/var/tmp", obs_project, build_dist)
mkdir_p pkg_dir
Dir.chdir osc_checkout_dir do
puts "building package..." if verbose
# pipe yes to osc build to automatic rebuild broken build root if it happen
command = "yes | osc -A '#{obs_api}' build"
command << " --no-verify" #ignore untrusted BS projects
command << " --release=1" #have always same release number
# have separated roots per target system, so sharing is more effficient
command << " --root=/var/tmp/build-root-#{build_dist}"
# store packages for given base system at one place, so it spped up rebuild
command << " --keep-pkgs=#{pkg_dir}"
command << " #{args[:osc_options]}"
command << " #{build_dist}"
sh command
end
ensure
cleaning
end
end
MAX_CHANGES_LINES = 20
desc "Commit package to devel project in build service if sources are correct and build"
task :commit => "osc:build" do
begin
checkout
copy_sources
Dir.chdir osc_checkout_dir do
puts "submitting package..." if verbose
# Take new lines from changes and use it as commit message.
# If a line starts with +, delete + and print it.
# Except skip the added "-----" header and the timestamp-author after that,
# and skip the +++ diff header
changes = `osc -A '#{obs_api}' diff *.changes | sed -n '/^+---/,+2b;/^+++/b;s/^+//;T;p'`.strip
if changes.empty?
# %h is short hash of a commit
git_ref = `git log --format=%h -n 1`.chomp
changes = "Updated to git ref #{git_ref}"
end
# provide only reasonable amount of changes
changes = changes.split("\n").take(MAX_CHANGES_LINES).join("\n")
sh "osc", "-A", obs_api, "commit", "-m", changes
puts "New package submitted to #{obs_project}" if verbose
end
ensure
cleaning
end
end
desc "Create submit request from updated devel project to target project if version change."
task :sr => "osc:commit" do
begin
checkout
file = Tempfile.new('yast-rake')
file.close
sh "osc -A '#{obs_api}' cat '#{obs_sr_project}' '#{package_name}' '#{package_name}.spec' > #{file.path}"
original_version = version_from_spec(file.path)
new_version = version_from_spec("#{package_dir}/#{package_name}.spec")
if new_version == original_version
puts "No version change => no submit request" if verbose
else
Rake::Task["osc:sr:force"].execute
end
ensure
cleaning
file.unlink if file
end
end
namespace "sr" do
desc "Create submit request from devel project to target project without any other packaging or checking"
task :force do
new_version = version_from_spec("#{package_dir}/#{package_name}.spec")
if Packaging::Configuration.instance.maintenance_mode
sh "yes | osc -A '#{obs_api}' maintenancerequest --no-cleanup '#{obs_project}' '#{package_name}' '#{obs_sr_project}' -m 'submit new version #{new_version}'"
else
sh "yes | osc -A '#{obs_api}' submitreq --no-cleanup '#{obs_project}' '#{package_name}' '#{obs_sr_project}' -m 'submit new version #{new_version}' --yes"
end
end
end
end
check that there is something to commit
#--
# Webyast Webservice framework
#
# Copyright (C) 2009, 2010 Novell, Inc.
# This library is free software; you can redistribute it and/or modify
# it only under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#++
require 'rake'
require "tempfile"
namespace :osc do
def obs_project
Packaging::Configuration.instance.obs_project
end
def obs_sr_project
Packaging::Configuration.instance.obs_sr_project
end
def package_name
Packaging::Configuration.instance.package_name
end
def package_dir
Packaging::Configuration.instance.package_dir
end
def build_dist
Packaging::Configuration.instance.obs_target
end
def cleaning
rm_rf obs_project
puts "cleaning" if verbose
end
def obs_api
Packaging::Configuration.instance.obs_api
end
def checkout
sh "osc -A '#{obs_api}' --traceback --verbose checkout '#{obs_project}' #{package_name}"
end
def osc_checkout_dir
File.join(Dir.pwd, obs_project, package_name)
end
def copy_sources
# clean project to easily add/remove new/old ones
Dir["#{osc_checkout_dir}/*"].each do |d|
rm d
end
# copy new
Dir["#{package_dir}/*"].each do |f|
cp f, osc_checkout_dir
end
Dir.chdir(osc_checkout_dir) do
sh "osc -A '#{obs_api}' addremove"
end
end
def version_from_spec spec_glob
version = `grep '^Version:' #{spec_glob}`
version.sub!(/^Version:\s*/, "")
version.sub!(/#.*$/, "")
version.strip!
version
end
def check_changes!
Dir["#{package_dir}/*"].each do |f|
orig = f.sub(/#{package_dir}\//, "")
if orig =~ /\.(tar|tbz2|tgz|tlz)/ # tar archive, so ignore archive creation time otherwise it always looks like new one
cmd = "diff <(tar -tvf #{f} | sort) <(tar -tvf #{osc_checkout_dir}/#{orig} | sort)"
else
cmd = "diff #{f} #{osc_checkout_dir}/#{orig}"
end
puts cmd if verbose
puts `#cmd}`
return if $?.exitstatus != 0 # there is something new
end
puts "Stop commiting, no difference from devel project"
exit 0
end
desc "Build package locally"
task :build, [:osc_options] => ["check:osc", "package"] do |t, args|
args.with_defaults = { :osc_options => "" }
raise "Missing information about your Build service project" if !build_dist || !obs_project || !package_name
begin
checkout
copy_sources
puts "Building package #{package_name} from project #{obs_project}" if verbose
pkg_dir = File.join("/var/tmp", obs_project, build_dist)
mkdir_p pkg_dir
Dir.chdir osc_checkout_dir do
puts "building package..." if verbose
# pipe yes to osc build to automatic rebuild broken build root if it happen
command = "yes | osc -A '#{obs_api}' build"
command << " --no-verify" #ignore untrusted BS projects
command << " --release=1" #have always same release number
# have separated roots per target system, so sharing is more effficient
command << " --root=/var/tmp/build-root-#{build_dist}"
# store packages for given base system at one place, so it spped up rebuild
command << " --keep-pkgs=#{pkg_dir}"
command << " #{args[:osc_options]}"
command << " #{build_dist}"
sh command
end
ensure
cleaning
end
end
MAX_CHANGES_LINES = 20
desc "Commit package to devel project in build service if sources are correct and build"
task :commit => "osc:build" do
begin
checkout
# check that there is some changes, otherwise it exit
check_changes!
copy_sources
Dir.chdir osc_checkout_dir do
puts "submitting package..." if verbose
# Take new lines from changes and use it as commit message.
# If a line starts with +, delete + and print it.
# Except skip the added "-----" header and the timestamp-author after that,
# and skip the +++ diff header
changes = `osc -A '#{obs_api}' diff *.changes | sed -n '/^+---/,+2b;/^+++/b;s/^+//;T;p'`.strip
if changes.empty?
# %h is short hash of a commit
git_ref = `git log --format=%h -n 1`.chomp
changes = "Updated to git ref #{git_ref}"
end
# provide only reasonable amount of changes
changes = changes.split("\n").take(MAX_CHANGES_LINES).join("\n")
sh "osc", "-A", obs_api, "commit", "-m", changes
puts "New package submitted to #{obs_project}" if verbose
end
ensure
cleaning
end
end
desc "Create submit request from updated devel project to target project if version change."
task :sr => "osc:commit" do
begin
checkout
file = Tempfile.new('yast-rake')
file.close
sh "osc -A '#{obs_api}' cat '#{obs_sr_project}' '#{package_name}' '#{package_name}.spec' > #{file.path}"
original_version = version_from_spec(file.path)
new_version = version_from_spec("#{package_dir}/#{package_name}.spec")
if new_version == original_version
puts "No version change => no submit request" if verbose
else
Rake::Task["osc:sr:force"].execute
end
ensure
cleaning
file.unlink if file
end
end
namespace "sr" do
desc "Create submit request from devel project to target project without any other packaging or checking"
task :force do
new_version = version_from_spec("#{package_dir}/#{package_name}.spec")
if Packaging::Configuration.instance.maintenance_mode
sh "yes | osc -A '#{obs_api}' maintenancerequest --no-cleanup '#{obs_project}' '#{package_name}' '#{obs_sr_project}' -m 'submit new version #{new_version}'"
else
sh "yes | osc -A '#{obs_api}' submitreq --no-cleanup '#{obs_project}' '#{package_name}' '#{obs_sr_project}' -m 'submit new version #{new_version}' --yes"
end
end
end
end
|
# encoding: utf-8
namespace :tcc do
desc 'TCC | Faz a migração dos dados do moodle para o Sistema de TCC'
task :remote, [:coursemodule_id, :hub_position, :tcc_definition_id] => [:environment] do |t, args|
moodle_config = YAML.load_file("#{Rails.root}/config/moodle.yml")['moodle']
Remote::OnlineText.establish_connection moodle_config
result = Remote::OnlineText.find_by_sql(["
SELECT DISTINCT u.id as id, u.username as username, u.firstname, u.lastname, ot.onlinetext as text,
otv.commenttext as comment, ot.assignment, assub.status, otv.status as status_version,
assub.timecreated, otv.timecreated as timecreated_version,
g.grade
FROM assign_submission AS assub
JOIN assignsubmission_onlinetext AS ot
ON (ot.submission = assub.id)
LEFT JOIN assignsubmission_textversion AS otv
ON (otv.submission = assub.id)
JOIN user u
ON (assub.userid = u.id)
JOIN course_modules cm
ON (cm.instance = assub.assignment)
JOIN modules m
ON (m.id = cm.module AND m.name LIKE 'assign')
LEFT JOIN assign_grades g
ON (u.id = g.userid AND g.assignment = assub.assignment)
WHERE cm.id = ?
ORDER BY u.username, ot.assignment, otv.timecreated", args[:coursemodule_id]])
result.with_progress("Migrando #{result.count} tuplas do texto online #{args[:coursemodule_id]} do moodle para eixo #{args[:hub_position]}") do |val|
user_id = val.id
created_at = (val.timecreated_version.nil?) ? val.timecreated : val.timecreated_version
tcc = get_tcc(user_id, args[:tcc_definition_id])
tcc.tutor_group = TutorGroup::get_tutor_group(val.username)
tcc.name = "#{val.firstname} #{val.lastname}"
hub = tcc.hubs.find_or_initialize_by_position(args[:hub_position])
hub.reflection = val.text
hub.commentary = val.comment
hub.grade = val.grade
hub.created_at = created_at
# status_onlinetext: draft, submitted
# status_onlinetextversion: null, evaluation, revision
#
# Determinando o estado que o hub deve ficar
#
states_to_modify = {'revision' => :sent_to_admin_for_revision, 'evaluation' => :sent_to_admin_for_evaluation}
case val.status
when 'submitted'
if val.status_version.nil?
# Houve envio e tem nota, está finalizado!
if !val.grade.nil? && val.grade != -1
new_state = :admin_evaluation_ok
else
# Houve envio e não tem nota, aluno quer nota
new_state = :sent_to_admin_for_evaluation
end
else
new_state = states_to_modify[val.status_version]
end
when 'draft'
new_state = :draft
end
#
# Transiciona estados
#
case new_state
when :draft
to_draft(hub)
when :sent_to_admin_for_revision
to_revision(hub)
when :sent_to_admin_for_evaluation
to_evaluation(hub)
when :admin_evaluation_ok
to_evaluation_ok(hub)
end
if hub.valid?
hub.save!
tcc.save!
else
puts "FALHA: #{hub.errors.inspect}"
end
end
end
def get_tcc(user_id, tcc_definition_id)
tcc = Tcc.find_by_moodle_user(user_id)
if tcc.nil?
tcc = Tcc.create(:moodle_user => user_id)
tcc.tcc_definition = TccDefinition.find(tcc_definition_id)
tcc.save!
end
tcc
end
def to_draft(hub)
case hub.aasm_current_state
when :draft
# ta certo
when :revision
send_back_to_student
when :evaluation
send_back_to_student
end
end
def to_revision(hub)
case hub.aasm_current_state
when :draft
hub.send_to_admin_for_revision
end
end
def to_evaluation(hub)
case hub.aasm_current_state
when :draft
hub.send_to_admin_for_evaluation
end
end
def to_evaluation_ok(hub)
case hub.aasm_current_state
when :draft
hub.send_to_admin_for_evaluation
hub.admin_evaluate_ok
end
end
end
Correção na condição que define quem está com nota e ok
# encoding: utf-8
namespace :tcc do
desc 'TCC | Faz a migração dos dados do moodle para o Sistema de TCC'
task :remote, [:coursemodule_id, :hub_position, :tcc_definition_id] => [:environment] do |t, args|
moodle_config = YAML.load_file("#{Rails.root}/config/moodle.yml")['moodle']
Remote::OnlineText.establish_connection moodle_config
result = Remote::OnlineText.find_by_sql(["
SELECT DISTINCT u.id as id, u.username as username, u.firstname, u.lastname, ot.onlinetext as text,
otv.commenttext as comment, ot.assignment, assub.status, otv.status as status_version,
assub.timecreated, otv.timecreated as timecreated_version,
g.grade
FROM assign_submission AS assub
JOIN assignsubmission_onlinetext AS ot
ON (ot.submission = assub.id)
LEFT JOIN assignsubmission_textversion AS otv
ON (otv.submission = assub.id)
JOIN user u
ON (assub.userid = u.id)
JOIN course_modules cm
ON (cm.instance = assub.assignment)
JOIN modules m
ON (m.id = cm.module AND m.name LIKE 'assign')
LEFT JOIN assign_grades g
ON (u.id = g.userid AND g.assignment = assub.assignment)
WHERE cm.id = ?
ORDER BY u.username, ot.assignment, otv.timecreated", args[:coursemodule_id]])
result.with_progress("Migrando #{result.count} tuplas do texto online #{args[:coursemodule_id]} do moodle para eixo #{args[:hub_position]}") do |val|
user_id = val.id
created_at = (val.timecreated_version.nil?) ? val.timecreated : val.timecreated_version
tcc = get_tcc(user_id, args[:tcc_definition_id])
tcc.tutor_group = TutorGroup::get_tutor_group(val.username)
tcc.name = "#{val.firstname} #{val.lastname}"
hub = tcc.hubs.find_or_initialize_by_position(args[:hub_position])
hub.reflection = val.text
hub.commentary = val.comment
hub.grade = val.grade
hub.created_at = created_at
# status_onlinetext: draft, submitted
# status_onlinetextversion: null, evaluation, revision
#
# Determinando o estado que o hub deve ficar
#
states_to_modify = {'revision' => :sent_to_admin_for_revision, 'evaluation' => :sent_to_admin_for_evaluation}
case val.status
when 'submitted'
if val.status_version.nil?
# Houve envio e tem nota, está finalizado!
if !val.grade.nil? && val.grade != -1
new_state = :admin_evaluation_ok
else
# Houve envio e não tem nota, aluno quer nota
new_state = :sent_to_admin_for_evaluation
end
else
new_state = states_to_modify[val.status_version]
if val.status_version == 'evaluation' and !val.grade.nil? && val.grade != -1
new_state = :admin_evaluation_ok
end
end
when 'draft'
new_state = :draft
end
#
# Transiciona estados
#
case new_state
when :draft
to_draft(hub)
when :sent_to_admin_for_revision
to_revision(hub)
when :sent_to_admin_for_evaluation
to_evaluation(hub)
when :admin_evaluation_ok
to_evaluation_ok(hub)
end
if hub.valid?
hub.save!
tcc.save!
else
puts "FALHA: #{hub.errors.inspect}"
end
end
end
def get_tcc(user_id, tcc_definition_id)
tcc = Tcc.find_by_moodle_user(user_id)
if tcc.nil?
tcc = Tcc.create(:moodle_user => user_id)
tcc.tcc_definition = TccDefinition.find(tcc_definition_id)
tcc.save!
end
tcc
end
def to_draft(hub)
case hub.aasm_current_state
when :draft
# ta certo
when :revision
send_back_to_student
when :evaluation
send_back_to_student
end
end
def to_revision(hub)
case hub.aasm_current_state
when :draft
hub.send_to_admin_for_revision
end
end
def to_evaluation(hub)
case hub.aasm_current_state
when :draft
hub.send_to_admin_for_evaluation
end
end
def to_evaluation_ok(hub)
case hub.aasm_current_state
when :draft
hub.send_to_admin_for_evaluation
hub.admin_evaluate_ok
end
end
end |
# If you struggle on this question for ~30 minutes and aren't getting anywhere, look at the solutions file, try to understand the code, then close the file, come back here, and try again to solve it.
# You are going to write a method called passthrough
# It receives an enumerable object, and an initial passthrough value, and a block
#
# For each of the elements in the enumerable object,
# it passes them the passthrough value and the element.
# Whatever the block returns, must be passed in as the
# next passthrough value for the next element.
#
# After we go through all the elements, the last passthrough value is returned to the caller
#
#
# EXAMPLE:
#
# passthrough 5..10 , 0 do |sum,num|
# sum + num
# end
#
# This should return 45 in the following manner:
# The first time the block is passed 0 , 5 and it returns 5
# The second time the block is passed 5 , 6 and it returns 11
# The third time the block is passed 11 , 7 and it returns 18
# The fourth time the block is passed 18 , 8 and it returns 26
# The fourth time the block is passed 26 , 9 and it returns 35
# The fourth time the block is passed 35 , 10 and it returns 45
# The method then returns 45
#
added solution to 4-3
# If you struggle on this question for ~30 minutes and aren't getting anywhere, look at the solutions file, try to understand the code, then close the file, come back here, and try again to solve it.
# You are going to write a method called passthrough
# It receives an enumerable object, and an initial passthrough value, and a block
#
# For each of the elements in the enumerable object,
# it passes them the passthrough value and the element.
# Whatever the block returns, must be passed in as the
# next passthrough value for the next element.
#
# After we go through all the elements, the last passthrough value is returned to the caller
#
#
# EXAMPLE:
#
# passthrough 5..10 , 0 do |sum,num|
# sum + num
# end
#
# This should return 45 in the following manner:
# The first time the block is passed 0 , 5 and it returns 5
# The second time the block is passed 5 , 6 and it returns 11
# The third time the block is passed 11 , 7 and it returns 18
# The fourth time the block is passed 18 , 8 and it returns 26
# The fourth time the block is passed 26 , 9 and it returns 35
# The fourth time the block is passed 35 , 10 and it returns 45
# The method then returns 45
#
def passthrough(enum, passed_in, &block)
enum.inject(passed_in, &block)
end
|
# frozen_string_literal: true
namespace :tmp do
task delete_multiple_episode_records_from_db_activities: :environment do
DbActivity.where(action: "multiple_episodes.create").delete_all
end
end
Remove tmp task
# frozen_string_literal: true
namespace :tmp do
end
|
module TBK
module VERSION
GEM = "1.0.1"
KCC = "6.0"
WEBSITE = "http://sagmor.com/tbk/"
end
end
Fix gem files listing. Closes #23
module TBK
module VERSION
GEM = "1.0.2"
KCC = "6.0"
WEBSITE = "http://sagmor.com/tbk/"
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.