hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
797bf9dfd62f720d7e31dbc5cb0726cf34a06721 | 1,209 | ##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
# Version 0.2 # 2011-02-25 #
# Updated version detection
##
Plugin.define "CF-Image-Hosting-Script" do
author "Brendan Coles <[email protected]>" # 2010-09-17
version "0.2"
description "A simple easy to use standalone image hosting script. This script aims to make it easy to setup image hosting site or just a site for you to share your photo with your friends,family,and collegues."
website "http://codefuture.co.uk/projects/imagehost/"
# Google results as at 2010-09-17 #
# 224 for "powered by CF Image Hosting Script"
# Dorks #
dorks [
'"powered by CF Image Hosting Script"'
]
# Matches #
matches [
# Powered by text
{ :text=>'<p>Powered By <a href="http://codefuture.co.uk/projects/imagehost/" title="Free PHP Image Hosting Script">CF Image Hosting script</a>' },
# Version Detection # Powered by text
{ :version=>/<p>Powered By <a href="http[s]*:\/\/codefuture.co.uk\/projects\/imagehost[\d\.]*[^>]+>CF Image Hosting script ([\d\.]+)<\/a>/ },
]
end
| 31 | 211 | 0.719603 |
61eafd7dc50d92b9b8e574ff0d4f5e54980d67c6 | 1,215 | require_relative "../lib/cmake"
class Libalkimia < Formula
desc "Library used by KDE Finance applications"
homepage "https://kmymoney.org"
head "https://invent.kde.org/office/alkimia.git", branch: "master"
stable do
url "https://download.kde.org/stable/alkimia/8.1.0/alkimia-8.1.0.tar.xz"
sha256 "916807352707b0490cdd9ca65682eff73b00ca523029bda6fe7a2749a1bc927c"
depends_on "kde-mac/kde/kf5-kdelibs4support"
end
depends_on "cmake" => [:build, :test]
depends_on "extra-cmake-modules" => [:build, :test]
depends_on "ninja" => :build
depends_on "gettext"
depends_on "gmp"
depends_on "kde-mac/kde/kf5-kcoreaddons"
depends_on "kde-mac/kde/kf5-knewstuff"
depends_on "kde-mac/kde/kf5-plasma-framework"
depends_on "kde-mac/kde/qt-webkit"
def install
args = kde_cmake_args
args << ("-DQt5WebKitWidgets_DIR=" + Formula["qt-webkit"].opt_prefix + "/lib/cmake/Qt5WebKitWidgets")
system "cmake", *args
system "cmake", "--build", "build"
system "cmake", "--install", "build"
prefix.install "build/install_manifest.txt"
end
test do
(testpath/"CMakeLists.txt").write("find_package(LibAlkimia5 REQUIRED)")
system "cmake", ".", "-Wno-dev"
end
end
| 30.375 | 105 | 0.702881 |
b9888bec37b04ff4a03a02a2ac15429d80c00788 | 3,218 | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Check that a copyright notice was given in each source file.
#
# The default regexp for an acceptable copyright notice can be found in
# config/default.yml. The default can be changed as follows:
#
# Style/Copyright:
# Notice: '^Copyright (\(c\) )?2\d{3} Acme Inc'
#
# This regex string is treated as an unanchored regex. For each file
# that RuboCop scans, a comment that matches this regex must be found or
# an offense is reported.
#
class Copyright < Cop
include RangeHelp
MSG = 'Include a copyright notice matching /%<notice>s/ before ' \
'any code.'
AUTOCORRECT_EMPTY_WARNING = 'An AutocorrectNotice must be defined in ' \
'your RuboCop config'
def investigate(processed_source)
return if notice.empty?
return if notice_found?(processed_source)
range = source_range(processed_source.buffer, 1, 0)
add_offense(insert_notice_before(processed_source),
location: range, message: format(MSG, notice: notice))
end
def autocorrect(token)
verify_autocorrect_notice!
lambda do |corrector|
range = token.nil? ? range_between(0, 0) : token.pos
corrector.insert_before(range, "#{autocorrect_notice}\n")
end
end
private
def notice
cop_config['Notice']
end
def autocorrect_notice
cop_config['AutocorrectNotice']
end
def verify_autocorrect_notice!
raise Warning, AUTOCORRECT_EMPTY_WARNING if autocorrect_notice.empty?
regex = Regexp.new(notice)
return if autocorrect_notice&.match?(regex)
raise Warning, "AutocorrectNotice '#{autocorrect_notice}' must " \
"match Notice /#{notice}/"
end
def insert_notice_before(processed_source)
token_index = 0
token_index += 1 if shebang_token?(processed_source, token_index)
token_index += 1 if encoding_token?(processed_source, token_index)
processed_source.tokens[token_index]
end
def shebang_token?(processed_source, token_index)
return false if token_index >= processed_source.tokens.size
token = processed_source.tokens[token_index]
token.comment? && /^#!.*$/.match?(token.text)
end
def encoding_token?(processed_source, token_index)
return false if token_index >= processed_source.tokens.size
token = processed_source.tokens[token_index]
token.comment? && /^#.*coding\s?[:=]\s?(?:UTF|utf)-8/.match?(token.text)
end
def notice_found?(processed_source)
notice_found = false
notice_regexp = Regexp.new(notice)
processed_source.each_token do |token|
break unless token.comment?
notice_found = notice_regexp.match?(token.text)
break if notice_found
end
notice_found
end
end
end
end
end
| 32.18 | 82 | 0.610938 |
1afaeac783bbc1ff8201b3c456450f111fb52168 | 370 | require 'rails_helper'
RSpec.describe PostsController, type: :controller do
describe '#render_404' do
before do
def controller.index
raise ActiveRecord::RecordNotFound
end
end
it 'renders the 404 page with' do
get :index
expect(response.code).to eq "404"
expect(response).to render_template("404")
end
end
end
| 20.555556 | 52 | 0.667568 |
6a2d116fc2a59ebaee7ed273c3030d823e2649c6 | 149 | class AddSpaceNameToSpaceTemplateSpaces < ActiveRecord::Migration
def change
add_column :space_template_spaces, :space_name, :string
end
end
| 24.833333 | 65 | 0.812081 |
01901382f31d4f892c6ddafb27098fa2841d892c | 2,622 | # Copyright 2017 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "helper"
describe Google::Cloud::Firestore::Batch, :create, :mock_firestore do
let(:batch) { Google::Cloud::Firestore::Batch.from_client firestore }
let(:document_path) { "users/mike" }
let(:database_path) { "projects/#{project}/databases/(default)" }
let(:documents_path) { "#{database_path}/documents" }
let(:commit_time) { Time.now }
let :create_writes do
[Google::Firestore::V1::Write.new(
update: Google::Firestore::V1::Document.new(
name: "#{documents_path}/#{document_path}",
fields: Google::Cloud::Firestore::Convert.hash_to_fields({ name: "Mike" })),
current_document: Google::Firestore::V1::Precondition.new(
exists: false)
)]
end
let :commit_resp do
Google::Firestore::V1::CommitResponse.new(
commit_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time),
write_results: [Google::Firestore::V1::WriteResult.new(
update_time: Google::Cloud::Firestore::Convert.time_to_timestamp(commit_time))]
)
end
it "creates a new document given a string path" do
firestore_mock.expect :commit, commit_resp, [database_path, writes: create_writes, options: default_options]
batch.create(document_path, { name: "Mike" })
resp = batch.commit
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "creates a new document given a DocumentReference" do
firestore_mock.expect :commit, commit_resp, [database_path, writes: create_writes, options: default_options]
doc = firestore.doc document_path
doc.must_be_kind_of Google::Cloud::Firestore::DocumentReference
batch.create(doc, { name: "Mike" })
resp = batch.commit
resp.must_be_kind_of Google::Cloud::Firestore::CommitResponse
resp.commit_time.must_equal commit_time
end
it "raises if not given a Hash" do
error = expect do
batch.create document_path, "not a hash"
end.must_raise ArgumentError
error.message.must_equal "data is required"
end
end
| 36.929577 | 112 | 0.7254 |
622a66e9d0556ef606f41b880b44e2cd5d717b10 | 683 | #
# Cookbook Name:: apache2
# Recipe:: autoindex
#
# Copyright 2008-2009, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
apache_module "autoindex" do
conf true
end
| 29.695652 | 74 | 0.749634 |
bf9c56151b940643535f311c70474a4144348c56 | 11,108 | module Devise
module LDAP
class Connection
attr_reader :ldap, :login
def initialize(params = {})
if ::Devise.ldap_config.is_a?(Proc)
ldap_config = ::Devise.ldap_config.call
else
ldap_config = YAML.load(ERB.new(File.read(::Devise.ldap_config || "#{Rails.root}/config/ldap.yml")).result)[Rails.env]
end
ldap_options = params
# Allow `ssl: true` shorthand in YAML, but enable more control with `encryption`
ldap_config["ssl"] = :simple_tls if ldap_config["ssl"] === true
ldap_options[:encryption] = ldap_config["ssl"].to_sym if ldap_config["ssl"]
if ldap_config["encryption"]
ldap_options[:encryption] = ldap_config["encryption"].deep_symbolize_keys
ldap_options[:encryption][:method] = ldap_options[:encryption][:method].to_sym if ldap_options[:encryption][:method]
if ldap_options[:encryption][:tls_options]
ldap_options[:encryption][:tls_options][:verify_mode] = OpenSSL::SSL::VERIFY_NONE if ldap_options[:encryption][:tls_options][:verify_mode] = "OpenSSL::SSL::VERIFY_NONE"
end
end
@ldap = Net::LDAP.new(ldap_options)
@ldap.host = ldap_config["host"]
@ldap.port = ldap_config["port"]
@ldap.base = ldap_config["base"]
@attribute = ldap_config["attribute"]
@allow_unauthenticated_bind = ldap_config["allow_unauthenticated_bind"]
@ldap_auth_username_builder = params[:ldap_auth_username_builder]
@group_base = ldap_config["group_base"]
@check_group_membership = ldap_config.has_key?("check_group_membership") ? ldap_config["check_group_membership"] : ::Devise.ldap_check_group_membership
@check_group_membership_without_admin = ldap_config.has_key?("check_group_membership_without_admin") ? ldap_config["check_group_membership_without_admin"] : ::Devise.ldap_check_group_membership_without_admin
@required_groups = ldap_config["required_groups"]
@group_membership_attribute = ldap_config.has_key?("group_membership_attribute") ? ldap_config["group_membership_attribute"] : "uniqueMember"
@required_attributes = ldap_config["require_attribute"]
@required_attributes_presence = ldap_config["require_attribute_presence"]
@ldap.auth ldap_config["admin_user"], ldap_config["admin_password"] if params[:admin]
@login = params[:login]
@password = params[:password]
@new_password = params[:new_password]
end
def delete_param(param)
update_ldap [[:delete, param.to_sym, nil]]
end
def set_param(param, new_value)
update_ldap( { param.to_sym => new_value } )
end
def dn
@dn ||= begin
DeviseLdapAuthenticatable::Logger.send("LDAP dn lookup: #{@attribute}=#{@login}")
ldap_entry = search_for_login
if ldap_entry.nil?
@ldap_auth_username_builder.call(@attribute,@login,@ldap)
else
ldap_entry.dn
end
end
end
def ldap_param_value(param)
ldap_entry = search_for_login
if ldap_entry
unless ldap_entry[param].empty?
value = ldap_entry.send(param)
DeviseLdapAuthenticatable::Logger.send("Requested param #{param} has value #{value}")
value
else
DeviseLdapAuthenticatable::Logger.send("Requested param #{param} does not exist")
value = nil
end
else
DeviseLdapAuthenticatable::Logger.send("Requested ldap entry does not exist")
value = nil
end
end
def authenticate!
return false unless (@password.present? || @allow_unauthenticated_bind)
@ldap.auth(dn, @password)
@ldap.bind
end
def authenticated?
authenticate!
end
def last_message_bad_credentials?
@ldap.get_operation_result.error_message.to_s.include? 'AcceptSecurityContext error, data 52e'
end
def last_message_expired_credentials?
@ldap.get_operation_result.error_message.to_s.include? 'AcceptSecurityContext error, data 773'
end
def authorized?
DeviseLdapAuthenticatable::Logger.send("Authorizing user #{dn}")
if !authenticated?
if last_message_bad_credentials?
DeviseLdapAuthenticatable::Logger.send("Not authorized because of invalid credentials.")
elsif last_message_expired_credentials?
DeviseLdapAuthenticatable::Logger.send("Not authorized because of expired credentials.")
else
DeviseLdapAuthenticatable::Logger.send("Not authorized because not authenticated.")
end
return false
elsif !in_required_groups?
DeviseLdapAuthenticatable::Logger.send("Not authorized because not in required groups.")
return false
elsif !has_required_attribute?
DeviseLdapAuthenticatable::Logger.send("Not authorized because does not have required attribute.")
return false
elsif !has_required_attribute_presence?
DeviseLdapAuthenticatable::Logger.send("Not authorized because does not have required attribute present.")
return false
else
return true
end
end
def expired_valid_credentials?
DeviseLdapAuthenticatable::Logger.send("Authorizing user #{dn}")
!authenticated? && last_message_expired_credentials?
end
def change_password!
update_ldap(:userPassword => ::Devise.ldap_auth_password_builder.call(@new_password))
end
def in_required_groups?
return true unless @check_group_membership || @check_group_membership_without_admin
## FIXME set errors here, the ldap.yml isn't set properly.
return false if @required_groups.nil?
for group in @required_groups
if group.is_a?(Array)
return false unless in_group?(group[1], group[0])
else
return false unless in_group?(group)
end
end
return true
end
def in_group?(group_name, group_attribute = LDAP::DEFAULT_GROUP_UNIQUE_MEMBER_LIST_KEY)
in_group = false
if @check_group_membership_without_admin
group_checking_ldap = @ldap
else
group_checking_ldap = Connection.admin
end
unless ::Devise.ldap_ad_group_check
group_checking_ldap.search(:base => group_name, :scope => Net::LDAP::SearchScope_BaseObject) do |entry|
if entry[group_attribute].include? dn
in_group = true
DeviseLdapAuthenticatable::Logger.send("User #{dn} IS included in group: #{group_name}")
end
end
else
# AD optimization - extension will recursively check sub-groups with one query
# "(memberof:1.2.840.113556.1.4.1941:=group_name)"
search_result = group_checking_ldap.search(:base => dn,
:filter => Net::LDAP::Filter.ex("memberof:1.2.840.113556.1.4.1941", group_name),
:scope => Net::LDAP::SearchScope_BaseObject)
# Will return the user entry if belongs to group otherwise nothing
if search_result.length == 1 && search_result[0].dn.eql?(dn)
in_group = true
DeviseLdapAuthenticatable::Logger.send("User #{dn} IS included in group: #{group_name}")
end
end
unless in_group
DeviseLdapAuthenticatable::Logger.send("User #{dn} is not in group: #{group_name}")
end
return in_group
end
def has_required_attribute?
return true unless ::Devise.ldap_check_attributes
admin_ldap = Connection.admin
user = find_ldap_user(admin_ldap)
@required_attributes.each do |key,val|
matching_attributes = user[key] & Array(val)
unless (matching_attributes).any?
DeviseLdapAuthenticatable::Logger.send("User #{dn} did not match attribute #{key}:#{val}")
return false
end
end
return true
end
def has_required_attribute_presence?
return true unless ::Devise.ldap_check_attributes_presence
user = search_for_login
@required_attributes_presence.each do |key,val|
if val && !user.attribute_names.include?(key.to_sym)
DeviseLdapAuthenticatable::Logger.send("User #{dn} doesn't include attribute #{key}")
return false
elsif !val && user.attribute_names.include?(key.to_sym)
DeviseLdapAuthenticatable::Logger.send("User #{dn} includes attribute #{key}")
return false
end
end
return true
end
def user_groups
admin_ldap = Connection.admin
DeviseLdapAuthenticatable::Logger.send("Getting groups for #{dn}")
filter = Net::LDAP::Filter.eq(@group_membership_attribute, dn)
admin_ldap.search(:filter => filter, :base => @group_base).collect(&:dn)
end
def valid_login?
!search_for_login.nil?
end
# Searches the LDAP for the login
#
# @return [Object] the LDAP entry found; nil if not found
def search_for_login
@login_ldap_entry ||= begin
DeviseLdapAuthenticatable::Logger.send("LDAP search for login: #{@attribute}=#{@login}")
filter = Net::LDAP::Filter.eq(@attribute.to_s, @login.to_s)
ldap_entry = nil
match_count = 0
@ldap.search(:filter => filter) {|entry| ldap_entry = entry; match_count+=1}
op_result= @ldap.get_operation_result
if op_result.code!=0 then
DeviseLdapAuthenticatable::Logger.send("LDAP Error #{op_result.code}: #{op_result.message}")
end
DeviseLdapAuthenticatable::Logger.send("LDAP search yielded #{match_count} matches")
ldap_entry
end
end
private
def self.admin
ldap = Connection.new(:admin => true).ldap
unless ldap.bind
DeviseLdapAuthenticatable::Logger.send("Cannot bind to admin LDAP user")
raise DeviseLdapAuthenticatable::LdapException, "Cannot connect to admin LDAP user"
end
return ldap
end
def find_ldap_user(ldap)
DeviseLdapAuthenticatable::Logger.send("Finding user: #{dn}")
ldap.search(:base => dn, :scope => Net::LDAP::SearchScope_BaseObject).try(:first)
end
def update_ldap(ops)
operations = []
if ops.is_a? Hash
ops.each do |key,value|
operations << [:replace,key,value]
end
elsif ops.is_a? Array
operations = ops
end
if ::Devise.ldap_use_admin_to_bind
privileged_ldap = Connection.admin
else
authenticate!
privileged_ldap = self.ldap
end
DeviseLdapAuthenticatable::Logger.send("Modifying user #{dn}")
privileged_ldap.modify(:dn => dn, :operations => operations)
end
end
end
end
| 37.026667 | 215 | 0.640889 |
ff1d961abf7bbccb7677d6c45e05a1e9bd2a4317 | 502 | def dfs(i, total)
return if total >= @min || @hash[i] && total >= @hash[i]
@hash[i] = total
return @min = total if i >= @days.size
@costs.each do |cost, day|
tmp = @days[i] + day
j = @days.bsearch_index { |ele| ele >= tmp } || @days.size
dfs(j, total+cost)
end
end
# @param {Integer[]} days
# @param {Integer[]} costs
# @return {Integer}
def mincost_tickets(days, costs)
@days, @costs = days, costs.zip([1, 7, 30])
@min, @hash= @days.size*costs[0], []
dfs(0, 0)
@min
end
| 23.904762 | 62 | 0.579681 |
1dd22d7a3ae0f25fa0b8590b6085de7a9bddbabc | 1,755 | # frozen_string_literal: true
module Groups
class CreateService < Groups::BaseService
def initialize(user, params = {})
@current_user, @params = user, params.dup
@chat_team = @params.delete(:create_chat_team)
end
def execute
remove_unallowed_params
@group = Group.new(params)
after_build_hook(@group, params)
unless can_use_visibility_level? && can_create_group?
return @group
end
@group.name ||= @group.path.dup
if create_chat_team?
response = Mattermost::CreateTeamService.new(@group, current_user).execute
return @group if @group.errors.any?
@group.build_chat_team(name: response['name'], team_id: response['id'])
end
@group.add_owner(current_user) if @group.save
@group
end
private
def after_build_hook(group, params)
# overridden in EE
end
def create_chat_team?
Gitlab.config.mattermost.enabled && @chat_team && group.chat_team.nil?
end
def can_create_group?
if @group.subgroup?
unless can?(current_user, :create_subgroup, @group.parent)
@group.parent = nil
@group.errors.add(:parent_id, s_('CreateGroup|You don’t have permission to create a subgroup in this group.'))
return false
end
else
unless can?(current_user, :create_group)
@group.errors.add(:base, s_('CreateGroup|You don’t have permission to create groups.'))
return false
end
end
true
end
def can_use_visibility_level?
unless Gitlab::VisibilityLevel.allowed_for?(current_user, visibility_level)
deny_visibility_level(@group)
return false
end
true
end
end
end
| 24.041096 | 120 | 0.645014 |
38a2e48e77e4097660081b9b5830065dc96fd3e4 | 181 | class AddStripePaymentMethodIdToAccount < ActiveRecord::Migration[6.0]
def change
add_column :accounts, :stripe_payment_method_id, :string, null: false, default: ""
end
end
| 30.166667 | 86 | 0.773481 |
1cc2c4573598c71ad7a0125051e398a9796c84e0 | 412 | class CreatePaymentCards < ActiveRecord::Migration[5.1]
def change
create_table :payment_cards do |t|
t.belongs_to :organization, null: false, index: true, foreign_key: true
t.string :stripe_id, null: false
t.string :brand, null: false
t.integer :exp_month, null: false
t.integer :exp_year, null: false
t.integer :last4, null: false
t.timestamps
end
end
end
| 29.428571 | 77 | 0.674757 |
6abfcfab8a0d4a317ccb1f1dbb8264e0688c0b4a | 1,997 | # Inspired by:
# https://github.com/ruby-debug/ruby-debug-ide/blob/master/ext/mkrf_conf.rb
# This file needs to be named mkrf_conf.rb
# so that rubygems will recognize it as a ruby extension
# file and not think it is a C extension file
require 'rubygems/specification'
require 'rubygems/dependency'
require 'rubygems/dependency_installer'
# Load up the rubygems dependency installer to install the dependencies
# we need based on the platform we are running under.
installer = Gem::DependencyInstaller.new
deps = []
begin
# Try to detect Cisco NX-OS and IOS XR environments
os = nil
if File.exist?('/etc/os-release')
cisco_release_file = nil
File.foreach('/etc/os-release') do |line|
next unless line[/^CISCO_RELEASE_INFO=/]
cisco_release_file = line[/^CISCO_RELEASE_INFO=(.*)$/, 1]
break
end
unless cisco_release_file.nil?
File.foreach(cisco_release_file) do |line|
next unless line[/^ID=/]
os = line[/^ID=(.*)$/, 1]
break
end
end
end
puts "Detected client OS as '#{os}'" unless os.nil?
# IOS XR doesn't need net_http_unix
os == 'ios_xr' || deps << Gem::Dependency.new('net_http_unix',
'~> 0.2', '>= 0.2.1')
# NX-OS doesn't need gRPC
os == 'nexus' || deps << Gem::Dependency.new('grpc', '~> 1.14.1')
deps.each do |dep|
installed = dep.matching_specs
if installed.empty?
puts "Installing #{dep}"
installed = installer.install dep
fail installer.errors[0] unless installer.errors.empty?
fail "Did not install #{dep}" if installed.empty?
else
puts "Found installed gems matching #{dep}:"
installed.each { |i| puts " #{i.name} (#{i.version})" }
end
end
rescue StandardError => e
puts e
puts e.backtrace.join("\n ")
exit(1)
end
# Create a dummy Rakefile to report successful 'compilation'
f = File.open(File.join(File.dirname(__FILE__), 'Rakefile'), 'w')
f.write("task :default\n")
f.close
| 31.203125 | 75 | 0.651477 |
08d3bd6f804104c6eb7a5dcfd7778179f46808df | 517 | module Shoulda
module Matchers
# @private
class Error < StandardError
def self.create(attributes)
allocate.tap do |error|
attributes.each do |name, value|
error.__send__("#{name}=", value)
end
error.__send__(:initialize)
end
end
def initialize(*args)
super
@message = message
end
def message
''
end
def inspect
%(#<#{self.class}: #{message}>)
end
end
end
end
| 17.233333 | 45 | 0.516441 |
d5272bad409ade6eb5d2b5417ad48145b3135416 | 162 | class AddDeactivatedAtToInstitutions < ActiveRecord::Migration[5.2]
def change
add_column :institutions, :deactivated_at, :datetime, default: nil
end
end
| 27 | 70 | 0.783951 |
117511bcca192410ef288af4df8dc8a33b5265df | 9,366 | # Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: MIT
# DO NOT MODIFY. THIS CODE IS GENERATED. CHANGES WILL BE OVERWRITTEN.
# vcenter - VMware vCenter Server provides a centralized platform for managing your VMware vSphere environments
require 'date'
module VSphereAutomation
module VCenter
class VcenterResourcePoolFilterSpec
# Identifiers of resource pools that can match the filter. If unset or empty, resource pools with any identifier match the filter. When clients pass a value of this structure as a parameter, the field must contain identifiers for the resource type: ResourcePool. When operations return a value of this structure as a result, the field will contain identifiers for the resource type: ResourcePool.
attr_accessor :resource_pools
# Names that resource pools must have to match the filter (see ResourcePool.Info.name). If unset or empty, resource pools with any name match the filter.
attr_accessor :names
# Resource pools that must contain the resource pool for the resource pool to match the filter. If unset or empty, resource pools in any resource pool match the filter. When clients pass a value of this structure as a parameter, the field must contain identifiers for the resource type: ResourcePool. When operations return a value of this structure as a result, the field will contain identifiers for the resource type: ResourcePool.
attr_accessor :parent_resource_pools
# Datacenters that must contain the resource pool for the resource pool to match the filter. If unset or empty, resource pools in any datacenter match the filter. When clients pass a value of this structure as a parameter, the field must contain identifiers for the resource type: Datacenter. When operations return a value of this structure as a result, the field will contain identifiers for the resource type: Datacenter.
attr_accessor :datacenters
# Hosts that must contain the resource pool for the resource pool to match the filter. If unset or empty, resource pools in any host match the filter. When clients pass a value of this structure as a parameter, the field must contain identifiers for the resource type: HostSystem. When operations return a value of this structure as a result, the field will contain identifiers for the resource type: HostSystem.
attr_accessor :hosts
# Clusters that must contain the resource pool for the resource pool to match the filter. If unset or empty, resource pools in any cluster match the filter. When clients pass a value of this structure as a parameter, the field must contain identifiers for the resource type: ClusterComputeResource. When operations return a value of this structure as a result, the field will contain identifiers for the resource type: ClusterComputeResource.
attr_accessor :clusters
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'resource_pools' => :'resource_pools',
:'names' => :'names',
:'parent_resource_pools' => :'parent_resource_pools',
:'datacenters' => :'datacenters',
:'hosts' => :'hosts',
:'clusters' => :'clusters'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'resource_pools' => :'Array<String>',
:'names' => :'Array<String>',
:'parent_resource_pools' => :'Array<String>',
:'datacenters' => :'Array<String>',
:'hosts' => :'Array<String>',
:'clusters' => :'Array<String>'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'resource_pools')
if (value = attributes[:'resource_pools']).is_a?(Array)
self.resource_pools = value
end
end
if attributes.has_key?(:'names')
if (value = attributes[:'names']).is_a?(Array)
self.names = value
end
end
if attributes.has_key?(:'parent_resource_pools')
if (value = attributes[:'parent_resource_pools']).is_a?(Array)
self.parent_resource_pools = value
end
end
if attributes.has_key?(:'datacenters')
if (value = attributes[:'datacenters']).is_a?(Array)
self.datacenters = value
end
end
if attributes.has_key?(:'hosts')
if (value = attributes[:'hosts']).is_a?(Array)
self.hosts = value
end
end
if attributes.has_key?(:'clusters')
if (value = attributes[:'clusters']).is_a?(Array)
self.clusters = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
resource_pools == o.resource_pools &&
names == o.names &&
parent_resource_pools == o.parent_resource_pools &&
datacenters == o.datacenters &&
hosts == o.hosts &&
clusters == o.clusters
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[resource_pools, names, parent_resource_pools, datacenters, hosts, clusters].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN, :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = VSphereAutomation::VCenter.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
end
| 38.073171 | 446 | 0.657698 |
335cb1cf2bc40e0460bcbbe0b2773ccf89a01f64 | 4,210 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = ENV['USE_SSL'].present?
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
# config.log_level = :debug
config.log_level = :info # NOTE: :debug floods our Papertrail plan
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "rgsoc_teams_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
config.action_mailer.smtp_settings = {
address: 'smtp.sendgrid.net',
port: 587,
domain: 'rgsoc.org',
user_name: ENV['SENDGRID_USERNAME'],
password: ENV['SENDGRID_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true
}
end
| 40.873786 | 102 | 0.738242 |
ed27dbfbadf21e793609a469fc4686187a2dae8c | 1,102 | module ApiLocationEventsConcern
extend ActiveSupport::Concern
included do
private
def create_json(resource)
resource.as_json(only: [:id, :event_id, :problem_id, :active, :length, :active_at, :created_at])
end
def update_json(resource)
resource.as_json(only: [:id, :event_id, :problem_id, :active, :length, :active_at, :created_at])
end
def show_json(resource)
resource.as_json(only: [:id, :event_id, :problem_id, :active, :length, :active_at, :created_at],
include: {
event: { only: [:id, :name] },
location: { only: [:id, :name], include: { path: { only: [:id, :name] } } },
master_camera_capture: { only: [:id], methods: :img_data },
camera_captures: { only: [:id, :created_at], methods: :img_data }
})
end
def resource_params
params.require(:location_event).permit(:event_id, :problem_id, :location_id, :active, :active_at, :length, :created_at, camera_capture_ids: [])
end
end
end
| 36.733333 | 149 | 0.583485 |
4a5fb169c936b98c0ca846046ce9cc9aba00bba9 | 275 | require 'spec_helper'
module TestFactories
module Fact
describe ID do
let(:fixed_id) { described_class.fixed_id }
it 'fixed_id is exactly this fixed id' do
expect(fixed_id).to eq '825e44d5-af33-4858-8047-549bd813daa8'
end
end
end
end
| 18.333333 | 69 | 0.68 |
331efa5259a9d8e24f74754a86b990cbed1dba17 | 708 | require "resqued/config"
require "resqued/runtime_info"
module Resqued
module TestCase
module LoadConfig
# Test your resqued config.
#
# If you do this to start resqued:
#
# $ resqued config/resqued-environment.rb config/resqued-workers.rb
#
# Then you'll want to do this in a test:
#
# assert_resqued 'config/resqued-environment.rb', 'config/resqued-workers.rb'
def assert_resqued(*paths)
config = Resqued::Config.new(paths)
config.before_fork(RuntimeInfo.new)
config.build_workers
config.after_fork(Resque::Worker.new("*"))
end
end
Default = LoadConfig
include Default
end
end
| 24.413793 | 87 | 0.639831 |
01749ff6d1dd2332fb2369febf2522df2468df92 | 52 | puts gets.match(/[$T].*G.*[$T]/) ? 'quiet': 'ALARM'
| 26 | 51 | 0.5 |
281737d9759f47643483179ad539dba97a216ff2 | 210 | require 'test_helper'
class <%= class_name %>PolicyTest < ActiveSupport::TestCase
def test_scope
end
def test_create
end
def test_show
end
def test_update
end
def test_destroy
end
end
| 10.5 | 59 | 0.714286 |
1cab0bd63214dbb3ba59bf4b9246901f5e6c8612 | 467 | module Jargon
class Localizations < Jargon::Resource
include Jargon::Helpers
include Jargon::Locales
def query(params = {})
rejects_id
client.get('/localizations', params)
end
def get
expects_id
client.get("/localizations/#{id}")
end
def save(localization)
client.save('/localizations', localization)
end
def delete
expects_id
client.delete("/localizations/#{id}")
end
end
end
| 17.961538 | 49 | 0.62955 |
f8127789616cc5f2c9ad837c9346d7f74f486b96 | 1,131 | # frozen_string_literal: true
require './lib/version'
Gem::Specification.new do |spec|
spec.name = 'danger-shiphawk-plugin'
spec.version = Danger::ShipHawkPlugin::VERSION
spec.summary = 'A Danger plugin for running Ruby files through Rubocop.'
spec.description = 'A Danger plugin for running Ruby files through Rubocop.'
spec.authors = 'ShipHawk Team'
spec.email = '[email protected]'
spec.files = Dir['README.md', 'LICENSE', 'lib/**/*']
spec.require_paths = ['lib']
spec.homepage = 'https://github.com/Shiphawk/danger-shiphawk-plugin'
spec.license = 'MIT'
spec.required_ruby_version = '>= 2.2.3'
spec.add_dependency 'danger'
spec.add_dependency 'rubocop'
# General ruby development
spec.add_development_dependency 'bundler', '~> 1.3'
spec.add_development_dependency 'rake', '~> 10.0'
# For validating the plugin lints
spec.add_development_dependency 'yard'
spec.add_development_dependency 'pry'
spec.add_development_dependency 'rspec', '~> 3.4'
end
| 36.483871 | 88 | 0.640141 |
03083b0d4f74148fa2de14b5a47312eea6debb21 | 10,578 | #-- copyright
# ReportingEngine
#
# Copyright (C) 2010 - 2014 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 3.
#
# 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
#++
require 'json'
module Report::Controller
def self.included(base)
base.class_eval do
attr_accessor :report_engine
helper_method :current_user
helper_method :allowed_to?
include ReportingHelper
helper ReportingHelper
helper { def engine; @report_engine; end }
before_action :determine_engine
before_action :prepare_query, only: [:index, :create]
before_action :find_optional_report, only: [:index, :show, :update, :destroy, :rename]
before_action :possibly_only_narrow_values
end
end
def index
table
end
##
# Render the report. Renders either the complete index or the table only
def table
if set_filter? && request.xhr?
self.response_body = render_widget(Widget::Table, @query)
end
end
##
# Create a new saved query. Returns the redirect url to an XHR or redirects directly
def create
@query.name = params[:query_name].present? ? params[:query_name] : ::I18n.t(:label_default)
@query.public! if make_query_public?
@query.send("#{user_key}=", current_user.id)
@query.save!
if request.xhr? # Update via AJAX - return url for redirect
render plain: url_for(action: 'show', id: @query.id)
else # Redirect to the new record
redirect_to action: 'show', id: @query.id
end
end
##
# Show a saved record, if found. Raises RecordNotFound if the specified query
# at :id does not exist
def show
if @query
store_query(@query)
table
render action: 'index' unless performed?
else
raise ActiveRecord::RecordNotFound
end
end
##
# Delete a saved record, if found. Redirects to index on success, raises a
# RecordNotFound if the query at :id does not exist
def destroy
if @query
@query.destroy if allowed_to? :destroy, @query
else
raise ActiveRecord::RecordNotFound
end
redirect_to action: 'index', default: 1
end
##
# Update a record with new query parameters and save it. Redirects to the
# specified record or renders the updated table on XHR
def update
if params[:set_filter].to_i == 1 # save
old_query = @query
prepare_query
old_query.migrate(@query)
old_query.save!
@query = old_query
end
if request.xhr?
table
else
redirect_to action: 'show', id: @query.id
end
end
##
# Rename a record and update its publicity. Redirects to the updated record or
# renders the updated name on XHR
def rename
@query.name = params[:query_name]
@query.public! if make_query_public?
@query.save!
store_query(@query)
unless request.xhr?
redirect_to action: 'show', id: @query.id
else
render plain: @query.name
end
end
##
# Determine the available values for the specified filter and return them as
# json, if that was requested. This will be executed INSTEAD of the actual action
def possibly_only_narrow_values
if params[:narrow_values] == '1'
sources = params[:sources]
dependent = params[:dependent]
query = report_engine.new
sources.each do |dependency|
query.filter(dependency.to_sym,
operator: params[:operators][dependency],
values: params[:values][dependency])
end
query.column(dependent)
values = [[::I18n.t(:label_inactive), '<<inactive>>']] + query.result.map { |r| r.fields[query.group_bys.first.field] }
# replace null-values with corresponding placeholder
values = values.map { |value| value.nil? ? [::I18n.t(:label_none), '<<null>>'] : value }
# try to find corresponding labels to the given values
values = values.map do |value|
filter = report_engine::Filter.const_get(dependent.camelcase.to_sym)
filter_value = filter.label_for_value value
if filter_value && filter_value.first.is_a?(Symbol)
[::I18n.t(filter_value.first), filter_value.second]
elsif filter_value && filter_value.first.is_a?(String)
[filter_value.first, filter_value.second]
else
value
end
end
render json: values.to_json
end
end
##
# Determine the requested engine by constantizing from the :engine parameter
# Sets @report_engine and @title based on that, and makes the engine available
# to views and widgets via the #engine method.
# Raises RecordNotFound on failure
def determine_engine
@report_engine = params[:engine].constantize
@title = "label_#{@report_engine.name.underscore}"
rescue NameError
raise ActiveRecord::RecordNotFound, 'No engine found - override #determine_engine'
end
##
# Determines if the request contains filters to set
def set_filter? # FIXME: rename to set_query?
params[:set_filter].to_i == 1
end
##
# Return the active filters
def filter_params
filters = http_filter_parameters if set_filter?
filters ||= session[report_engine.name.underscore.to_sym].try(:[], :filters)
filters ||= default_filter_parameters
end
##
# Return the active group bys
def group_params
groups = http_group_parameters if set_filter?
groups ||= session[report_engine.name.underscore.to_sym].try(:[], :groups)
groups ||= default_group_parameters
end
##
# Extract active filters from the http params
def http_filter_parameters
params[:fields] ||= []
(params[:fields].reject(&:empty?) || []).inject(operators: {}, values: {}) do |hash, field|
hash[:operators][field.to_sym] = params[:operators][field]
hash[:values][field.to_sym] = params[:values][field]
hash
end
end
##
# Extract active group bys from the http params
def http_group_parameters
if params[:groups]
rows = params[:groups]['rows']
columns = params[:groups]['columns']
end
{ rows: (rows || []), columns: (columns || []) }
end
##
# Set a default query to cut down initial load time
def default_filter_parameters
{ operators: {}, values: {} }
end
##
# Set a default query to cut down initial load time
def default_group_parameters
{ columns: [:sector_id], rows: [:country_id] }
end
##
# Determines if the query settings should be reset
def force_default?
params[:default].to_i == 1
end
##
# Prepare the query from the request
def prepare_query
determine_settings
@query = build_query(session[report_engine.name.underscore.to_sym][:filters],
session[report_engine.name.underscore.to_sym][:groups])
end
##
# Determine the query settings the current request and save it to
# the session.
def determine_settings
if force_default?
filters = default_filter_parameters
groups = default_group_parameters
session[report_engine.name.underscore.to_sym].try :delete, :name
else
filters = filter_params
groups = group_params
end
cookie = session[report_engine.name.underscore.to_sym] || {}
session[report_engine.name.underscore.to_sym] = cookie.merge(filters: filters, groups: groups)
end
##
# Build the query from the passed session hash
def build_query(filters, groups = {})
query = report_engine.new
query.tap do |q|
filters[:operators].each do |filter, operator|
unless filters[:values][filter] == ['<<inactive>>']
values = Array(filters[:values][filter]).map { |v| v == '<<null>>' ? nil : v }
q.filter(filter.to_sym,
operator: operator,
values: values)
end
end
end
groups[:columns].try(:reverse_each) { |c| query.column(c) }
groups[:rows].try(:reverse_each) { |r| query.row(r) }
query
end
##
# Store query in the session
def store_query(_query)
cookie = {}
cookie[:groups] = @query.group_bys.inject({}) do |h, group|
((h[:"#{group.type}s"] ||= []) << group.underscore_name.to_sym) && h
end
cookie[:filters] = @query.filters.inject(operators: {}, values: {}) do |h, filter|
h[:operators][filter.underscore_name.to_sym] = filter.operator.to_s
h[:values][filter.underscore_name.to_sym] = filter.values
h
end
cookie[:name] = @query.name if @query.name
session[report_engine.name.underscore.to_sym] = cookie
end
##
# Override in subclass if user key
def user_key
'user_id'
end
##
# Override in subclass if you like
def is_public_sql(val = true)
"(is_public = #{val ? report_engine.reporting_connection.quoted_true : report_engine.reporting_connection.quoted_false})"
end
##
# Abstract: Implementation required in application
def allowed_to?(_action, _subject, _user = current_user)
raise NotImplementedError, "The #{self.class} should have implemented #allowed_to?(action, subject, user)"
end
def make_query_public?
!!params[:query_is_public]
end
# renders option tags for each available value for a single filter
def available_values
if name = params[:filter_name]
f_cls = report_engine::Filter.const_get(name.to_s.camelcase)
filter = f_cls.new.tap do |f|
f.values = JSON.parse(params[:values].gsub("'", '"')) if params[:values].present? and params[:values]
end
render_widget Widget::Filters::Option, filter, to: canvas = ''
render plain: canvas, layout: !request.xhr?
end
end
##
# Find a report if :id was passed as parameter.
# Raises RecordNotFound if an invalid :id was passed.
#
# @param query An optional query added to the disjunction qualifiying reports to be returned.
def find_optional_report(query = '1=0')
if params[:id]
@query = report_engine
.where(["#{is_public_sql} OR (#{user_key} = ?) OR (#{query})", current_user.id])
.find(params[:id].to_i)
@query.deserialize if @query
end
rescue ActiveRecord::RecordNotFound
end
end
| 31.20354 | 125 | 0.670259 |
6267703e5dc45d2a9bcc9daaf8ef06e3c6782ffb | 447 | class Candybar < Cask
version '3.3.4'
sha256 'f305596f195445016b35c9d99a40789c6671195e9cbad0b6e92e808b6c633ad6'
url "https://panic.com/candybar/d/CandyBar%20#{version}.zip"
homepage 'http://www.panic.com/blog/candybar-mountain-lion-and-beyond'
app 'CandyBar.app'
caveats <<-EOS.undent
Candybar is free of charge. Visit the following link for a license
http://panic.com/bin/setup.php/cb3/PPQA-YAMA-E3KP-VHXG-B6AL-L
EOS
end
| 31.928571 | 75 | 0.749441 |
791d66166eedd7c39966d26ebe36ec9d499a5b8f | 572 | class Catalog::Property < ActiveRecord::Base
validates :name, presence: true, uniqueness: true
has_many :product_properties, class_name: Catalog::ProductProperty,
foreign_key: :catalog_property_id,
dependent: :delete_all
has_many :category_properties, class_name: Catalog::CategoryProperty,
foreign_key: :catalog_property_id,
dependent: :delete_all
def self.warranty
where("name = 'гарантия' OR name = 'Гарантия'").first
end
end
| 40.857143 | 71 | 0.608392 |
1a7243a7111c821e30d127762fe0491582dc83a9 | 551 | #
# RSMP base class
#
module RSMP
module Logging
attr_reader :archive, :logger
def initialize_logging options
@archive = options[:archive] || RSMP::Archive.new
@logger = options[:logger] || RSMP::Logger.new(options[:log_settings])
end
def author
end
def log str, options={}
default = { str:str, level: :log, author: author, ip: @ip, port: @port }
prepared = RSMP::Archive.prepare_item default.merge(options)
@archive.add prepared
@logger.log prepared
prepared
end
end
end | 21.192308 | 78 | 0.638838 |
5df1d4c5ca2ded3a44043281b551944c7266e909 | 167 | class AddHstore < ActiveRecord::Migration
def up
execute 'CREATE EXTENSION IF NOT EXISTS hstore'
end
def down
execute 'DROP EXTENSION hstore'
end
end
| 16.7 | 51 | 0.724551 |
7a1d8a808edb4b8e7bd821fb81534413d9d0b27a | 389 | cask 'whatpulse' do
version '2.6'
sha256 '90fecfd945d78b2b38900765a16f0a6d1114badd636629b45cf0f59d585b130b'
url "http://amcdn.whatpulse.org/files/whatpulse-mac-#{version}.dmg"
name 'WhatPulse'
homepage 'http://www.whatpulse.org/'
license :gratis
pkg "WhatPulse #{version}.mpkg"
uninstall pkgutil: 'com.lostdomain.whatpulse',
quit: 'com.whatpulse.mac'
end
| 25.933333 | 75 | 0.722365 |
ac4c80a35568a85bff6302aca7de9f1b3794d8d4 | 6,201 | # encoding: utf-8
# author: Dominik Richter
# author: Christoph Hartmann
require 'helper'
describe Inspec::MockProvider do
let(:subject) { Inspec::MockProvider.new(target) }
describe 'without data' do
let(:target) {{ mock: {}}}
it 'has no files on empty' do
subject.files.must_equal []
end
end
describe 'with_data' do
let(:file_name) { rand.to_s }
let(:file_content) { rand.to_s }
let(:target) {{ mock: { file_name => file_content } }}
it 'has files' do
subject.files.must_equal [file_name]
end
it 'can read a file' do
subject.read(file_name).must_equal file_content
end
end
end
describe Inspec::DirProvider do
let(:subject) { Inspec::DirProvider.new(target) }
describe 'applied to this file' do
let(:target) { __FILE__ }
it 'must only contain this file' do
subject.files.must_equal [__FILE__]
end
it 'must not read if the file doesnt exist' do
subject.read('file-does-not-exist').must_be_nil
end
it 'must not read files not covered' do
not_covered = File.expand_path('../../helper.rb', __FILE__)
puts "#{not_covered}"
File.file?(not_covered).must_equal true
subject.read(not_covered).must_be_nil
end
it 'must read the contents of the file' do
subject.read(__FILE__).must_equal File.read(__FILE__)
end
end
describe 'applied to this folder' do
let(:target) { File.dirname(__FILE__) }
it 'must contain all files' do
subject.files.must_include __FILE__
end
it 'must not read if the file doesnt exist' do
subject.read('file-not-in-folder').must_be_nil
end
it 'must not read files not covered' do
not_covered = File.expand_path('../../helper.rb', __FILE__)
File.file?(not_covered).must_equal true
subject.read(not_covered).must_be_nil
end
it 'must read the contents of the file' do
subject.read(__FILE__).must_equal File.read(__FILE__)
end
end
end
describe Inspec::ZipProvider do
let(:subject) { Inspec::ZipProvider.new(target) }
describe 'applied to a tar archive' do
let(:target) { MockLoader.profile_zip('complete-profile') }
it 'must contain all files' do
subject.files.sort.must_equal %w{inspec.yml libraries libraries/testlib.rb
controls controls/filesystem_spec.rb}.sort
end
it 'must not read if the file isnt included' do
subject.read('file-not-in-archive').must_be_nil
end
it 'must read the contents of the file' do
subject.read('inspec.yml').must_match(/^name: complete$/)
end
end
end
describe Inspec::ZipProvider do
let(:subject) { Inspec::ZipProvider.new(target) }
describe 'applied to a tar archive' do
let(:target) { MockLoader.profile_zip('complete-profile') }
it 'must contain all files' do
subject.files.sort.must_equal %w{inspec.yml libraries libraries/testlib.rb
controls controls/filesystem_spec.rb}.sort
end
it 'must not read if the file isnt included' do
subject.read('file-not-in-archive').must_be_nil
end
it 'must read the contents of the file' do
subject.read('inspec.yml').must_match(/^name: complete$/)
end
end
end
describe Inspec::TarProvider do
let(:subject) { Inspec::TarProvider.new(target) }
describe 'applied to a tar archive' do
let(:target) { MockLoader.profile_tgz('complete-profile') }
it 'must contain all files' do
subject.files.sort.must_equal %w{inspec.yml libraries libraries/testlib.rb
controls controls/filesystem_spec.rb}.sort
end
it 'must not read if the file isnt included' do
subject.read('file-not-in-archive').must_be_nil
end
it 'must read the contents of the file' do
subject.read('inspec.yml').must_match(/^name: complete$/)
end
end
end
describe Inspec::RelativeFileProvider do
def fetcher
src_fetcher.expects(:files).returns(in_files).at_least_once
Inspec::RelativeFileProvider.new(src_fetcher)
end
let(:src_fetcher) { mock() }
IN_AND_OUT = {
[] => [],
%w{file} => %w{file},
# don't prefix just by filename
%w{file file_a} => %w{file file_a},
%w{path/file path/file_a} => %w{file file_a},
%w{path/to/file} => %w{file},
%w{/path/to/file} => %w{file},
%w{alice bob} => %w{alice bob},
# mixed paths
%w{x/a y/b} => %w{x/a y/b},
%w{/x/a /y/b} => %w{x/a y/b},
%w{z/x/a z/y/b} => %w{x/a y/b},
%w{/z/x/a /z/y/b} => %w{x/a y/b},
# mixed with relative path
%w{a path/to/b} => %w{a path/to/b},
%w{path/to/b a} => %w{path/to/b a},
%w{path/to/b path/a} => %w{to/b a},
%w{path/to/b path/a c} => %w{path/to/b path/a c},
# When the first element is the directory
%w{path/ path/to/b path/a} => %w{to/b a},
%w{path path/to/b path/a} => %w{to/b a},
# mixed with absolute paths
%w{/path/to/b /a} => %w{path/to/b a},
%w{/path/to/b /path/a} => %w{to/b a},
%w{/path/to/b /path/a /c} => %w{path/to/b path/a c},
# mixing absolute and relative paths
%w{path/a /path/b} => %w{path/a /path/b},
%w{/path/a path/b} => %w{/path/a path/b},
# extract folder structure buildup
%w{/a /a/b /a/b/c} => %w{c},
%w{/a /a/b /a/b/c/d/e} => %w{e},
# extract folder structure buildup (relative)
%w{a a/b a/b/c} => %w{c},
%w{a a/b a/b/c/d/e} => %w{e},
# extract folder structure buildup (relative)
%w{a/ a/b/ a/b/c} => %w{c},
%w{a/ a/b/ a/b/c/d/e} => %w{e},
# ignore pax_global_header, which are commonly seen in github tars and are not
# ignored by all tar streaming tools, its not extracted by GNU tar since 1.14
%w{/pax_global_header /a/b} => %w{b},
%w{pax_global_header a/b} => %w{b},
}.each do |ins, outs|
describe 'empty profile' do
let(:in_files) { ins }
it "turns #{ins} into #{outs}" do
fetcher.files.must_equal outs
end
end
end
end
| 30.101942 | 82 | 0.601838 |
0378a1869143cda6113cef486754f3e6f717596e | 1,732 | #
# Be sure to run `pod lib lint SEETools.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'SEETools'
s.version = '0.1.0'
s.summary = 'Tools'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
* Kit 视图框架
**View 视图
SEETagView
**ViewController 控制器
SEETagViewController
* Tools
**Chain
**SEETools
DESC
s.homepage = 'https://github.com/[email protected]/SEETools'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '[email protected]' => '[email protected]' }
s.source = { :git => 'https://github.com/[email protected]/SEETools.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'SEETools/Classes/**/*'
# s.resource_bundles = {
# 'SEETools' => ['SEETools/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit', 'Foundation'
s.subspec 'Kit' do |kit|
s.dependency 'Masonry'
end
s.subspec 'Tools' do |tools|
end
end
| 25.850746 | 109 | 0.62067 |
61cbda2e0aaeda1e6740b9a6f2e35ed49df2e3c7 | 471 | #
# This file is part of ruby-ffi.
# For licensing, see LICENSE.SPECS
#
require File.expand_path(File.join(File.dirname(__FILE__), "spec_helper"))
describe "FFI.errno" do
module LibTest
extend FFI::Library
ffi_lib TestLibrary::PATH
attach_function :setLastError, [ :int ], :void
end
it "FFI.errno contains errno from last function" do
LibTest.setLastError(0)
LibTest.setLastError(0x12345678)
expect(FFI.errno).to eq(0x12345678)
end
end
| 22.428571 | 74 | 0.721868 |
1d3c9ba2c061da7deef8696441cfd3d954bdd25c | 1,143 | module CanBeConstrained
def constraint
#Don't bother storing it, and most importantly, don't reuse it because things like multipler and constant must always be reset
PurplishLayout::ConstraintProxy.new(self)
end
def constrained_views(*views, &block)
block.call(*(views.map {|e| e.constraint}))
end
def common_superview(v)
if v.superview == self
self
elsif superview == v
v
else
(superviews & v.superviews)[0]
end
end
def superviews
v = self
result = []
loop do
v = v.superview
break unless v
result << v
end
result
end
def all_subviews
subviews.map { |e| [e] + e.all_subviews }.flatten
end
def all_subviews_and_self
all_subviews + [self]
end
def constraints_for_view(view, direction=nil)
constraints = all_subviews_and_self.map {|e| e.constraints.select { |e| e.firstItem == view || e.secondItem == view }}.flatten
if direction == :horizontal
constraints.select {|e| e.horizontal? }
elsif direction == :vertical
constraints.select {|e| e.vertical? }
else
constraints
end
end
end
| 22.411765 | 130 | 0.651794 |
bf69f8405a9e672f634afb59beb2f324d1ee7edb | 2,658 | module MiqReport::Notification
def notify_user_of_report(run_on, result, options)
userid = options[:userid]
url = options[:email_url_prefix]
user = User.lookup_by_userid(userid)
from = options[:email] && !options[:email][:from].blank? ? options[:email][:from] : ::Settings.smtp.from
to = options[:email] ? options[:email][:to] : user.try(:email)
msg = nil
msg = "The system is not configured with a 'from' email address." if from.blank?
msg = "No to: email address provided." if to.blank?
unless msg.nil?
_log.warn("Failed to email report because: #{msg}")
return
end
send_if_empty = options.fetch_path(:email, :send_if_empty)
send_if_empty = true if send_if_empty.nil?
if !self.table_has_records? && !send_if_empty
_log.info("No records found for scheduled report and :send_if_empty option is false, no Email will be sent. ")
return
end
_log.info("Emailing to: #{to.inspect} report results: [#{result.name}]")
body = notify_email_body(url, result, to)
subject = run_on.strftime("Your report '#{title}' generated on %m/%d/%Y is ready")
curr_tz = Time.zone # Save current time zone setting
Time.zone = user ? user.get_timezone : MiqServer.my_server.server_timezone
if self.table_has_records?
attach_types = options.fetch_path(:email, :attach) || [:pdf] # support legacy schedules
attachments = attach_types.collect do |atype|
target = atype == :pdf ? result : self
{
:content_type => "application/#{atype}",
:filename => "#{title} #{run_on.utc.iso8601}.#{atype}",
:body => target.send("to_#{atype}")
}
end
end
begin
_log.info("Queuing email user: [#{user.name}] report results: [#{result.name}] to: #{to.inspect}")
options = {
:to => to,
:from => from,
:subject => subject,
:body => body,
:attachment => attachments,
}
GenericMailer.deliver_queue(:generic_notification, options)
rescue => err
_log.error("Queuing email user: [#{user.name}] report results: [#{result.name}] failed with error: [#{err.class.name}] [#{err}]")
end
Time.zone = curr_tz # Restore original time zone setting
end
def notify_email_body(_url, _result, recipients)
if self.table_has_records?
_("Please find attached scheduled report \"%{name}\". This report was sent to: %{recipients}.") %
{:name => name, :recipients => recipients.join(", ")}
else
_("No records found for scheduled report \"%{name}\"") % {:name => name}
end
end
end
| 37.43662 | 135 | 0.62453 |
bf69c5dd4fba794d1fd6bdf0366d7a530d7c1ca1 | 1,128 | module Beekeeper
class Logger
def self.fatal(error, logger: nil)
message = if error.respond_to? :backtrace
message_with_backtrace(error)
else
error
end
internal_logger(logger).fatal message
end
def self.error(error, logger: nil)
message = if error.respond_to? :backtrace
message_with_backtrace(error)
else
error
end
internal_logger(logger).error message
end
private
def self.message_with_backtrace(error)
trace = clean(error.backtrace)
"\n#{error.class.name} (#{error.message}):\n#{trace.join}"
end
def self.clean(backtrace)
bc = ActiveSupport::BacktraceCleaner.new
bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix
bc.add_silencer { |line| line =~ /puma|rubygems|vendor|bin/ } # skip any lines from puma or rubygems
bc.clean(backtrace).map! { |t| " #{t}\n" }
end
def self.internal_logger(logger)
logger || Rails.logger
end
end
end
| 26.857143 | 106 | 0.590426 |
3816edfc1f9a901a0fcdfabdc2619bf11fc38c33 | 1,281 | class Passwdqc < Formula
desc "Password/passphrase strength checking and enforcement toolset"
homepage "https://www.openwall.com/passwdqc/"
url "https://www.openwall.com/passwdqc/passwdqc-1.3.1.tar.gz"
sha256 "d1fedeaf759e8a0f32d28b5811ef11b5a5365154849190f4b7fab670a70ffb14"
bottle do
cellar :any
sha256 "49e4a3baa4adf8f13f1c9b145be4d55c02e02a9b8dad50d2b96721ba82851d17" => :catalina
sha256 "e0f9450b595fb6935ed0cba174755cda95a7ff2fc7f9cc0e9e9027f69e5c1b6c" => :mojave
sha256 "f3225da4795b1f3c89e25aac62101021f533faebe52fda91101a497da156f797" => :high_sierra
sha256 "e63d866e12db3c5b031b33681a8a6b5163908cbbedde6d33e72e2543a4a75ef2" => :sierra
sha256 "607a5adfb33eca79f847569357c77d643b9be4b17ba73c915575990ad676bddd" => :el_capitan
sha256 "6aac1b96be6144cdb889af5cbcccc3c6779593f3544abdc186d17c61cc4acf34" => :yosemite
end
def install
args = %W[
BINDIR=#{bin}
CC=#{ENV.cc}
CONFDIR=#{etc}
DEVEL_LIBDIR=#{lib}
INCLUDEDIR=#{include}
MANDIR=#{man}
PREFIX=#{prefix}
SECUREDIR_DARWIN=#{prefix}/pam
SHARED_LIBDIR=#{lib}
]
system "make", *args
system "make", "install", *args
end
test do
pipe_output("#{bin}/pwqcheck -1", shell_output("#{bin}/pwqgen"))
end
end
| 33.710526 | 93 | 0.740047 |
d56ae9f266e3dfcd704da0a5e8972d4bdd104b25 | 4,049 | #
# Invokers are responsible for
#
# 1. grabbing work off a job broker (such as a starling or rabbitmq server).
# 2. routing (mapping) that work onto the correct worker method.
# 3.invoking the worker method, passing any arguments that came off the broker.
#
# Invokers should implement their own concurrency strategies. For example,
# The there is a ThreadedPoller which starts a thread for each Worker class.
#
# This base Invoker class defines the methods an Invoker needs to implement.
#
module Workling
module Remote
module Invokers
class Base
attr_accessor :sleep_time, :reset_time
#
# call up with super in the subclass constructor.
#
def initialize(routing, client)
@routing = routing
@client = client
@sleep_time = Workling.config[:sleep_time] || 2
@reset_time = Workling.config[:reset_time] || 30
@@mutex ||= Mutex.new
end
#
# Starts main Invoker Loop. The invoker runs until stop() is called.
#
def listen
raise NotImplementedError.new("Implement listen() in your Invoker. ")
end
#
# Gracefully stops the Invoker. The currently executing Jobs should be allowed
# to finish.
#
def stop
raise NotImplementedError.new("Implement stop() in your Invoker. ")
end
#
# Runs the worker method, given
#
# type: the worker route
# args: the arguments to be passed into the worker method.
#
def run(type, args)
worker = @routing[type]
method = @routing.method_name(type)
worker.dispatch_to_worker_method(method, args)
end
# returns the Workling::Base.logger
def logger; Workling::Base.logger; end
protected
# handle opening and closing of client. pass code block to this method.
def connect
@client.connect
begin
yield
ensure
@client.close
ActiveRecord::Base.verify_active_connections!
end
end
#
# Loops through the available routes, yielding for each route.
# This continues until @shutdown is set on this instance.
#
def loop_routes
while(!@shutdown) do
ensure_activerecord_connection
routes.each do |route|
break if @shutdown
yield route
end
sleep self.sleep_time
end
end
#
# Returns the complete set of active routes
#
def routes
@active_routes ||= Workling::Discovery.discovered.map { |clazz| @routing.queue_names_routing_class(clazz) }.flatten
end
# Thanks for this Brent!
#
# ...Just a heads up, due to how rails’ MySQL adapter handles this
# call ‘ActiveRecord::Base.connection.active?’, you’ll need
# to wrap the code that checks for a connection in in a mutex.
#
# ....I noticed this while working with a multi-core machine that
# was spawning multiple workling threads. Some of my workling
# threads would hit serious issues at this block of code without
# the mutex.
#
def ensure_activerecord_connection
@@mutex.synchronize do
unless ActiveRecord::Base.connection.active? # Keep MySQL connection alive
unless ActiveRecord::Base.connection.reconnect!
logger.fatal("Failed - Database not available!")
break
end
end
end
end
end
end
end
end | 32.918699 | 127 | 0.544332 |
f8f0a69622f42f5304cde52eb9d925f5450eaa2f | 1,660 | # frozen_string_literal: true
# ActiveRecord custom data type for storing datetimes with timezone information.
# See https://gitlab.com/gitlab-org/gitlab-foss/merge_requests/11229
require 'active_record/connection_adapters/postgresql_adapter'
module ActiveRecord::ConnectionAdapters::PostgreSQL::OID
# Add the class `DateTimeWithTimeZone` so we can map `timestamptz` to it.
class DateTimeWithTimeZone < DateTime
def type
:datetime_with_timezone
end
end
end
module RegisterDateTimeWithTimeZone
# Run original `initialize_type_map` and then register `timestamptz` as a
# `DateTimeWithTimeZone`.
#
# Apparently it does not matter that the original `initialize_type_map`
# aliases `timestamptz` to `timestamp`.
#
# When schema dumping, `timestamptz` columns will be output as
# `t.datetime_with_timezone`.
def initialize_type_map(mapping = type_map)
super mapping
register_class_with_precision(
mapping,
'timestamptz',
ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::DateTimeWithTimeZone
)
end
end
class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
prepend RegisterDateTimeWithTimeZone
# Add column type `datetime_with_timezone` so we can do this in
# migrations:
#
# add_column(:users, :datetime_with_timezone)
#
NATIVE_DATABASE_TYPES[:datetime_with_timezone] = { name: 'timestamptz' }
end
# Ensure `datetime_with_timezone` columns are correctly written to schema.rb
if (ActiveRecord::Base.connection.active? rescue false)
ActiveRecord::Base.connection.send :reload_type_map
end
ActiveRecord::Base.time_zone_aware_types += [:datetime_with_timezone]
| 30.740741 | 84 | 0.775301 |
91e63f931c48cdaacec3c9ef7626bf2a06051249 | 1,499 | module ElectricWindowsOperable
def open_windows
'Windows opening...'
end
def close_windows
'Windows closing...'
end
end
class Vehicule
@@number_of_object = 0
attr_accessor :speed, :color
attr_reader :year, :model
def initialize(y, c, m)
@year = y
@color = c
@model = m
@speed = 0
@@number_of_object += 1
end
def speed_up(num)
self.speed += num
end
def brake(num)
self.speed -= num
end
def shut_off
self.speed = 0
end
def current_speed
"Currently at #{speed} km/h"
end
def spray_paint(pigment)
old_color = color
self.color = pigment
"Changing vehicule color from #{old_color} to #{color}."
end
def age
"This vehicule is #{calculate_age} years old!"
end
def self.mileage(km, litres)
"#{format('%.2f', km / litres)} Kilometers per Liter"
end
def self.number_of_object_created
@@number_of_object
end
private
def calculate_age
current_year = Time.now.year
current_year - year
end
end
class MyCar < Vehicule
NUMBER_OF_SEATS = 4
def to_s
"That is a really nice #{color} #{model.capitalize} car from #{year}!"
end
end
class MyTruck < Vehicule
include ElectricWindowsOperable
NUMBER_OF_SEATS = 6
def to_s
"That is a really nice #{color} #{model.capitalize} truck from #{year}!"
end
end
japanese_car = MyCar.new(1999, 'yellow', 'toyota')
puts japanese_car.age
american_car = MyTruck.new(2004, 'blue', 'ford')
puts american_car.age
| 16.11828 | 76 | 0.663109 |
d5886984908c03578f8aa8a5b2505e7d9e496f1c | 2,389 | # frozen_string_literal: true
require 'forwardable'
module Faraday
# Response represents an HTTP response from making an HTTP request.
class Response
# Used for simple response middleware.
class Middleware < Faraday::Middleware
# Override this to modify the environment after the response has finished.
# Calls the `parse` method if defined
# `parse` method can be defined as private, public and protected
def on_complete(env)
return unless respond_to?(:parse, true) && env.parse_body?
env.body = parse(env.body)
end
end
extend Forwardable
extend MiddlewareRegistry
register_middleware File.expand_path('response', __dir__),
raise_error: [:RaiseError, 'raise_error'],
logger: [:Logger, 'logger'],
json: [:Json, 'json']
def initialize(env = nil)
@env = Env.from(env) if env
@on_complete_callbacks = []
end
attr_reader :env
def status
finished? ? env.status : nil
end
def reason_phrase
finished? ? env.reason_phrase : nil
end
def headers
finished? ? env.response_headers : {}
end
def_delegator :headers, :[]
def body
finished? ? env.body : nil
end
def finished?
!!env
end
def on_complete(&block)
if !finished?
@on_complete_callbacks << block
else
yield(env)
end
self
end
def finish(env)
raise 'response already finished' if finished?
@env = env.is_a?(Env) ? env : Env.from(env)
@on_complete_callbacks.each { |callback| callback.call(@env) }
self
end
def success?
finished? && env.success?
end
def to_hash
{
status: env.status, body: env.body,
response_headers: env.response_headers
}
end
# because @on_complete_callbacks cannot be marshalled
def marshal_dump
finished? ? to_hash : nil
end
def marshal_load(env)
@env = Env.from(env)
end
# Expand the env with more properties, without overriding existing ones.
# Useful for applying request params after restoring a marshalled Response.
def apply_request(request_env)
raise "response didn't finish yet" unless finished?
@env = Env.from(request_env).update(@env)
self
end
end
end
| 22.971154 | 80 | 0.62118 |
916f0c88df0e75550f1de45fd179548f21bde735 | 2,194 | # encoding: utf-8
require "logstash/util/loggable"
require "logstash/util"
require "concurrent"
module LogStash module Instrument module PeriodicPoller
class Base
include LogStash::Util::Loggable
DEFAULT_OPTIONS = {
:polling_interval => 5,
:polling_timeout => 120
}
public
def initialize(metric, options = {})
@metric = metric
@options = DEFAULT_OPTIONS.merge(options)
configure_task
end
def update(time, result, exception)
return unless exception
if exception.is_a?(Concurrent::TimeoutError)
# On a busy system this can happen, we just log it as a debug
# event instead of an error, Some of the JVM calls can take a long time or block.
logger.debug("PeriodicPoller: Timeout exception",
:poller => self,
:result => result,
:polling_timeout => @options[:polling_timeout],
:polling_interval => @options[:polling_interval],
:exception => exception.class,
:executed_at => time)
else
logger.error("PeriodicPoller: exception",
:poller => self,
:result => result,
:exception => exception.class,
:polling_timeout => @options[:polling_timeout],
:polling_interval => @options[:polling_interval],
:executed_at => time)
end
end
def collect
raise NotImplementedError, "#{self.class.name} need to implement `#collect`"
end
def start
logger.debug("PeriodicPoller: Starting",
:polling_interval => @options[:polling_interval],
:polling_timeout => @options[:polling_timeout]) if logger.debug?
collect # Collect data right away if possible
@task.execute
end
def stop
logger.debug("PeriodicPoller: Stopping")
@task.shutdown
end
protected
def configure_task
@task = Concurrent::TimerTask.new { collect }
@task.execution_interval = @options[:polling_interval]
@task.timeout_interval = @options[:polling_timeout]
@task.add_observer(self)
end
end
end
end; end
| 29.648649 | 89 | 0.61258 |
ac7b046b94689a1da5c983626f59c4cb959c1cf4 | 1,562 | module PlinkAdmin
class UserUpdateWithActiveStateManager
attr_accessor :user_record
def initialize(user_record)
raise ArgumentError unless user_record.is_a?(Plink::UserRecord)
@user_record = user_record
end
def update_attributes(params)
user_params = params.to_h.symbolize_keys
deactivating = user_params[:is_force_deactivated] == '1' ? true : false
if @user_record.is_force_deactivated != deactivating
user_params.merge!(active_state_params(deactivating))
update_subscriptions(user_params)
end
@user_record.update_attributes(user_params)
end
private
def active_state_params(deactivating)
deactivating ? deactivation_params : reactivation_params
end
def deactivation_params
{
deactivation_date: Time.zone.now,
password_hash: 'resetByAdmin_' + @user_record.password_hash,
email: 'resetByAdmin_' + @user_record.email
}
end
def reactivation_params
{
deactivation_date: nil,
password_hash: @user_record.password_hash.gsub(/resetByAdmin_/,''),
email: @user_record.email.gsub(/resetByAdmin_/,'')
}
end
def update_subscriptions(user_params)
subscribed = user_params[:is_force_deactivated] == '0' ? '1':'0'
preferences = {is_subscribed: subscribed, daily_contest_reminder: subscribed}
plink_user_service.update_subscription_preferences(@user_record.id, preferences)
end
def plink_user_service
Plink::UserService.new(true)
end
end
end
| 28.4 | 86 | 0.706146 |
91f3d1ccc23d0ee06b42947cffd4858809813db1 | 3,388 | FactoryGirl.define do
factory :employer_profile_no_attestation, class: EmployerProfile do
organization { FactoryGirl.build(:organization) }
entity_kind "c_corporation"
sic_code "1111"
transient do
employee_roles []
end
before :create do |employer_profile, evaluator|
unless evaluator.employee_roles.blank?
employer_profile.employee_roles.push *Array.wrap(evaluator.employee_roles)
end
end
end
factory :employer_profile do
organization { FactoryGirl.build(:organization) }
entity_kind "c_corporation"
sic_code "1111"
transient do
employee_roles []
attested true
end
trait :with_full_inbox do
after :create do |employer_profile, evaluator|
inbox { FactoryGirl.create(:inbox, :with_message, recipient: employer_profile) }
end
end
trait :congress do
plan_years { [FactoryGirl.build(:plan_year, :with_benefit_group_congress)] }
end
before :create do |employer_profile, evaluator|
unless evaluator.employee_roles.blank?
employer_profile.employee_roles.push *Array.wrap(evaluator.employee_roles)
end
end
after(:create) do |employer_profile, evaluator|
if evaluator.attested
create(:employer_attestation, employer_profile: employer_profile)
else
create(:employer_attestation, employer_profile: employer_profile, aasm_state: 'unsubmitted')
end
end
factory :employer_profile_congress, traits: [:congress]
end
factory :registered_employer, class: EmployerProfile do
organization { FactoryGirl.build(:organization) }
entity_kind "c_corporation"
sic_code '1111'
transient do
start_on TimeKeeper.date_of_record.beginning_of_month
plan_year_state 'draft'
renewal_plan_year_state 'renewing_draft'
reference_plan_id { FactoryGirl.create(:plan).id }
renewal_reference_plan_id { FactoryGirl.create(:plan).id }
dental_reference_plan_id nil
dental_renewal_reference_plan_id nil
with_dental false
is_conversion false
end
factory :employer_with_planyear do
after(:create) do |employer, evaluator|
create(:custom_plan_year, employer_profile: employer, start_on: evaluator.start_on, aasm_state: evaluator.plan_year_state, with_dental: evaluator.with_dental, reference_plan: evaluator.reference_plan_id, dental_reference_plan: evaluator.dental_reference_plan_id)
create(:employer_attestation, employer_profile: employer)
end
end
factory :employer_with_renewing_planyear do
after(:create) do |employer, evaluator|
create(:custom_plan_year, employer_profile: employer, start_on: evaluator.start_on - 1.year, aasm_state: 'active', is_conversion: evaluator.is_conversion, with_dental: evaluator.with_dental, reference_plan: evaluator.reference_plan_id, dental_reference_plan: evaluator.dental_reference_plan_id)
create(:custom_plan_year, employer_profile: employer, start_on: evaluator.start_on, aasm_state: evaluator.renewal_plan_year_state, renewing: true, with_dental: evaluator.with_dental, reference_plan: evaluator.renewal_reference_plan_id, dental_reference_plan: evaluator.dental_renewal_reference_plan_id)
create(:employer_attestation, employer_profile: employer)
end
end
end
end
| 38.5 | 310 | 0.739669 |
ac185b9c13bade5a924d202c80710efc14618eb5 | 1,727 | require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper.rb')
require 'linode'
describe Linode::Linode::Job do
before :each do
@api_key = 'foo'
@linode = Linode::Linode::Job.new(:api_key => @api_key)
end
it 'should be a Linode instance' do
@linode.class.should < Linode
end
%w(list).each do |action|
it "should allow accessing the #{action} API" do
@linode.should respond_to(action.to_sym)
end
describe "when accessing the #{action} API" do
it 'should allow a data hash' do
lambda { @linode.send(action.to_sym, {}) }.should_not raise_error(ArgumentError)
end
it 'should not require arguments' do
lambda { @linode.send(action.to_sym) }.should_not raise_error(ArgumentError)
end
it "should request the avail.#{action} action" do
@linode.expects(:send_request).with {|api_action, data| api_action == "linode.job.#{action}" }
@linode.send(action.to_sym)
end
it 'should provide the data hash when making its request' do
@linode.expects(:send_request).with {|api_action, data| data = { :foo => :bar } }
@linode.send(action.to_sym, {:foo => :bar})
end
it 'should return the result of the request' do
@linode.expects(:send_request).returns(:bar => :baz)
@linode.send(action.to_sym).should == { :bar => :baz }
end
it "should consider the documentation to live at http://www.linode.com/api/linode/linode.job.#{action}" do
@linode.documentation_path(Linode.action_path(@linode.class.name, action)).should == "http://www.linode.com/api/linode/linode.job.#{action}"
end
end
end
end
| 35.244898 | 148 | 0.63231 |
bfd5266dbb47f7e6eb35df7c227c3ff57e0df1fe | 1,848 | # frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
config.public_file_server.enabled = true
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=3600"
}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
config.action_mailer.perform_caching = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Write to disk for tests
config.active_storage.service = :test
end
| 38.5 | 85 | 0.771645 |
f7b3e1d8e049317bd73cb7a1d8d46d00d6556c61 | 144 | class AddDeletedAtToTransferItems < ActiveRecord::Migration
def change
add_column :spree_transfer_items, :deleted_at, :datetime
end
end
| 24 | 60 | 0.805556 |
b9ef25e686153ba4b9546e86349bc0f285491cce | 443 | class CheckinsEvent
def self.properties(action, checkin)
{
action: action,
user_id: checkin.user_id,
work_id: checkin.episode.work_id,
episode_id: checkin.episode_id,
has_comment: checkin.comment.present?,
shared_sns: checkin.shared_sns?,
keen: { timestamp: checkin.created_at }
}
end
def self.publish(action, checkin)
Keen.publish(:checkins, properties(action, checkin))
end
end
| 24.611111 | 56 | 0.683973 |
79e3dc237a3984c421007f7404f836b5c1965468 | 482 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module HrTil
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 30.125 | 82 | 0.761411 |
332ddf4bbc78e3b0675660a81b7f8deb9b480f69 | 202 | class Array
alias :__old_plus :+
def +(val)
result = __old_plus(val.cur)
if val.reactive? && !result.reactive?
result = ReactiveValue.new(result)
end
return result
end
end
| 15.538462 | 41 | 0.638614 |
d52f3d07fd0dbd4c43f52dbb93127d4f02bf7a3a | 3,981 | require "language/go"
class GitlabRunner < Formula
desc "The official GitLab CI runner written in Go"
homepage "https://gitlab.com/gitlab-org/gitlab-runner"
url "https://gitlab.com/gitlab-org/gitlab-runner.git",
:tag => "v10.1.0",
:revision => "c1ecf97f92aaeee1b8dafe8f58d38d8c7d8aa1ff"
head "https://gitlab.com/gitlab-org/gitlab-runner.git"
bottle do
sha256 "3f0fcd5aca52d0b897315195886be90bc15f21ca5c4b2cce95e05be262b84602" => :high_sierra
sha256 "145bd7b92e810bca7f9ceee70f5ad53e7d81256167f29175a6c6f36de1b12056" => :sierra
sha256 "206fef60e1b8cbb78ec63f71e7c816bc179c71eaeba611015de4913034bcbed3" => :el_capitan
sha256 "c169d2f20421f4c211e45660f72cb17a68dff6c586b385a706a25e6023710d21" => :x86_64_linux
end
depends_on "go" => :build
depends_on "docker" => :recommended
go_resource "github.com/jteeuwen/go-bindata" do
url "https://github.com/jteeuwen/go-bindata.git",
:revision => "a0ff2567cfb70903282db057e799fd826784d41d"
end
resource "prebuilt-x86_64.tar.xz" do
url "https://gitlab-runner-downloads.s3.amazonaws.com/v10.1.0/docker/prebuilt-x86_64.tar.xz",
:using => :nounzip
version "10.1.0"
sha256 "24f7ac81a210ab46ee0852e7ec258ac0a9d3d14dec12dca5406d459435e60e41"
end
resource "prebuilt-arm.tar.xz" do
url "https://gitlab-runner-downloads.s3.amazonaws.com/v10.1.0/docker/prebuilt-arm.tar.xz",
:using => :nounzip
version "10.1.0"
sha256 "9c14a91d5398e8ef99e13b57afa7430aa660791cf8f045e52a4b9566f247f22f"
end
def install
ENV["GOPATH"] = buildpath
dir = buildpath/"src/gitlab.com/gitlab-org/gitlab-runner"
dir.install buildpath.children
ENV.prepend_create_path "PATH", buildpath/"bin"
Language::Go.stage_deps resources, buildpath/"src"
cd "src/github.com/jteeuwen/go-bindata/go-bindata" do
system "go", "install"
end
cd dir do
Pathname.pwd.install resource("prebuilt-x86_64.tar.xz"),
resource("prebuilt-arm.tar.xz")
system "go-bindata", "-pkg", "docker", "-nocompress", "-nomemcopy",
"-nometadata", "-o",
"#{dir}/executors/docker/bindata.go",
"prebuilt-x86_64.tar.xz",
"prebuilt-arm.tar.xz"
proj = "gitlab.com/gitlab-org/gitlab-runner"
commit = Utils.popen_read("git", "rev-parse", "--short", "HEAD").chomp
branch = version.to_s.split(".")[0..1].join("-") + "-stable"
built = Time.new.strftime("%Y-%m-%dT%H:%M:%S%:z")
system "go", "build", "-ldflags", <<~EOS
-X #{proj}/common.NAME=gitlab-runner
-X #{proj}/common.VERSION=#{version}
-X #{proj}/common.REVISION=#{commit}
-X #{proj}/common.BRANCH=#{branch}
-X #{proj}/common.BUILT=#{built}
EOS
bin.install "gitlab-runner"
prefix.install_metafiles
end
end
plist_options :manual => "gitlab-runner start"
def plist; <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SessionCreate</key><false/>
<key>KeepAlive</key><true/>
<key>RunAtLoad</key><true/>
<key>Disabled</key><false/>
<key>Label</key>
<string>#{plist_name}</string>
<key>ProgramArguments</key>
<array>
<string>#{opt_bin}/gitlab-runner</string>
<string>run</string>
<string>--working-directory</string>
<string>#{ENV["HOME"]}</string>
<string>--config</string>
<string>#{ENV["HOME"]}/.gitlab-runner/config.toml</string>
<string>--service</string>
<string>gitlab-runner</string>
<string>--syslog</string>
</array>
</dict>
</plist>
EOS
end
test do
assert_match version.to_s, shell_output("#{bin}/gitlab-runner --version")
end
end
| 35.864865 | 106 | 0.635016 |
bf0ae18ff4fb4b34184ac29d35ea147f10887ab4 | 1,997 | class ResponseProcessingController < ApplicationController
before_action { @hide_available_languages = true }
def index
@rp_name = current_transaction.rp_name
outcome = POLICY_PROXY.matching_outcome(session[:verify_session_id])
case outcome
when MatchingOutcomeResponse::GOTO_HUB_LANDING_PAGE
report_to_analytics("Matching Outcome - Hub Landing")
redirect_to start_path
when MatchingOutcomeResponse::SEND_NO_MATCH_RESPONSE_TO_TRANSACTION
report_to_analytics("Matching Outcome - No Match")
redirect_to redirect_to_service_signing_in_path
when MatchingOutcomeResponse::SEND_SUCCESSFUL_MATCH_RESPONSE_TO_TRANSACTION
report_to_analytics("Matching Outcome - Match")
redirect_to redirect_to_service_signing_in_path
when MatchingOutcomeResponse::SEND_USER_ACCOUNT_CREATED_RESPONSE_TO_TRANSACTION
report_to_analytics("Unknown User Outcome - Account Created")
redirect_to redirect_to_service_signing_in_path
when MatchingOutcomeResponse::GET_C3_DATA
report_to_analytics("Matching Outcome - Cycle3")
redirect_to further_information_path
when MatchingOutcomeResponse::SHOW_MATCHING_ERROR_PAGE
report_to_analytics("Matching Outcome - Error")
render_error_page("MATCHING_ERROR_PAGE")
when MatchingOutcomeResponse::USER_ACCOUNT_CREATION_FAILED
report_to_analytics("Unknown User Outcome - Account Creation Failed")
render_error_page("ACCOUNT_CREATION_FAILED_PAGE")
when MatchingOutcomeResponse::WAIT
render
else
something_went_wrong("Unknown matching response #{outcome.inspect}")
end
end
def render_error_page(feedback_source)
@hide_available_languages = false
@other_ways_text = current_transaction.other_ways_text
@other_ways_description = current_transaction.other_ways_description
@redirect_path = redirect_to_service_error_path
render "matching_error", status: 500, locals: { error_feedback_source: feedback_source }
end
end
| 44.377778 | 92 | 0.7997 |
1d4dcfdd56b833aaa0e1c035e7b0accdc6f7eb3b | 583 | require_relative '../automated_init'
context "Activation" do
context "Optional Factory Method Parameter" do
receiver = OpenStruct.new
factory_method = Controls::FactoryMethod.name
cls = Class.new do
Configure.activate(self, factory_method: factory_method)
configure :some_attr
extend Controls::FactoryMethod
extend Controls::FactoryMethod::Proof
end
context "Receiver is Configured" do
cls.configure(receiver)
test "Factory method was invoked" do
assert(cls.factory_method_called?)
end
end
end
end
| 21.592593 | 62 | 0.703259 |
1d87bd1d0502216ed07bf283add4e65aaed6bf14 | 1,296 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/firestore/admin/v1/firestore_admin"
require "google/cloud/firestore/admin/v1/version"
module Google
module Cloud
module Firestore
module Admin
##
# To load this package, including all its services, and instantiate a client:
#
# require "google/cloud/firestore/admin/v1"
# client = ::Google::Cloud::Firestore::Admin::V1::FirestoreAdmin::Client.new
#
module V1
end
end
end
end
end
helper_path = ::File.join __dir__, "v1", "_helpers.rb"
require "google/cloud/firestore/admin/v1/_helpers" if ::File.file? helper_path
| 31.609756 | 88 | 0.709877 |
183f8716d454c57061caf71867a6db4b553d4090 | 2,001 | class InviteRequest < ActiveRecord::Base
acts_as_list
validates :email, :presence => true, :email_veracity => true
validates_uniqueness_of :email, :message => "is already part of our queue."
before_validation :compare_with_users, :on => :create
# Realign positions if they're incorrect
def self.reset_order
first_request = self.find(:first, :order => :position)
unless first_request && first_request.position == 1
requests = self.find(:all, :order => :position)
requests.each_with_index {|request, index| request.update_attribute(:position, index + 1)}
end
end
def proposed_fill_date
admin_settings = Rails.cache.fetch("admin_settings"){AdminSetting.first}
number_of_rounds = (self.position.to_f/admin_settings.invite_from_queue_number.to_f).ceil - 1
proposed_date = admin_settings.invite_from_queue_at.to_date + (admin_settings.invite_from_queue_frequency * number_of_rounds).days
Date.today > proposed_date ? Date.today : proposed_date
end
#Ensure that invite request is for a new user
def compare_with_users
if User.find_by_email(self.email)
errors.add(:email, "is already being used by an account holder.")
return false
end
end
#Invite a specified number of users
def self.invite
admin_settings = Rails.cache.fetch("admin_settings"){AdminSetting.first}
self.order(:position).limit(admin_settings.invite_from_queue_number).each do |request|
request.invite_and_remove
end
InviteRequest.reset_order
end
#Turn a request into an invite and then remove it from the queue
def invite_and_remove(creator=nil)
invitation = creator ? creator.invitations.build(:invitee_email => self.email, :from_queue => true) :
Invitation.new(:invitee_email => self.email, :from_queue => true)
if invitation.save
Rails.logger.info "#{invitation.invitee_email} was invited at #{Time.now}"
self.destroy
end
end
end
| 39.235294 | 134 | 0.716142 |
1d32b5e7bb1ed4d49dafecc80649f6fce96e41e2 | 1,171 | module HealthDataStandards
module Import
module C32
class ImmunizationImporter < CDA::SectionImporter
def initialize(entry_finder=CDA::EntryFinder.new("//cda:section[cda:templateId/@root='2.16.840.1.113883.3.88.11.83.117']/cda:entry/cda:substanceAdministration"))
super(entry_finder)
@code_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code"
@description_xpath = "./cda:consumable/cda:manufacturedProduct/cda:manufacturedMaterial/cda:code/cda:originalText/cda:reference[@value]"
@entry_class = Immunization
end
def create_entry(entry_element, nrh = CDA::NarrativeReferenceHandler.new)
immunization = super
extract_reason_or_negation(entry_element, immunization)
extract_performer(entry_element, immunization)
immunization
end
private
def extract_performer(parent_element, immunization)
performer_element = parent_element.at_xpath("./cda:performer")
immunization.performer = import_actor(performer_element) if performer_element
end
end
end
end
end | 40.37931 | 169 | 0.701964 |
398ab7279bfdc8d987b666c9989855f3235db7ad | 24,140 | # frozen_string_literal: true
require 'time'
require 'test/unit'
class TestTimeExtension < Test::Unit::TestCase # :nodoc:
def test_rfc822
t = Time.rfc2822("26 Aug 76 14:30 EDT")
assert_equal(Time.utc(1976, 8, 26, 14, 30) + 4 * 3600, t)
assert_equal(-4 * 3600, t.utc_offset)
t = Time.rfc2822("27 Aug 76 09:32 PDT")
assert_equal(Time.utc(1976, 8, 27, 9, 32) + 7 * 3600, t)
assert_equal(-7 * 3600, t.utc_offset)
end
def test_rfc2822
t = Time.rfc2822("Fri, 21 Nov 1997 09:55:06 -0600")
assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600, t)
assert_equal(-6 * 3600, t.utc_offset)
t = Time.rfc2822("Tue, 1 Jul 2003 10:52:37 +0200")
assert_equal(Time.utc(2003, 7, 1, 10, 52, 37) - 2 * 3600, t)
assert_equal(2 * 3600, t.utc_offset)
t = Time.rfc2822("Fri, 21 Nov 1997 10:01:10 -0600")
assert_equal(Time.utc(1997, 11, 21, 10, 1, 10) + 6 * 3600, t)
assert_equal(-6 * 3600, t.utc_offset)
t = Time.rfc2822("Fri, 21 Nov 1997 11:00:00 -0600")
assert_equal(Time.utc(1997, 11, 21, 11, 0, 0) + 6 * 3600, t)
assert_equal(-6 * 3600, t.utc_offset)
t = Time.rfc2822("Mon, 24 Nov 1997 14:22:01 -0800")
assert_equal(Time.utc(1997, 11, 24, 14, 22, 1) + 8 * 3600, t)
assert_equal(-8 * 3600, t.utc_offset)
begin
Time.at(-1)
rescue ArgumentError
# ignore
else
t = Time.rfc2822("Thu, 13 Feb 1969 23:32:54 -0330")
assert_equal(Time.utc(1969, 2, 13, 23, 32, 54) + 3 * 3600 + 30 * 60, t)
assert_equal(-3 * 3600 - 30 * 60, t.utc_offset)
t = Time.rfc2822(" Thu,
13
Feb
1969
23:32
-0330 (Newfoundland Time)")
assert_equal(Time.utc(1969, 2, 13, 23, 32, 0) + 3 * 3600 + 30 * 60, t)
assert_equal(-3 * 3600 - 30 * 60, t.utc_offset)
end
t = Time.rfc2822("21 Nov 97 09:55:06 GMT")
assert_equal(Time.utc(1997, 11, 21, 9, 55, 6), t)
assert_equal(0, t.utc_offset)
t = Time.rfc2822("Fri, 21 Nov 1997 09 : 55 : 06 -0600")
assert_equal(Time.utc(1997, 11, 21, 9, 55, 6) + 6 * 3600, t)
assert_equal(-6 * 3600, t.utc_offset)
assert_raise(ArgumentError) {
# inner comment is not supported.
Time.rfc2822("Fri, 21 Nov 1997 09(comment): 55 : 06 -0600")
}
t = Time.rfc2822("Mon, 01 Jan 0001 00:00:00 -0000")
assert_equal(Time.utc(1, 1, 1, 0, 0, 0), t)
assert_equal(0, t.utc_offset)
assert_equal(true, t.utc?)
end
def test_encode_rfc2822
t = Time.utc(1)
assert_equal("Mon, 01 Jan 0001 00:00:00 -0000", t.rfc2822)
end
def test_rfc2616
t = Time.utc(1994, 11, 6, 8, 49, 37)
assert_equal(t, Time.httpdate("Sun, 06 Nov 1994 08:49:37 GMT"))
assert_equal(t, Time.httpdate("Sunday, 06-Nov-94 08:49:37 GMT"))
assert_equal(t, Time.httpdate("Sun Nov 6 08:49:37 1994"))
assert_equal(Time.utc(1995, 11, 15, 6, 25, 24),
Time.httpdate("Wed, 15 Nov 1995 06:25:24 GMT"))
assert_equal(Time.utc(1995, 11, 15, 4, 58, 8),
Time.httpdate("Wed, 15 Nov 1995 04:58:08 GMT"))
assert_equal(Time.utc(1994, 11, 15, 8, 12, 31),
Time.httpdate("Tue, 15 Nov 1994 08:12:31 GMT"))
assert_equal(Time.utc(1994, 12, 1, 16, 0, 0),
Time.httpdate("Thu, 01 Dec 1994 16:00:00 GMT"))
assert_equal(Time.utc(1994, 10, 29, 19, 43, 31),
Time.httpdate("Sat, 29 Oct 1994 19:43:31 GMT"))
assert_equal(Time.utc(1994, 11, 15, 12, 45, 26),
Time.httpdate("Tue, 15 Nov 1994 12:45:26 GMT"))
assert_equal(Time.utc(1999, 12, 31, 23, 59, 59),
Time.httpdate("Fri, 31 Dec 1999 23:59:59 GMT"))
assert_equal(Time.utc(2007, 12, 23, 11, 22, 33),
Time.httpdate('Sunday, 23-Dec-07 11:22:33 GMT'))
end
def test_encode_httpdate
t = Time.utc(1)
assert_equal("Mon, 01 Jan 0001 00:00:00 GMT", t.httpdate)
end
def subtest_xmlschema_alias(method)
t = Time.utc(1985, 4, 12, 23, 20, 50, 520000)
s = "1985-04-12T23:20:50.52Z"
assert_equal(t, Time.__send__(method, s))
assert_equal(s, t.__send__(method, 2))
t = Time.utc(1996, 12, 20, 0, 39, 57)
s = "1996-12-19T16:39:57-08:00"
assert_equal(t, Time.__send__(method, s))
# There is no way to generate time string with arbitrary timezone.
s = "1996-12-20T00:39:57Z"
assert_equal(t, Time.__send__(method, s))
assert_equal(s, t.iso8601)
t = Time.utc(1990, 12, 31, 23, 59, 60)
s = "1990-12-31T23:59:60Z"
assert_equal(t, Time.__send__(method, s))
# leap second is representable only if timezone file has it.
s = "1990-12-31T15:59:60-08:00"
assert_equal(t, Time.__send__(method, s))
begin
Time.at(-1)
rescue ArgumentError
# ignore
else
t = Time.utc(1937, 1, 1, 11, 40, 27, 870000)
s = "1937-01-01T12:00:27.87+00:20"
assert_equal(t, Time.__send__(method, s))
end
end
# http://www.w3.org/TR/xmlschema-2/
def subtest_xmlschema(method)
assert_equal(Time.utc(1999, 5, 31, 13, 20, 0) + 5 * 3600,
Time.__send__(method, "1999-05-31T13:20:00-05:00"))
assert_equal(Time.local(2000, 1, 20, 12, 0, 0),
Time.__send__(method, "2000-01-20T12:00:00"))
assert_equal(Time.utc(2000, 1, 20, 12, 0, 0),
Time.__send__(method, "2000-01-20T12:00:00Z"))
assert_equal(Time.utc(2000, 1, 20, 12, 0, 0) - 12 * 3600,
Time.__send__(method, "2000-01-20T12:00:00+12:00"))
assert_equal(Time.utc(2000, 1, 20, 12, 0, 0) + 13 * 3600,
Time.__send__(method, "2000-01-20T12:00:00-13:00"))
assert_equal(Time.utc(2000, 3, 4, 23, 0, 0) - 3 * 3600,
Time.__send__(method, "2000-03-04T23:00:00+03:00"))
assert_equal(Time.utc(2000, 3, 4, 20, 0, 0),
Time.__send__(method, "2000-03-04T20:00:00Z"))
assert_equal(Time.local(2000, 1, 15, 0, 0, 0),
Time.__send__(method, "2000-01-15T00:00:00"))
assert_equal(Time.local(2000, 2, 15, 0, 0, 0),
Time.__send__(method, "2000-02-15T00:00:00"))
assert_equal(Time.local(2000, 1, 15, 12, 0, 0),
Time.__send__(method, "2000-01-15T12:00:00"))
assert_equal(Time.utc(2000, 1, 16, 12, 0, 0),
Time.__send__(method, "2000-01-16T12:00:00Z"))
assert_equal(Time.local(2000, 1, 1, 12, 0, 0),
Time.__send__(method, "2000-01-01T12:00:00"))
assert_equal(Time.utc(1999, 12, 31, 23, 0, 0),
Time.__send__(method, "1999-12-31T23:00:00Z"))
assert_equal(Time.local(2000, 1, 16, 12, 0, 0),
Time.__send__(method, "2000-01-16T12:00:00"))
assert_equal(Time.local(2000, 1, 16, 0, 0, 0),
Time.__send__(method, "2000-01-16T00:00:00"))
assert_equal(Time.utc(2000, 1, 12, 12, 13, 14),
Time.__send__(method, "2000-01-12T12:13:14Z"))
assert_equal(Time.utc(2001, 4, 17, 19, 23, 17, 300000),
Time.__send__(method, "2001-04-17T19:23:17.3Z"))
assert_equal(Time.utc(2000, 1, 2, 0, 0, 0),
Time.__send__(method, "2000-01-01T24:00:00Z"))
assert_raise(ArgumentError) { Time.__send__(method, "2000-01-01T00:00:00.+00:00") }
end
def subtest_xmlschema_encode(method)
bug6100 = '[ruby-core:42997]'
t = Time.utc(2001, 4, 17, 19, 23, 17, 300000)
assert_equal("2001-04-17T19:23:17Z", t.__send__(method))
assert_equal("2001-04-17T19:23:17.3Z", t.__send__(method, 1))
assert_equal("2001-04-17T19:23:17.300000Z", t.__send__(method, 6))
assert_equal("2001-04-17T19:23:17.3000000Z", t.__send__(method, 7))
assert_equal("2001-04-17T19:23:17.3Z", t.__send__(method, 1.9), bug6100)
t = Time.utc(2001, 4, 17, 19, 23, 17, 123456)
assert_equal("2001-04-17T19:23:17.1234560Z", t.__send__(method, 7))
assert_equal("2001-04-17T19:23:17.123456Z", t.__send__(method, 6))
assert_equal("2001-04-17T19:23:17.12345Z", t.__send__(method, 5))
assert_equal("2001-04-17T19:23:17.1Z", t.__send__(method, 1))
assert_equal("2001-04-17T19:23:17.1Z", t.__send__(method, 1.9), bug6100)
t = Time.at(2.quo(3)).getlocal("+09:00")
assert_equal("1970-01-01T09:00:00.666+09:00", t.__send__(method, 3))
assert_equal("1970-01-01T09:00:00.6666666666+09:00", t.__send__(method, 10))
assert_equal("1970-01-01T09:00:00.66666666666666666666+09:00", t.__send__(method, 20))
assert_equal("1970-01-01T09:00:00.6+09:00", t.__send__(method, 1.1), bug6100)
assert_equal("1970-01-01T09:00:00.666+09:00", t.__send__(method, 3.2), bug6100)
t = Time.at(123456789.quo(9999999999)).getlocal("+09:00")
assert_equal("1970-01-01T09:00:00.012+09:00", t.__send__(method, 3))
assert_equal("1970-01-01T09:00:00.012345678+09:00", t.__send__(method, 9))
assert_equal("1970-01-01T09:00:00.0123456789+09:00", t.__send__(method, 10))
assert_equal("1970-01-01T09:00:00.0123456789012345678+09:00", t.__send__(method, 19))
assert_equal("1970-01-01T09:00:00.01234567890123456789+09:00", t.__send__(method, 20))
assert_equal("1970-01-01T09:00:00.012+09:00", t.__send__(method, 3.8), bug6100)
t = Time.utc(1)
assert_equal("0001-01-01T00:00:00Z", t.__send__(method))
begin
Time.at(-1)
rescue ArgumentError
# ignore
else
t = Time.utc(1960, 12, 31, 23, 0, 0, 123456)
assert_equal("1960-12-31T23:00:00.123456Z", t.__send__(method, 6))
end
assert_equal(249, Time.__send__(method, "2008-06-05T23:49:23.000249+09:00").usec)
assert_equal("10000-01-01T00:00:00Z", Time.utc(10000).__send__(method))
assert_equal("9999-01-01T00:00:00Z", Time.utc(9999).__send__(method))
assert_equal("0001-01-01T00:00:00Z", Time.utc(1).__send__(method)) # 1 AD
assert_equal("0000-01-01T00:00:00Z", Time.utc(0).__send__(method)) # 1 BC
assert_equal("-0001-01-01T00:00:00Z", Time.utc(-1).__send__(method)) # 2 BC
assert_equal("-0004-01-01T00:00:00Z", Time.utc(-4).__send__(method)) # 5 BC
assert_equal("-9999-01-01T00:00:00Z", Time.utc(-9999).__send__(method))
assert_equal("-10000-01-01T00:00:00Z", Time.utc(-10000).__send__(method))
end
def test_completion
now = Time.local(2001,11,29,21,26,35)
assert_equal(Time.local( 2001,11,29,21,12),
Time.parse("2001/11/29 21:12", now))
assert_equal(Time.local( 2001,11,29),
Time.parse("2001/11/29", now))
assert_equal(Time.local( 2001,11,29),
Time.parse( "11/29", now))
#assert_equal(Time.local(2001,11,1), Time.parse("Nov", now))
assert_equal(Time.local( 2001,11,29,10,22),
Time.parse( "10:22", now))
assert_raise(ArgumentError) { Time.parse("foo", now) }
end
def test_completion_with_different_timezone
now = Time.new(2001,2,3,0,0,0,"+09:00") # 2001-02-02 15:00:00 UTC
t = Time.parse("10:20:30 GMT", now)
assert_equal(Time.utc(2001,2,2,10,20,30), t)
assert_equal(false, t.utc?)
assert_equal(0, t.utc_offset)
end
def test_invalid
# They were actually used in some web sites.
assert_raise(ArgumentError) { Time.httpdate("1 Dec 2001 10:23:57 GMT") }
assert_raise(ArgumentError) { Time.httpdate("Sat, 1 Dec 2001 10:25:42 GMT") }
assert_raise(ArgumentError) { Time.httpdate("Sat, 1-Dec-2001 10:53:55 GMT") }
assert_raise(ArgumentError) { Time.httpdate("Saturday, 01-Dec-2001 10:15:34 GMT") }
assert_raise(ArgumentError) { Time.httpdate("Saturday, 01-Dec-101 11:10:07 GMT") }
assert_raise(ArgumentError) { Time.httpdate("Fri, 30 Nov 2001 21:30:00 JST") }
# They were actually used in some mails.
assert_raise(ArgumentError) { Time.rfc2822("01-5-20") }
assert_raise(ArgumentError) { Time.rfc2822("7/21/00") }
assert_raise(ArgumentError) { Time.rfc2822("2001-8-28") }
assert_raise(ArgumentError) { Time.rfc2822("00-5-6 1:13:06") }
assert_raise(ArgumentError) { Time.rfc2822("2001-9-27 9:36:49") }
assert_raise(ArgumentError) { Time.rfc2822("2000-12-13 11:01:11") }
assert_raise(ArgumentError) { Time.rfc2822("2001/10/17 04:29:55") }
assert_raise(ArgumentError) { Time.rfc2822("9/4/2001 9:23:19 PM") }
assert_raise(ArgumentError) { Time.rfc2822("01 Nov 2001 09:04:31") }
assert_raise(ArgumentError) { Time.rfc2822("13 Feb 2001 16:4 GMT") }
assert_raise(ArgumentError) { Time.rfc2822("01 Oct 00 5:41:19 PM") }
assert_raise(ArgumentError) { Time.rfc2822("2 Jul 00 00:51:37 JST") }
assert_raise(ArgumentError) { Time.rfc2822("01 11 2001 06:55:57 -0500") }
assert_raise(ArgumentError) { Time.rfc2822("18 \343\366\356\341\370 2000") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, Oct 2001 18:53:32") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 2 Nov 2001 03:47:54") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 27 Jul 2001 11.14.14 +0200") }
assert_raise(ArgumentError) { Time.rfc2822("Thu, 2 Nov 2000 04:13:53 -600") }
assert_raise(ArgumentError) { Time.rfc2822("Wed, 5 Apr 2000 22:57:09 JST") }
assert_raise(ArgumentError) { Time.rfc2822("Mon, 11 Sep 2000 19:47:33 00000") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 28 Apr 2000 20:40:47 +-900") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 19 Jan 2001 8:15:36 AM -0500") }
assert_raise(ArgumentError) { Time.rfc2822("Thursday, Sep 27 2001 7:42:35 AM EST") }
assert_raise(ArgumentError) { Time.rfc2822("3/11/2001 1:31:57 PM Pacific Daylight Time") }
assert_raise(ArgumentError) { Time.rfc2822("Mi, 28 Mrz 2001 11:51:36") }
assert_raise(ArgumentError) { Time.rfc2822("P, 30 sept 2001 23:03:14") }
assert_raise(ArgumentError) { Time.rfc2822("fr, 11 aug 2000 18:39:22") }
assert_raise(ArgumentError) { Time.rfc2822("Fr, 21 Sep 2001 17:44:03 -1000") }
assert_raise(ArgumentError) { Time.rfc2822("Mo, 18 Jun 2001 19:21:40 -1000") }
assert_raise(ArgumentError) { Time.rfc2822("l\366, 12 aug 2000 18:53:20") }
assert_raise(ArgumentError) { Time.rfc2822("l\366, 26 maj 2001 00:15:58") }
assert_raise(ArgumentError) { Time.rfc2822("Dom, 30 Sep 2001 17:36:30") }
assert_raise(ArgumentError) { Time.rfc2822("%&, 31 %2/ 2000 15:44:47 -0500") }
assert_raise(ArgumentError) { Time.rfc2822("dom, 26 ago 2001 03:57:07 -0300") }
assert_raise(ArgumentError) { Time.rfc2822("ter, 04 set 2001 16:27:58 -0300") }
assert_raise(ArgumentError) { Time.rfc2822("Wen, 3 oct 2001 23:17:49 -0400") }
assert_raise(ArgumentError) { Time.rfc2822("Wen, 3 oct 2001 23:17:49 -0400") }
assert_raise(ArgumentError) { Time.rfc2822("ele, 11 h: 2000 12:42:15 -0500") }
assert_raise(ArgumentError) { Time.rfc2822("Tue, 14 Aug 2001 3:55:3 +0200") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 25 Aug 2000 9:3:48 +0800") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 1 Dec 2000 0:57:50 EST") }
assert_raise(ArgumentError) { Time.rfc2822("Mon, 7 May 2001 9:39:51 +0200") }
assert_raise(ArgumentError) { Time.rfc2822("Wed, 1 Aug 2001 16:9:15 +0200") }
assert_raise(ArgumentError) { Time.rfc2822("Wed, 23 Aug 2000 9:17:36 +0800") }
assert_raise(ArgumentError) { Time.rfc2822("Fri, 11 Aug 2000 10:4:42 +0800") }
assert_raise(ArgumentError) { Time.rfc2822("Sat, 15 Sep 2001 13:22:2 +0300") }
assert_raise(ArgumentError) { Time.rfc2822("Wed,16 \276\305\324\302 2001 20:06:25 +0800") }
assert_raise(ArgumentError) { Time.rfc2822("Wed,7 \312\256\322\273\324\302 2001 23:47:22 +0800") }
assert_raise(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=C5=DA),?= 10 2 2001 23:32:26 +0900 (JST)") }
assert_raise(ArgumentError) { Time.rfc2822("\307\341\314\343\332\311, 30 \344\346\335\343\310\321 2001 10:01:06") }
assert_raise(ArgumentError) { Time.rfc2822("=?iso-8859-1?Q?(=BF=E5),?= 12 =?iso-8859-1?Q?9=B7=EE?= 2001 14:52:41\n+0900 (JST)") }
# Out of range arguments
assert_raise(ArgumentError) { Time.parse("2014-13-13T18:00:00-0900") }
end
def test_zone_0000
assert_equal(true, Time.parse("2000-01-01T00:00:00Z").utc?)
assert_equal(true, Time.parse("2000-01-01T00:00:00-00:00").utc?)
assert_equal(false, Time.parse("2000-01-01T00:00:00+00:00").utc?)
assert_equal(false, Time.parse("Sat, 01 Jan 2000 00:00:00 GMT").utc?)
assert_equal(true, Time.parse("Sat, 01 Jan 2000 00:00:00 -0000").utc?)
assert_equal(false, Time.parse("Sat, 01 Jan 2000 00:00:00 +0000").utc?)
assert_equal(false, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 GMT").utc?)
assert_equal(true, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 -0000").utc?)
assert_equal(false, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 +0000").utc?)
assert_equal(true, Time.rfc2822("Sat, 01 Jan 2000 00:00:00 UTC").utc?)
end
def test_rfc2822_utc_roundtrip_winter
t1 = Time.local(2008,12,1)
t2 = Time.rfc2822(t1.rfc2822)
assert_equal(t1.utc?, t2.utc?, "[ruby-dev:37126]")
end
def test_rfc2822_utc_roundtrip_summer
t1 = Time.local(2008,8,1)
t2 = Time.rfc2822(t1.rfc2822)
assert_equal(t1.utc?, t2.utc?)
end
def test_parse_now_nil
assert_equal(Time.new(2000,1,1,0,0,0,"+11:00"),
Time.parse("2000-01-01T00:00:00+11:00", nil))
end
def test_parse_leap_second
t = Time.utc(1998,12,31,23,59,59)
assert_equal(t, Time.parse("Thu Dec 31 23:59:59 UTC 1998"))
assert_equal(t, Time.parse("Fri Dec 31 23:59:59 -0000 1998"));t.localtime
assert_equal(t, Time.parse("Fri Jan 1 08:59:59 +0900 1999"))
assert_equal(t, Time.parse("Fri Jan 1 00:59:59 +0100 1999"))
assert_equal(t, Time.parse("Fri Dec 31 23:59:59 +0000 1998"))
assert_equal(t, Time.parse("Fri Dec 31 22:59:59 -0100 1998"));t.utc
t += 1
assert_equal(t, Time.parse("Thu Dec 31 23:59:60 UTC 1998"))
assert_equal(t, Time.parse("Fri Dec 31 23:59:60 -0000 1998"));t.localtime
assert_equal(t, Time.parse("Fri Jan 1 08:59:60 +0900 1999"))
assert_equal(t, Time.parse("Fri Jan 1 00:59:60 +0100 1999"))
assert_equal(t, Time.parse("Fri Dec 31 23:59:60 +0000 1998"))
assert_equal(t, Time.parse("Fri Dec 31 22:59:60 -0100 1998"));t.utc
t += 1 if t.sec == 60
assert_equal(t, Time.parse("Thu Jan 1 00:00:00 UTC 1999"))
assert_equal(t, Time.parse("Fri Jan 1 00:00:00 -0000 1999"));t.localtime
assert_equal(t, Time.parse("Fri Jan 1 09:00:00 +0900 1999"))
assert_equal(t, Time.parse("Fri Jan 1 01:00:00 +0100 1999"))
assert_equal(t, Time.parse("Fri Jan 1 00:00:00 +0000 1999"))
assert_equal(t, Time.parse("Fri Dec 31 23:00:00 -0100 1998"))
end
def test_rfc2822_leap_second
t = Time.utc(1998,12,31,23,59,59)
assert_equal(t, Time.rfc2822("Thu, 31 Dec 1998 23:59:59 UTC"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:59 -0000"));t.localtime
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 08:59:59 +0900"))
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:59:59 +0100"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:59 +0000"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 22:59:59 -0100"));t.utc
t += 1
assert_equal(t, Time.rfc2822("Thu, 31 Dec 1998 23:59:60 UTC"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:60 -0000"));t.localtime
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 08:59:60 +0900"))
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:59:60 +0100"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:59:60 +0000"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 22:59:60 -0100"));t.utc
t += 1 if t.sec == 60
assert_equal(t, Time.rfc2822("Thu, 1 Jan 1999 00:00:00 UTC"))
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:00:00 -0000"));t.localtime
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 09:00:00 +0900"))
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 01:00:00 +0100"))
assert_equal(t, Time.rfc2822("Fri, 1 Jan 1999 00:00:00 +0000"))
assert_equal(t, Time.rfc2822("Fri, 31 Dec 1998 23:00:00 -0100"))
end
def subtest_xmlschema_leap_second(method)
t = Time.utc(1998,12,31,23,59,59)
assert_equal(t, Time.__send__(method, "1998-12-31T23:59:59Z"))
assert_equal(t, Time.__send__(method, "1998-12-31T23:59:59-00:00"));t.localtime
assert_equal(t, Time.__send__(method, "1999-01-01T08:59:59+09:00"))
assert_equal(t, Time.__send__(method, "1999-01-01T00:59:59+01:00"))
assert_equal(t, Time.__send__(method, "1998-12-31T23:59:59+00:00"))
assert_equal(t, Time.__send__(method, "1998-12-31T22:59:59-01:00"));t.utc
t += 1
assert_equal(t, Time.__send__(method, "1998-12-31T23:59:60Z"))
assert_equal(t, Time.__send__(method, "1998-12-31T23:59:60-00:00"));t.localtime
assert_equal(t, Time.__send__(method, "1999-01-01T08:59:60+09:00"))
assert_equal(t, Time.__send__(method, "1999-01-01T00:59:60+01:00"))
assert_equal(t, Time.__send__(method, "1998-12-31T23:59:60+00:00"))
assert_equal(t, Time.__send__(method, "1998-12-31T22:59:60-01:00"));t.utc
t += 1 if t.sec == 60
assert_equal(t, Time.__send__(method, "1999-01-01T00:00:00Z"))
assert_equal(t, Time.__send__(method, "1999-01-01T00:00:00-00:00"));t.localtime
assert_equal(t, Time.__send__(method, "1999-01-01T09:00:00+09:00"))
assert_equal(t, Time.__send__(method, "1999-01-01T01:00:00+01:00"))
assert_equal(t, Time.__send__(method, "1999-01-01T00:00:00+00:00"))
assert_equal(t, Time.__send__(method, "1998-12-31T23:00:00-01:00"))
end
def subtest_xmlschema_fraction(method)
assert_equal(500000, Time.__send__(method, "2000-01-01T00:00:00.5+00:00").tv_usec)
end
def test_ruby_talk_152866
t = Time::xmlschema('2005-08-30T22:48:00-07:00')
assert_equal(30, t.day)
assert_equal(8, t.mon)
assert_equal(-7*3600, t.utc_offset)
t.utc
assert_equal(31, t.day)
assert_equal(8, t.mon)
assert_equal(0, t.utc_offset)
end
def test_parse_fraction
assert_equal(500000, Time.parse("2000-01-01T00:00:00.5+00:00").tv_usec)
end
def test_strptime
assert_equal(Time.utc(2005, 8, 28, 06, 54, 20), Time.strptime("28/Aug/2005:06:54:20 +0000", "%d/%b/%Y:%T %z"))
assert_equal(Time.at(1).localtime, Time.strptime("1", "%s"))
assert_equal(false, Time.strptime('0', '%s').utc?)
end
def test_strptime_empty
assert_raise(ArgumentError) { Time.strptime('', '') }
assert_raise(ArgumentError) { Time.strptime('+09:00', '%z') } # [ruby-core:62351] by matz.
end
def test_strptime_s_z
t = Time.strptime('0 +0100', '%s %z')
assert_equal(0, t.to_r)
assert_equal(3600, t.utc_offset)
t = Time.strptime('0 UTC', '%s %z')
assert_equal(0, t.to_r)
assert_equal(0, t.utc_offset)
assert_equal(true, t.utc?)
end
def test_strptime_s_N
assert_equal(Time.at(1, 500000), Time.strptime("1.5", "%s.%N"))
assert_equal(Time.at(-2, 500000), Time.strptime("-1.5", "%s.%N"))
t = Time.strptime("1.000000000001", "%s.%N")
assert_equal(1, t.to_i)
assert_equal(Rational("0.000000000001"), t.subsec)
t = Time.strptime("-1.000000000001", "%s.%N")
assert_equal(-2, t.to_i)
assert_equal(1-Rational("0.000000000001"), t.subsec)
end
def test_strptime_Ymd_z
t = Time.strptime('20010203 -0200', '%Y%m%d %z')
assert_equal(2001, t.year)
assert_equal(2, t.mon)
assert_equal(3, t.day)
assert_equal(0, t.hour)
assert_equal(0, t.min)
assert_equal(0, t.sec)
assert_equal(-7200, t.utc_offset)
t = Time.strptime('20010203 UTC', '%Y%m%d %z')
assert_equal(2001, t.year)
assert_equal(2, t.mon)
assert_equal(3, t.day)
assert_equal(0, t.hour)
assert_equal(0, t.min)
assert_equal(0, t.sec)
assert_equal(0, t.utc_offset)
assert_equal(true, t.utc?)
end
def test_nsec
assert_equal(123456789, Time.parse("2000-01-01T00:00:00.123456789+00:00").tv_nsec)
end
def subtest_xmlschema_nsec(method)
assert_equal(123456789, Time.__send__(method, "2000-01-01T00:00:00.123456789+00:00").tv_nsec)
end
def test_huge_precision
bug4456 = '[ruby-dev:43284]'
assert_normal_exit %q{ Time.now.strftime("%1000000000F") }, bug4456
end
instance_methods(false).grep(/\Asub(test_xmlschema.*)/) do |sub|
test = $1
define_method(test) {__send__(sub, :xmlschema)}
define_method(test.sub(/xmlschema/, 'iso8601')) {__send__(sub, :iso8601)}
end
end
| 47.519685 | 134 | 0.647349 |
033c45c8fab90407d792fa260edead735b56ee3f | 1,671 | require File.expand_path('../helper', __FILE__)
begin
require 'nokogiri'
class NokogiriTest < Test::Unit::TestCase
def nokogiri_app(&block)
mock_app do
set :views, File.dirname(__FILE__) + '/views'
get('/', &block)
end
get '/'
end
it 'renders inline Nokogiri strings' do
nokogiri_app { nokogiri 'xml' }
assert ok?
assert_body %(<?xml version="1.0"?>\n)
end
it 'renders inline blocks' do
nokogiri_app do
@name = "Frank & Mary"
nokogiri { |xml| xml.couple @name }
end
assert ok?
assert_body %(<?xml version="1.0"?>\n<couple>Frank & Mary</couple>\n)
end
it 'renders .nokogiri files in views path' do
nokogiri_app do
@name = "Blue"
nokogiri :hello
end
assert ok?
assert_body "<?xml version=\"1.0\"?>\n<exclaim>You're my boy, Blue!</exclaim>\n"
end
it "renders with inline layouts" do
next if Tilt::VERSION <= "1.1"
mock_app do
layout { %(xml.layout { xml << yield }) }
get('/') { nokogiri %(xml.em 'Hello World') }
end
get '/'
assert ok?
assert_body %(<?xml version="1.0"?>\n<layout>\n <em>Hello World</em>\n</layout>\n)
end
it "renders with file layouts" do
next if Tilt::VERSION <= "1.1"
nokogiri_app {
nokogiri %(xml.em 'Hello World'), :layout => :layout2
}
assert ok?
assert_body %(<?xml version="1.0"?>\n<layout>\n <em>Hello World</em>\n</layout>\n)
end
it "raises error if template not found" do
mock_app { get('/') { nokogiri :no_such_template } }
assert_raise(Errno::ENOENT) { get('/') }
end
end
rescue LoadError
warn "#{$!.to_s}: skipping nokogiri tests"
end
| 24.573529 | 87 | 0.605625 |
e811ae9594c237c332d81ff5123f295d10d80093 | 4,540 | # == Schema Information
#
# Table name: expense_items
#
# id :integer not null, primary key
# position :integer
# created_at :datetime
# updated_at :datetime
# expense_group_id :integer
# has_details :boolean default(FALSE), not null
# maximum_available :integer
# has_custom_cost :boolean default(FALSE), not null
# maximum_per_registrant :integer default(0)
# cost_cents :integer
# tax_cents :integer default(0), not null
#
# Indexes
#
# index_expense_items_expense_group_id (expense_group_id)
#
class ExpenseItem < ActiveRecord::Base
validates :name, :cost, :expense_group, presence: true
validates :has_details, inclusion: { in: [true, false] } # because it's a boolean
validates :has_custom_cost, inclusion: { in: [true, false] } # because it's a boolean
monetize :tax_cents, :cost_cents, numericality: { greater_than_or_equal_to: 0 }
monetize :total_cost_cents
has_many :payment_details, dependent: :restrict_with_exception
has_many :registrant_expense_items, inverse_of: :expense_item, dependent: :restrict_with_exception
has_many :coupon_code_expense_items, dependent: :destroy
translates :name, :details_label, fallbacks_for_empty_translations: true
accepts_nested_attributes_for :translations
belongs_to :expense_group, inverse_of: :expense_items
validates :expense_group_id, uniqueness: true, if: "(expense_group.try(:competitor_required) == true) or (expense_group.try(:noncompetitor_required) == true)"
acts_as_restful_list
before_destroy :check_for_payment_details
after_create :create_reg_items
def self.ordered
order(:expense_group_id, :position)
end
def self.user_manageable
includes(:expense_group).where(expense_groups: { registration_items: false })
end
# items paid for
def paid_items
payment_details.paid.where(refunded: false)
end
def refunded_items
payment_details.paid.where(refunded: true)
end
def num_paid_with_coupon
paid_items.with_coupon.count
end
def num_paid_without_coupon
num_paid - num_paid_with_coupon
end
# How many of this expense item are free
def num_free
free_items.count
end
def free_items
paid_free_items + free_items_with_reg_paid
end
# Items which are fully paid
def num_paid
paid_items.count
end
# how much have we received for the paid items
def total_amount_paid
paid_items.map(&:cost).inject(:+).to_f
end
def total_amount_paid_after_refunds
refunded_items.map(&:cost).inject(:+).to_f
end
# Items which are unpaid.
# Note: Free items which are associated with Paid Registrants are considered Paid/Free.
def unpaid_items
reis = registrant_expense_items.joins(:registrant).where(registrants: {deleted: false})
reis.free.select{ |rei| !rei.registrant.reg_paid? } + reis.where(free: false)
end
def num_unpaid
unpaid_items.count # free.select{|rei| !rei.registrant.reg_paid? }.count + unpaid_items.where(free: false).count
end
def create_reg_items
if expense_group.competitor_required?
Registrant.competitor.each do |reg|
reg.build_registration_item(self)
reg.save
end
end
if expense_group.noncompetitor_required?
Registrant.noncompetitor.each do |reg|
reg.build_registration_item(self)
reg.save
end
end
end
def check_for_payment_details
if payment_details.count > 0
errors[:base] << "cannot delete expense_item containing a matching payment"
return false
end
end
def to_s
expense_group.to_s + " - " + name
end
def total_cost_cents
(cost_cents + tax_cents) if cost_cents && tax_cents
end
def num_selected_items
num_unpaid + num_paid
end
def can_i_add?(num_to_add)
if maximum_available.nil?
true
else
num_selected_items + num_to_add <= maximum_available
end
end
def maximum_reached?
if maximum_available.nil?
false
else
num_selected_items >= maximum_available
end
end
def has_limits?
return true if maximum_available && maximum_available > 0
return true if maximum_per_registrant && maximum_per_registrant > 0
false
end
private
def paid_free_items
paid_items.free
end
def free_items_with_reg_paid
registrant_expense_items.joins(:registrant).where(registrants: {deleted: false}).free.select{ |rei| rei.registrant.reg_paid? }
end
end
| 26.549708 | 160 | 0.712996 |
e22c070c467db34b7b13e64e674c6b0fcdd37483 | 1,121 | module Vagrant
module Serial
module Middleware
class StopForwardingPorts
def initialize(app, env)
@app = app
end
def call(env)
if env[:vm].config.serial.set?
FileUtils.mkdir_p(env[:vm].config.serial.sockets_path) if env[:vm].config.serial.set? && !File.directory?(env[:vm].config.serial.sockets_path)
env[:ui].info "Stopping serial ports forwarding..."
if env[:vm].config.serial.forward_com1
`/sbin/start-stop-daemon --stop --quiet --pidfile #{env[:vm].config.serial.sockets_path}/socat.#{env[:vm].uuid}-com1.pid --exec /usr/bin/socat && rm #{env[:vm].config.serial.sockets_path}/socat.#{env[:vm].uuid}-com1.pid`
end
if env[:vm].config.serial.forward_com2
`/sbin/start-stop-daemon --stop --quiet --pidfile #{env[:vm].config.serial.sockets_path}/socat.#{env[:vm].uuid}-com2.pid --exec /usr/bin/socat && rm #{env[:vm].config.serial.sockets_path}/socat.#{env[:vm].uuid}-com2.pid`
end
end
@app.call(env)
end
end
end
end
end
| 37.366667 | 234 | 0.599465 |
621d52c88dbddbdd9e7599229e6e55a9dfa14285 | 12,342 | # Copyright (c) 2010 - 2011, Ruby Science Foundation
# All rights reserved.
#
# Please see LICENSE.txt for additional copyright notices.
#
# By contributing source code to SciRuby, you agree to be bound by our Contributor
# Agreement:
#
# * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement
#
# === validation.rb
#
module Rubyvis
module Scale
class Ordinal
def size
@r.size
end
end
end
end
warn "[DEPRECATION] SciRuby::Validation is deprecated and will be replaced in the near future."
# Added by John O. Woods.
#
# Methods for quantifying the predictive abilities of binary classifier systems (i.e., true positives, false positives,
# etc.)
#
# This module is likely to go away soon, or to change significantly.
#
module SciRuby
module Validation
# Binary confusion matrix for generating Receiver Operating Characteristic (ROC) and Precision-Recall curves.
class Binary
DEFAULT_VIS_OPTIONS = {
:width => 400,
:height => 400,
:left => 20,
:bottom => 20,
:right => 10,
:top => 5,
:line_color => "#66abca",
:line_width => 2
}
# Create a new confusion matrix, with +total_positives+ as the number of items that are known to be correct.
# +initial_negatives+ is the total number of items to be tested as we push each prediction/set of predictions.
def initialize initial_negatives, total_positives
raise(ArgumentError, "total predictions should be greater or equal to total positives") unless initial_negatives >= total_positives
@tp, @p, @tn, @n = [0], [0], [initial_negatives - total_positives], [initial_negatives]
@threshold = { 1.0 => 0 }
@roc_area = 0.0
end
# Allows us to zoom right in on a specific score and find out how many positives have been hit by the time
# we've gotten that far down the list.
attr_reader :threshold
# True positives axis
attr_reader :tp
alias :tp_axis :tp
alias :true_positives_axis :tp
# Positives (true and false) axis
attr_reader :p
alias :p_axis :p
alias :positives_axis :p
# True negatives axis
attr_reader :tn
alias :tn_axis :tn
alias :true_negatives_axis :tn
# Negatives (true and false) axis
attr_reader :n
alias :n_axis :n
alias :negatives_axis :n
# Area under the Receiver-Operating Characteristic (ROC) curve.
attr_reader :roc_area
# Data for a visualization/plot
def data type
if type == :roc
fpr_axis.zip(tpr_axis)
elsif type == :precision_recall
tpr_axis.zip(precision_axis)
else
raise ArgumentError, "Unrecognized plot type: #{type.to_s}"
end
end
class << self
# Generate an empty panel.
def vis options = {}
options.reverse_merge! DEFAULT_VIS_OPTIONS
x = Rubyvis::Scale.linear(0.0, 1.0).range(0, options[:width])
y = Rubyvis::Scale.linear(0.0, 1.0).range(0, options[:height])
v = Rubyvis::Panel.new do
width options[:width]
height options[:height]
bottom options[:bottom]
left options[:left]
right options[:right]
top options[:top]
end
v.add(pv.Rule).
data(y.ticks()).
bottom(y).
strokeStyle( lambda {|dd| dd != 0 ? "#eee" : "#000"} ).
anchor("left").add(pv.Label).
visible( lambda {|dd| dd > 0 and dd < 1} ).
text(y.tick_format)
# X-axis and ticks.
v.add(pv.Rule).
data(x.ticks()).
left(x).
stroke_style( lambda {|dd| dd != 0 ? "#eee" : "#000"} ).
anchor("bottom").add(pv.Label).
visible( lambda {|dd| dd > 0 and dd < 1} ).
text(x.tick_format)
v
end
# Plot an array of curves, or a hash of real and control curves. Kind of cluttered.
def plot hsh_or_ary, type, options = {}
vis = begin
if hsh_or_ary.is_a?(OpenStruct)
plot_hash hsh_or_ary, type, options
elsif hsh_or_ary.is_a?(Array)
plot_array hsh_or_ary, type, options
end
end
vis.render()
require "rsvg2"
svg = RSVG::Handle.new_from_data(vis.to_svg).tap { |s| s.close }
SciRuby::Plotter.new svg
end
protected
# Plot :real and :control arrays on the same panel. Not really very useful, as it gets too cluttered.
def plot_hash hsh, type, options = {}
options[:colors] ||= :category10
options[:line_width] ||= 2
colors = Rubyvis::Colors.send(options[:colors])
options[:panel] = vis(options) # set up panel and store it in the options hash
hsh.real.each_index do |i|
options[:panel] = hsh.real[i].vis(type, options.merge({ :line_color => colors[i % colors.size] }))
end if hsh.respond_to?(:real) # may not have anything but controls
hsh.control.each_index do |i|
options[:panel] = hsh.control[i].vis(type, options.merge({ :line_color => colors[i % colors.size] }))
end if hsh.respond_to?(:control) # May not have a control set up
options[:panel]
end
# Plot multiple Validation::Binary objects on the same panel.
def plot_array ary, type, options = {}
options[:colors] ||= :category10
colors = Rubyvis::Colors.send(options[:colors])
options[:panel] = vis(options) # set up panel
ary.each_index do |i|
options[:panel] = ary[i].vis(type, options.merge({:line_color => colors[i % colors.size]}))
end
options[:panel]
end
end
# RubyVis object for a plot
def vis type, options = {}
options.reverse_merge! DEFAULT_VIS_OPTIONS
d = data(type)
x = Rubyvis::Scale.linear(0.0, 1.0).range(0, options[:width])
y = Rubyvis::Scale.linear(0.0, 1.0).range(0, options[:height])
# Use existing panel or create new empty one
v = options.has_key?(:panel) ? options[:panel] : self.class.send(:vis, options)
v.add(Rubyvis::Panel).
data(d).
add(Rubyvis::Dot).
left(lambda { |dd| x.scale(dd[0])} ).
bottom(lambda { |dd| y.scale(dd[1])} ).
stroke_style("black").
shape_size(2).
title(lambda { |dd| "%0.1f" % dd[1]} )
v.add(Rubyvis::Line).
data(d).
line_width(options[:line_width]).
left(lambda { |dd| x.scale(dd[0])} ).
bottom(lambda { |dd| y.scale(dd[1])} ).
stroke_style(options[:line_color]).
anchor("bottom")
v
end
# Plot on a new or existing panel. To use an existing panel, just set option :panel to be a
# Rubyvis::Panel object.
#
# To use a new panel, just don't set :panel. You can provide various options as for the vis()
# method.
#
# The first argument should be the type of plot, :roc or :precision_recall.
def plot type, options = {}
v = vis(type, options)
v.render()
require "rsvg2"
svg = RSVG::Handle.new_from_data(v.to_svg).tap { |s| s.close }
SciRuby::Plotter.new svg
end
# Get the "actual" precision at some recall value.
def precision_at_fraction_recall val
@p.each_index do |i|
return actual_precision(i) if tpr(i) < val
end
0.0
end
# Push the number of predicted and the number of correctly predicted for a given score. ROC area thus far is
# calculated instantly and returned.
def push predicted, correctly_predicted, score = nil
raise(ArgumentError, "Requires two integers as arguments") unless predicted.is_a?(Fixnum) && correctly_predicted.is_a?(Fixnum)
raise(ArgumentError, "First argument should be greater than or equal to second argument") unless predicted >= correctly_predicted
@threshold[score] = @p.size unless score.nil?
last_i = p.size - 1
i = p.size
@p << @p[last_i] + predicted
@n << @n[last_i] - predicted
@tp << @tp[last_i] + correctly_predicted
@tn << @tn[last_i] - predicted + correctly_predicted
delta_tpr = tpr(i) - tpr(last_i)
delta_fpr = fpr(i) - fpr(last_i)
@roc_area += (tpr(last_i) + 0.5 * delta_tpr) * delta_fpr
end
# Some methods you'd want to validate don't offer scores for each and every item. In that case, just call
# push_remainder in order to ensure the line gets drawn all the way to the right.
def push_remainder
# push all remaining negatives, none correct, score of 0.
push n.last, n.first - tn.first, 0.0
end
# Given some bin +i+, what is the true positive rate / sensitivity / recall
def tpr(i)
[ @tp[i].quo(@tp[i] + @n[i] - @tn[i]), 1 ].min
end
alias :sensitivity :tpr
alias :recall :tpr
# Given some bin +i+, what is the false positive rate / fallout?
def fpr(i)
begin
[ (@p[i] - @tp[i]).quo(@p[i] - @tp[i] + @tn[i]), 1 ].min
rescue ZeroDivisionError => e
STDERR.puts "TP axis: #{tp_axis.inspect}"
STDERR.puts "P axis: #{p_axis.inspect}"
STDERR.puts "TN axis: #{tn_axis.inspect}"
STDERR.puts "N axis: #{n_axis.inspect}"
raise ZeroDivisionError, "i=#{i}, p[i]=#{@p[i]}, tp[i]=#{@tp[i]}, tn[i]=#{@tn[i]}"
end
end
alias :fallout :fpr
# Calculate the actual precision at some point.
#
# This is used because a precision-recall curve actually levels out the stair-steps, and sometimes you need
# the true value instead.
#
# To get the leveled-out values, you would use precision_axis_and_area or just precision_axis.
def actual_precision(i)
return 1 if @p[i] == 0 # Prevents ZeroDivisionError.
begin
[ @tp[i].quo(@p[i]), 1 ].min
rescue ZeroDivisionError => e
STDERR.puts "TP axis: #{tp_axis.inspect}"
STDERR.puts "P axis: #{p_axis.inspect}"
STDERR.puts "TN axis: #{tn_axis.inspect}"
STDERR.puts "N axis: #{n_axis.inspect}"
raise ZeroDivisionError, "i=#{i}, p[i]=#{@p[i]}, tp[i]=#{@tp[i]}, tn[i]=#{@tn[i]}"
end
end
# True positive rate axis (as we walk through the list of predictions from best-scored to worst-scored)
def tpr_axis
axis = []
@p.each_index do |i|
axis << tpr(i)
end
axis
end
# False positive rate axis
def fpr_axis
axis = []
@p.each_index do |i|
axis << fpr(i)
end
axis
end
# Precision axis for a precision-recall plot; and the area under the precision-recall curve.
#
# Returns an OpenStruct with two attributes: precision_axis (an array), and area (a Fixnum).
def precision_axis_and_area
prec = Array.new(@p.size)
area = 0.0
i = @p.size - 1
max = prec[i] = actual_precision(i); i -= 1
while i >= 0
max = prec[i] = [max, actual_precision(i)].max
area += ( tpr(i+1).to_f - tpr(i).to_f ) * max
i -= 1
end
prec[0] = 1.0
OpenStruct.new({:precision_axis => prec, :area => area})
end
# Returns the number of prediction score bins.
def bins
@p.size - 1
end
# Returns the size of the plot (for axes).
def size
@p.size
end
# Returns the total number of predictions, correct and incorrect.
def max
@n[0]
end
# Returns the total number of known values.
def known
@n[0] - @tn[0]
end
# Returns just the precision axis without the area. Note that it takes just as long to calculate; this just
# leaves off the area if you don't need it.
def precision_axis
precision_axis_and_area.precision_axis
end
end
end
end
| 32.308901 | 139 | 0.575433 |
1c6e2cef3555d7fed038bef124d39d0e85678f58 | 8,564 | module Rya
# Contains extensions to core Ruby classes and modules.
module CoreExtensions
module Array
# Scales with respect to the min and max of the data actually in the Array.
def scale new_min, new_max
old_min = self.min
old_max = self.max
self.scale_fixed old_min, old_max, new_min, new_max
end
# Scales with respect to a fixed old_min and old_max
def scale_fixed old_min, old_max, new_min, new_max
self.map do |elem|
Rya::ExtendedClasses::MATH.scale elem, old_min, old_max, new_min, new_max
end
end
end
module File
# Check if a string specifies an executable command on the PATH.
#
# @param cmd The name of a command to check, or a path to an actual executable binary.
#
# @return nil if the cmd is not executable or it is not on the PATH.
# @return [String] /path/to/cmd if the cmd is executable or is on the PATH.
#
# @example
# File.extend Rya::CoreExtensions::File
# File.command? "ls" #=> "/bin/ls"
# File.command? "arstoien" #=> nil
# File.command? "/bin/ls" #=> "/bin/ls"
#
# @note See https://stackoverflow.com/questions/2108727.
def command? cmd
return cmd if Object::File.executable? cmd
exts = ENV["PATHEXT"] ? ENV["PATHEXT"].split(";") : [""]
ENV["PATH"].split(Object::File::PATH_SEPARATOR).each do |path|
exts.each do |ext|
exe = Object::File.join path, "#{cmd}#{ext}"
return exe if Object::File.executable?(exe) && !Object::File.directory?(exe)
end
end
nil
end
end
module Math
def scale val, old_min, old_max, new_min, new_max
# This can happen if you use the mean across non-zero samples.
if old_max - old_min == 0
# TODO better default value than this?
(new_min + new_max) / 2;
else
((((new_max - new_min) * (val - old_min)) / (old_max - old_min).to_f) + new_min)
end
end
end
module String
# Use dynamic programming to find the length of the longest common substring.
#
# @param other The other string to test against.
#
# @example
# str = String.new("apple").extend Rya::CoreExtensions::String
# other = "ppie"
#
# str.longest_common_substring other #=> 2
#
# @note This is the algorithm from https://www.geeksforgeeks.org/longest-common-substring/
def longest_common_substring other
if self.empty? || other.empty?
return 0
end
self_len = self.length
other_len = other.length
longest_common_suffix = Object::Array.new(self_len + 1) { Object::Array.new(other_len + 1, 0) }
len = 0
(self_len + 1).times do |i|
(other_len + 1).times do |j|
if i.zero? || j.zero? # this is for the dummy column
longest_common_suffix[i][j] = 0
elsif self[i - 1] == other[j - 1]
val = longest_common_suffix[i - 1][j - 1] + 1
longest_common_suffix[i][j] = val
len = [len, val].max
else
longest_common_suffix[i][j] = 0
end
end
end
len
end
end
module Time
# Nicely format date and time
def date_and_time fmt = "%F %T.%L"
Object::Time.now.strftime fmt
end
# Run whatever is in the block and log the time it takes.
def time_it title = "", logger = nil, run: true
if run
t = Object::Time.now
yield
time = Object::Time.now - t
if title == ""
msg = "Finished in #{time} seconds"
else
msg = "#{title} finished in #{time} seconds"
end
if logger
logger.info msg
else
STDERR.puts msg
end
end
end
end
module Process
include CoreExtensions::Time
# I run your program until it succeeds or I fail too many times.
#
# @example I'll keep retrying your command line program until it succeeds.
# klass = Class.new { extend Rya::CoreExtensions::Process }
# max_attempts = 10
#
# tries = klass.run_until_success max_attempts do
# # This command returns a Process::Status object!
# klass.run_it "echo 'hi'"
# end
#
# tries == 1 #=> true
#
# @example I'll raise an error if the program doesn't succeed after max_attempts tries.
# klass = Class.new { extend Rya::CoreExtensions::Process }
# max_attempts = 10
#
# begin
# klass.run_until_success max_attempts do
# # This command returns a Process::Status object!
# klass.run_it "ls 'file_that_doesnt_exist'"
# end
# rescue Rya::MaxAttemptsExceededError => err
# STDERR.puts "The command didn't succeed after #{max_attempts} tries!"
# end
#
# @param max_attempts [Integer] max attempts before I fail
#
# @yield The block specifies the command you want to run. Make sure that it returns something that responds to exitstatus!
#
# @return [Integer] the number of attempts before successful completion
#
# @raise [Rya::Error] if the block does not return an object that responds to exitstatus (e.g., Prosses::Status)
# @raise [Rya::MaxAttemptsExceededError] if the program fails more than max_attempts times
#
def run_until_success max_attempts, &block
max_attempts.times do |attempt_index|
proc_status = yield block
unless proc_status.respond_to? :exitstatus
raise Rya::Error, "The block did not return an object that responds to exitstatus"
end
if proc_status.exitstatus.zero?
return attempt_index + 1
end
end
raise Rya::MaxAttemptsExceededError, "max_attempts exceeded"
end
# Runs a command and outputs stdout and stderr
def run_it *a, &b
exit_status, stdout, stderr = systemu *a, &b
puts stdout unless stdout.empty?
STDERR.puts stderr unless stderr.empty?
exit_status
end
# Like run_it() but will raise Rya::AbortIf::Exit on non-zero exit status.
def run_it! *a, &b
exit_status = self.run_it *a, &b
# Sometimes, exited? is not true and there will be no exit
# status. Success should catch all failures.
Rya::AbortIf.abort_unless exit_status.success?,
"Command failed with status " \
"'#{exit_status.to_s}' " \
"when running '#{a.inspect}', " \
"'#{b.inspect}'"
exit_status
end
# Run a command and time it as well!
#
# @param title Give your command a snappy title to log!
# @param cmd The actual command you want to run
# @param logger Something that responds to #info for printing. If nil, just print to STDERR.
# @param run If true, actually run the command, if false, then don't.
#
# @note The 'run' keyword argument is nice if you have some big pipeline and you need to temporarily prevent sections of the code from running.
#
# @example
#
# Process.extend Rya::CoreExtensions::Process
#
# Process.run_and_time_it! "Saying hello",
# %Q{echo "hello world"}
#
# Process.run_and_time_it! "This will not run",
# "echo 'hey'",
# run: false
#
# Process.run_and_time_it! "This will raise SystemExit",
# "ls arstoeiarntoairnt"
def run_and_time_it! title = "",
cmd = "",
logger = Rya::AbortIf::logger,
run: true,
&b
time_it title, logger, run: run do
Rya::AbortIf.logger.debug { "Running: #{cmd}" }
run_it! cmd, &b
end
end
end
end
end
module Rya
# Mainly for use within the CoreExtensions module definitions
module ExtendedClasses
MATH = Class.new.extend(Rya::CoreExtensions::Math)
STRING = Class.new.extend(Rya::CoreExtensions::String)
end
end
| 32.195489 | 149 | 0.563755 |
26515dd591c8946733fe0df06badb1a1eaf04242 | 1,142 | class ChainHeadResponse < Dry::Struct
attribute :chainhead, Types::String
attribute :chaininprocesslist, Types::Bool
def self.from_dynamic!(d)
jsonData = d
d = Types::Hash[d]
if(jsonData.has_key? 'result')
d = d.fetch("result")
else
d = d.fetch("error")
end
new(
chainhead: d.has_key?('chainhead') ? d.fetch("chainhead") : nil,
chaininprocesslist: d.has_key?('chaininprocesslist') ? d.fetch("chaininprocesslist") : false,
)
end
def self.from_json!(json)
from_dynamic!(JSON.parse(json))
end
def to_dynamic
{
"chainhead" => @chainhead,
"chaininprocesslist" => @chaininprocesslist,
}
end
def to_json(options = nil)
JSON.generate(to_dynamic, options)
end
end
# This code may look verbose in Ruby but
# it performs some complex validation of JSON data which we REQUIRE for correctness
#
# To parse this JSON, add 'dry-struct' and 'dry-types' gems, then do:
#
# entry_response = EntryResponse.from_json! "{…}"
# puts entry_response.entrydata.blockdate.even?
#
# If from_json! succeeds, the value returned matches the schema. | 26.55814 | 102 | 0.66725 |
bb81fcca5e7eb041388fd04be97649008406fd8d | 2,134 | #
# tkextlib/iwidgets/selectionbox.rb
# by Hidetoshi NAGAI ([email protected])
#
require 'tk'
require 'tkextlib/iwidgets.rb'
module Tk
module Iwidgets
class Selectionbox < Tk::Itk::Widget
end
end
end
class Tk::Iwidgets::Selectionbox
TkCommandNames = ['::iwidgets::selectionbox'.freeze].freeze
WidgetClassName = 'Selectionbox'.freeze
WidgetClassNames[WidgetClassName] = self
def __boolval_optkeys
super() << 'itemson' << 'selectionon'
end
private :__boolval_optkeys
def __strval_optkeys
super() << 'itemslabel' << 'selectionlabel'
end
private :__strval_optkeys
def child_site
window(tk_call(@path, 'childsite'))
end
def clear_items
tk_call(@path, 'clear', 'items')
self
end
def clear_selection
tk_call(@path, 'clear', 'selection')
self
end
def get
tk_call(@path, 'get')
end
def insert_items(idx, *args)
tk_call(@path, 'insert', 'items', idx, *args)
end
def insert_selection(pos, text)
tk_call(@path, 'insert', 'selection', pos, text)
end
def select_item
tk_call(@path, 'selectitem')
self
end
# based on TkListbox ( and TkTextWin )
def curselection
list(tk_send_without_enc('curselection'))
end
def delete(first, last=None)
tk_send_without_enc('delete', first, last)
self
end
def index(idx)
tk_send_without_enc('index', idx).to_i
end
def nearest(y)
tk_send_without_enc('nearest', y).to_i
end
def scan_mark(x, y)
tk_send_without_enc('scan', 'mark', x, y)
self
end
def scan_dragto(x, y)
tk_send_without_enc('scan', 'dragto', x, y)
self
end
def selection_anchor(index)
tk_send_without_enc('selection', 'anchor', index)
self
end
def selection_clear(first, last=None)
tk_send_without_enc('selection', 'clear', first, last)
self
end
def selection_includes(index)
bool(tk_send_without_enc('selection', 'includes', index))
end
def selection_set(first, last=None)
tk_send_without_enc('selection', 'set', first, last)
self
end
def size
tk_send_without_enc('size').to_i
end
end
| 20.718447 | 75 | 0.672446 |
bf3a1cac616da688079238ef870a1258380a75bb | 297 | class OperaNext < Cask
version '24.0.1558.25'
sha256 '43e312a807baf3f8ad3a89a27bfaf7baefbe02a8a0dc92c6bb01e27a16569d72'
url "http://get.geo.opera.com/pub/opera-next/#{version}/mac/Opera_Next_#{version}_Setup.dmg"
homepage 'http://www.opera.com/computer/next'
link 'Opera Next.app'
end
| 29.7 | 94 | 0.767677 |
edd0248f704108a4052bb178d4ee8b2c3fe6022b | 5,463 | class GccAT6 < Formula
desc "GNU compiler collection"
homepage "https://gcc.gnu.org"
url "https://ftp.gnu.org/gnu/gcc/gcc-6.5.0/gcc-6.5.0.tar.xz"
mirror "https://ftpmirror.gnu.org/gcc/gcc-6.5.0/gcc-6.5.0.tar.xz"
sha256 "7ef1796ce497e89479183702635b14bb7a46b53249209a5e0f999bebf4740945"
revision 6
livecheck do
url :stable
regex(%r{href=.*?gcc[._-]v?(6(?:\.\d+)+)(?:/?["' >]|\.t)}i)
end
bottle do
sha256 big_sur: "64a10f90cc5ba048b3355e28fca2159c506e0e24489810bcb9688ba26221c928"
sha256 catalina: "d82b14c535897ff2f9371481733512dbafd9701f09855e3d1ed6bb9bb3357f7e"
sha256 mojave: "1279be27b958b93146217adb2073596c9504f7c6a746eea421a63769a8a76c10"
end
# The bottles are built on systems with the CLT installed, and do not work
# out of the box on Xcode-only systems due to an incorrect sysroot.
pour_bottle? do
on_macos do
reason "The bottle needs the Xcode CLT to be installed."
satisfy { MacOS::CLT.installed? }
end
end
depends_on arch: :x86_64
depends_on "gmp"
depends_on "isl"
depends_on "libmpc"
depends_on "mpfr"
uses_from_macos "zlib"
on_linux do
depends_on "binutils"
end
# GCC bootstraps itself, so it is OK to have an incompatible C++ stdlib
cxxstdlib_check :skip
# Patch for Xcode bug, taken from https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89864#c43
# This should be removed in the next release of GCC if fixed by apple; this is an xcode bug,
# but this patch is a work around committed to GCC trunk
if MacOS::Xcode.version >= "10.2"
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/91d57ebe88e17255965fa88b53541335ef16f64a/gcc%406/gcc6-xcode10.2.patch"
sha256 "0f091e8b260bcfa36a537fad76823654be3ee8462512473e0b63ed83ead18085"
end
end
def install
# GCC will suffer build errors if forced to use a particular linker.
ENV.delete "LD"
# C, C++, ObjC, Fortran compilers are always built
languages = %w[c c++ objc obj-c++ fortran]
version_suffix = version.major.to_s
# Even when suffixes are appended, the info pages conflict when
# install-info is run so pretend we have an outdated makeinfo
# to prevent their build.
ENV["gcc_cv_prog_makeinfo_modern"] = "no"
args = [
"--build=x86_64-apple-darwin#{OS.kernel_version}",
"--prefix=#{prefix}",
"--libdir=#{lib}/gcc/#{version_suffix}",
"--enable-languages=#{languages.join(",")}",
# Make most executables versioned to avoid conflicts.
"--program-suffix=-#{version_suffix}",
"--with-gmp=#{Formula["gmp"].opt_prefix}",
"--with-mpfr=#{Formula["mpfr"].opt_prefix}",
"--with-mpc=#{Formula["libmpc"].opt_prefix}",
"--with-isl=#{Formula["isl"].opt_prefix}",
"--with-system-zlib",
"--enable-stage1-checking",
"--enable-checking=release",
"--enable-lto",
# Use 'bootstrap-debug' build configuration to force stripping of object
# files prior to comparison during bootstrap (broken by Xcode 6.3).
"--with-build-config=bootstrap-debug",
"--disable-werror",
"--with-pkgversion=Homebrew GCC #{pkg_version} #{build.used_options*" "}".strip,
"--with-bugurl=#{tap.issues_url}",
"--disable-nls",
]
# Xcode 10 dropped 32-bit support
args << "--disable-multilib" if DevelopmentTools.clang_build_version >= 1000
# System headers may not be in /usr/include
sdk = MacOS.sdk_path_if_needed
if sdk
args << "--with-native-system-header-dir=/usr/include"
args << "--with-sysroot=#{sdk}"
end
# Avoid reference to sed shim
args << "SED=/usr/bin/sed"
# Ensure correct install names when linking against libgcc_s;
# see discussion in https://github.com/Homebrew/homebrew/pull/34303
inreplace "libgcc/config/t-slibgcc-darwin", "@shlib_slibdir@", "#{HOMEBREW_PREFIX}/lib/gcc/#{version_suffix}"
mkdir "build" do
system "../configure", *args
system "make", "bootstrap"
system "make", "install"
end
# Handle conflicts between GCC formulae and avoid interfering
# with system compilers.
# Rename man7.
Dir.glob(man7/"*.7") { |file| add_suffix file, version_suffix }
# Even when we disable building info pages some are still installed.
info.rmtree
end
def add_suffix(file, suffix)
dir = File.dirname(file)
ext = File.extname(file)
base = File.basename(file, ext)
File.rename file, "#{dir}/#{base}-#{suffix}#{ext}"
end
test do
(testpath/"hello-c.c").write <<~EOS
#include <stdio.h>
int main()
{
puts("Hello, world!");
return 0;
}
EOS
system "#{bin}/gcc-#{version.major}", "-o", "hello-c", "hello-c.c"
assert_equal "Hello, world!\n", `./hello-c`
(testpath/"hello-cc.cc").write <<~EOS
#include <iostream>
int main()
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
EOS
system "#{bin}/g++-#{version.major}", "-o", "hello-cc", "hello-cc.cc"
assert_equal "Hello, world!\n", `./hello-cc`
fixture = <<~EOS
integer,parameter::m=10000
real::a(m), b(m)
real::fact=0.5
do concurrent (i=1:m)
a(i) = a(i) + fact*b(i)
end do
print *, "done"
end
EOS
(testpath/"in.f90").write(fixture)
system "#{bin}/gfortran-#{version.major}", "-o", "test", "in.f90"
assert_equal "done", `./test`.strip
end
end
| 32.325444 | 140 | 0.647446 |
f7430f7958037705a596b9b3ba0b6c7036ea92f9 | 27,188 | #!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../test_helper'
class EngineTest < Test::Unit::TestCase
# A map of erroneous Sass documents to the error messages they should produce.
# The error messages may be arrays;
# if so, the second element should be the line number that should be reported for the error.
# If this isn't provided, the tests will assume the line number should be the last line of the document.
EXCEPTION_MAP = {
"!!!\n a" => "Illegal nesting: nesting within a header command is illegal.",
"a\n b" => "Illegal nesting: nesting within plain text is illegal.",
"/ a\n b" => "Illegal nesting: nesting within a tag that already has content is illegal.",
"% a" => 'Invalid tag: "% a".',
"%p a\n b" => "Illegal nesting: content can't be both given on the same line as %p and nested within it.",
"%p=" => "There's no Ruby code for = to evaluate.",
"%p~" => "There's no Ruby code for ~ to evaluate.",
"~" => "There's no Ruby code for ~ to evaluate.",
"=" => "There's no Ruby code for = to evaluate.",
"%p/\n a" => "Illegal nesting: nesting within a self-closing tag is illegal.",
":a\n b" => ['Filter "a" is not defined.', 1],
":a= b" => 'Invalid filter name ":a= b".',
"." => "Illegal element: classes and ids must have values.",
".#" => "Illegal element: classes and ids must have values.",
".{} a" => "Illegal element: classes and ids must have values.",
".= a" => "Illegal element: classes and ids must have values.",
"%p..a" => "Illegal element: classes and ids must have values.",
"%a/ b" => "Self-closing tags can't have content.",
"%p{:a => 'b',\n:c => 'd'}/ e" => ["Self-closing tags can't have content.", 2],
"%p{:a => 'b',\n:c => 'd'}=" => ["There's no Ruby code for = to evaluate.", 2],
"%p.{:a => 'b',\n:c => 'd'} e" => ["Illegal element: classes and ids must have values.", 1],
"%p{:a => 'b',\n:c => 'd',\n:e => 'f'}\n%p/ a" => ["Self-closing tags can't have content.", 4],
"%p{:a => 'b',\n:c => 'd',\n:e => 'f'}\n- raise 'foo'" => ["foo", 4],
"%p{:a => 'b',\n:c => raise('foo'),\n:e => 'f'}" => ["foo", 2],
"%p{:a => 'b',\n:c => 'd',\n:e => raise('foo')}" => ["foo", 3],
" %p foo" => "Indenting at the beginning of the document is illegal.",
" %p foo" => "Indenting at the beginning of the document is illegal.",
"- end" => <<END.rstrip,
You don't need to use "- end" in Haml. Use indentation instead:
- if foo?
%strong Foo!
- else
Not foo.
END
" \n\t\n %p foo" => ["Indenting at the beginning of the document is illegal.", 3],
"\n\n %p foo" => ["Indenting at the beginning of the document is illegal.", 3],
"%p\n foo\n foo" => ["Inconsistent indentation: 1 space was used for indentation, but the rest of the document was indented using 2 spaces.", 3],
"%p\n foo\n%p\n foo" => ["Inconsistent indentation: 1 space was used for indentation, but the rest of the document was indented using 2 spaces.", 4],
"%p\n\t\tfoo\n\tfoo" => ["Inconsistent indentation: 1 tab was used for indentation, but the rest of the document was indented using 2 tabs.", 3],
"%p\n foo\n foo" => ["Inconsistent indentation: 3 spaces were used for indentation, but the rest of the document was indented using 2 spaces.", 3],
"%p\n foo\n %p\n bar" => ["Inconsistent indentation: 3 spaces were used for indentation, but the rest of the document was indented using 2 spaces.", 4],
"%p\n :plain\n bar\n \t baz" => ['Inconsistent indentation: " \t " was used for indentation, but the rest of the document was indented using 2 spaces.', 4],
"%p\n foo\n%p\n bar" => ["The line was indented 2 levels deeper than the previous line.", 4],
"%p\n foo\n %p\n bar" => ["The line was indented 3 levels deeper than the previous line.", 4],
"%p\n \tfoo" => ["Indentation can't use both tabs and spaces.", 2],
# Regression tests
"- raise 'foo'\n\n\n\nbar" => ["foo", 1],
"= 'foo'\n-raise 'foo'" => ["foo", 2],
"\n\n\n- raise 'foo'" => ["foo", 4],
"%p foo |\n bar |\n baz |\nbop\n- raise 'foo'" => ["foo", 5],
"foo\n\n\n bar" => ["Illegal nesting: nesting within plain text is illegal.", 4],
"%p/\n\n bar" => ["Illegal nesting: nesting within a self-closing tag is illegal.", 3],
"%p foo\n\n bar" => ["Illegal nesting: content can't be both given on the same line as %p and nested within it.", 3],
"/ foo\n\n bar" => ["Illegal nesting: nesting within a tag that already has content is illegal.", 3],
"!!!\n\n bar" => ["Illegal nesting: nesting within a header command is illegal.", 3],
"foo\n:ruby\n 1\n 2\n 3\n- raise 'foo'" => ["foo", 6],
}
User = Struct.new('User', :id)
def render(text, options = {}, &block)
scope = options.delete(:scope) || Object.new
locals = options.delete(:locals) || {}
Haml::Engine.new(text, options).to_html(scope, locals, &block)
end
def test_flexible_tabulation
assert_equal("<p>\n foo\n</p>\n<q>\n bar\n <a>\n baz\n </a>\n</q>\n",
render("%p\n foo\n%q\n bar\n %a\n baz"))
assert_equal("<p>\n foo\n</p>\n<q>\n bar\n <a>\n baz\n </a>\n</q>\n",
render("%p\n\tfoo\n%q\n\tbar\n\t%a\n\t\tbaz"))
assert_equal("<p>\n \t \t bar\n baz\n</p>\n",
render("%p\n :plain\n \t \t bar\n baz"))
end
def test_empty_render_should_remain_empty
assert_equal('', render(''))
end
def test_attributes_should_render_correctly
assert_equal("<div class='atlantis' style='ugly'></div>", render(".atlantis{:style => 'ugly'}").chomp)
end
def test_ruby_code_should_work_inside_attributes
author = 'hcatlin'
assert_equal("<p class='3'>foo</p>", render("%p{:class => 1+2} foo").chomp)
end
def test_nil_should_render_empty_tag
assert_equal("<div class='no_attributes'></div>",
render(".no_attributes{:nil => nil}").chomp)
end
def test_strings_should_get_stripped_inside_tags
assert_equal("<div class='stripped'>This should have no spaces in front of it</div>",
render(".stripped This should have no spaces in front of it").chomp)
end
def test_one_liner_should_be_one_line
assert_equal("<p>Hello</p>", render('%p Hello').chomp)
end
def test_one_liner_with_newline_shouldnt_be_one_line
assert_equal("<p>\n foo\n bar\n</p>", render('%p= "foo\nbar"').chomp)
end
def test_multi_render
engine = Haml::Engine.new("%strong Hi there!")
assert_equal("<strong>Hi there!</strong>\n", engine.to_html)
assert_equal("<strong>Hi there!</strong>\n", engine.to_html)
assert_equal("<strong>Hi there!</strong>\n", engine.to_html)
end
def test_double_equals
assert_equal("<p>Hello World</p>\n", render('%p== Hello #{who}', :locals => {:who => 'World'}))
assert_equal("<p>\n Hello World\n</p>\n", render("%p\n == Hello \#{who}", :locals => {:who => 'World'}))
end
def test_double_equals_in_the_middle_of_a_string
assert_equal("\"title 'Title'. \"\n",
render("== \"title '\#{\"Title\"}'. \""))
end
def test_nil_tag_value_should_render_as_empty
assert_equal("<p></p>\n", render("%p= nil"))
end
def test_tag_with_failed_if_should_render_as_empty
assert_equal("<p></p>\n", render("%p= 'Hello' if false"))
end
def test_static_attributes_with_empty_attr
assert_equal("<img alt='' src='/foo.png' />\n", render("%img{:src => '/foo.png', :alt => ''}"))
end
def test_dynamic_attributes_with_empty_attr
assert_equal("<img alt='' src='/foo.png' />\n", render("%img{:width => nil, :src => '/foo.png', :alt => String.new}"))
end
def test_attribute_hash_with_newlines
assert_equal("<p a='b' c='d'>foop</p>\n", render("%p{:a => 'b',\n :c => 'd'} foop"))
assert_equal("<p a='b' c='d'>\n foop\n</p>\n", render("%p{:a => 'b',\n :c => 'd'}\n foop"))
assert_equal("<p a='b' c='d' />\n", render("%p{:a => 'b',\n :c => 'd'}/"))
assert_equal("<p a='b' c='d' e='f'></p>\n", render("%p{:a => 'b',\n :c => 'd',\n :e => 'f'}"))
end
def test_end_of_file_multiline
assert_equal("<p>0</p>\n<p>1</p>\n<p>2</p>\n", render("- for i in (0...3)\n %p= |\n i |"))
end
def test_cr_newline
assert_equal("<p>foo</p>\n<p>bar</p>\n<p>baz</p>\n<p>boom</p>\n", render("%p foo\r%p bar\r\n%p baz\n\r%p boom"))
end
def test_textareas
assert_equal("<textarea>Foo
 bar
 baz</textarea>\n",
render('%textarea= "Foo\n bar\n baz"'))
assert_equal("<pre>Foo
 bar
 baz</pre>\n",
render('%pre= "Foo\n bar\n baz"'))
assert_equal("<textarea>#{'a' * 100}</textarea>\n",
render("%textarea #{'a' * 100}"))
assert_equal("<p>\n <textarea>Foo\n Bar\n Baz</textarea>\n</p>\n", render(<<SOURCE))
%p
%textarea
Foo
Bar
Baz
SOURCE
end
def test_boolean_attributes
assert_equal("<p bar baz='true' foo='bar'></p>\n",
render("%p{:foo => 'bar', :bar => true, :baz => 'true'}", :format => :html4))
assert_equal("<p bar='bar' baz='true' foo='bar'></p>\n",
render("%p{:foo => 'bar', :bar => true, :baz => 'true'}", :format => :xhtml))
assert_equal("<p baz='false' foo='bar'></p>\n",
render("%p{:foo => 'bar', :bar => false, :baz => 'false'}", :format => :html4))
assert_equal("<p baz='false' foo='bar'></p>\n",
render("%p{:foo => 'bar', :bar => false, :baz => 'false'}", :format => :xhtml))
end
def test_both_whitespace_nukes_work_together
assert_equal(<<RESULT, render(<<SOURCE))
<p><q>Foo
Bar</q></p>
RESULT
%p
%q><= "Foo\\nBar"
SOURCE
end
# HTML escaping tests
def test_ampersand_equals_should_escape
assert_equal("<p>\n foo & bar\n</p>\n", render("%p\n &= 'foo & bar'", :escape_html => false))
end
def test_ampersand_equals_inline_should_escape
assert_equal("<p>foo & bar</p>\n", render("%p&= 'foo & bar'", :escape_html => false))
end
def test_ampersand_equals_should_escape_before_preserve
assert_equal("<textarea>foo
bar</textarea>\n", render('%textarea&= "foo\nbar"', :escape_html => false))
end
def test_bang_equals_should_not_escape
assert_equal("<p>\n foo & bar\n</p>\n", render("%p\n != 'foo & bar'", :escape_html => true))
end
def test_bang_equals_inline_should_not_escape
assert_equal("<p>foo & bar</p>\n", render("%p!= 'foo & bar'", :escape_html => true))
end
def test_static_attributes_should_be_escaped
assert_equal("<img class='atlantis' style='ugly&stupid' />\n",
render("%img.atlantis{:style => 'ugly&stupid'}"))
assert_equal("<div class='atlantis' style='ugly&stupid'>foo</div>\n",
render(".atlantis{:style => 'ugly&stupid'} foo"))
assert_equal("<p class='atlantis' style='ugly&stupid'>foo</p>\n",
render("%p.atlantis{:style => 'ugly&stupid'}= 'foo'"))
assert_equal("<p class='atlantis' style='ugly
stupid'></p>\n",
render("%p.atlantis{:style => \"ugly\\nstupid\"}"))
end
def test_dynamic_attributes_should_be_escaped
assert_equal("<img alt='' src='&foo.png' />\n",
render("%img{:width => nil, :src => '&foo.png', :alt => String.new}"))
assert_equal("<p alt='' src='&foo.png'>foo</p>\n",
render("%p{:width => nil, :src => '&foo.png', :alt => String.new} foo"))
assert_equal("<div alt='' src='&foo.png'>foo</div>\n",
render("%div{:width => nil, :src => '&foo.png', :alt => String.new}= 'foo'"))
assert_equal("<img alt='' src='foo
.png' />\n",
render("%img{:width => nil, :src => \"foo\\n.png\", :alt => String.new}"))
end
def test_string_interpolation_should_be_esaped
assert_equal("<p>4&3</p>\n", render("%p== #{2+2}&#{2+1}", :escape_html => true))
assert_equal("<p>4&3</p>\n", render("%p== #{2+2}&#{2+1}", :escape_html => false))
end
def test_escaped_inline_string_interpolation
assert_equal("<p>4&3</p>\n", render("%p&== #{2+2}&#{2+1}", :escape_html => true))
assert_equal("<p>4&3</p>\n", render("%p&== #{2+2}&#{2+1}", :escape_html => false))
end
def test_unescaped_inline_string_interpolation
assert_equal("<p>4&3</p>\n", render("%p!== #{2+2}&#{2+1}", :escape_html => true))
assert_equal("<p>4&3</p>\n", render("%p!== #{2+2}&#{2+1}", :escape_html => false))
end
def test_escaped_string_interpolation
assert_equal("<p>\n 4&3\n</p>\n", render("%p\n &== #{2+2}&#{2+1}", :escape_html => true))
assert_equal("<p>\n 4&3\n</p>\n", render("%p\n &== #{2+2}&#{2+1}", :escape_html => false))
end
def test_unescaped_string_interpolation
assert_equal("<p>\n 4&3\n</p>\n", render("%p\n !== #{2+2}&#{2+1}", :escape_html => true))
assert_equal("<p>\n 4&3\n</p>\n", render("%p\n !== #{2+2}&#{2+1}", :escape_html => false))
end
def test_scripts_should_respect_escape_html_option
assert_equal("<p>\n foo & bar\n</p>\n", render("%p\n = 'foo & bar'", :escape_html => true))
assert_equal("<p>\n foo & bar\n</p>\n", render("%p\n = 'foo & bar'", :escape_html => false))
end
def test_inline_scripts_should_respect_escape_html_option
assert_equal("<p>foo & bar</p>\n", render("%p= 'foo & bar'", :escape_html => true))
assert_equal("<p>foo & bar</p>\n", render("%p= 'foo & bar'", :escape_html => false))
end
def test_script_ending_in_comment_should_render_when_html_is_escaped
assert_equal("foo&bar\n", render("= 'foo&bar' #comment", :escape_html => true))
end
# Options tests
def test_filename_and_line
begin
render("\n\n = abc", :filename => 'test', :line => 2)
rescue Exception => e
assert_kind_of Haml::SyntaxError, e
assert_match /test:4/, e.backtrace.first
end
begin
render("\n\n= 123\n\n= nil[]", :filename => 'test', :line => 2)
rescue Exception => e
assert_kind_of NoMethodError, e
assert_match /test:6/, e.backtrace.first
end
end
def test_stop_eval
assert_equal("", render("= 'Hello'", :suppress_eval => true))
assert_equal("", render("- puts 'foo'", :suppress_eval => true))
assert_equal("<div id='foo' yes='no' />\n", render("#foo{:yes => 'no'}/", :suppress_eval => true))
assert_equal("<div id='foo' />\n", render("#foo{:yes => 'no', :call => a_function() }/", :suppress_eval => true))
assert_equal("<div />\n", render("%div[1]/", :suppress_eval => true))
assert_equal("", render(":ruby\n puts 'hello'", :suppress_eval => true))
end
def test_attr_wrapper
assert_equal("<p strange=*attrs*></p>\n", render("%p{ :strange => 'attrs'}", :attr_wrapper => '*'))
assert_equal("<p escaped='quo\"te'></p>\n", render("%p{ :escaped => 'quo\"te'}", :attr_wrapper => '"'))
assert_equal("<p escaped=\"quo'te\"></p>\n", render("%p{ :escaped => 'quo\\'te'}", :attr_wrapper => '"'))
assert_equal("<p escaped=\"q'uo"te\"></p>\n", render("%p{ :escaped => 'q\\'uo\"te'}", :attr_wrapper => '"'))
assert_equal("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n", render("!!! XML", :attr_wrapper => '"'))
end
def test_attrs_parsed_correctly
assert_equal("<p boom=>biddly='bar => baz'></p>\n", render("%p{'boom=>biddly' => 'bar => baz'}"))
assert_equal("<p foo,bar='baz, qux'></p>\n", render("%p{'foo,bar' => 'baz, qux'}"))
assert_equal("<p escaped='quo
te'></p>\n", render("%p{ :escaped => \"quo\\nte\"}"))
assert_equal("<p escaped='quo4te'></p>\n", render("%p{ :escaped => \"quo\#{2 + 2}te\"}"))
end
def test_correct_parsing_with_brackets
assert_equal("<p class='foo'>{tada} foo</p>\n", render("%p{:class => 'foo'} {tada} foo"))
assert_equal("<p class='foo'>deep {nested { things }}</p>\n", render("%p{:class => 'foo'} deep {nested { things }}"))
assert_equal("<p class='bar foo'>{a { d</p>\n", render("%p{{:class => 'foo'}, :class => 'bar'} {a { d"))
assert_equal("<p foo='bar'>a}</p>\n", render("%p{:foo => 'bar'} a}"))
foo = []
foo[0] = Struct.new('Foo', :id).new
assert_equal("<p class='struct_foo' id='struct_foo_new'>New User]</p>\n",
render("%p[foo[0]] New User]", :locals => {:foo => foo}))
assert_equal("<p class='prefix_struct_foo' id='prefix_struct_foo_new'>New User]</p>\n",
render("%p[foo[0], :prefix] New User]", :locals => {:foo => foo}))
foo[0].id = 1
assert_equal("<p class='struct_foo' id='struct_foo_1'>New User]</p>\n",
render("%p[foo[0]] New User]", :locals => {:foo => foo}))
assert_equal("<p class='prefix_struct_foo' id='prefix_struct_foo_1'>New User]</p>\n",
render("%p[foo[0], :prefix] New User]", :locals => {:foo => foo}))
end
def test_empty_attrs
assert_equal("<p attr=''>empty</p>\n", render("%p{ :attr => '' } empty"))
assert_equal("<p attr=''>empty</p>\n", render("%p{ :attr => x } empty", :locals => {:x => ''}))
end
def test_nil_attrs
assert_equal("<p>nil</p>\n", render("%p{ :attr => nil } nil"))
assert_equal("<p>nil</p>\n", render("%p{ :attr => x } nil", :locals => {:x => nil}))
end
def test_nil_id_with_syntactic_id
assert_equal("<p id='foo'>nil</p>\n", render("%p#foo{:id => nil} nil"))
assert_equal("<p id='foo_bar'>nil</p>\n", render("%p#foo{{:id => 'bar'}, :id => nil} nil"))
assert_equal("<p id='foo_bar'>nil</p>\n", render("%p#foo{{:id => nil}, :id => 'bar'} nil"))
end
def test_nil_class_with_syntactic_class
assert_equal("<p class='foo'>nil</p>\n", render("%p.foo{:class => nil} nil"))
assert_equal("<p class='bar foo'>nil</p>\n", render("%p.bar.foo{:class => nil} nil"))
assert_equal("<p class='bar foo'>nil</p>\n", render("%p.foo{{:class => 'bar'}, :class => nil} nil"))
assert_equal("<p class='bar foo'>nil</p>\n", render("%p.foo{{:class => nil}, :class => 'bar'} nil"))
end
def test_locals
assert_equal("<p>Paragraph!</p>\n", render("%p= text", :locals => { :text => "Paragraph!" }))
end
def test_dynamic_attrs_shouldnt_register_as_literal_values
assert_equal("<p a='b2c'></p>\n", render('%p{:a => "b#{1 + 1}c"}'))
assert_equal("<p a='b2c'></p>\n", render("%p{:a => 'b' + (1 + 1).to_s + 'c'}"))
end
def test_dynamic_attrs_with_self_closed_tag
assert_equal("<a b='2' />\nc\n", render("%a{'b' => 1 + 1}/\n= 'c'\n"))
end
def test_exceptions
EXCEPTION_MAP.each do |key, value|
begin
render(key)
rescue Exception => err
value = [value] unless value.is_a?(Array)
assert_equal(value.first, err.message, "Line: #{key}")
assert_equal(value[1] || key.split("\n").length, err.backtrace[0].gsub('(haml):', '').to_i, "Line: #{key}")
else
assert(false, "Exception not raised for\n#{key}")
end
end
end
def test_exception_line
render("a\nb\n!!!\n c\nd")
rescue Haml::SyntaxError => e
assert_equal("(haml):4", e.backtrace[0])
else
assert(false, '"a\nb\n!!!\n c\nd" doesn\'t produce an exception')
end
def test_exception
render("%p\n hi\n %a= undefined\n= 12")
rescue Exception => e
assert_match("(haml):3", e.backtrace[0])
else
# Test failed... should have raised an exception
assert(false)
end
def test_compile_error
render("a\nb\n- fee)\nc")
rescue Exception => e
assert_match(/^compile error\n\(haml\):3: syntax error/i, e.message)
else
assert(false,
'"a\nb\n- fee)\nc" doesn\'t produce an exception!')
end
def test_unbalanced_brackets
render('== #{1 + 5} foo #{6 + 7 bar #{8 + 9}')
rescue Haml::SyntaxError => e
assert_equal("Unbalanced brackets.", e.message)
end
def test_balanced_conditional_comments
assert_equal("<!--[if !(IE 6)|(IE 7)]> Bracket: ] <![endif]-->\n",
render("/[if !(IE 6)|(IE 7)] Bracket: ]"))
end
def test_no_bluecloth
Kernel.module_eval do
def gem_original_require_with_bluecloth(file)
raise LoadError if file == 'bluecloth'
gem_original_require_without_bluecloth(file)
end
alias_method :gem_original_require_without_bluecloth, :gem_original_require
alias_method :gem_original_require, :gem_original_require_with_bluecloth
end
begin
assert_equal("<h1>Foo</h1>\t<p>- a\n- b</p>\n",
Haml::Engine.new(":markdown\n Foo\n ===\n - a\n - b").to_html)
rescue Haml::Error => e
if e.message == "Can't run Markdown filter; required 'bluecloth' or 'redcloth', but none were found"
puts "\nCouldn't require 'bluecloth' or 'redcloth'; skipping a test."
else
raise e
end
end
Kernel.module_eval do
alias_method :gem_original_require, :gem_original_require_without_bluecloth
end
end
def test_no_redcloth
Kernel.module_eval do
def gem_original_require_with_redcloth(file)
raise LoadError if file == 'redcloth'
gem_original_require_without_redcloth(file)
end
alias_method :gem_original_require_without_redcloth, :gem_original_require
alias_method :gem_original_require, :gem_original_require_with_redcloth
end
begin
Haml::Engine.new(":redcloth\n _foo_").to_html
rescue Haml::Error
else
assert(false, "No exception raised!")
end
Kernel.module_eval do
alias_method :gem_original_require, :gem_original_require_without_redcloth
end
end
def test_no_redcloth_or_bluecloth
Kernel.module_eval do
def gem_original_require_with_redcloth_and_bluecloth(file)
raise LoadError if file == 'redcloth' || file == 'bluecloth'
gem_original_require_without_redcloth_and_bluecloth(file)
end
alias_method :gem_original_require_without_redcloth_and_bluecloth, :gem_original_require
alias_method :gem_original_require, :gem_original_require_with_redcloth_and_bluecloth
end
begin
Haml::Engine.new(":markdown\n _foo_").to_html
rescue Haml::Error
else
assert(false, "No exception raised!")
end
Kernel.module_eval do
alias_method :gem_original_require, :gem_original_require_without_redcloth_and_bluecloth
end
end
def test_empty_filter
assert_equal(<<END, render(':javascript'))
<script type='text/javascript'>
//<![CDATA[
//]]>
</script>
END
end
def test_ugly_filter
assert_equal(<<END, render(":sass\n #foo\n bar: baz", :ugly => true))
#foo {
bar: baz; }
END
end
def test_local_assigns_dont_modify_class
assert_equal("bar\n", render("= foo", :locals => {:foo => 'bar'}))
assert_equal(nil, defined?(foo))
end
def test_object_ref_with_nil_id
user = User.new
assert_equal("<p class='struct_user' id='struct_user_new'>New User</p>\n",
render("%p[user] New User", :locals => {:user => user}))
end
def test_object_ref_before_attrs
user = User.new 42
assert_equal("<p class='struct_user' id='struct_user_42' style='width: 100px;'>New User</p>\n",
render("%p[user]{:style => 'width: 100px;'} New User", :locals => {:user => user}))
end
def test_non_literal_attributes
assert_equal("<p a1='foo' a2='bar' a3='baz' />\n",
render("%p{a2, a1, :a3 => 'baz'}/",
:locals => {:a1 => {:a1 => 'foo'}, :a2 => {:a2 => 'bar'}}))
end
def test_render_should_accept_a_binding_as_scope
string = "This is a string!"
string.instance_variable_set("@var", "Instance variable")
b = string.instance_eval do
var = "Local variable"
binding
end
assert_equal("<p>THIS IS A STRING!</p>\n<p>Instance variable</p>\n<p>Local variable</p>\n",
render("%p= upcase\n%p= @var\n%p= var", :scope => b))
end
def test_yield_should_work_with_binding
assert_equal("12\nFOO\n", render("= yield\n= upcase", :scope => "foo".instance_eval{binding}) { 12 })
end
def test_yield_should_work_with_def_method
s = "foo"
Haml::Engine.new("= yield\n= upcase").def_method(s, :render)
assert_equal("12\nFOO\n", s.render { 12 })
end
def test_def_method_with_module
Haml::Engine.new("= yield\n= upcase").def_method(String, :render_haml)
assert_equal("12\nFOO\n", "foo".render_haml { 12 })
end
def test_def_method_locals
obj = Object.new
Haml::Engine.new("%p= foo\n.bar{:baz => baz}= boom").def_method(obj, :render, :foo, :baz, :boom)
assert_equal("<p>1</p>\n<div baz='2' class='bar'>3</div>\n", obj.render(:foo => 1, :baz => 2, :boom => 3))
end
def test_render_proc_locals
proc = Haml::Engine.new("%p= foo\n.bar{:baz => baz}= boom").render_proc(Object.new, :foo, :baz, :boom)
assert_equal("<p>1</p>\n<div baz='2' class='bar'>3</div>\n", proc[:foo => 1, :baz => 2, :boom => 3])
end
def test_render_proc_with_binding
assert_equal("FOO\n", Haml::Engine.new("= upcase").render_proc("foo".instance_eval{binding}).call)
end
def test_ugly_true
assert_equal("<div id='outer'>\n<div id='inner'>\n<p>hello world</p>\n</div>\n</div>\n",
render("#outer\n #inner\n %p hello world", :ugly => true))
assert_equal("<p>#{'s' * 75}</p>\n",
render("%p #{'s' * 75}", :ugly => true))
assert_equal("<p>#{'s' * 75}</p>\n",
render("%p= 's' * 75", :ugly => true))
end
def test_auto_preserve_unless_ugly
assert_equal("<pre>foo
bar</pre>\n", render('%pre="foo\nbar"'))
assert_equal("<pre>foo\nbar</pre>\n", render("%pre\n foo\n bar"))
assert_equal("<pre>foo\nbar</pre>\n", render('%pre="foo\nbar"', :ugly => true))
assert_equal("<pre>foo\nbar</pre>\n", render("%pre\n foo\n bar", :ugly => true))
end
def test_xhtml_output_option
assert_equal "<p>\n <br />\n</p>\n", render("%p\n %br", :format => :xhtml)
assert_equal "<a />\n", render("%a/", :format => :xhtml)
end
def test_arbitrary_output_option
assert_raise(Haml::Error, "Invalid output format :html1") { Haml::Engine.new("%br", :format => :html1) }
end
# HTML 4.0
def test_html_has_no_self_closing_tags
assert_equal "<p>\n <br>\n</p>\n", render("%p\n %br", :format => :html4)
assert_equal "<br>\n", render("%br/", :format => :html4)
end
def test_html_renders_empty_node_with_closing_tag
assert_equal "<div class='foo'></div>\n", render(".foo", :format => :html4)
end
def test_html_ignores_explicit_self_closing_declaration
assert_equal "<a></a>\n", render("%a/", :format => :html4)
end
def test_html_ignores_xml_prolog_declaration
assert_equal "", render('!!! XML', :format => :html4)
end
def test_html_has_different_doctype
assert_equal %{<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n},
render('!!!', :format => :html4)
end
# because anything before the doctype triggers quirks mode in IE
def test_xml_prolog_and_doctype_dont_result_in_a_leading_whitespace_in_html
assert_no_match /^\s+/, render("!!! xml\n!!!", :format => :html4)
end
# HTML5
def test_html5_doctype
assert_equal %{<!DOCTYPE html>\n}, render('!!!', :format => :html5)
end
end
| 41.699387 | 171 | 0.60295 |
d5f49ac4579aa2a193bea5af5f5c016f0fc686d3 | 258 | require 'optparse'
require 'bundler'
require 'typhoeus'
require 'json'
require 'ruby-progressbar'
require 'csv'
require 'date'
require 'yaml'
require 'active_support/all'
require 'byebug'
Dir[File.dirname(__FILE__) + "/lib/*.rb"].each{ |file| require file } | 21.5 | 69 | 0.744186 |
39e29f8dc3dc7f1e136e15cecc943e8a56f5eb93 | 3,433 | module ApiSchema
class ResourceDefinition
include ::Swagger::Blocks::ClassMethods
def initialize(method, api_version, base_path, extra_path = nil)
@base_path = base_path
@extra_path = extra_path
@method = method
@api_version = api_version
@header_params = []
@path_params = []
@query_params = []
@errors = []
end
HeaderParam = ::Struct.new(:name, :type, :required)
PathParam = ::Struct.new(:name, :type, :required)
QueryParam = ::Struct.new(:name, :type, :required)
attr_accessor :desc_file_path
attr_reader :method, :api_version, :summary, :description, :header_params,
:body_param, :path_params, :query_params, :resp, :errors,
:base_path, :extra_path, :full_path, :desc_file_name
def name(name)
@summary = name
end
def desc(desc)
@description = desc
end
def desc_file(desc_file_name)
@desc_file_name = desc_file_name
end
def header(name, type, required: true)
@header_params << HeaderParam.new(name, type, required)
end
def body(body_param)
@body_param = body_param
end
def path_param(name, type, required: true)
@path_params << PathParam.new(name, type, required)
end
def query_param(name, type, required: true)
@query_params << QueryParam.new(name, type, required)
end
def response(code, model_name = nil, &block)
@resp = Response.new(code, model_name)
if block && model_name.nil?
block.call(@resp)
end
end
def error!(*codes)
@errors = *codes
end
def with_path_param?
!path_params.empty?
end
def with_body?
!!body_param
end
def with_errors?
!errors.empty?
end
def generate_full_path
@full_path = with_path_param? ? "/#{base_path}/{id}" : "/#{base_path}"
@full_path << "/#{extra_path}" if extra_path
end
def build_description
@description = IO.read(desc_file_path, encoding: 'utf-8')
end
def build_neighbors(neighbors)
generate_full_path
neighbors[full_path] ||= []
neighbors[full_path] << self
end
def build(neighbors)
error_model = :error_model
error_desc = {
'401' => "Unauthorized",
'403' => "Forbidden",
'404' => "Not found",
'422' => "Unprocessable Entity"
}
build_description if desc_file_name
resource = self
swagger_path resource.full_path do
neighbors[resource.full_path].each do |r|
operation(r.method) do
key :summary, r.summary
key :description, r.description
key :operationId, "#{r.method}_#{r.full_path}"
key :tags, r.base_path
security do
key :authorization, []
end
body_param(r.body_param) if r.with_body?
r.header_params.each do |p|
header_param(p.name, p.type, p.required)
end
r.path_params.each do |p|
path_param(p.name, p.type, p.required)
end
r.query_params.each do |p|
query_param(p.name, p.type, p.required)
end
success_response(r.resp.code, r.resp.model, r.resp.fields)
error_responses(error_model, error_desc, *r.errors) if r.with_errors?
end
end
end
end
end
end
| 25.81203 | 81 | 0.593067 |
6294ab9313f95d170280a94ac81d1776feaedf45 | 47 | module BootstrapHelper
VERSION = "0.0.1"
end
| 11.75 | 22 | 0.723404 |
f75e5eb56382822e28723a67ad2e9f1e8e70d034 | 4,903 | # frozen_string_literal: true
require 'cucumber/core/test/action'
require 'cucumber/core/test/duration_matcher'
module Cucumber
module Core
module Test
describe Action do
context "constructed without a block" do
it "raises an error" do
expect { Action.new }.to raise_error(ArgumentError)
end
end
context "location" do
context "with location passed to the constructor" do
let(:location) { double }
it "returns the location passed to the constructor" do
action = Action.new(location) {}
expect( action.location ).to be location
end
end
context "without location passed to the constructor" do
let(:block) { proc {} }
it "returns the location of the block passed to the constructor" do
action = Action.new(&block)
expect( action.location ).to eq Test::Location.new(*block.source_location)
end
end
end
context "executing" do
it "executes the block passed to the constructor" do
executed = false
action = Action.new { executed = true }
action.execute
expect( executed ).to be_truthy
end
it "returns a passed result if the block doesn't fail" do
action = Action.new {}
expect( action.execute ).to be_passed
end
it "returns a failed result when the block raises an error" do
exception = StandardError.new
action = Action.new { raise exception }
result = action.execute
expect( result ).to be_failed
expect( result.exception ).to eq exception
end
it "yields the args passed to #execute to the block" do
args = [double, double]
args_spy = nil
action = Action.new { |arg1, arg2| args_spy = [arg1, arg2] }
action.execute(*args)
expect(args_spy).to eq args
end
it "returns a pending result if a Result::Pending error is raised" do
exception = Result::Pending.new("TODO")
action = Action.new { raise exception }
result = action.execute
expect( result ).to be_pending
expect( result.message ).to eq "TODO"
end
it "returns a skipped result if a Result::Skipped error is raised" do
exception = Result::Skipped.new("Not working right now")
action = Action.new { raise exception }
result = action.execute
expect( result ).to be_skipped
expect( result.message ).to eq "Not working right now"
end
it "returns an undefined result if a Result::Undefined error is raised" do
exception = Result::Undefined.new("new step")
action = Action.new { raise exception }
result = action.execute
expect( result ).to be_undefined
expect( result.message ).to eq "new step"
end
context "recording the duration" do
before do
allow( Timer::MonotonicTime ).to receive(:time_in_nanoseconds).and_return(525702744080000, 525702744080001)
end
it "records the nanoseconds duration of the execution on the result" do
action = Action.new { }
duration = action.execute.duration
expect( duration ).to be_duration 1
end
it "records the duration of a failed execution" do
action = Action.new { raise StandardError }
duration = action.execute.duration
expect( duration ).to be_duration 1
end
end
end
context "skipping" do
it "does not execute the block" do
executed = false
action = Action.new { executed = true }
action.skip
expect( executed ).to be_falsey
end
it "returns a skipped result" do
action = Action.new {}
expect( action.skip ).to be_skipped
end
end
end
describe UndefinedAction do
let(:location) { double }
let(:action) { UndefinedAction.new(location) }
let(:test_step) { double }
context "location" do
it "returns the location passed to the constructor" do
expect( action.location ).to be location
end
end
context "executing" do
it "returns an undefined result" do
expect( action.execute ).to be_undefined
end
end
context "skipping" do
it "returns an undefined result" do
expect( action.skip ).to be_undefined
end
end
end
end
end
end
| 31.632258 | 121 | 0.562513 |
399d13c819846bd21ad6e5a03ed1144890857ec3 | 12,526 | # frozen_string_literal: true
require "rails/generators/rails/app/app_generator"
require "date"
module Rails
# The plugin builder allows you to override elements of the plugin
# generator without being forced to reverse the operations of the default
# generator.
#
# This allows you to override entire operations, like the creation of the
# Gemfile, \README, or JavaScript files, without needing to know exactly
# what those operations do so you can create another template action.
class PluginBuilder
def rakefile
template "Rakefile"
end
def app
if mountable?
if api?
directory "app", exclude_pattern: %r{app/(views|helpers)}
else
directory "app"
empty_directory_with_keep_file "app/assets/images/#{namespaced_name}"
end
elsif full?
empty_directory_with_keep_file "app/models"
empty_directory_with_keep_file "app/controllers"
empty_directory_with_keep_file "app/mailers"
unless api?
empty_directory_with_keep_file "app/assets/images/#{namespaced_name}"
empty_directory_with_keep_file "app/helpers"
empty_directory_with_keep_file "app/views"
end
end
end
def readme
template "README.md"
end
def gemfile
template "Gemfile"
end
def license
template "MIT-LICENSE"
end
def gemspec
template "%name%.gemspec"
end
def gitignore
template "gitignore", ".gitignore"
end
def version_control
if !options[:skip_git] && !options[:pretend]
run "git init", capture: options[:quiet], abort_on_failure: false
end
end
def lib
template "lib/%namespaced_name%.rb"
template "lib/tasks/%namespaced_name%_tasks.rake"
template "lib/%namespaced_name%/version.rb"
if engine?
template "lib/%namespaced_name%/engine.rb"
else
template "lib/%namespaced_name%/railtie.rb"
end
end
def config
template "config/routes.rb" if engine?
end
def test
template "test/test_helper.rb"
template "test/%namespaced_name%_test.rb"
append_file "Rakefile", <<-EOF
#{rakefile_test_tasks}
task default: :test
EOF
if engine?
template "test/integration/navigation_test.rb"
end
end
PASSTHROUGH_OPTIONS = [
:skip_active_record, :skip_active_storage, :skip_action_mailer, :skip_javascript, :skip_action_cable, :skip_sprockets, :database,
:api, :quiet, :pretend, :skip
]
def generate_test_dummy(force = false)
opts = (options.dup || {}).keep_if { |k, _| PASSTHROUGH_OPTIONS.map(&:to_s).include?(k) }
opts[:force] = force
opts[:skip_bundle] = true
opts[:skip_listen] = true
opts[:skip_git] = true
opts[:skip_turbolinks] = true
opts[:skip_webpack_install] = true
opts[:dummy_app] = true
invoke Rails::Generators::AppGenerator,
[ File.expand_path(dummy_path, destination_root) ], opts
end
def test_dummy_config
template "rails/boot.rb", "#{dummy_path}/config/boot.rb", force: true
template "rails/application.rb", "#{dummy_path}/config/application.rb", force: true
if mountable?
template "rails/routes.rb", "#{dummy_path}/config/routes.rb", force: true
end
end
def test_dummy_assets
template "rails/javascripts.js", "#{dummy_path}/app/javascript/packs/application.js", force: true
template "rails/stylesheets.css", "#{dummy_path}/app/assets/stylesheets/application.css", force: true
template "rails/dummy_manifest.js", "#{dummy_path}/app/assets/config/manifest.js", force: true
end
def test_dummy_clean
inside dummy_path do
remove_file "db/seeds.rb"
remove_file "Gemfile"
remove_file "lib/tasks"
remove_file "public/robots.txt"
remove_file "README.md"
remove_file "test"
remove_file "vendor"
end
end
def assets_manifest
template "rails/engine_manifest.js", "app/assets/config/#{underscored_name}_manifest.js"
end
def stylesheets
if mountable?
copy_file "rails/stylesheets.css",
"app/assets/stylesheets/#{namespaced_name}/application.css"
elsif full?
empty_directory_with_keep_file "app/assets/stylesheets/#{namespaced_name}"
end
end
def bin(force = false)
bin_file = engine? ? "bin/rails.tt" : "bin/test.tt"
template bin_file, force: force do |content|
"#{shebang}\n" + content
end
chmod "bin", 0755, verbose: false
end
def gemfile_entry
return unless inside_application?
gemfile_in_app_path = File.join(rails_app_path, "Gemfile")
if File.exist? gemfile_in_app_path
entry = "\ngem '#{name}', path: '#{relative_path}'"
append_file gemfile_in_app_path, entry
end
end
end
module Generators
class PluginGenerator < AppBase # :nodoc:
add_shared_options_for "plugin"
alias_method :plugin_path, :app_path
class_option :dummy_path, type: :string, default: "test/dummy",
desc: "Create dummy application at given path"
class_option :full, type: :boolean, default: false,
desc: "Generate a rails engine with bundled Rails application for testing"
class_option :mountable, type: :boolean, default: false,
desc: "Generate mountable isolated application"
class_option :skip_gemspec, type: :boolean, default: false,
desc: "Skip gemspec file"
class_option :skip_gemfile_entry, type: :boolean, default: false,
desc: "If creating plugin in application's directory " \
"skip adding entry to Gemfile"
class_option :api, type: :boolean, default: false,
desc: "Generate a smaller stack for API application plugins"
def initialize(*args)
@dummy_path = nil
super
end
public_task :set_default_accessors!
public_task :create_root
def create_root_files
build(:readme)
build(:rakefile)
build(:gemspec) unless options[:skip_gemspec]
build(:license)
build(:gitignore) unless options[:skip_git]
build(:gemfile) unless options[:skip_gemfile]
build(:version_control)
end
def create_app_files
build(:app)
end
def create_config_files
build(:config)
end
def create_lib_files
build(:lib)
end
def create_assets_manifest_file
build(:assets_manifest) if !api? && engine?
end
def create_public_stylesheets_files
build(:stylesheets) unless api?
end
def create_bin_files
build(:bin)
end
def create_test_files
build(:test) unless options[:skip_test]
end
def create_test_dummy_files
return unless with_dummy_app?
create_dummy_app
end
def update_gemfile
build(:gemfile_entry) unless options[:skip_gemfile_entry]
end
def finish_template
build(:leftovers)
end
public_task :apply_rails_template
def name
@name ||= begin
# same as ActiveSupport::Inflector#underscore except not replacing '-'
underscored = original_name.dup
underscored.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
underscored.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
underscored.downcase!
underscored
end
end
def underscored_name
@underscored_name ||= original_name.underscore
end
def namespaced_name
@namespaced_name ||= name.tr("-", "/")
end
private
def create_dummy_app(path = nil)
dummy_path(path) if path
say_status :vendor_app, dummy_path
mute do
build(:generate_test_dummy)
store_application_definition!
build(:test_dummy_config)
build(:test_dummy_assets)
build(:test_dummy_clean)
# ensure that bin/rails has proper dummy_path
build(:bin, true)
end
end
def engine?
full? || mountable? || options[:engine]
end
def full?
options[:full]
end
def mountable?
options[:mountable]
end
def skip_git?
options[:skip_git]
end
def with_dummy_app?
options[:skip_test].blank? || options[:dummy_path] != "test/dummy"
end
def api?
options[:api]
end
def self.banner
"rails plugin new #{arguments.map(&:usage).join(' ')} [options]"
end
def original_name
@original_name ||= File.basename(destination_root)
end
def modules
@modules ||= namespaced_name.camelize.split("::")
end
def wrap_in_modules(unwrapped_code)
unwrapped_code = "#{unwrapped_code}".strip.gsub(/\s$\n/, "")
modules.reverse.inject(unwrapped_code) do |content, mod|
str = +"module #{mod}\n"
str << content.lines.map { |line| " #{line}" }.join
str << (content.present? ? "\nend" : "end")
end
end
def camelized_modules
@camelized_modules ||= namespaced_name.camelize
end
def humanized
@humanized ||= original_name.underscore.humanize
end
def camelized
@camelized ||= name.gsub(/\W/, "_").squeeze("_").camelize
end
def author
default = "TODO: Write your name"
if skip_git?
@author = default
else
@author = `git config user.name`.chomp rescue default
end
end
def email
default = "TODO: Write your email address"
if skip_git?
@email = default
else
@email = `git config user.email`.chomp rescue default
end
end
def valid_const?
if /-\d/.match?(original_name)
raise Error, "Invalid plugin name #{original_name}. Please give a name which does not contain a namespace starting with numeric characters."
elsif /[^\w-]+/.match?(original_name)
raise Error, "Invalid plugin name #{original_name}. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters."
elsif /^\d/.match?(camelized)
raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers."
elsif RESERVED_NAMES.include?(name)
raise Error, "Invalid plugin name #{original_name}. Please give a " \
"name which does not match one of the reserved rails " \
"words: #{RESERVED_NAMES.join(", ")}"
elsif Object.const_defined?(camelized)
raise Error, "Invalid plugin name #{original_name}, constant #{camelized} is already in use. Please choose another plugin name."
end
end
def application_definition
@application_definition ||= begin
dummy_application_path = File.expand_path("#{dummy_path}/config/application.rb", destination_root)
unless options[:pretend] || !File.exist?(dummy_application_path)
contents = File.read(dummy_application_path)
contents[(contents.index(/module ([\w]+)\n(.*)class Application/m))..-1]
end
end
end
alias :store_application_definition! :application_definition
def get_builder_class
defined?(::PluginBuilder) ? ::PluginBuilder : Rails::PluginBuilder
end
def rakefile_test_tasks
<<-RUBY
require 'rake/testtask'
Rake::TestTask.new(:test) do |t|
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = false
end
RUBY
end
def dummy_path(path = nil)
@dummy_path = path if path
@dummy_path || options[:dummy_path]
end
def mute(&block)
shell.mute(&block)
end
def rails_app_path
APP_PATH.sub("/config/application", "") if defined?(APP_PATH)
end
def inside_application?
rails_app_path && destination_root.start_with?(rails_app_path.to_s)
end
def relative_path
return unless inside_application?
app_path.sub(/^#{rails_app_path}\//, "")
end
end
end
end
| 28.663616 | 150 | 0.613684 |
39cdda0790391d9d15f6be3d4d193489d821b8a4 | 702 | class SessionsController < ApplicationController
def new
# @srs = .new
end
def create
# sessions[:email]
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
session[:user_id] = user.id
flash[:success]="You have logged in successfully"
redirect_to user_path(user)
else
flash.now[:danger] = "There was something wrong in password or email"
render 'new'
end
end
def destroy
session[:user_id] = nil
flash[:success] = "You have successfully logged out"
redirect_to root_path
end
end | 30.521739 | 81 | 0.595442 |
b9a4ef9570fb9e3da883289efc8a4ff9bb0ac1ef | 8,694 | # frozen_string_literal: true
RSpec.describe Faraday::RackBuilder do
# mock handler classes
(Handler = Struct.new(:app)).class_eval do
def call(env)
env[:request_headers]['X-Middleware'] ||= ''
env[:request_headers]['X-Middleware'] += ":#{self.class.name.split('::').last}"
app.call(env)
end
end
class Apple < Handler
end
class Orange < Handler
end
class Banana < Handler
end
subject { conn.builder }
context 'with default stack' do
let(:conn) { Faraday::Connection.new }
it { expect(subject[0]).to eq(Faraday::Request.lookup_middleware(:url_encoded)) }
it { expect(subject.adapter).to eq(Faraday::Adapter.lookup_middleware(Faraday.default_adapter)) }
end
context 'with custom empty block' do
let(:conn) { Faraday::Connection.new {} }
it { expect(subject[0]).to be_nil }
it { expect(subject.adapter).to eq(Faraday::Adapter.lookup_middleware(Faraday.default_adapter)) }
end
context 'with custom adapter only' do
let(:conn) do
Faraday::Connection.new do |builder|
builder.adapter :test do |stub|
stub.get('/') { |_| [200, {}, ''] }
end
end
end
it { expect(subject[0]).to be_nil }
it { expect(subject.adapter).to eq(Faraday::Adapter.lookup_middleware(:test)) }
end
context 'with custom handler and adapter' do
let(:conn) do
Faraday::Connection.new do |builder|
builder.use Apple
builder.adapter :test do |stub|
stub.get('/') { |_| [200, {}, ''] }
end
end
end
it 'locks the stack after making a request' do
expect(subject.locked?).to be_falsey
conn.get('/')
expect(subject.locked?).to be_truthy
expect { subject.use(Orange) }.to raise_error(Faraday::RackBuilder::StackLocked)
end
it 'dup stack is unlocked' do
expect(subject.locked?).to be_falsey
subject.lock!
expect(subject.locked?).to be_truthy
dup = subject.dup
expect(dup).to eq(subject)
expect(dup.locked?).to be_falsey
end
it 'allows to compare handlers' do
expect(subject.handlers.first).to eq(Faraday::RackBuilder::Handler.new(Apple))
end
end
context 'when having a single handler' do
let(:conn) { Faraday::Connection.new {} }
before { subject.use(Apple) }
it { expect(subject.handlers).to eq([Apple]) }
it 'allows rebuilding' do
subject.build do |builder|
builder.use(Orange)
end
expect(subject.handlers).to eq([Orange])
end
it 'allows use' do
subject.use(Orange)
expect(subject.handlers).to eq([Apple, Orange])
end
it 'allows insert_before' do
subject.insert_before(Apple, Orange)
expect(subject.handlers).to eq([Orange, Apple])
end
it 'allows insert_after' do
subject.insert_after(Apple, Orange)
expect(subject.handlers).to eq([Apple, Orange])
end
it 'raises an error trying to use an unregistered symbol' do
expect { subject.use(:apple) }.to raise_error(Faraday::Error) do |err|
expect(err.message).to eq(':apple is not registered on Faraday::Middleware')
end
end
end
context 'with custom registered middleware' do
let(:conn) { Faraday::Connection.new {} }
after { Faraday::Middleware.unregister_middleware(:apple) }
it 'allows to register with constant' do
Faraday::Middleware.register_middleware(apple: Apple)
subject.use(:apple)
expect(subject.handlers).to eq([Apple])
end
end
context 'when having two handlers' do
let(:conn) { Faraday::Connection.new {} }
before do
subject.use(Apple)
subject.use(Orange)
end
it 'allows insert_before' do
subject.insert_before(Orange, Banana)
expect(subject.handlers).to eq([Apple, Banana, Orange])
end
it 'allows insert_after' do
subject.insert_after(Apple, Banana)
expect(subject.handlers).to eq([Apple, Banana, Orange])
end
it 'allows to swap handlers' do
subject.swap(Apple, Banana)
expect(subject.handlers).to eq([Banana, Orange])
end
it 'allows to delete a handler' do
subject.delete(Apple)
expect(subject.handlers).to eq([Orange])
end
end
context 'when middleware is added with named arguments' do
let(:conn) { Faraday::Connection.new {} }
let(:dog_middleware) do
Class.new(Faraday::Middleware) do
attr_accessor :name
def initialize(app, name:)
super(app)
@name = name
end
end
end
let(:dog) do
subject.handlers.find { |handler| handler == dog_middleware }.build
end
it 'adds a handler to construct middleware with options passed to use' do
subject.use dog_middleware, name: 'Rex'
expect { dog }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(dog.name).to eq('Rex')
end
end
context 'when a middleware is added with named arguments' do
let(:conn) { Faraday::Connection.new {} }
let(:cat_request) do
Class.new(Faraday::Middleware) do
attr_accessor :name
def initialize(app, name:)
super(app)
@name = name
end
end
end
let(:cat) do
subject.handlers.find { |handler| handler == cat_request }.build
end
it 'adds a handler to construct request adapter with options passed to request' do
Faraday::Request.register_middleware cat_request: cat_request
subject.request :cat_request, name: 'Felix'
expect { cat }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(cat.name).to eq('Felix')
end
end
context 'when a middleware is added with named arguments' do
let(:conn) { Faraday::Connection.new {} }
let(:fish_response) do
Class.new(Faraday::Middleware) do
attr_accessor :name
def initialize(app, name:)
super(app)
@name = name
end
end
end
let(:fish) do
subject.handlers.find { |handler| handler == fish_response }.build
end
it 'adds a handler to construct response adapter with options passed to response' do
Faraday::Response.register_middleware fish_response: fish_response
subject.response :fish_response, name: 'Bubbles'
expect { fish }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(fish.name).to eq('Bubbles')
end
end
context 'when a plain adapter is added with named arguments' do
let(:conn) { Faraday::Connection.new {} }
let(:rabbit_adapter) do
Class.new(Faraday::Adapter) do
attr_accessor :name
def initialize(app, name:)
super(app)
@name = name
end
end
end
let(:rabbit) do
subject.adapter.build
end
it 'adds a handler to construct adapter with options passed to adapter' do
Faraday::Adapter.register_middleware rabbit_adapter: rabbit_adapter
subject.adapter :rabbit_adapter, name: 'Thumper'
expect { rabbit }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(rabbit.name).to eq('Thumper')
end
end
context 'when handlers are directly added or updated' do
let(:conn) { Faraday::Connection.new {} }
let(:rock_handler) do
Class.new do
attr_accessor :name
def initialize(_app, name:)
@name = name
end
end
end
let(:rock) do
subject.handlers.find { |handler| handler == rock_handler }.build
end
it 'adds a handler to construct adapter with options passed to insert' do
subject.insert 0, rock_handler, name: 'Stony'
expect { rock }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(rock.name).to eq('Stony')
end
it 'adds a handler with options passed to insert_after' do
subject.insert_after 0, rock_handler, name: 'Rocky'
expect { rock }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(rock.name).to eq('Rocky')
end
it 'adds a handler with options passed to swap' do
subject.insert 0, rock_handler, name: 'Flint'
subject.swap 0, rock_handler, name: 'Chert'
expect { rock }.to_not output(
/warning: Using the last argument as keyword parameters is deprecated/
).to_stderr
expect(rock.name).to eq('Chert')
end
end
end
| 28.227273 | 101 | 0.643087 |
1ca307534a136e39039215c181d25b152a325c17 | 156,540 | #------------------------------------------------------------------------
# (The MIT License)
#
# Copyright (c) 2008-2011 Rhomobile, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# http://rhomobile.com
#------------------------------------------------------------------------
require 'json'
require File.expand_path(File.join(File.dirname(__FILE__), 'iphonecommon'))
require File.dirname(__FILE__) + '/../../../lib/build/BuildConfig'
$use_temp_keychain = false
$out_file_buf_enable = false
$out_file_buf_path = 'rhobuildlog.txt'
$out_file_buf = []
APPLE_PUSH = 0
FCM_PUSH = 1
UNKNOWN_PUSH = -1
puts 'iphone.rake execute' if USE_TRACES
puts 'ENV["RHO_BUNDLE_BUILD_LOG_FILE"] = '+ENV["RHO_BUNDLE_BUILD_LOG_FILE"].to_s if USE_TRACES
if (ENV["RHO_BUNDLE_BUILD_LOG_FILE"] != nil)
$out_file_buf_path = ENV["RHO_BUNDLE_BUILD_LOG_FILE"]
$out_file_buf_enable = true
load File.expand_path(File.join(File.dirname(__FILE__), 'putsOverride.rake'))
end
def save_out_file
if $out_file_buf_enable
f = File.new($out_file_buf_path,"w")
$out_file_buf.each do |line|
f.write(line)
f.write("\n")
end
f.close
end
end
def load_plist(fname)
require 'cfpropertylist'
plist = CFPropertyList::List.new(:file => fname)
data = CFPropertyList.native_types(plist.value)
data
end
def save_plist(fname, hash_data = {})
require 'cfpropertylist'
plist = CFPropertyList::List.new
plist.value = CFPropertyList.guess(hash_data)
plist.save(fname, CFPropertyList::List::FORMAT_XML,{:formatted=>true})
end
def update_plist_block(fname)
hash = load_plist(fname)
if block_given?
yield hash
end
save_plist(fname, hash)
hash
end
def set_app_plist_options(fname, appname, bundle_identifier, version, url_scheme)
update_plist_block(fname) do |hash|
hash['CFBundleDisplayName'] = appname
hash['CFBundleIdentifier'] = bundle_identifier
if hash['CFBundleURLTypes'].empty?
hash['CFBundleURLTypes'] = {'CFBundleURLName' => bundle_identifier, 'CFBundleURLSchemes' => [url_scheme] }
else
elem = hash['CFBundleURLTypes'].first
elem['CFBundleURLName'] = bundle_identifier
elem['CFBundleURLSchemes'] = [url_scheme] unless url_scheme.nil?
end
unless version.nil?
hash['CFBundleVersion'] = version
hash['CFBundleShortVersionString'] = version
end
if block_given?
yield hash
end
end
end
def get_ext_plist_changes(ext_path_to_cfg_map)
changed_value = {}
extension_name = {}
ext_path_to_cfg_map.each do |ext, conf|
plist_addons = BuildConfig.find_elem(conf, 'iphone/plist_changes')
unless plist_addons.nil?
full_patj = File.join(ext, plist_addons.to_s)
if File.exist?(full_patj)
hash = load_plist(full_patj)
hash.each do |k, v|
if extension_name.has_key?(k)
BuildOutput.error(["Extension #{ext} overrides key #{k} that was set by #{extension_name[k]}"])
end
extension_name[k] = ext
changed_value[k] = v
end
end
end
end
return extension_name, changed_value
end
#
# def set_ui_prerendered_icon(val)
# add = (val=~(/(true|t|yes|y|1)$/i))?true:false
#
# ret_value = nil
#
# #fname = $config["build"]["iphonepath"] + "/Info.plist"
# fname = $app_path + "/project/iphone/Info.plist"
# nextline = false
# replaced = false
# dictcnt = 0
# buf = ""
# File.new(fname,"r").read.each_line do |line|
# matches = (line =~ /UIPrerenderedIcon/)?true:false
# if nextline and not replaced
# ret_value = true
# return ret_value if add
#
# replaced = true
# else
# if (line=~/<\/dict>/)
# if add and (dictcnt==1)
# buf << "<key>UIPrerenderedIcon</key>\n"
# buf << "<true/>\n"
# end
# dictcnt = dictcnt-1
# elsif (line=~/<dict>/)
# dictcnt = dictcnt+1
# end
#
# buf << line unless ( matches and not add )
# end
# nextline = matches
# end
#
# File.open(fname,"w") { |f| f.write(buf) }
# return ret_value
# end
def recursive_replace_bool(value)
if value.kind_of?(Hash)
value.each_key do |nkey|
value[nkey] = recursive_replace_bool(value[nkey])
end
elsif value.kind_of?(Array)
new_array = []
value.each do |el|
new_array << recursive_replace_bool(el)
end
else
if (value.to_s.downcase == 'true') || (value.to_s.downcase == 'yes')
value = true
end
if (value.to_s.downcase == 'false') || (value.to_s.downcase == 'no')
value = false
end
end
return value
end
def recursive_merge_hash(hash, key, value)
old_value = hash[key]
if old_value.nil?
hash[key] = value
elsif value.kind_of?(Array)
if old_value.kind_of?(Array)
value.each do |element|
if !old_value.include?(element)
old_value << element
end
end
else
hash[key] = value
end
elsif value.kind_of?(Hash)
if old_value.kind_of?(Hash)
value.each do |nkey, nvalue|
recursive_merge_hash(old_value, nkey, nvalue)
end
else
hash[key] = value
end
else
hash[key] = value
end
end
def recursive_remove_hash(hash, key)
if key.kind_of?(Array)
key.each do |element|
recursive_remove_hash(hash, element)
end
elsif key.kind_of?(Hash)
key.each do |keykey, keyvalue|
if hash.has_key? keykey
oldkey = hash[keykey]
recursive_remove_hash(oldkey, keyvalue)
end
end
elsif key.kind_of?(String)
#if hash.has_key? key
hash.delete(key)
#end
end
end
def update_plist_procedure
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
vendor = $app_config['vendor'] ? $app_config['vendor'] : "rhomobile"
bundle_identifier = "com.#{vendor}.#{appname}"
bundle_identifier = $app_config["iphone"]["BundleIdentifier"] unless $app_config["iphone"]["BundleIdentifier"].nil?
on_suspend = $app_config["iphone"]["UIApplicationExitsOnSuspend"]
on_suspend_value = false
if on_suspend.nil?
puts "UIApplicationExitsOnSuspend not configured, using default of false"
elsif on_suspend.to_s.downcase == "true" || on_suspend.to_s == "1"
on_suspend_value = true
elsif on_suspend.to_s.downcase == "false" || on_suspend.to_s == "0"
on_suspend_value = false
else
raise "UIApplicationExitsOnSuspend is not set to a valid value. Current value: '#{$app_config["iphone"]["UIApplicationExitsOnSuspend"]}'"
end
init_extensions( nil, "get_ext_xml_paths")
ext_name, changed_value = get_ext_plist_changes($app_extension_cfg)
set_app_plist_options($app_path + "/project/iphone/Info.plist", appname, bundle_identifier, $app_config["version"], $app_config["iphone"]["BundleURLScheme"]) do |hash|
if !(on_suspend.nil?)
hash['UIApplicationExitsOnSuspend'] = on_suspend_value
end
changed_value.each do |k, v|
puts "Info.plist: Setting key #{k} = #{v} from #{File.basename(ext_name[k])}"
hash[k] = v
end
#setup GPS access
gps_request_text = nil
if $app_config["capabilities"].index("gps") != nil
gps_request_text = 'application tracks your position'
end
if !$app_config["iphone"].nil?
if !$app_config["iphone"]["capabilities"].nil?
if $app_config["iphone"]["capabilities"].index("gps") != nil
gps_request_text = 'application tracks your position'
end
end
end
if gps_request_text != nil
if hash['NSLocationWhenInUseUsageDescription'] == nil
puts "Info.plist: added key [NSLocationWhenInUseUsageDescription]"
hash['NSLocationWhenInUseUsageDescription'] = gps_request_text
end
end
#setup Camera access
camera_request_text = nil
if $app_config["capabilities"].index("camera") != nil
camera_request_text = 'application wants to use camera'
end
if !$app_config["iphone"].nil?
if !$app_config["iphone"]["capabilities"].nil?
if $app_config["iphone"]["capabilities"].index("camera") != nil
camera_request_text = 'application wants to use camera'
end
end
end
if camera_request_text != nil
if hash['NSCameraUsageDescription'] == nil
puts "Info.plist: added key [NSCameraUsageDescription]"
hash['NSCameraUsageDescription'] = camera_request_text
end
end
#LSApplicationQueriesSchemes
if $app_config["iphone"].has_key?("ApplicationQueriesSchemes")
arr_app_queries_schemes = $app_config["iphone"]["ApplicationQueriesSchemes"]
if arr_app_queries_schemes.kind_of?(Array)
hash['LSApplicationQueriesSchemes'] = arr_app_queries_schemes
else
hash['LSApplicationQueriesSchemes'] = []
end
end
#http_connection_domains
if $app_config["iphone"].has_key?("http_connection_domains")
http_connection_domains = $app_config["iphone"]["http_connection_domains"]
if http_connection_domains.kind_of?(Array)
if !hash.has_key?("NSAppTransportSecurity")
hash['NSAppTransportSecurity'] = {}
end
hash['NSAppTransportSecurity']['NSExceptionDomains'] = {}
http_connection_domains.each do |domain|
domain_hash = {}
domain_hash['NSIncludesSubdomains'] = true
domain_hash['NSTemporaryExceptionAllowsInsecureHTTPLoads'] = true
domain_hash['NSTemporaryExceptionMinimumTLSVersion'] = 'TLSv1.0'
domain_hash['NSExceptionAllowsInsecureHTTPLoads'] = true
domain_hash['NSExceptionMinimumTLSVersion'] = 'TLSv1.0'
hash['NSAppTransportSecurity']['NSExceptionDomains'][domain.to_s] = domain_hash
end
end
end
# add custom data
if $app_config["iphone"].has_key?("info_plist_data_remove")
info_plist_data_remove = $app_config["iphone"]["info_plist_data_remove"]
if info_plist_data_remove.kind_of?(Array)
info_plist_data_remove.each do |key|
recursive_remove_hash(hash, key)
end
end
end
if $app_config["iphone"].has_key?("info_plist_data")
info_plist_data = $app_config["iphone"]["info_plist_data"]
if info_plist_data.kind_of?(Hash)
info_plist_data.each do |key, value|
value = recursive_replace_bool(value)
recursive_merge_hash(hash, key, value)
end
end
end
set_app_icon()
set_default_images(false, hash)
end
end
def set_signing_identity(identity,profile,entitlements,provisioning_style,development_team)
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| (w.capitalize) }.join("")
#fname = $config["build"]["iphonepath"] + "/rhorunner.xcodeproj/project.pbxproj"
fname = $app_path + "/project/iphone" + "/" + appname_fixed + ".xcodeproj/project.pbxproj"
buf = ""
File.new(fname,"r").read.each_line do |line|
if entitlements != nil
line.gsub!(/CODE_SIGN_ENTITLEMENTS = .*;/,"CODE_SIGN_ENTITLEMENTS = \"#{entitlements}\";")
end
if provisioning_style != nil
line.gsub!(/ProvisioningStyle = .*;/,"ProvisioningStyle = \"#{provisioning_style}\";")
end
if development_team != nil
line.gsub!(/DevelopmentTeam = .*;/,"DevelopmentTeam = \"#{development_team}\";")
line.gsub!(/DEVELOPMENT_TEAM = .*;/,"DEVELOPMENT_TEAM = \"#{development_team}\";")
end
line.gsub!(/CODE_SIGN_IDENTITY = .*;/,"CODE_SIGN_IDENTITY = \"#{identity}\";")
line.gsub!(/"CODE_SIGN_IDENTITY\[sdk=iphoneos\*\]" = .*;/,"\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"#{identity}\";")
if profile and profile.to_s != ""
line.gsub!(/PROVISIONING_PROFILE = .*;/,"PROVISIONING_PROFILE = \"#{profile}\";")
line.gsub!(/"PROVISIONING_PROFILE\[sdk=iphoneos\*\]" = .*;/,"\"PROVISIONING_PROFILE[sdk=iphoneos*]\" = \"#{profile}\";")
end
puts line if line =~ /CODE_SIGN/
buf << line
end
File.open(fname,"w") { |f| f.write(buf) }
end
def make_app_info
fname = File.join($app_path, 'bin', 'target', 'iOS', $sdk, $configuration, 'app_info.txt')
buf = ""
urlscheme = 'rhodes'
urlscheme = $app_config["name"] unless $app_config["name"].nil?
urlscheme = $app_config["iphone"]["BundleURLScheme"] unless $app_config["iphone"]["BundleURLScheme"].nil?
urlscheme = urlscheme.split(/[^a-zA-Z0-9\_\-]/).map{|w| w}.join("_")
buf << urlscheme
File.open(fname,"w") { |f| f.write(buf) }
end
def prepare_production_ipa (app_path, app_name)
puts 'Preparing *.IPA file ...'
tmp_dir = File.join(app_path, "tmp_ipa")
mkdir_p tmp_dir
payload_dir = File.join(tmp_dir, "Payload")
mkdir_p payload_dir
app_file = File.join(app_path, app_name + ".app")
app_in_payload = File.join(payload_dir, app_name + ".app")
mprovision_in_app = File.join(app_file, "embedded.mobileprovision")
mprovision_in_payload = File.join(payload_dir, app_name + ".mobileprovision")
cp_r app_file, app_in_payload
executable_file = File.join(app_in_payload, 'rhorunner')
if !File.executable? executable_file
begin
File.chmod 0700, executable_file
puts 'executable attribute was writed for : '+executable_file
rescue Exception => e
puts 'ERROR: can not change attribute for executable in application package ! Try to run build command with sudo: prefix.'
end
end
#cp mprovision_in_app, mprovision_in_payload
# now iTunesArtwork should be placed into application bundle !
#cp itunes_artwork, itunes_artwork_dst
currentdir = Dir.pwd()
chdir tmp_dir
sh %{zip -r -y temporary_archive.zip .}
ipa_file_path = File.join(app_path, app_name + ".ipa")
rm_rf ipa_file_path
cp 'temporary_archive.zip', ipa_file_path
Dir.chdir currentdir
rm_rf tmp_dir
return ipa_file_path
end
#TODO: support assets !
def copy_all_png_from_icon_folder_to_product(app_path)
# rm_rf File.join(app_path, "*.png")
#
# app_icon_folder = File.join($app_path, 'resources', 'ios')
# if File.exists? app_icon_folder
# # NEW resources
# Dir.glob(File.join(app_icon_folder, "icon*.png")).each do |icon_file|
# cp icon_file, app_path
# end
# else
# app_icon_folder = File.join($app_path, 'icon')
# Dir.glob(File.join(app_icon_folder, "*.png")).each do |icon_file|
# cp icon_file, app_path
# end
# end
end
def prepare_production_plist (app_path, app_name)
puts 'Preparing application production plist ...'
$plist_title = app_name
$plist_subtitle = app_name
$plist_icon_url = "http://example.com/icon57.png"
$plist_ipa_url = "http://example.com/"+app_name+".ipa"
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
vendor = $app_config['vendor'] ? $app_config['vendor'] : "rhomobile"
$plist_bundle_id = "com.#{vendor}.#{appname}"
$plist_bundle_id = $app_config["iphone"]["BundleIdentifier"] unless $app_config["iphone"]["BundleIdentifier"].nil?
$plist_bundle_version = "1.0"
$plist_bundle_version = $app_config["version"] unless $app_config["version"].nil?
if !$app_config["iphone"].nil?
if !$app_config["iphone"]["production"].nil?
$plist_title = $app_config["iphone"]["production"]["app_plist_title"] unless $app_config["iphone"]["production"]["app_plist_title"].nil?
$plist_subtitle = $app_config["iphone"]["production"]["app_plist_subtitle"] unless $app_config["iphone"]["production"]["app_plist_subtitle"].nil?
$plist_icon_url = $app_config["iphone"]["production"]["app_plist_icon_url"] unless $app_config["iphone"]["production"]["app_plist_icon_url"].nil?
$plist_ipa_url = $app_config["iphone"]["production"]["app_plist_ipa_url"] unless $app_config["iphone"]["production"]["app_plist_ipa_url"].nil?
end
end
rbText = ERB.new( IO.read(File.join($config["build"]["iphonepath"], "rbuild", "ApplicationPlist.erb")) ).result
fAlx = File.new(File.join(app_path, app_name + ".plist"), "w")
fAlx.write(rbText)
fAlx.close()
end
ICONS = [
'icon20.png',
'icon29.png',
'icon40.png',
'icon50.png',
'icon57.png',
'icon58.png',
'icon60.png',
'icon72.png',
'icon76.png',
'icon80.png',
'icon87.png',
'icon100.png',
'icon114.png',
'icon120.png',
'icon144.png',
'icon152.png',
'icon167.png',
'icon180.png',
'icon1024.png']
def set_app_icon
puts "set icon"
#ipath = $config["build"]["iphonepath"]
begin
ICONS.each do |icon|
name = icon
ipath = $app_path + "/project/iphone/Media.xcassets/AppIcon.appiconset"
icon = File.join(ipath, name)
appicon_old = File.join($app_path, 'icon', name)
appicon = appicon_old
if icon == 'icon1024.png'
itunes_artwork_default = File.join($app_path, "resources","ios","iTunesArtwork.png")
itunes_artwork = itunes_artwork_default
if !$app_config["iphone"].nil?
if !$app_config["iphone"]["production"].nil?
if !$app_config["iphone"]["production"]["ipa_itunesartwork_image"].nil?
art_test_name = $app_config["iphone"]["production"]["ipa_itunesartwork_image"]
if File.exists? art_test_name
itunes_artwork = art_test_name
else
art_test_name = File.join($app_path,$app_config["iphone"]["production"]["ipa_itunesartwork_image"])
if File.exists? art_test_name
itunes_artwork = art_test_name
else
itunes_artwork = $app_config["iphone"]["production"]["ipa_itunesartwork_image"]
end
end
end
end
end
itunes_artwork_2 = itunes_artwork
itunes_artwork_2 = itunes_artwork_2.gsub(".png", "@2x.png")
if itunes_artwork_2.index('@2x') == nil
itunes_artwork_2 = itunes_artwork_2.gsub(".PNG", "@2x.PNG")
end
if itunes_artwork_2.index('@2x') == nil
itunes_artwork_2 = itunes_artwork_2 + '@2x'
end
if File.exists? itunes_artwork_2
appicon = itunes_artwork_2
end
end
appicon_new = File.join($app_path, 'resources', 'ios', name)
if File.exists? appicon_new
appicon = appicon_new
end
if File.exists? appicon
if File.exists? ipath
rm_f ipath
end
cp appicon, ipath
else
#puts "WARNING: application should have next icon file : "+ name + '.png !!!'
BuildOutput.warning("Can not found next icon file : "+ name + ' , Use default Rhodes image !!!' )
end
end
rescue => e
puts "WARNING!!! Can not change icon: #{e.to_s}"
end
end
LOADINGIMAGES = [
'Default.png',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'Default-Portrait.png',
'[email protected]',
'Default-Landscape.png',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
def remove_lines_from_xcode_project(array_with_substrings)
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| (w.capitalize) }.join("")
fname = $app_path + "/project/iphone" + "/" + appname_fixed + ".xcodeproj/project.pbxproj"
buf = ""
File.new(fname,"r").read.each_line do |line|
is_remove = false
array_with_substrings.each do |rimg|
if line.include?(rimg)
is_remove = true
end
end
if !is_remove
buf << line
end
end
File.open(fname,"w") { |f| f.write(buf) }
end
def set_default_images(make_bak, plist_hash)
puts "set_default_images"
ipath = $app_path + "/project/iphone/Media.xcassets/LaunchImage.launchimage"
begin
contents_json_fname = File.join($app_path, "/project/iphone/Media.xcassets/LaunchImage.launchimage/Contents.json")
contents_json = JSON.parse(File.read(contents_json_fname))
contents_json_was_changed = false
launch_image_is_valid = false
LOADINGIMAGES.each do |name|
oldname = name.sub('Default', 'loading')
imag = File.join(ipath, name)
appimage = File.join($app_path, 'app', oldname)
name_ios_ext = oldname.sub('.png', '.iphone.png')
appsimage = File.join($app_path, 'app', name_ios_ext)
resourcesiamge = File.join($app_path, 'resources', 'ios', name)
if File.exists? appsimage
appimage = appsimage
end
if File.exists? resourcesiamge
appimage = resourcesiamge
end
#bundlei = File.join($srcdir, defname + '.png')
if File.exists? imag
rm_f imag
end
if File.exist? appimage
#if File.exists? imag
# rm_f imag
#end
puts "$$$ appimage = "+appimage
cp appimage, imag
if name != "Default.png"
# should be not just Default.png
launch_image_is_valid = true
end
else
puts "$$$ NO appimage = "+appimage
images = contents_json["images"]
images.each do |image|
if image["filename"] == name
images.delete(image)
contents_json_was_changed = true
end
end
BuildOutput.warning("Can not found next default file : "+ name + ' , removed from project but can be required for AppStore - please add this image if it required !!!' )
end
end
if contents_json_was_changed
content = JSON.generate(contents_json)
File.open( contents_json_fname, "w"){|file| file.write(content)}
end
if !launch_image_is_valid
# we shoud remove LaunchImage from project - app not has launch image
BuildOutput.warning("remove LaunchImage from project - because not found any applicable images (old 320x480 is not enough!)")
remove_lines_from_xcode_project(["ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage;"])
end
rescue => e
puts "WARNING!!! Can not change default image: #{e.to_s}"
end
end
def update_xcode_project_files_by_capabilities
info_plist = $app_path + "/project/iphone/Info.plist"
dev_ent = $app_path + "/project/iphone/rhorunner_development.entitlements"
prd_ent = $app_path + "/project/iphone/rhorunner_production.entitlements"
hash_info_plist = load_plist(info_plist)
hash_dev_ent = load_plist(dev_ent)
hash_prd_ent = load_plist(prd_ent)
#if($push_type == FCM_PUSH)
#framework_src = File.join($startdir, 'lib', 'extensions', 'fcm-push', 'ext', 'iphone', 'Frameworks')
#firebase_h_src = File.join($startdir, 'platform', 'iphone', 'Firebase.h')
#googleservice_plist_src = File.join($startdir, 'platform', 'iphone', 'GoogleService-Info.plist')
#framework_dst = File.join($app_path, 'project', 'iphone')
#cp_r framework_src, framework_dst
#cp_r firebase_h_src, framework_dst
#cp_r googleservice_plist_src, framework_dst
#end
#bluetooth
bt_capability = false
if $app_config['capabilities'] != nil
if $app_config['capabilities'].index('bluetooth')
bt_capability = true
end
end
if $app_config['iphone'] != nil
if $app_config['iphone']['capabilities'] != nil
if $app_config['iphone']['capabilities'].index('bluetooth')
bt_capability = true
end
end
end
if bt_capability
if hash_info_plist['UIRequiredDeviceCapabilities'] == nil
hash_info_plist['UIRequiredDeviceCapabilities'] = []
end
hash_info_plist['UIRequiredDeviceCapabilities'] << "gamekit"
else
remove_lines_from_xcode_project(['GameKit.framework'])
if hash_info_plist['UIRequiredDeviceCapabilities'] != nil
hash_info_plist['UIRequiredDeviceCapabilities'].delete("gamekit")
end
end
barcode_etension_exist = false
if $app_config['extensions'] != nil
if $app_config['extensions'].index('barcode')
barcode_etension_exist = true
end
end
if $app_config['iphone'] != nil
if $app_config['iphone']['extensions'] != nil
if $app_config['iphone']['extensions'].index('barcode')
barcode_etension_exist = true
end
end
end
if barcode_etension_exist
if $app_config['iphone'] != nil
if $app_config['iphone']['barcode_engine'] != nil
$barcode_engine = $app_config['iphone']['barcode_engine'].upcase
if $barcode_engine != 'ZXING' && $barcode_engine != 'ZBAR' && $barcode_engine != 'APPLE_BARCODE_ENGINE' then
raise 'ERROR: Unknown barcode engine, select Apples or ZBar or ZXing please in build.yml [iphone][barcode_engine] setup to APPLE_BARCODE_ENGINE or ZXING or ZBAR !'
end
else
$barcode_engine = 'APPLE_BARCODE_ENGINE'
end
else
$barcode_engine = 'APPLE_BARCODE_ENGINE'
end
end
puts "$$$ $barcode_engine.to_s = "+$barcode_engine.to_s
if !$barcode_engine.to_s.empty?
File.open(File.join($startdir, "platform", "shared", "common", "barcode_engine.h"), 'w+') do |file|
file.puts "// WARNING! THIS FILE IS GENERATED AUTOMATICALLY! DO NOT EDIT IT MANUALLY!"
file.puts "#define #{$barcode_engine} 1"
end
end
#external_accessory
zebra_printing_ext = false
if $app_config['extensions'] != nil
if $app_config['extensions'].index('printing_zebra')
zebra_printing_ext = true
end
end
if $app_config['iphone'] != nil
if $app_config['iphone']['extensions'] != nil
if $app_config['iphone']['extensions'].index('printing_zebra')
zebra_printing_ext = true
end
end
end
if zebra_printing_ext
if $app_config['capabilities'] == nil
$app_config['capabilities'] = []
end
if $app_config['capabilities'].index('external_accessory')
else
$app_config['capabilities'] << "external_accessory"
end
end
ea_capability = false
if $app_config['capabilities'] != nil
if $app_config['capabilities'].index('external_accessory')
ea_capability = true
end
end
if $app_config['iphone'] != nil
if $app_config['iphone']['capabilities'] != nil
if $app_config['iphone']['capabilities'].index('external_accessory')
ea_capability = true
end
end
end
if ea_capability
hash_dev_ent['com.apple.external-accessory.wireless-configuration'] = true
hash_prd_ent['com.apple.external-accessory.wireless-configuration'] = true
else
hash_dev_ent.delete('com.apple.external-accessory.wireless-configuration')
hash_prd_ent.delete('com.apple.external-accessory.wireless-configuration')
remove_lines_from_xcode_project(['ExternalAccessory.framework', 'com.apple.BackgroundModes = {enabled = 1;};'])
end
#push
if $ios_push_capability
hash_dev_ent['aps-environment'] = 'development'
hash_prd_ent['aps-environment'] = 'production'
else
hash_dev_ent.delete('aps-environment')
hash_prd_ent.delete('aps-environment')
remove_lines_from_xcode_project(['com.apple.Push = {enabled = 1;};'])
end
if $push_type == APPLE_PUSH || !$ios_push_capability
lines_to_delete = []
lines_to_delete << 'AC1F5D5F20615B6C00B818B8 /* GoogleToolboxForMac.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5620615B6B00B818B8 /* GoogleToolboxForMac.framework */; };'
lines_to_delete << 'AC1F5D6020615B6C00B818B8 /* FirebaseAnalytics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5720615B6B00B818B8 /* FirebaseAnalytics.framework */; };'
lines_to_delete << 'AC1F5D6120615B6C00B818B8 /* FirebaseCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5820615B6B00B818B8 /* FirebaseCore.framework */; };'
lines_to_delete << 'AC1F5D6220615B6C00B818B8 /* FirebaseCoreDiagnostics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5920615B6B00B818B8 /* FirebaseCoreDiagnostics.framework */; };'
lines_to_delete << 'AC1F5D6320615B6C00B818B8 /* FirebaseInstanceID.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5A20615B6B00B818B8 /* FirebaseInstanceID.framework */; };'
lines_to_delete << 'AC1F5D6420615B6C00B818B8 /* FirebaseMessaging.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5B20615B6C00B818B8 /* FirebaseMessaging.framework */; };'
lines_to_delete << 'AC1F5D6520615B6C00B818B8 /* FirebaseNanoPB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5C20615B6C00B818B8 /* FirebaseNanoPB.framework */; };'
lines_to_delete << 'AC1F5D6620615B6C00B818B8 /* Protobuf.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5D20615B6C00B818B8 /* Protobuf.framework */; };'
lines_to_delete << 'AC1F5D6720615B6C00B818B8 /* nanopb.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D5E20615B6C00B818B8 /* nanopb.framework */; };'
lines_to_delete << 'AC1F5D6920615B8E00B818B8 /* StoreKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AC1F5D6820615B8600B818B8 /* StoreKit.framework */; };'
lines_to_delete << 'ACB0C9CB2058111F00A7F5E0 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = ACB0C9CA2058111F00A7F5E0 /* GoogleService-Info.plist */; };'
lines_to_delete << 'AC1F5D5620615B6B00B818B8 /* GoogleToolboxForMac.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GoogleToolboxForMac.framework; path = Frameworks/GoogleToolboxForMac.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5720615B6B00B818B8 /* FirebaseAnalytics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseAnalytics.framework; path = Frameworks/FirebaseAnalytics.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5820615B6B00B818B8 /* FirebaseCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseCore.framework; path = Frameworks/FirebaseCore.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5920615B6B00B818B8 /* FirebaseCoreDiagnostics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseCoreDiagnostics.framework; path = Frameworks/FirebaseCoreDiagnostics.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5A20615B6B00B818B8 /* FirebaseInstanceID.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseInstanceID.framework; path = Frameworks/FirebaseInstanceID.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5B20615B6C00B818B8 /* FirebaseMessaging.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseMessaging.framework; path = Frameworks/FirebaseMessaging.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5C20615B6C00B818B8 /* FirebaseNanoPB.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = FirebaseNanoPB.framework; path = Frameworks/FirebaseNanoPB.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5D20615B6C00B818B8 /* Protobuf.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Protobuf.framework; path = Frameworks/Protobuf.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D5E20615B6C00B818B8 /* nanopb.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = nanopb.framework; path = Frameworks/nanopb.framework; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D6820615B8600B818B8 /* StoreKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS11.1.sdk/System/Library/Frameworks/StoreKit.framework; sourceTree = DEVELOPER_DIR; };'
lines_to_delete << 'ACB0C9CA2058111F00A7F5E0 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = "<group>"; };'
lines_to_delete << 'AC1F5D6920615B8E00B818B8 /* StoreKit.framework */,'
lines_to_delete << 'AC1F5D6020615B6C00B818B8 /* FirebaseAnalytics.framework */,'
lines_to_delete << 'AC1F5D6120615B6C00B818B8 /* FirebaseCore.framework */,'
lines_to_delete << 'AC1F5D6220615B6C00B818B8 /* FirebaseCoreDiagnostics.framework */,'
lines_to_delete << 'AC1F5D6320615B6C00B818B8 /* FirebaseInstanceID.framework */,'
lines_to_delete << 'AC1F5D6420615B6C00B818B8 /* FirebaseMessaging.framework */,'
lines_to_delete << 'AC1F5D6520615B6C00B818B8 /* FirebaseNanoPB.framework */,'
lines_to_delete << 'AC1F5D5F20615B6C00B818B8 /* GoogleToolboxForMac.framework */,'
lines_to_delete << 'AC1F5D6720615B6C00B818B8 /* nanopb.framework */,'
lines_to_delete << 'AC1F5D6620615B6C00B818B8 /* Protobuf.framework */,'
lines_to_delete << 'ACB0C9CA2058111F00A7F5E0 /* GoogleService-Info.plist */,'
lines_to_delete << 'AC1F5D6820615B8600B818B8 /* StoreKit.framework */,'
lines_to_delete << 'AC1F5D5720615B6B00B818B8 /* FirebaseAnalytics.framework */,'
lines_to_delete << 'AC1F5D5820615B6B00B818B8 /* FirebaseCore.framework */,'
lines_to_delete << 'AC1F5D5920615B6B00B818B8 /* FirebaseCoreDiagnostics.framework */,'
lines_to_delete << 'AC1F5D5A20615B6B00B818B8 /* FirebaseInstanceID.framework */,'
lines_to_delete << 'AC1F5D5B20615B6C00B818B8 /* FirebaseMessaging.framework */,'
lines_to_delete << 'AC1F5D5C20615B6C00B818B8 /* FirebaseNanoPB.framework */,'
lines_to_delete << 'AC1F5D5620615B6B00B818B8 /* GoogleToolboxForMac.framework */,'
lines_to_delete << 'AC1F5D5E20615B6C00B818B8 /* nanopb.framework */,'
lines_to_delete << 'AC1F5D5D20615B6C00B818B8 /* Protobuf.framework */,'
lines_to_delete << 'ACB0C9CB2058111F00A7F5E0 /* GoogleService-Info.plist in Resources */,'
remove_lines_from_xcode_project(lines_to_delete)
end
#keychain access
enable_keychain = false
if $app_config['capabilities'] != nil
if $app_config['capabilities'].index('keychain')
enable_keychain = true
end
end
if $app_config['iphone'] != nil
if $app_config['iphone']['capabilities'] != nil
if $app_config['iphone']['capabilities'].index('keychain')
enable_keychain = true
end
end
end
# required for database encryption
if $app_config['encrypt_database'] != nil
if $app_config['encrypt_database'] == '1'
enable_keychain = true
end
end
if enable_keychain
else
remove_lines_from_xcode_project(['com.apple.Keychain = {enabled = 1;};'])
end
save_plist(info_plist, hash_info_plist)
save_plist(dev_ent, hash_dev_ent)
save_plist(prd_ent, hash_prd_ent)
end
def copy_entitlements_file_from_app
#enti_rho_name = File.join($config["build"]["iphonepath"], "Entitlements.plist")
enti_rho_name = File.join($app_path + "/project/iphone", "Entitlements.plist")
enti_app_name = File.join($app_path, "Entitlements.plist")
if !$app_config["iphone"].nil?
if !$app_config["iphone"]["entitlements_file"].nil?
enti_test_name = $app_config["iphone"]["entitlements_file"]
if File.exists? enti_test_name
enti_app_name = enti_test_name
else
enti_test_name = File.join($app_path, $app_config["iphone"]["entitlements_file"])
if File.exists? enti_test_name
enti_app_name = enti_test_name
else
enti_app_name = $app_config["iphone"]["entitlements_file"]
end
end
end
end
#if File.exists? enti_app_name
# puts 'Copy Entitlements.plist from application ...'
# cp enti_rho_name, (enti_rho_name + '_bak')
# rm_f enti_rho_name
# cp enti_app_name,enti_rho_name
#end
end
def restore_entitlements_file
#enti_rho_name = File.join($config["build"]["iphonepath"], "Entitlements.plist")
enti_rho_name = File.join($app_path + "/project/iphone", "Entitlements.plist")
if File.exists?(enti_rho_name + '_bak')
puts 'restore Entitlements.plist ...'
rm_f enti_rho_name
cp (enti_rho_name + '_bak'), enti_rho_name
rm_f (enti_rho_name + '_bak')
end
end
def basedir
File.join(File.dirname(__FILE__),'..','..','..')
end
def app_expanded_path(appname)
File.expand_path(File.join(basedir,'spec',appname))
end
def check_sdk(sdkname)
puts 'Check SDK :'
args = ['-version', '-sdk', sdkname]
puts Jake.run($xcodebuild,args)
ret = $?
chdir $startdir
unless ret == 0
puts ""
puts "ERROR: invalid SDK in BUILD.YML !"
puts sdkname+' is NOT installed on this computer !'
puts ""
puts "See all installed SDKs on this computer :"
args = ['-showsdks']
Jake.run($xcodebuild,args)
exit 1
end
end
def get_xcode_version
info_path = '/Applications/XCode.app/Contents/version.plist'
ret_value = '0.0'
if File.exists? info_path
hash = load_plist(info_path)
ret_value = hash['CFBundleShortVersionString'] if hash.has_key?('CFBundleShortVersionString')
else
puts '$$$ can not find XCode version file ['+info_path+']'
end
puts '$$$ XCode version is '+ret_value
return ret_value
end
def kill_iphone_simulator
puts 'kill "iPhone Simulator"'
`killall -9 "iPhone Simulator"`
`killall -9 "iOS Simulator"`
`killall -9 iphonesim`
`killall -9 iphonesim_43`
`killall -9 iphonesim_51`
`killall -9 iphonesim_6`
`killall -9 iphonesim_7`
`killall -9 iphonesim_8`
`killall -9 com.apple.CoreSimulator.CoreSimulatorService`
`killall -9 Simulator`
end
namespace "config" do
namespace "iphone" do
task :app_config do
puts 'Detect Push options'
$ios_push_capability = false
if !$app_config['capabilities'].nil?
if !$app_config['capabilities'].index('push').nil?
$ios_push_capability = true
end
end
if !$app_config['iphone'].nil?
if !$app_config['iphone']['capabilities'].nil?
if !$app_config['iphone']['capabilities'].index('push').nil?
$ios_push_capability = true
end
end
end
$push_type = APPLE_PUSH
if $ios_push_capability
if ((!$app_config['extensions'].nil?) && !$app_config['extensions'].index('fcm-push').nil?) ||
(!$app_config['iphone'].nil? && !$app_config['iphone']['extensions'].nil? &&
!$app_config['iphone']['extensions'].index('fcm-push').nil? )
$push_type = FCM_PUSH
puts 'Its fcm push'
else
puts 'Its apple push'
end
else
puts 'Its no push'
end
if $ios_push_capability && ($push_type == APPLE_PUSH)
# add ApplePush extension if it not exists
if !( ((!$app_config['extensions'].nil?) && !$app_config['extensions'].index('applePush').nil?) ||
(!$app_config['iphone'].nil? && !$app_config['iphone']['extensions'].nil? &&
!$app_config['iphone']['extensions'].index('applePush').nil? ) )
if $app_config['extensions'].nil?
$app_config['extensions'] = []
end
$app_config['extensions'] << 'applePush'
puts "applePush extension added"
end
end
$file_map_name = "rhofilelist.txt"
end
end
task :set_iphone_platform do
$current_platform = "iphone"
end
task :iphone => [:set_iphone_platform, "config:common", "switch_app"] do
$use_prebuild_data = false
#$rubypath = "res/build-tools/RubyMac" #path to RubyMac
if RUBY_PLATFORM =~ /(win|w)32$/
$all_files_mask = "*.*"
$rubypath = "res/build-tools/RhoRuby.exe"
else
$all_files_mask = "*"
if RUBY_PLATFORM =~ /darwin/
$rubypath = "res/build-tools/RubyMac"
else
$rubypath = "res/build-tools/rubylinux"
end
end
$file_map_name = "rhofilelist.txt"
iphonepath = $app_path + "/project/iphone" #$config["build"]["iphonepath"]
$builddir = $config["build"]["iphonepath"] + "/rbuild" #iphonepath + "/rbuild"
$bindir = File.join(iphonepath, "bin")#Jake.get_absolute(iphonepath) + "/bin"
$srcdir = $bindir + "/RhoBundle"
$targetdir = $app_path + "/bin/target/iOS"
$excludelib = ['**/builtinME.rb','**/ServeME.rb','**/dateME.rb','**/rationalME.rb']
$tmpdir = $bindir +"/tmp"
if $devroot.nil?
$devroot = $app_config["iphone"]["xcodepath"]
if $devroot == nil
$devroot = $config["env"]["paths"]["xcodepath"]
end
if $devroot != nil
$devroot = File.join($devroot, 'Contents/Developer')
end
end
$devroot = '/Applications/Xcode.app/Contents/Developer' if $devroot.nil?
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_51') if $iphonesim.nil?
#check for XCode 6
xcode_version = get_xcode_version
xcode_version = xcode_version[0..(xcode_version.index('.')-1)]
if xcode_version.to_i >= 6
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_6')
end
if xcode_version.to_i >= 7
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_7')
end
if xcode_version.to_i >= 8
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_8')
end
$xcodebuild = $devroot + "/usr/bin/xcodebuild"
if !File.exists? $xcodebuild
$devroot = '/Developer'
$xcodebuild = $devroot + "/usr/bin/xcodebuild"
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim')
else
#additional checking for iphonesimulator version
if !File.exists? '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks/DVTiPhoneSimulatorRemoteClient.framework'
#check for XCode 6
xcode_version = get_xcode_version
xcode_version = xcode_version[0..(xcode_version.index('.')-1)]
if xcode_version.to_i >= 8
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_8')
elsif xcode_version.to_i >= 7
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_7')
elsif xcode_version.to_i >= 6
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_6')
if xcode_version.to_i >= 7
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_7')
end
if xcode_version.to_i >= 8
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_8')
end
else
$iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim_43')
end
end
end
if (!File.exists? $xcodebuild) && (!$skip_checking_XCode)
puts 'ERROR: can not found XCode command line tools'
puts 'Install XCode to default location'
puts 'For XCode from 4.3 and later - you should install Command Line Tools package ! Open XCode - Preferences... - Downloads - Components - Command Line Tools'
exit 1
end
if !$skip_checking_XCode
$homedir = ENV['HOME']
$simdir = "#{$homedir}/Library/Application Support/iPhone Simulator/"
$sim = $devroot + "/Platforms/iPhoneSimulator.platform/Developer/Applications"
$guid = `uuidgen`.strip
$applog = File.join($homedir,$app_config["applog"]) if $app_config["applog"]
else
if RUBY_PLATFORM =~ /(win|w)32$/
$homedir = ''
$devroot = ''
$sim = ''
$guid = ''
$applog = ''
else
if RUBY_PLATFORM =~ /darwin/
$homedir = ENV['HOME']
$simdir = ''
$sim = ''
$guid = ''
$applog = ''
else
$homedir = ''
$devroot = ''
$sim = ''
$guid = ''
$applog = ''
end
end
end
$entitlements = nil
if $app_config["iphone"].nil?
$signidentity = $config["env"]["iphone"]["codesignidentity"]
$provisionprofile = $config["env"]["iphone"]["provisionprofile"]
$provisioning_style = $config["env"]["iphone"]["provisioning_style"]
$development_team = $config["env"]["iphone"]["development_team"]
$entitlements = $config["env"]["iphone"]["entitlements"]
$configuration = $config["env"]["iphone"]["configuration"]
$sdk = $config["env"]["iphone"]["sdk"]
$emulatortarget = 'iphone'
else
$signidentity = $app_config["iphone"]["codesignidentity"]
$provisionprofile = $app_config["iphone"]["provisionprofile"]
$provisioning_style = $app_config["iphone"]["provisioning_style"]
$development_team = $app_config["iphone"]["development_team"]
$entitlements = $app_config["iphone"]["entitlements"]
$configuration = $app_config["iphone"]["configuration"]
$sdk = $app_config["iphone"]["sdk"]
$emulatortarget = $app_config["iphone"]["emulatortarget"]
if $emulatortarget == nil
$emulatortarget = 'iphone'
end
end
if $entitlements == ""
$entitlements = nil
end
if $signidentity == nil
$signidentity = 'iPhone Developer'
end
# find UUID for name of mobileprovision
if (!$skip_checking_XCode) && ($provisionprofile != nil)
$homedir = ENV['HOME']
mp_folder = "#{$homedir}/Library/MobileDevice/Provisioning Profiles/"
mp_latest_UUID = nil
mp_latest_Time = nil
if File.exists? mp_folder
if $use_temp_keychain
puts "Prepare temporary keychain for use security tool"
args = ['delete-keychain', 'tmp']
Jake.run2('security',args)
args = ['create-keychain', '-p ""','rhobuildtmp']
Jake.run2('security',args)
end
Dir.entries(mp_folder).select do |entry|
path = File.join(mp_folder,entry)
#puts '$$$ '+path.to_s
if !(File.directory? path) and !(entry =='.' || entry == '..' || entry == '.DS_Store')
#puts ' $$$ '+path.to_s
plist_path = path
# make XML
xml_lines_arr = []
if $use_temp_keychain
args = ['cms', '-D', '-k', 'rhobuildtmp', '-i', plist_path]
else
args = ['cms', '-D', '-i', plist_path]
end
Jake.run2('security',args,{:rootdir => $startdir, :hide_output => true}) do |line|
xml_lines_arr << line.to_s
true
end
xml_lines = xml_lines_arr.join.to_s
#puts '%%%%%%% '+xml_lines
plist_obj = CFPropertyList::List.new(:data => xml_lines)
mp_plist_hash = CFPropertyList.native_types(plist_obj.value)
#puts ' $$$ '+mp_plist_hash.to_s
mp_name = mp_plist_hash['Name']
mp_uuid = mp_plist_hash['UUID']
mp_creation_date = mp_plist_hash['CreationDate']
#puts ' '+mp_creation_date.class.to_s+' '+mp_creation_date.to_s
#puts '$$$$$ MP: Name: "'+mp_name+'" UUID: ['+mp_uuid+']'
if mp_name == $provisionprofile
puts 'Found MobileProvision Name: "'+mp_name+'" UUID: ['+mp_uuid+'] Creation Time: '+mp_creation_date.to_s+' File: '+path.to_s
#$provisionprofile = mp_uuid
if mp_latest_UUID == nil
mp_latest_UUID = mp_uuid
mp_latest_Time = mp_creation_date
else
if mp_creation_date > mp_latest_Time
mp_latest_UUID = mp_uuid
mp_latest_Time = mp_creation_date
end
end
end
end
end
if $use_temp_keychain
args = ['delete-keychain', 'rhobuildtmp']
Jake.run2('security',args)
end
end
if mp_latest_UUID != nil
$provisionprofile = mp_latest_UUID
end
puts 'Processed MobileProvision UUID = '+$provisionprofile.to_s
end
# process special SDK names: latest, latest_simulator, latest_device
if ($sdk =~ /latest/) && (!$skip_checking_XCode)
args = ['-showsdks']
nullversion = Gem::Version.new('0.0')
latestsimulator = Gem::Version.new('0.0')
latestdevice = Gem::Version.new('0.0')
simulatorsdkmask = /(.*)iphonesimulator([0-9]+).([0-9]+)(.*)/
devicemask = /(.*)iphoneos([0-9]+).([0-9]+)(.*)/
Jake.run2($xcodebuild,args,{:rootdir => $startdir, :hide_output => true}) do |line|
#puts 'LINE = '+line.to_s
if (simulatorsdkmask=~line) == 0
parsed = line.scan(simulatorsdkmask)
curver = Gem::Version.new(parsed[0][1].to_s+'.'+parsed[0][2].to_s)
if curver > latestsimulator
latestsimulator = curver
end
end
if (devicemask=~line) == 0
parsed = line.scan(devicemask)
curver = Gem::Version.new(parsed[0][1].to_s+'.'+parsed[0][2].to_s)
if curver > latestdevice
latestdevice = curver
end
end
true
end
puts 'detect latestsimulator sdk = '+latestsimulator.to_s
puts 'detect latestdevice sdk = '+latestdevice.to_s
retx = $?
#puts '### +'+retx.to_s
if retx == 0
if $sdk.to_s.downcase == 'latest'
if Rake.application.top_level_tasks.to_s =~ /run/
$sdk = 'latest_simulator'
else
$sdk = 'latest_device'
end
end
if $sdk.to_s.downcase == 'latest_simulator'
if nullversion != latestsimulator
$sdk = 'iphonesimulator'+latestsimulator.to_s
end
end
if $sdk.to_s.downcase == 'latest_device'
if nullversion != latestsimulator
$sdk = 'iphoneos'+latestdevice.to_s
end
end
else
puts "ERROR: cannot run xcodebuild for get list of installed SDKs !"
end
end
if $sdk !~ /iphone/
if Rake.application.top_level_tasks.to_s =~ /run/
$sdk = "iphonesimulator#{$sdk}"
else
$sdk = "iphoneos#{$sdk}"
end
end
puts 'SDK = '+$sdk
if !$skip_checking_XCode
check_sdk($sdk)
end
if $sdk =~ /iphonesimulator/
$sdkver = $sdk.gsub(/iphonesimulator/,"")
$sdkroot = $devroot + "/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" + $sdkver + ".sdk"
else
$sdkver = $sdk.gsub(/iphoneos/,"")
$sdkroot = $devroot + "/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS" + $sdkver + ".sdk"
end
$emulator_version = nil
plist = File.join($sdkroot, 'System/Library/CoreServices/SystemVersion.plist')
if File.exists? plist
File.open(plist, 'r') do |f|
while line = f.gets
next unless line =~ /<string>(#{$sdkver.gsub('.', '\.')}[^<]*)<\/string>/
$emulator_version = $1
break unless $emulator_version.nil?
end
end
end
if !$skip_checking_XCode
unless File.exists? $homedir + "/.profile"
File.open($homedir + "/.profile","w") {|f| f << "#" }
chmod 0744, $homedir + "/.profile"
end
end
#if $app_config["iphone"] and $app_config["iphone"]["extensions"]
# $app_config["extensions"] += $app_config["iphone"]["extensions"] if $app_config["extensions"]
# $app_config["iphone"]["extensions"] = nil
#end
# check environment variables setted by XCode (when we executed from XCode)
#xcode_sdk_name = ENV['SDK_NAME']
#$sdk = xcode_sdk_name if not xcode_sdk_name.nil?
#$xcode_sdk_dir = ENV['SDK_DIR']
#xcode_configuration = ENV['CONFIGURATION']
#$configuration = xcode_configuration if not xcode_configuration.nil?
#make_project_bakup
end
end
namespace "build" do
namespace "iphone" do
# desc "Build iphone rhobundle"
# [build:iphone:rhobundle]
task :rhobundle => ["config:iphone"] do
print_timestamp('build:iphone:rhobundle START')
ENV["RHO_BUNDLE_ALREADY_BUILDED"] = "NO"
#chdir 'platform/iphone'
chdir File.join($app_path, 'project','iphone')
rm_rf 'bin'
#rm_rf 'build/Debug-*'
#rm_rf 'build/Release-*'
chdir $startdir
if (ENV["SDK_NAME"] != nil) and (ENV["CONFIGURATION"] != nil)
#we should override build.yml parameters by parameters from XCode !
$sdk = ENV["SDK_NAME"]
$configuration = ENV["CONFIGURATION"]
end
Rake::Task["build:bundle:noxruby"].execute
copy_generated_sources_and_binaries
if !$skip_build_extensions
Rake::Task["build:iphone:extensions"].execute
end
ENV["RHO_BUNDLE_ALREADY_BUILDED"] = "YES"
# Store hash
File.open(File.join($srcdir, "hash"), "w") { |f| f.write(get_dir_hash($srcdir).hexdigest) }
# Store app name
File.open(File.join($srcdir, "name"), "w") { |f| f.write($app_config["name"]) }
Jake.build_file_map( File.join($srcdir, "apps"), "rhofilelist.txt" )
print_timestamp('build:iphone:rhobundle FINISH')
save_out_file
end
# [build:iphone:rhodeslib_framework]
desc "Build iphone framework - set target path : rake build:iphone:rhodeslib_framework['/Users/myuser/mypath']"
task :rhodeslib_framework, [:target_path] => ["config:set_iphone_platform", "config:common"] do |t, args|
require $startdir + '/lib/build/jake.rb'
print_timestamp('build:iphone:rhodeslib_framework START')
currentdir = Dir.pwd()
# copied from build upgrade bundle
target_path = args[:target_path]
Rake::Task['config:iphone'].invoke
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
iphone_project = File.join($app_path, "project","iphone","#{appname_fixed}.xcodeproj")
if !File.exist?(iphone_project)
puts '$ make iphone XCode project for application'
Rake::Task['build:iphone:make_xcode_project'].invoke
end
# prepare tmp folder
lib_temp_dir = File.join($startdir, "platform/iphone/Framework/LibFactory")
rm_rf lib_temp_dir if File.exists? lib_temp_dir
mkdir_p lib_temp_dir
libs = []
# build rhodes system libs
rhodes_libs = {}
rhodes_libs['RhoApplication'] = { :path => File.join($startdir, "platform/iphone/Framework/RhoApplication"), :target => "RhoApplication"}
rhodes_libs['rhoextlib'] = { :path => File.join($startdir, "platform/iphone/rhoextlib"), :target => 'rhoextlib'}
rhodes_libs['rhosynclib'] = { :path => File.join($startdir, "platform/iphone/rhosynclib"), :target => 'rhosynclib'}
rhodes_libs['rhorubylib'] = { :path => File.join($startdir, "platform/iphone/rhorubylib"), :target => 'rhorubylib'}
rhodes_libs['RhoLib'] = { :path => File.join($startdir, "platform/iphone/RhoLib"), :target => 'RhoLib'}
rhodes_libs['curl'] = { :path => File.join($startdir, "platform/iphone/curl"), :target => 'curl'}
rhodes_libs['RhoAppBaseLib'] = { :path => File.join($startdir, "platform/iphone/RhoAppBaseLib"), :target => 'RhoAppBaseStandaloneLib'}
# skip this step - now all of those libsincluded into framework project
rhodes_libs = {}
rhodes_libs.each do |libname, libconfig|
# build
#args = ['install', '-scheme', libconfig[:target]+"Aggregated", '-project', libname + ".xcodeproj"]
Dir.chdir libconfig[:path]
#ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir})
lib_iphoneos_dir = File.join(libconfig[:path], "iphoneos")
lib_iphonesimulator_dir = File.join(libconfig[:path], "iphonesimulator")
lib_aggregated_dir = File.join(libconfig[:path], "aggregated")
lib_file_name = "lib" + libconfig[:target] + ".a"
lib_iphoneos_path = File.join(lib_iphoneos_dir, lib_file_name)
lib_iphonesimulator_path = File.join(lib_iphonesimulator_dir, lib_file_name)
lib_aggregated_path = File.join(lib_aggregated_dir, lib_file_name)
rm_rf lib_iphoneos_dir if File.exists? lib_iphoneos_dir
rm_rf lib_iphonesimulator_dir if File.exists? lib_iphonesimulator_dir
rm_rf lib_aggregated_dir if File.exists? lib_aggregated_dir
args = ['clean', 'build', '-scheme', libconfig[:target], '-project', libname + ".xcodeproj", "-sdk", "iphoneos", "-configuration", "Release"]
ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir,:string_for_add_to_command_line => ' CONFIGURATION_BUILD_DIR='+lib_iphoneos_dir+' ARCHS="arm64 arm64e armv7 armv7s"'})
args = ['clean', 'build', '-scheme', libconfig[:target], '-project', libname + ".xcodeproj", "-sdk", "iphonesimulator", "-configuration", "Release"]
ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir,:string_for_add_to_command_line => ' CONFIGURATION_BUILD_DIR='+lib_iphonesimulator_dir+' ARCHS="i386 x86_64"'})
mkdir_p lib_aggregated_dir
#result_lib = File.join(libconfig[:path], libconfig[:target]+"-Aggregated", lib_file_name)
args = []
args << "-create"
args << "-output"
args << lib_aggregated_path
args << lib_iphonesimulator_path
args << lib_iphoneos_path
IPhoneBuild.run_and_trace("lipo",args,{:rootdir => $startdir})
#copy result
target_lib = File.join(lib_temp_dir, lib_file_name)
cp_r lib_aggregated_path,target_lib
# count lib
libs << lib_file_name
end
#build extensions
Dir.chdir currentdir
Rake::Task['build:iphone:extension_libs'].invoke
#Rake::Task["build:bundle:noxruby"].execute
#copy extensions libs to tmp folder
puts "$$$ $app_extensions_list = "+$app_extensions_list.to_s
$app_extensions_list.each do |ext, commin_ext_path |
lib_ext_path = File.join($app_builddir, "extensions", ext, "lib")
# copy all libs from this folder
psize = lib_ext_path.size+1
Dir.glob(File.join(lib_ext_path,'*.a')).each do |artefact|
puts " $$$ artefact = "+artefact.to_s
if (File.file? artefact)
relpath = artefact[psize..-1]
libs << relpath
target_lib = File.join(lib_temp_dir, relpath)
cp_r artefact, target_lib
end
end
end
#join libs to one fat
Dir.chdir lib_temp_dir
#libtool -static -o result.a libCoreAPI.a
#args = ["-static", "-o", "RhodesFrameworkStaticLib.a"]
args = ["-static", "-o", "libRhodesExtensionsLib.a"]
lib_list = ""
libs.each do |lib|
args << lib
lib_list << File.join(lib_temp_dir, lib) + "\n"
end
#ret = IPhoneBuild.run_and_trace("libtool",args,{:rootdir => $startdir})
#build framework base
framework_dir = File.join($startdir, "platform/iphone/Framework/Rhodes")
File.open(File.join(framework_dir,"rhodeslibs.txt"),"w") { |f| f.write lib_list }
args = ['clean', 'install', '-scheme', "Framework", '-project', "Rhodes.xcodeproj"]
Dir.chdir framework_dir
ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir})
# copy lib
#framework_lib_path = File.join(framework_dir, "Rhodes-Aggregated/Rhodes.framework/Rhodes")
#target_lib = File.join(lib_temp_dir, "Rhodes.a")
#cp_r framework_lib_path, target_lib
#libs << "Rhodes.a"
#copy final lib to framework
#rm_rf framework_lib_path
#cp_r File.join(lib_temp_dir, "RhodesFrameworkLib.a"), framework_lib_path
# copy result framework to target path
framework_path = File.join(framework_dir, "Rhodes-Aggregated/Rhodes.framework")
framework_target_path = File.join(target_path, "Rhodes.framework")
rm_rf framework_target_path if File.exists? framework_target_path
cp_r framework_path, framework_target_path
Dir.chdir currentdir
print_timestamp('build:iphone:rhodeslib_framework FINISH')
end
# [build:iphone:rhodeslib_prepare_xcodeproject]
#desc "Prepare customers's XCode project for Rhodes Framework - set target path : rake build:iphone:rhodeslib_prepare_xcodeproject['/Users/myuser/my_xcode_project_fullpath']"
task :rhodeslib_prepare_xcodeproject, [:project_path, :target_name] => ["config:set_iphone_platform", "config:common"] do |t, args|
print_timestamp('build:iphone:rhodeslib_prepare_xcodeproject START')
currentdir = Dir.pwd()
# copied from build upgrade bundle
project_path = args[:project_path]
target_name = args[:target_name]
project_dir = File.dirname(project_path)
require 'xcodeproj'
project = Xcodeproj::Project.open(project_path)
Dir.chdir currentdir
print_timestamp('build:iphone:rhodeslib_prepare_xcodeproject FINISH')
end
=begin
#if use_old_scheme
elements = []
binplist = File.join(ENV['HOME'], 'Library', 'Preferences', 'com.apple.iphonesimulator.plist')
xmlplist = '/tmp/iphone.plist'
if File.exists? binplist
`plutil -convert xml1 -o #{xmlplist} #{binplist}`
elements = []
doc = REXML::Document.new(File.new(xmlplist))
nextignore = false
doc.elements.each('plist/dict/*') do |element|
if nextignore
nextignore = false
next
end
if element.name == 'key'
if element.text == 'currentSDKRoot' or element.text == 'SimulateDevice'
nextignore = true
next
end
end
elements << element
end
end
e = REXML::Element.new 'key'
e.text = 'SimulateDevice'
elements << e
e = REXML::Element.new 'string'
e.text = $sdkver == '3.2' ? 'iPad' : 'iPhone'
elements << e
e = REXML::Element.new 'key'
e.text = 'currentSDKRoot'
elements << e
e = REXML::Element.new 'string'
e.text = $sdkroot
elements << e
File.open(xmlplist, 'w') do |f|
f.puts "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
f.puts "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
f.puts "<plist version=\"1.0\">"
f.puts "<dict>"
elements.each do |e|
f.puts "\t#{e.to_s}"
end
f.puts "</dict>"
f.puts "</plist>"
end
`plutil -convert binary1 -o #{binplist} #{xmlplist}`
rhorunner = File.join($app_path, "/project/iphone") + "/build/#{$configuration}-iphonesimulator/rhorunner.app"
puts "rhorunner: #{rhorunner}"
puts "our app name: #{$app_config['name']}"
puts "simdir: #{$simdir}"
Dir.glob(File.join($simdir, $sdkver, "Applications", "*")).each do |simapppath|
need_rm = true if File.directory? simapppath
if File.exists?(File.join(simapppath, 'rhorunner.app', 'name'))
name = File.read(File.join(simapppath, 'rhorunner.app', 'name'))
puts "found app name: #{name}"
guid = File.basename(simapppath)
puts "found guid: #{guid}"
if name == $app_config['name']
$guid = guid
need_rm = false
end
end
rm_rf simapppath if need_rm
rm_rf simapppath + ".sb" if need_rm
end
puts "app guid: #{$guid}"
mkdir_p File.join($simdir, $sdkver)
simapp = File.join($simdir, $sdkver, "Applications")
simlink = File.join($simdir, $sdkver, "Library", "Preferences")
$simrhodes = File.join(simapp, $guid)
chmod 0744, File.join($simrhodes, "rhorunner.app", "rhorunner") unless !File.exists?(File.join($simrhodes, "rhorunner.app", "rhorunner"))
mkdir_p File.join($simrhodes, "Documents")
mkdir_p File.join($simrhodes, "Library", "Preferences")
mkdir_p File.join($simrhodes, "Library", "Caches", "Private Documents")
rm_rf File.join($simrhodes, 'rhorunner.app')
cp_r rhorunner, $simrhodes
['com.apple.PeoplePicker.plist', '.GlobalPreferences.plist'].each do |f|
`ln -f -s "#{simlink}/#{f}" "#{$simrhodes}/Library/Preferences/#{f}"`
end
#>>>>>>>>>>
#`echo "#{$applog}" > "#{$simrhodes}/Documents/rhologpath.txt"`
rholog = simapp + "/" + $guid + "/Library/Caches/Private Documents/rholog.txt"
#simpublic = simapp + "/" + $guid + "/Documents/apps/public"
simpublic = simapp + "/" + $guid + "/Library/Caches/Private Documents/apps/public"
apppublic = $app_path + "/sim-public-#{$sdkver}"
apprholog = $app_path + "/rholog-#{$sdkver}.txt"
apprholog = $app_path + "/" + $app_config["applog"] if $app_config["applog"]
rm_f apprholog
rm_f apppublic
#`ln -f -s "#{simpublic}" "#{apppublic}"`
#`ln -f -s "#{rholog}" "#{apprholog}"`
`echo > "#{rholog}"`
f = File.new("#{simapp}/#{$guid}.sb","w")
f << "(version 1)\n(debug deny)\n(allow default)\n"
f.close
#end
=end
# [build:iphone:rhodeslib_bundle]
desc "Build iphone rhobundle - set target path : rake build:iphone:rhodeslib_bundle['/Users/myuser/mypath']"
task :rhodeslib_bundle, [:target_path] => ["config:set_iphone_platform", "config:common"] do |t, args|
print_timestamp('build:iphone:rhodeslib_bundle START')
# copied from build upgrade bundle
target_path = args[:target_path]
$skip_checking_XCode = true
$skip_build_rhodes_main = true
$skip_build_extensions = true
$skip_build_xmls = true
$use_prebuild_data = true
Rake::Task['config:iphone'].invoke
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
iphone_project = File.join($app_path, "project","iphone","#{appname_fixed}.xcodeproj")
if !File.exist?(iphone_project)
puts '$ make iphone XCode project for application'
Rake::Task['build:iphone:make_xcode_project'].invoke
end
Rake::Task['build:iphone:rhobundle'].invoke
#puts '$$$$$$$$$$$$$$$$$$'
#puts 'targetdir = '+$targetdir.to_s
#puts 'bindir = '+$bindir.to_s
mkdir_p target_path if not File.exists? target_path
# copy RhoBundle folder from $bindir to target_path
source_RhoBundle = File.join($bindir, "RhoBundle")
target_RhoBundle = File.join(target_path, "RhoBundle")
rm_rf target_RhoBundle if File.exists? target_RhoBundle
cp_r source_RhoBundle, target_path
print_timestamp('build:iphone:rhodeslib_bundle FINISH')
end
desc "build upgrade package with full bundle"
task :upgrade_package => ["config:set_iphone_platform", "config:common"] do
$skip_checking_XCode = true
$skip_build_rhodes_main = true
$skip_build_extensions = true
$skip_build_xmls = true
$use_prebuild_data = true
Rake::Task['config:iphone'].invoke
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
iphone_project = File.join($app_path, "project","iphone","#{appname_fixed}.xcodeproj")
if !File.exist?(iphone_project)
puts '$ make iphone XCode project for application'
Rake::Task['build:iphone:make_xcode_project'].invoke
end
Rake::Task['build:iphone:rhobundle'].invoke
#puts '$$$$$$$$$$$$$$$$$$'
#puts 'targetdir = '+$targetdir.to_s
#puts 'bindir = '+$bindir.to_s
mkdir_p $targetdir if not File.exists? $targetdir
zip_file_path = File.join($targetdir, "upgrade_bundle.zip")
Jake.zip_upgrade_bundle( $bindir, zip_file_path)
end
task :check_update => ["config:iphone"] do
mkdir_p File.join($app_path, 'development')
RhoDevelopment.setup(File.join($app_path, 'development'), 'iphone')
is_require_full_update = RhoDevelopment.is_require_full_update
result = RhoDevelopment.check_changes_from_last_build(File.join($app_path, 'upgrade_package_add_files.txt'), File.join($app_path, 'upgrade_package_remove_files.txt'))
puts '$$$ RhoDevelopment.is_require_full_update() = '+is_require_full_update.to_s
puts '$$$ RhoDevelopment.check_changes_from_last_build() = '+result.class.to_s
end
desc "build upgrade package with part of bundle (changes configure by two text files - see documentation)"
task :upgrade_package_partial => ["config:set_iphone_platform", "config:common"] do
print_timestamp('build:iphone:upgrade_package_partial START')
$skip_checking_XCode = true
Rake::Task['config:iphone'].invoke
#puts '$$$$$$$$$$$$$$$$$$'
#puts 'targetdir = '+$targetdir.to_s
#puts 'bindir = '+$bindir.to_s
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
iphone_project = File.join($app_path, "project","iphone","#{appname_fixed}.xcodeproj")
if !File.exist?(iphone_project)
puts '$ make iphone XCode project for application'
Rake::Task['build:iphone:make_xcode_project'].invoke
end
$skip_build_rhodes_main = true
$skip_build_extensions = true
$skip_build_xmls = true
$use_prebuild_data = true
Rake::Task['build:iphone:rhobundle'].invoke
# process partial update
add_list_full_name = File.join($app_path, 'upgrade_package_add_files.txt')
remove_list_full_name = File.join($app_path, 'upgrade_package_remove_files.txt')
src_folder = File.join($bindir, 'RhoBundle')
src_folder = File.join(src_folder, 'apps')
tmp_folder = $bindir + '_tmp_partial'
rm_rf tmp_folder if File.exists? tmp_folder
mkdir_p tmp_folder
dst_tmp_folder = File.join(tmp_folder, 'RhoBundle')
mkdir_p dst_tmp_folder
# copy all
cp_r src_folder, dst_tmp_folder
dst_tmp_folder = File.join(dst_tmp_folder, 'apps')
mkdir_p dst_tmp_folder
add_files = []
if File.exists? add_list_full_name
File.open(add_list_full_name, "r") do |f|
while line = f.gets
fixed_path = line.gsub('.rb', '.iseq').gsub('.erb', '_erb.iseq').chomp
add_files << fixed_path
puts '### ['+fixed_path+']'
end
end
end
remove_files = []
if File.exists? remove_list_full_name
File.open(remove_list_full_name, "r") do |f|
while line = f.gets
fixed_path = line.gsub('.rb', '.iseq').gsub('.erb', '_erb.iseq').chomp
remove_files << fixed_path
#puts '### ['+fixed_path+']'
end
end
end
psize = dst_tmp_folder.size+1
Dir.glob(File.join(dst_tmp_folder, '**','*')).sort.each do |f|
relpath = f[psize..-1]
if File.file?(f)
#puts '$$$ ['+relpath+']'
if (not add_files.include?(relpath)) && (relpath != 'rhofilelist.txt')
rm_rf f
end
end
end
Jake.build_file_map( dst_tmp_folder, "upgrade_package_add_files.txt" )
#if File.exists? add_list_full_name
# File.open(File.join(dst_tmp_folder, 'upgrade_package_add_files.txt'), "w") do |f|
# add_files.each do |j|
# f.puts "#{j}\tfile\t0\t0"
# end
# end
#end
if File.exists? remove_list_full_name
File.open(File.join(dst_tmp_folder, 'upgrade_package_remove_files.txt'), "w") do |f|
remove_files.each do |j|
f.puts "#{j}"
#f.puts "#{j}\tfile\t0\t0"
end
end
end
mkdir_p $targetdir if not File.exists? $targetdir
zip_file_path = File.join($targetdir, "upgrade_bundle_partial.zip")
Jake.zip_upgrade_bundle( tmp_folder, zip_file_path)
rm_rf tmp_folder
print_timestamp('build:iphone:upgrade_package_partial FINISH')
end
def check_for_rebuild( result_lib_file, patternlist_file )
if patternlist_file == nil
return true
end
if !File.exist?(result_lib_file) || !File.exist?(patternlist_file)
return true
end
patterns = []
File.new(patternlist_file,"r").read.each_line do |line|
if line.size > 0
patterns << line.tr("\n","")
end
end
#patterns << '../../../../../../platform/shared/common/app_build_capabilities.h'
list_of_files = []
fillist = FileList.new
patterns.each do |p|
fillist.include(p)
end
fillist.each do |fil|
list_of_files << fil
end
list_of_files << File.join( $startdir ,'platform','shared','common','app_build_capabilities.h')
if !FileUtils.uptodate?(result_lib_file, list_of_files)
return true
end
return false
end
def is_options_was_changed(options_hash, options_file)
puts " is_options_was_changed( "+options_hash.to_s+", "+options_file.to_s+")"
if !File.exist?(options_file)
File.open(options_file,"w") {|f| f.write(YAML::dump(options_hash)) }
return true
else
saved_options = YAML.load_file(options_file)
if saved_options.to_a != options_hash.to_a
File.open(options_file,"w") {|f| f.write(YAML::dump(options_hash)) }
return true
end
end
return false
end
def run_build_for_extension(extpath, xcodeproject, xcodetarget, depfile)
# only depfile is optional parameter !
currentdir = Dir.pwd()
Dir.chdir File.join(extpath, "platform","iphone")
xcodeproject = File.basename(xcodeproject)
if depfile != nil
depfile = File.basename(depfile)
end
targetdir = ENV['TARGET_TEMP_DIR']
tempdir = ENV['TEMP_FILES_DIR']
rootdir = ENV['RHO_ROOT']
xcodebuild = ENV['XCODEBUILD']
configuration = ENV['CONFIGURATION']
sdk = ENV['SDK_NAME']
bindir = ENV['PLATFORM_DEVELOPER_BIN_DIR']
sdkroot = ENV['SDKROOT']
arch = ENV['ARCHS']
gccbin = bindir + '/gcc-4.2'
arbin = bindir + '/ar'
#xcode_version = ENV['XCODE_VERSION_ACTUAL']
xcode_version = get_xcode_version
iphone_path = '.'
simulator = sdk =~ /iphonesimulator/
if configuration == 'Distribution'
configuration = 'Release'
end
build_config_folder = configuration + '-' + ( simulator ? "iphonesimulator" : "iphoneos")
result_lib_folder = File.join(iphone_path, 'build', build_config_folder)
FileUtils.mkdir(File.join(iphone_path, "build") ) unless File.exist? File.join(iphone_path, "build")
FileUtils.mkdir(File.join(iphone_path, "build", build_config_folder) ) unless File.exist? File.join(iphone_path, "build", build_config_folder)
result_lib = result_lib_folder + '/lib'+xcodetarget+'.a'
target_lib = targetdir + '/lib'+xcodetarget+'.a'
puts "BEGIN build xcode extension : ["+extpath+"]"
puts " result_lib : ["+result_lib+"]"
puts " target_lib : ["+target_lib+"]"
puts " depfile : ["+depfile.to_s+"]"
puts " configuration : ["+configuration+"]"
puts " sdk : ["+sdk+"]"
rm_rf target_lib
check_f_r = check_for_rebuild(result_lib, depfile)
puts " check_for_rebuild = "+check_f_r.to_s
check_configuration = {
"configuration" => configuration,
"sdk" => sdk,
"xcode_version" => xcode_version,
"is_jsapp" => $js_application.to_s,
"is_nodejsapp" => $nodejs_application.to_s,
"is_rubynodejsapp" => $rubynodejs_application.to_s
}
is_opt_c = is_options_was_changed( check_configuration, File.join(result_lib_folder, "lastbuildoptions.yml"))
puts " is_options_was_changed = "+is_opt_c.to_s
result_lib_exist = File.exist?(result_lib)
puts " result_lib_exist('"+result_lib+"') = "+result_lib_exist.to_s
if check_f_r || is_opt_c || (!result_lib_exist)
rm_rf result_lib
puts " we should rebuild because previous builded library is not actual or not exist !"
# library bot found ! We should build it !
puts " build xcode extension !"
#rm_rf 'build'
rm_rf result_lib_folder
args = ['build', '-scheme', xcodetarget, '-configuration', configuration, '-sdk', sdk, '-project', xcodeproject]
additional_string = ''
if simulator
#args << '-arch'
#args << 'i386'
additional_string = ' CONFIGURATION_BUILD_DIR='+result_lib_folder+' ARCHS="i386 x86_64"'
else
additional_string = ' CONFIGURATION_BUILD_DIR='+result_lib_folder+' ARCHS="arm64 arm64e armv7 armv7s"'
end
require rootdir + '/lib/build/jake.rb'
ret = IPhoneBuild.run_and_trace(xcodebuild,args,{:rootdir => rootdir, :string_for_add_to_command_line => additional_string})
# save configuration
is_options_was_changed( check_configuration, File.join(result_lib_folder, "lastbuildoptions.yml"))
else
puts " ssskip rebuild because previous builded library is still actual !"
end
cp result_lib,target_lib
Dir.chdir currentdir
puts "END build xcode extension : ["+extpath+"]"
end
def build_extension_lib(extpath, sdk, target_dir, xcodeproject, xcodetarget, depfile)
puts "build extension START :" + extpath
ENV["SDK_NAME"] ||= sdk
sdk = ENV["SDK_NAME"]
#puts "xcodeproject = "+xcodeproject.to_s
#puts "xcodetarget = "+xcodetarget.to_s
if sdk =~ /iphonesimulator/
$sdkver = sdk.gsub(/iphonesimulator/,"")
$sdkroot = $devroot + "/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" + $sdkver + ".sdk"
else
$sdkver = sdk.gsub(/iphoneos/,"")
$sdkroot = $devroot + "/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS" + $sdkver + ".sdk"
end
ENV['RHO_PLATFORM'] = 'iphone'
simulator = sdk =~ /iphonesimulator/
ENV["PLATFORM_DEVELOPER_BIN_DIR"] ||= $devroot + "/Platforms/" + ( simulator ? "iPhoneSimulator" : "iPhoneOS" ) +
".platform/Developer/usr/bin"
ENV["SDKROOT"] = $sdkroot
#ENV["SDKROOT"] = $xcode_sdk_dir if not $xcode_sdk_dir.nil?
ENV["BUILD_DIR"] ||= $startdir + "/platform/iphone/build"
ENV["TARGET_TEMP_DIR"] ||= target_dir
ENV["TEMP_FILES_DIR"] ||= ENV["TARGET_TEMP_DIR"]
ENV["ARCHS"] ||= simulator ? "i386 x86_64" : "arm64 arm64e armv7 armv7s"
ENV["RHO_ROOT"] = $startdir
# added by dmitrys
ENV["XCODEBUILD"] = $xcodebuild
ENV["CONFIGURATION"] ||= $configuration
ENV["RHO_APP_DIR"] = $app_path
build_script = File.join(extpath, 'build')
if (xcodeproject != nil) and (xcodetarget != nil)
run_build_for_extension(extpath, xcodeproject, xcodetarget, depfile)
else
# modify executable attribute
if File.exists? build_script
if !File.executable? build_script
#puts 'change executable attribute for build script in extension : '+build_script
begin
#File.chmod 0700, build_script
#puts 'executable attribute was writed for : '+build_script
rescue Exception => e
puts 'ERROR: can not change attribute for build script in extension ! Try to run build command with sudo: prefix.'
end
else
puts 'build script in extension already executable : '+build_script
end
if simulator
ENV["XCODE_BUILD_ADDITIONAL_STRING_TO_COMMAND_LINE"] = ' ARCHS="i386 x86_64"'
else
ENV["XCODE_BUILD_ADDITIONAL_STRING_TO_COMMAND_LINE"] = ' ARCHS="arm64 arm64e armv7 armv7s"'
end
#puts '$$$$$$$$$$$$$$$$$$ START'
currentdir = Dir.pwd()
Dir.chdir extpath
sh %{$SHELL ./build}
#Jake.run32("$SHELL "+build_script)
ENV["XCODE_BUILD_ADDITIONAL_STRING_TO_COMMAND_LINE"] = ''
Dir.chdir currentdir
#puts '$$$$$$$$$$$$$$$$$$ FINISH'
#if File.executable? build_script
#puts Jake.run('./build', [], extpath)
#exit 1 unless $? == 0
#else
# puts 'ERROR: build script in extension is not executable !'
#end
else
puts 'build script in extension not found => pure ruby extension'
end
end
puts "build extension FINISH :" + extpath
end
def build_extension_libs(sdk, target_dir)
puts "extpaths: #{$app_config["extpaths"].inspect.to_s}"
$stdout.flush
$app_extensions_list.each do |ext, commin_ext_path |
if commin_ext_path != nil
print_timestamp('process extension "'+ext+'" START')
#puts '######################## ext='+ext.to_s+' path='+commin_ext_path.to_s
extpath = File.join( commin_ext_path, 'ext')
prebuilt_copy = false
xcodeproject = nil #xcodeproject
xcodetarget = nil #xcodetarget
depfile = nil #rebuild_deplist
extyml = File.join(commin_ext_path,"ext.yml")
if File.file? extyml
extconf = Jake.config(File.open(extyml))
extconf_iphone = extconf['iphone']
exttype = 'build'
exttype = extconf_iphone['exttype'] if extconf_iphone and extconf_iphone['exttype']
xcodeproject = extconf_iphone['xcodeproject'] if extconf_iphone and extconf_iphone['xcodeproject']
xcodetarget = extconf_iphone['xcodetarget'] if extconf_iphone and extconf_iphone['xcodetarget']
depfile = extconf_iphone['rebuild_deplist'] if extconf_iphone and extconf_iphone['rebuild_deplist']
if exttype == 'prebuilt'
prebuiltpath = Dir.glob(File.join(extpath, '**', 'iphone'))
if prebuiltpath.count > 0
prebuiltpath = prebuiltpath.first
else
raise "iphone:exttype is 'prebuilt' but prebuilt path is not found #{prebuiltpath.inspect}"
end
libes = extconf["libraries"]
if libes != nil
libname = libes.first
libpath = File.join(prebuiltpath, "lib"+libname+".a")
if File.file? libpath
targetlibpath = File.join(target_dir, "lib"+libname+".a")
cp libpath, targetlibpath
prebuilt_copy = true
else
raise "iphone:exttype is 'prebuilt' but lib path is not found #{libpath.inspect}"
end
end
end
end
if ! prebuilt_copy
if $use_prebuild_data && (ext == 'coreapi')
prebuild_root = File.join($startdir, "platform/iphone/prebuild")
prebuild_ruby = File.join(prebuild_root, "ruby")
prebuild_noruby = File.join(prebuild_root, "noruby")
coreapi_ruby = File.join(prebuild_ruby, "libCoreAPI.a")
coreapi_noruby = File.join(prebuild_noruby, "libCoreAPI.a")
coreapi_lib = coreapi_ruby
if $js_application
coreapi_lib = coreapi_noruby
end
if File.exist?(coreapi_lib)
coreapi_lib_dst = File.join(target_dir, 'libCoreAPI.a')
cp coreapi_lib, coreapi_lib_dst
else
build_extension_lib(extpath, sdk, target_dir, xcodeproject, xcodetarget, depfile)
end
else
build_extension_lib(extpath, sdk, target_dir, xcodeproject, xcodetarget, depfile)
end
end
print_timestamp('process extension "'+ext+'" FINISH')
end
end
end
#[build:iphone:extension_libs]
task :extension_libs => ["config:iphone", "build:bundle:noxruby"] do
#chdir 'platform/iphone'
chdir File.join($app_path, 'project/iphone')
rm_rf 'bin'
rm_rf 'build/Debug-*'
rm_rf 'build/Release-*'
chdir $startdir
if $sdk =~ /iphonesimulator/
$sdkver = $sdk.gsub(/iphonesimulator/,"")
else
$sdkver = $sdk.gsub(/iphoneos/,"")
end
if $configuration.to_s.downcase == "release"
$confdir = "release"
else
$confdir = "debug"
end
$app_builddir = File.join($targetdir, $confdir)
simsdk = "iphonesimulator"+$sdkver
devsdk = "iphoneos"+$sdkver
sim_target_dir = $startdir + "/platform/iphone/build/rhorunner.build/#{$configuration}-" +
"iphonesimulator" + "/rhorunner.build"
dev_target_dir = $startdir + "/platform/iphone/build/rhorunner.build/#{$configuration}-" +
"iphoneos" + "/rhorunner.build"
puts "extpaths: #{$app_config["extpaths"].inspect.to_s}"
$stdout.flush
print_timestamp('build extension libs START')
$app_extensions_list.each do |ext, commin_ext_path |
puts " ±±± extension ["+ext.to_s+"],["+commin_ext_path.to_s+"]"
if commin_ext_path != nil
extpath = File.join( commin_ext_path, 'ext')
extyml = File.join( commin_ext_path, "ext.yml")
xcodeproject = nil #xcodeproject
xcodetarget = nil #xcodetarget
depfile = nil #rebuild_deplist
puts " ±±± extension ext.yml ["+extyml.to_s+"]"
if File.file? extyml
extconf = Jake.config(File.open(extyml))
#extconf_iphone = extconf['iphone']
exttype = 'build'
extconf_iphone = extconf['iphone']
exttype = extconf_iphone['exttype'] if extconf_iphone and extconf_iphone['exttype']
xcodeproject = extconf_iphone['xcodeproject'] if extconf_iphone and extconf_iphone['xcodeproject']
xcodetarget = extconf_iphone['xcodetarget'] if extconf_iphone and extconf_iphone['xcodetarget']
depfile = extconf_iphone['rebuild_deplist'] if extconf_iphone and extconf_iphone['rebuild_deplist']
libes = extconf["libraries"]
if extconf_iphone
if extconf_iphone["libraries"] != nil
libes = extconf_iphone["libraries"]
end
end
puts " ±±± extension libes ["+libes.to_s+"] exttype ["+exttype.to_s+"]"
if (libes != nil) && (exttype != 'prebuilt')
libname = libes.first
prebuiltpath = Dir.glob(File.join(extpath, '**', 'iphone'))
puts " ±±± extension prebuiltpath ["+prebuiltpath.to_s+"]"
if prebuiltpath != nil && prebuiltpath.count > 0
print_timestamp('build extension "'+ext+'" START')
prebuiltpath = prebuiltpath.first
libpath = File.join(prebuiltpath, "lib"+libname+".a")
libsimpath = File.join(prebuiltpath, "lib"+libname+"386.a")
libdevpath = File.join(prebuiltpath, "lib"+libname+"ARM.a")
libbinpath = File.join($app_builddir, "extensions", ext, "lib", "lib"+libname+".a")
ENV["TARGET_TEMP_DIR"] = prebuiltpath
ENV["ARCHS"] = "i386 x86_64"
ENV["SDK_NAME"] = simsdk
build_extension_lib(extpath, simsdk, prebuiltpath, xcodeproject, xcodetarget, depfile)
cp libpath, libsimpath
rm_f libpath
ENV["ARCHS"] = "arm64 arm64e armv7 armv7s"
ENV["SDK_NAME"] = devsdk
build_extension_lib(extpath, devsdk, prebuiltpath, xcodeproject, xcodetarget, depfile)
cp libpath, libdevpath
rm_f libpath
args = []
args << "-create"
args << "-output"
args << libpath
args << libsimpath
args << libdevpath
IPhoneBuild.run_and_trace("lipo",args,{:rootdir => $startdir})
mkdir_p File.join($app_builddir, "extensions", ext, "lib")
cp libpath, libbinpath
rm_f libsimpath
rm_f libdevpath
# copy all files from extension folder to extension binary folder
Dir.glob(File.join(commin_ext_path,'*')).each do |artefact|
if (artefact != extpath) && (artefact != extyml) && ((File.file? artefact) || (File.directory? artefact))
cp_r artefact, File.join($app_builddir, "extensions", ext)
end
end
print_timestamp('build extension "'+ext+'" FINISH')
end
end
end
end
end
print_timestamp('build extension libs FINISH')
end
#[build:iphone:extensions]
task :extensions => "config:iphone" do
print_timestamp('build:iphone:extensions START')
simulator = $sdk =~ /iphonesimulator/
target_dir = ''
if ENV["TARGET_TEMP_DIR"] and ENV["TARGET_TEMP_DIR"] != ""
target_dir = ENV["TARGET_TEMP_DIR"]
else
target_dir = File.join($app_path, "/project/iphone") + "/build/rhorunner.build/#{$configuration}-" +
( simulator ? "iphonesimulator" : "iphoneos") + "/rhorunner.build"
end
build_extension_libs($sdk, target_dir)
print_timestamp('build:iphone:extensions FINISH')
end
def build_rhodes_lib(targetdir)
# only depfile is optional parameter !
rhodes_xcode_project_folder = File.join($startdir, '/platform/iphone/')
currentdir = Dir.pwd()
Dir.chdir File.join(rhodes_xcode_project_folder)
xcodeproject = 'Rhodes.xcodeproj'
xcodetarget = 'Rhodes'
#tempdir = ENV['TEMP_FILES_DIR']
#rootdir = ENV['RHO_ROOT']
configuration = 'Release'
sdk = $sdk
#bindir = ENV['PLATFORM_DEVELOPER_BIN_DIR']
#sdkroot = ENV['SDKROOT']
#arch = ENV['ARCHS']
#gccbin = bindir + '/gcc-4.2'
#arbin = bindir + '/ar'
iphone_path = '.'
simulator = sdk =~ /iphonesimulator/
if configuration == 'Distribution'
configuration = 'Release'
end
result_lib = iphone_path + '/build/' + configuration + '-' + ( simulator ? "iphonesimulator" : "iphoneos") + '/lib'+xcodetarget+'.a'
target_lib = targetdir + '/lib'+xcodetarget+'.a'
#if check_for_rebuild(result_lib, depfile) || is_options_was_changed({"configuration" => configuration,"sdk" => sdk}, "lastbuildoptions.yml")
rm_rf 'build'
rm_rf target_lib
args = ['build', '-scheme', xcodetarget, '-configuration', configuration, '-sdk', sdk, '-project', xcodeproject, '-quiet']
additional_string = ''
if simulator
# args << '-arch'
# args << 'i386 x86_64'
additional_string = ' ARCHS="i386 x86_64"'
end
require $startdir + '/lib/build/jake.rb'
ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir, :string_for_add_to_command_line => additional_string})
#else
#
# puts "ssskip rebuild because previous builded library is still actual !"
# rm_rf target_lib
#
#end
cp result_lib,target_lib
Dir.chdir currentdir
end
#[build:iphone:make_prebuild_core]
task :make_prebuild_core do
currentdir = Dir.pwd()
# remove prebuild folder
prebuild_root = File.join($startdir, "platform/iphone/prebuild")
rm_rf prebuild_root
prebuild_ruby = File.join(prebuild_root, "ruby")
prebuild_noruby = File.join(prebuild_root, "noruby")
mkdir_p prebuild_ruby
mkdir_p prebuild_noruby
coreapi_ruby = File.join(prebuild_ruby, "libCoreAPI.a")
coreapi_noruby = File.join(prebuild_noruby, "libCoreAPI.a")
prebuild_base_app_folder = File.join($startdir, "res/prebuild_base_app");
prebuild_base_app_build_yml = File.join(prebuild_base_app_folder, "build.yml")
coreapi_root = File.join($startdir, "lib/commonAPI/coreapi")
#$app_config = YAML::load_file(prebuild_base_app_build_yml)
$app_config = Jake.config(File.open(prebuild_base_app_build_yml))
$app_config_disable_reread = true
puts "%%% $app_config[javascript_application] = "+$app_config["javascript_application"].to_s
$app_path = File.expand_path(prebuild_base_app_folder)
chdir File.join($startdir)
$app_extensions_list = {}
$app_extensions_list['coreapi'] = coreapi_root
#ruby
rm_rf File.join(prebuild_base_app_folder, 'project')
Rake::Task['clean:iphone'].invoke
#$app_config["javascript_application"] = "false"
Rake::Task['config:common'].invoke
Rake::Task['config:iphone'].invoke
$js_application = false
Rake::Task['build:bundle:prepare_native_generated_files'].invoke
#coreAPI
Rake::Task['build:iphone:extension_libs'].invoke
#Rhodes
build_rhodes_lib(prebuild_ruby)
#copy
cp File.join(prebuild_base_app_folder, "bin/target/iOS/release/extensions/coreapi/lib/libCoreAPI.a"), coreapi_ruby
#Rhodes
#noruby
rm_rf File.join(prebuild_base_app_folder, 'project')
$app_config['javascript_application'] = 'true'
puts "%%% $app_config[javascript_application] = "+$app_config["javascript_application"].to_s
Rake::Task['clean:iphone'].reenable
Rake::Task['config:common'].reenable
Rake::Task['config:iphone'].reenable
Rake::Task['build:bundle:prepare_native_generated_files'].reenable
Rake::Task['build:iphone:extension_libs'].reenable
#Rake::Task['clean:iphone'].invoke
#Rake::Task['config:common'].invoke
#Rake::Task['config:iphone'].invoke
$js_application = true
Rake::Task['build:bundle:prepare_native_generated_files'].invoke
#coreAPI
Rake::Task['build:iphone:extension_libs'].invoke
#Rhodes
build_rhodes_lib(prebuild_noruby)
#copy
#copy
cp File.join(prebuild_base_app_folder, "bin/target/iOS/release/extensions/coreapi/lib/libCoreAPI.a"), coreapi_noruby
Dir.chdir currentdir
end
def copy_generated_sources_and_binaries
#copy sources
extensions_src = File.join($startdir, 'platform','shared','ruby','ext','rho','extensions.c')
extensions_dst = File.join($app_path, 'project','iphone','Rhodes','extensions.c')
#rm_rf extensions_dst
#cp extensions_src, extensions_dst
Jake.copyIfNeeded extensions_src, extensions_dst
properties_src = File.join($startdir, 'platform','shared','common','app_build_configs.c')
properties_dst = File.join($app_path, 'project','iphone','Rhodes','app_build_configs.c')
#rm_rf properties_dst
#cp properties_src, properties_dst
Jake.copyIfNeeded properties_src, properties_dst
# old code for use prebuild libraries:
#copy libCoreAPI.a and Rhodes.a
#prebuild_root = File.join($startdir, "platform","iphone","prebuild")
#prebuild_ruby = File.join(prebuild_root, "ruby")
#prebuild_noruby = File.join(prebuild_root, "noruby")
#coreapi_ruby = File.join(prebuild_ruby, "libCoreAPI.a")
#coreapi_noruby = File.join(prebuild_noruby, "libCoreAPI.a")
#rhodes_ruby = File.join(prebuild_ruby, "libRhodes.a")
#rhodes_noruby = File.join(prebuild_noruby, "libRhodes.a")
#coreapi_lib = coreapi_ruby
#rhodes_lib = rhodes_ruby
#if $js_application
# coreapi_lib = coreapi_noruby
# rhodes_lib = rhodes_noruby
# end
#if File.exist?(coreapi_lib)
# coreapi_lib_dst = File.join($app_path, 'project/iphone/Rhodes/libCoreAPI.a')
# rm_rf coreapi_lib_dst
# cp coreapi_lib, coreapi_lib_dst
#end
#if File.exist?(rhodes_lib)
# rhodes_lib_dst = File.join($app_path, 'project/iphone/Rhodes/libRhodes.a')
# rm_rf rhodes_lib_dst
# cp rhodes_lib, rhodes_lib_dst
# end
end
#[build:iphone:setup_xcode_project]
desc "make/change generated XCode project for build application"
task :setup_xcode_project, [:use_temp_keychain] do |t, args|
print_timestamp('build:iphone:setup_xcode_project START')
args.with_defaults(:use_temp_keychain => "do_not_use_temp_keychain")
$use_temp_keychain = args[:use_temp_keychain] == "use_temp_keychain"
Rake::Task['config:iphone'].invoke
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
iphone_project = File.join($app_path, "project","iphone","#{appname_fixed}.xcodeproj")
xcode_project_checker = GeneralTimeChecker.new
xcode_project_checker.init($startdir, $app_path, "xcode_project")
if !File.exist?(iphone_project)
puts '$ make iphone XCode project for application'
Rake::Task['build:iphone:make_xcode_project'].invoke
else
chdir $app_path
build_yml_filepath = File.join($app_path, "build.yml")
build_yml_updated = xcode_project_checker.check(build_yml_filepath)
if build_yml_updated
puts '$ prepare iphone XCode project for application'
rhogenpath = File.join($startdir, 'bin', 'rhogen')
Jake.run32("\"#{rhogenpath}\" iphone_project #{appname_fixed} \"#{$startdir}\"")
Rake::Task['build:iphone:update_plist'].invoke
if !$skip_build_xmls
Rake::Task['build:bundle:prepare_native_generated_files'].invoke
rm_rf File.join('project','iphone','toremoved')
rm_rf File.join('project','iphone','toremovef')
end
update_xcode_project_files_by_capabilities
else
puts "$ build.yml not changed after last XCode project generation !"
end
end
copy_generated_sources_and_binaries
xcode_project_checker.update
print_timestamp('build:iphone:setup_xcode_project FINISH')
end
#[build:iphone:update_plist]
task :update_plist => ["config:iphone"] do
chdir $app_path
puts 'update info.plist'
update_plist_procedure
set_signing_identity($signidentity,$provisionprofile,$entitlements,$provisioning_style,$development_team) #if $signidentity.to_s != ""
end
#[build:iphone:make_xcode_project]
task :make_xcode_project => ["config:iphone"] do
print_timestamp('build:iphone:make_xcode_project START')
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
chdir $app_path
rm_rf File.join('project','iphone')
puts 'prepare iphone XCode project for application'
rhogenpath = File.join($startdir, 'bin', 'rhogen')
if $use_prebuild_data
Jake.run32("\"#{rhogenpath}\" iphone_project_prebuild #{appname_fixed} \"#{$startdir}\"")
else
Jake.run32("\"#{rhogenpath}\" iphone_project #{appname_fixed} \"#{$startdir}\"")
end
#make_project_bakup
#restore_project_from_bak
#fix issue with Application Base generated file - hardcoded !!!
#xml_path = File.join($startdir, "/lib/commonAPI/coreapi/ext/Application.xml")
#Jake.run3("\"#{$startdir}/bin/rhogen\" api \"#{xml_path}\"")
update_plist_procedure
if $entitlements == ""
if $configuration == "Distribution"
$entitlements = "Entitlements.plist"
end
end
set_signing_identity($signidentity,$provisionprofile,$entitlements,$provisioning_style,$development_team) #if $signidentity.to_s != ""
copy_entitlements_file_from_app
Rake::Task['build:bundle:prepare_native_generated_files'].invoke
rm_rf File.join('project','iphone','toremoved')
rm_rf File.join('project','iphone','toremovef')
update_xcode_project_files_by_capabilities
copy_generated_sources_and_binaries
print_timestamp('build:iphone:make_xcode_project FINISH')
end
#[build:iphone:rhodes]
task :rhodes => "config:iphone" do
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
Rake::Task['build:iphone:setup_xcode_project'].invoke
Rake::Task['build:iphone:rhodes_old'].invoke
end
#[build:iphone:rhodes_old]
# desc "Build rhodes"
task :rhodes_old => ["config:iphone", "build:iphone:rhobundle"] do
print_timestamp('build:iphone:rhodes START')
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
appname_project = appname_fixed.slice(0, 1).capitalize + appname_fixed.slice(1..-1) + ".xcodeproj"
#saved_name = ''
#saved_version = ''
#saved_identifier = ''
#saved_url_scheme = ''
#saved_url_name = ''
#saved_name = set_app_name($app_config["name"]) unless $app_config["name"].nil?
#saved_version = set_app_version($app_config["version"]) unless $app_config["version"].nil?
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
#vendor = $app_config['vendor'] ? $app_config['vendor'] : "rhomobile"
#bundle_identifier = "com.#{vendor}.#{appname}"
#bundle_identifier = $app_config["iphone"]["BundleIdentifier"] unless $app_config["iphone"]["BundleIdentifier"].nil?
#saved_identifier = set_app_bundle_identifier(bundle_identifier)
# Set UIApplicationExitsOnSuspend.
on_suspend = $app_config["iphone"]["UIApplicationExitsOnSuspend"]
on_suspend_value = false
if on_suspend.nil?
puts "UIApplicationExitsOnSuspend not configured, using default of false"
elsif on_suspend.to_s.downcase == "true" || on_suspend.to_s == "1"
on_suspend_value = true
elsif on_suspend.to_s.downcase == "false" || on_suspend.to_s == "0"
on_suspend_value = false
else
raise "UIApplicationExitsOnSuspend is not set to a valid value. Current value: '#{$app_config["iphone"]["UIApplicationExitsOnSuspend"]}'"
end
update_plist_block($app_path + "/project/iphone/Info.plist") do |hash|
if !(on_suspend.nil?)
hash['UIApplicationExitsOnSuspend'] = on_suspend_value
end
end
#icon_has_gloss_effect = $app_config["iphone"]["IconHasGlossEffect"] unless $app_config["iphone"]["IconHasGlossEffect"].nil?
#icon_has_gloss_effect = set_ui_prerendered_icon(icon_has_gloss_effect)
#saved_url_scheme = set_app_url_scheme($app_config["iphone"]["BundleURLScheme"]) unless $app_config["iphone"]["BundleURLScheme"].nil?
#saved_url_name = set_app_url_name(bundle_identifier)
#set_app_icon(true)
#set_default_images(true)
if $entitlements == ""
if $configuration == "Distribution"
$entitlements = "Entitlements.plist"
end
end
#set_signing_identity($signidentity,$provisionprofile,$entitlements.to_s) if $signidentity.to_s != ""
#copy_entitlements_file_from_app
#chdir $config["build"]["iphonepath"]
chdir File.join($app_path, "project","iphone")
args = ['build', '-scheme', 'rhorunner', '-configuration', $configuration, '-sdk', $sdk, '-project', appname_project, '-quiet']
additional_string = ''
if $sdk =~ /iphonesimulator/
# args << '-arch'
# args << 'i386'
additional_string = ' ARCHS="i386 x86_64"'
end
ret = 0
if !$skip_build_rhodes_main
ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir, :string_for_add_to_command_line => additional_string})
end
ENV["RHO_BUNDLE_ALREADY_BUILDED"] = "NO"
chdir $startdir
#set_app_name(saved_name) unless $app_config["name"].nil?
#set_app_version(saved_version) unless $app_config["version"].nil?
#set_app_bundle_identifier(saved_identifier) unless $app_config["iphone"]["BundleIdentifier"].nil?
#set_app_url_scheme(saved_url_scheme) unless $app_config["iphone"]["BundleURLScheme"].nil?
#set_app_url_name(saved_url_name) unless $app_config["iphone"]["BundleIdentifier"].nil?
#set_ui_prerendered_icon(icon_has_gloss_effect)
# Set UIApplicationExitsOnSuspend.
#if $app_config["iphone"]["UIApplicationExitsOnSuspend"].nil?
# puts "UIApplicationExitsOnSuspend not configured, using default of false"
# set_app_exit_on_suspend(false)
#elsif $app_config["iphone"]["UIApplicationExitsOnSuspend"].to_s.downcase == "true" || $app_config["iphone"]["UIApplicationExitsOnSuspend"].to_s == "1"
# set_app_exit_on_suspend(true)
#elsif $app_config["iphone"]["UIApplicationExitsOnSuspend"].to_s.downcase == "false" || $app_config["iphone"]["UIApplicationExitsOnSuspend"].to_s == "0"
# set_app_exit_on_suspend(false)
#else
# raise "UIApplicationExitsOnSuspend is not set to a valid value. Current value: '#{$app_config["iphone"]["UIApplicationExitsOnSuspend"]}'"
#end
#restore_entitlements_file
#restore_default_images
#restore_app_icon
unless ret == 0
puts '************************************'
puts "ERROR during building by XCode !"
puts 'XCode return next error code = '+ret.to_s
exit 1
end
print_timestamp('build:iphone:rhodes FINISH')
end
end
end
namespace "run" do
namespace "iphone" do
task :build => 'run:buildsim'
task :debug => :run
#[run:iphone]
task :run => 'config:iphone' do
print_timestamp('run:iphone:run START')
mkdir_p $tmpdir
log_name = File.join($app_path, 'rholog.txt')
File.delete(log_name) if File.exist?(log_name)
rhorunner = File.join(File.join($app_path, "/project/iphone"),"build/#{$configuration}-iphonesimulator/rhorunner.app")
commandis = $iphonesim + ' launch "' + rhorunner + '" ' + $sdkver.gsub(/([0-9]\.[0-9]).*/,'\1') + ' ' + $emulatortarget + ' "' +log_name+'"'
kill_iphone_simulator
$ios_run_completed = false
#thr = Thread.new do
#end
#Thread.new {
thr = Thread.new do
puts 'start thread with execution of application'
#if ($emulatortarget != 'iphone') && ($emulatortarget != 'ipad')
# puts 'use old execution way - just open iPhone Simulator'
# system("open \"#{$sim}/iPhone Simulator.app\"")
# $ios_run_completed = true
# sleep(1000)
#else
puts 'use iphonesim tool - open iPhone Simulator and execute our application, also support device family (iphone/ipad)'
puts 'Execute command: '+commandis
system(commandis)
$ios_run_completed = true
sleep(1000)
#end
#}
end
print_timestamp('application was launched in simulator')
#if ($emulatortarget != 'iphone') && ($emulatortarget != 'ipad')
# thr.join
#else
puts 'start waiting for run application in Simulator'
while (!File.exist?(log_name)) && (!$ios_run_completed)
puts ' ... still waiting'
sleep(1)
end
puts 'stop waiting - application started'
#sleep(1000)
thr.kill
#thr.join
puts 'application is started in Simulator'
exit
#end
print_timestamp('run:iphone FINISH')
puts "end build iphone app"
exit
end
#[run:iphone:spec]
task :spec => ["clean:iphone"] do
#task :spec do
is_timeout = false
is_correct_stop = false
Jake.decorate_spec do
Rake::Task['run:buildsim'].invoke
# Run local http server
$iphonespec = true
#httpserver = false
#httpserver = true if File.exist? "#{$app_path}/app/spec/library/net/http/http/fixtures/http_server.rb"
#if httpserver
# require "#{$app_path}/app/spec/library/net/http/http/fixtures/http_server"
# NetHTTPSpecs.start_server
#end
$dont_exit_on_failure = false
Jake.before_run_spec
kill_iphone_simulator
mkdir_p $tmpdir
#log_name = File.join($tmpdir, 'logout')
log_name = File.join($app_path, 'rholog.txt')
File.delete(log_name) if File.exist?(log_name)
$iphone_end_spec = false
Thread.new {
# run spec
rhorunner = File.join(File.join($app_path, "project","iphone"),"build","#{$configuration}-iphonesimulator","rhorunner.app")
#iphonesim = File.join($startdir, 'res/build-tools/iphonesim/build/Release/iphonesim')
commandis = $iphonesim + ' launch "' + rhorunner + '" ' + $sdkver.gsub(/([0-9]\.[0-9]).*/,'\1') + ' ' + $emulatortarget + ' "' +log_name+'"'
puts 'use iphonesim tool - open iPhone Simulator and execute our application, also support device family (iphone/ipad) '
puts 'execute command : ' + commandis
system(commandis)
#$iphone_end_spec = true
}
start = Time.now
puts "Waiting for iphone app log ..."
while (!File.exist?(log_name)) && (!$iphone_end_spec)
sleep(1)
end
timeout_in_seconds = 30*60
log_lines = []
last_spec_line = ""
last_spec_iseq_line = ""
start_logging = Time.now
puts "Start reading log ..."
File.open(log_name, 'r:UTF-8') do |io|
while !$iphone_end_spec do
io.each do |line|
line = line.force_encoding('ASCII-8BIT')
$logger.debug line
log_lines << line
if line.class.method_defined? "valid_encoding?"
$iphone_end_spec = !Jake.process_spec_output(line) if line.valid_encoding?
else
$iphone_end_spec = !Jake.process_spec_output(line)
end
# FIXME: Workaround to avoid endless loop in the case of System.exit
# seg. fault: (SEGV received in SEGV handler)
# Looking at log end marker from mspec runner
is_mspec_stop = line =~ /MSpec runner stopped/
is_terminated = line =~ /\| \*\*\*Terminated\s+(.*)/
is_correct_stop = true if is_mspec_stop || is_terminated
$iphone_end_spec = true if is_mspec_stop
last_spec_line = line if line =~ /_spec/
last_spec_iseq_line = line if line =~ /_spec.iseq/
#check for timeout
if (Time.now.to_i - start_logging.to_i) > timeout_in_seconds
$iphone_end_spec = true
is_timeout = true
end
if $iphone_end_spec
puts "%%% stop spec by this line : ["+line.to_s+"]"
end
break if $iphone_end_spec
end
sleep(3) unless $iphone_end_spec
end
end
puts "Processing spec results ..."
Jake.process_spec_results(start)
if is_timeout || !is_correct_stop
puts "Tests has issues : is_timeout["+is_timeout.to_s+"], timeout["+timeout_in_seconds.to_s+" sec], not_correct_terminated_line["+(!is_correct_stop).to_s+"] !"
puts "Tests stoped by timeout ( "+timeout_in_seconds.to_s+" sec ) !"
puts "last_spec_line = ["+last_spec_line.to_s+"]"
puts "last_spec_iseq_line = ["+last_spec_iseq_line.to_s+"]"
puts "last spec executed = ["+$latest_test_line.to_s+"]"
puts "This is last 1024 lines from log :"
idx = log_lines.size-1024
if idx < 0
idx = 0
end
while idx < log_lines.size
puts "line ["+idx.to_s+"]: "+log_lines[idx]
idx = idx + 1
end
end
#File.delete(log_name) if File.exist?(log_name)
# kill_iphone_simulator
$stdout.flush
end
unless $dont_exit_on_failure
exit 1 if is_timeout
exit 1 if $total.to_i==0
exit 1 if !is_correct_stop
exit $failed.to_i
end
end
# Alias for above task
task "emulator:spec" => :spec
task :spec_old => ["clean:iphone",:buildsim] do
sdkroot = $devroot + "/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" +
$sdk.gsub(/iphonesimulator/,"") + ".sdk"
old_user_home = ENV["CFFIXED_USER_HOME"]
old_dyld_root = ENV["DYLD_ROOT_PATH"]
old_dyld_framework = ENV["DYLD_FRAMEWORK_PATH"]
old_iphone_simulator = ENV["IPHONE_SIMULATOR_ROOT"]
ENV["CFFIXED_USER_HOME"] = $simrhodes
ENV["DYLD_ROOT_PATH"] = sdkroot
ENV["DYLD_FRAMEWORK_PATH"] = sdkroot + "/System/Library/Frameworks"
ENV["IPHONE_SIMULATOR_ROOT"] = sdkroot
command = '"' + $simrhodes + '/rhorunner.app/rhorunner"' + " -RegisterForSystemEvents"
#if someone runs against the wrong app, kill after 120 seconds
Thread.new {
sleep 300
`killall -9 rhorunner`
}
`killall -9 rhorunner`
# Run local http server
$iphonespec = true
httpserver = false
httpserver = true if File.exist? "#{$app_path}/app/spec/library/net/http/http/fixtures/http_server.rb"
if httpserver
require "#{$app_path}/app/spec/library/net/http/http/fixtures/http_server"
NetHTTPSpecs.start_server
end
Jake.before_run_spec
start = Time.now
io = IO.popen(command)
io.each do |line|
Jake.process_spec_output(line)
end
Jake.process_spec_results(start)
$stdout.flush
NetHTTPSpecs.stop_server if httpserver
ENV["CFFIXED_USER_HOME"] = old_user_home
ENV["DYLD_ROOT_PATH"] = old_dyld_root
ENV["DYLD_FRAMEWORK_PATH"] = old_dyld_framework
ENV["IPHONE_SIMULATOR_ROOT"] = old_iphone_simulator
unless $dont_exit_on_failure
exit 1 if $total.to_i==0
exit $failed.to_i
end
end
rhosim_task = lambda do |name, &block|
task name => ["config:set_iphone_platform", "config:common"] do
$rhosim_config = "platform='iphone'\r\n"
block.()
end
end
desc "Run application on RhoSimulator"
rhosim_task.(:rhosimulator) { Rake::Task["run:rhosimulator"].invoke }
namespace :rhosimulator do
rhosim_task.(:build) { Rake::Task["run:rhosimulator:build"].invoke }
rhosim_task.(:debug) { Rake::Task["run:rhosimulator:run" ].invoke('wait') }
end
task :get_log => ["config:iphone"] do
#puts $simapppath
# $sdkver = $emulator_version.to_s unless $emulator_version.nil?
#
# simapp = File.join($simdir, $sdkver, "Applications")
#
# Dir.glob(File.join($simdir, $sdkver, "Applications", "*")).each do |simapppath|
# need_rm = true if File.directory? simapppath
# if File.exists?(File.join(simapppath, 'rhorunner.app', 'name'))
# name = File.read(File.join(simapppath, 'rhorunner.app', 'name'))
# puts "found app name: #{name}"
# guid = File.basename(simapppath)
# puts "found guid: #{guid}"
# if name == $app_config['name']
# $guid = guid
# need_rm = false
# end
# end
# rm_rf simapppath if need_rm
# rm_rf simapppath + ".sb" if need_rm
# end
#
# simapp = File.join($simdir, $emulator_version, "Applications")
#
#
# rholog = simapp + "/" + $guid + "/Library/Caches/Private Documents/rholog.txt"
log_name = File.join($app_path, 'rholog.txt')
puts "log_file=" + log_name
end
#[run:iphone:simulator:package]
namespace "simulator" do
desc "run IPA package on simulator"
task :package, [:package_path] => ["config:iphone"] do |t, args|
currentdir = Dir.pwd()
package_path = args[:package_path]
#unpack package
tmp_dir = File.join($tmpdir, 'launch_package')
rm_rf tmp_dir
mkdir_p tmp_dir
#cp package_path, File.join(tmp_dir, 'package.ipa')
Jake.run('unzip', [package_path, '-d', tmp_dir])
Dir.chdir File.join(tmp_dir, 'Payload')
app_file = nil
Dir::glob(File.join(tmp_dir, 'Payload', '*.app')).each { |x| app_file = x }
if app_file == nil
raise 'can not find *.app folder inside package !'
end
puts '$$$ founded app folder is ['+app_file+']'
log_name = File.join($app_path, 'rholog.txt')
File.delete(log_name) if File.exist?(log_name)
commandis = $iphonesim + ' launch "' + app_file + '" ' + $sdkver.gsub(/([0-9]\.[0-9]).*/,'\1') + ' ' + $emulatortarget + ' "' +log_name+'"'
kill_iphone_simulator
$ios_run_completed = false
thr = Thread.new do
puts 'start thread with execution of application'
#if ($emulatortarget != 'iphone') && ($emulatortarget != 'ipad')
# puts 'use old execution way - just open iPhone Simulator'
# system("open \"#{$sim}/iPhone Simulator.app\"")
# $ios_run_completed = true
# sleep(1000)
#else
puts 'use iphonesim tool - open iPhone Simulator and execute our application, also support device family (iphone/ipad)'
puts 'Execute command: '+commandis
system(commandis)
$ios_run_completed = true
sleep(1000)
#end
#}
end
#if ($emulatortarget != 'iphone') && ($emulatortarget != 'ipad')
# thr.join
#else
puts 'start waiting for run application in Simulator'
while (!File.exist?(log_name)) && (!$ios_run_completed)
puts ' ... still waiting'
sleep(1)
end
puts 'stop waiting - application started'
#sleep(1000)
thr.kill
#thr.join
puts 'application is started in Simulator'
exit
#end
puts "end run iphone app package"
Dir.chdir currentdir
end
end
end
task :buildsim => ["config:iphone", "build:iphone:rhodes"] do
print_timestamp('run:buildsim START')
unless $sdk =~ /^iphonesimulator/
puts "SDK must be one of the iphonesimulator sdks to run in the iphone simulator"
exit 1
end
kill_iphone_simulator
#use_old_scheme = ($emulatortarget != 'iphone') && ($emulatortarget != 'ipad')
use_old_scheme = false
$sdkver = $sdk.gsub(/^iphonesimulator/, '')
# Workaround: sometimes sdkver could differ from emulator version.
# Example: iPhone SDK 4.0.1. In this case sdk is still iphonesimulator4.0 but version of simulator is 4.0.1
$sdkver = $emulator_version.to_s unless $emulator_version.nil?
=begin
#if use_old_scheme
elements = []
binplist = File.join(ENV['HOME'], 'Library', 'Preferences', 'com.apple.iphonesimulator.plist')
xmlplist = '/tmp/iphone.plist'
if File.exists? binplist
`plutil -convert xml1 -o #{xmlplist} #{binplist}`
elements = []
doc = REXML::Document.new(File.new(xmlplist))
nextignore = false
doc.elements.each('plist/dict/*') do |element|
if nextignore
nextignore = false
next
end
if element.name == 'key'
if element.text == 'currentSDKRoot' or element.text == 'SimulateDevice'
nextignore = true
next
end
end
elements << element
end
end
e = REXML::Element.new 'key'
e.text = 'SimulateDevice'
elements << e
e = REXML::Element.new 'string'
e.text = $sdkver == '3.2' ? 'iPad' : 'iPhone'
elements << e
e = REXML::Element.new 'key'
e.text = 'currentSDKRoot'
elements << e
e = REXML::Element.new 'string'
e.text = $sdkroot
elements << e
File.open(xmlplist, 'w') do |f|
f.puts "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
f.puts "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
f.puts "<plist version=\"1.0\">"
f.puts "<dict>"
elements.each do |e|
f.puts "\t#{e.to_s}"
end
f.puts "</dict>"
f.puts "</plist>"
end
`plutil -convert binary1 -o #{binplist} #{xmlplist}`
rhorunner = File.join($app_path, "/project/iphone") + "/build/#{$configuration}-iphonesimulator/rhorunner.app"
puts "rhorunner: #{rhorunner}"
puts "our app name: #{$app_config['name']}"
puts "simdir: #{$simdir}"
Dir.glob(File.join($simdir, $sdkver, "Applications", "*")).each do |simapppath|
need_rm = true if File.directory? simapppath
if File.exists?(File.join(simapppath, 'rhorunner.app', 'name'))
name = File.read(File.join(simapppath, 'rhorunner.app', 'name'))
puts "found app name: #{name}"
guid = File.basename(simapppath)
puts "found guid: #{guid}"
if name == $app_config['name']
$guid = guid
need_rm = false
end
end
rm_rf simapppath if need_rm
rm_rf simapppath + ".sb" if need_rm
end
puts "app guid: #{$guid}"
mkdir_p File.join($simdir, $sdkver)
simapp = File.join($simdir, $sdkver, "Applications")
simlink = File.join($simdir, $sdkver, "Library", "Preferences")
$simrhodes = File.join(simapp, $guid)
chmod 0744, File.join($simrhodes, "rhorunner.app", "rhorunner") unless !File.exists?(File.join($simrhodes, "rhorunner.app", "rhorunner"))
mkdir_p File.join($simrhodes, "Documents")
mkdir_p File.join($simrhodes, "Library", "Preferences")
mkdir_p File.join($simrhodes, "Library", "Caches", "Private Documents")
rm_rf File.join($simrhodes, 'rhorunner.app')
cp_r rhorunner, $simrhodes
['com.apple.PeoplePicker.plist', '.GlobalPreferences.plist'].each do |f|
`ln -f -s "#{simlink}/#{f}" "#{$simrhodes}/Library/Preferences/#{f}"`
end
#>>>>>>>>>>
#`echo "#{$applog}" > "#{$simrhodes}/Documents/rhologpath.txt"`
rholog = simapp + "/" + $guid + "/Library/Caches/Private Documents/rholog.txt"
#simpublic = simapp + "/" + $guid + "/Documents/apps/public"
simpublic = simapp + "/" + $guid + "/Library/Caches/Private Documents/apps/public"
apppublic = $app_path + "/sim-public-#{$sdkver}"
apprholog = $app_path + "/rholog-#{$sdkver}.txt"
apprholog = $app_path + "/" + $app_config["applog"] if $app_config["applog"]
rm_f apprholog
rm_f apppublic
#`ln -f -s "#{simpublic}" "#{apppublic}"`
#`ln -f -s "#{rholog}" "#{apprholog}"`
`echo > "#{rholog}"`
f = File.new("#{simapp}/#{$guid}.sb","w")
f << "(version 1)\n(debug deny)\n(allow default)\n"
f.close
#end
=end
print_timestamp('run:buildsim FINISH')
end
# split this off separate so running it normally is run:iphone
# testing we will not launch emulator directly
desc "Builds everything, launches iphone simulator"
task :iphone => ['run:iphone:build', 'run:iphone:run']
task :allspecs do
$dont_exit_on_failure = true
Rake::Task['run:iphone:phone_spec'].invoke
Rake::Task['run:iphone:framework_spec'].invoke
failure_output = ""
if $failed.to_i > 0
failure_output = ""
failure_output += "phone_spec failures:\n\n" + File.open(app_expanded_path('phone_spec') + "/faillog.txt").read if
File.exist?(app_expanded_path('phone_spec') + "/faillog.txt")
failure_output += "framework_spec failures:\n\n" + File.open(app_expanded_path('framework_spec') + "/faillog.txt").read if
File.exist?(app_expanded_path('framework_spec') + "/faillog.txt")
chdir basedir
File.open("faillog.txt", "w") { |io| failure_output.each {|x| io << x } }
end
puts "Agg Total: #{$total}"
puts "Agg Passed: #{$passed}"
puts "Agg Failed: #{$failed}"
exit 1 if $total.to_i==0
exit $failed.to_i
end
namespace "device" do
desc "run IPA package on device"
task :package, [:package_path] => ["config:iphone"] do |t, args|
raise "run on device is UNSUPPORTED !!!"
end
end
end
namespace "clean" do
desc "Clean iphone"
task :iphone => ["clean:iphone:all", "clean:common"]
namespace "iphone" do
# desc "Clean rhodes binaries"
task :rhodes => ["config:iphone"] do
app_path = File.join($app_path, 'bin', 'target', 'iOS')
rm_rf app_path
iphone_project_folder = File.join($app_path, "project","iphone")
iphone_build_folder = File.join(iphone_project_folder,"build")
rm_rf iphone_build_folder if File.exists? iphone_build_folder
appname = $app_config["name"] ? $app_config["name"] : "rhorunner"
appname_fixed = appname.split(/[^a-zA-Z0-9]/).map { |w| w }.join("")
appname_project = appname_fixed.slice(0, 1).capitalize + appname_fixed.slice(1..-1) + ".xcodeproj"
if File.exists?(iphone_project_folder)
chdir iphone_project_folder
args = ['clean', '-scheme', 'rhorunner', '-configuration', $configuration, '-sdk', $sdk, '-project', appname_project, '-quiet']
if RUBY_PLATFORM =~ /(win|w)32$/
else
ret = IPhoneBuild.run_and_trace($xcodebuild,args,{:rootdir => $startdir})
unless ret == 0
puts "Error cleaning"
exit 1
end
end
chdir $startdir
chdir File.join($app_path, "project","iphone")
rm_rf File.join('build','Debug-*')
rm_rf File.join('build','Release-*')
chdir $startdir
end
=begin
# check hash for remove only current application
found = true
while found do
found = false
Find.find($simdir) do |path|
if File.basename(path) == "rhorunner.app"
if File.exists?(File.join(path, 'name'))
name = File.read(File.join(path, 'name'))
puts "found app name: #{name}"
guid = File.basename(File.dirname(path))
puts "found guid: #{guid}"
if name == $app_config['name']
puts '>> We found our application !'
$guid = guid
found = true
end
end
end
end
if found
Dir.glob($simdir + '*').each do |sdk|
simapp = sdk + "/Applications"
simrhodes = File.join(simapp,$guid)
rm_rf simrhodes
rm_rf simrhodes + ".sb"
end
end
end
=end
end
# desc "Clean rhobundle"
task :rhobundle => ["config:iphone"] do
if File.exists?($bindir)
rm_rf $bindir
end
end
def run_clean_for_extension(extpath, xcodeproject, xcodetarget)
# only depfile is optional parameter !
currentdir = Dir.pwd()
Dir.chdir File.join(extpath, "platform/iphone")
xcodeproject = File.basename(xcodeproject)
#targetdir = ENV['TARGET_TEMP_DIR']
tempdir = ENV['TEMP_FILES_DIR']
rootdir = ENV['RHO_ROOT']
xcodebuild = ENV['XCODEBUILD']
configuration = ENV['CONFIGURATION']
sdk = ENV['SDK_NAME']
bindir = ENV['PLATFORM_DEVELOPER_BIN_DIR']
sdkroot = ENV['SDKROOT']
arch = ENV['ARCHS']
gccbin = bindir + '/gcc-4.2'
arbin = bindir + '/ar'
iphone_path = '.'
simulator = sdk =~ /iphonesimulator/
if configuration == 'Distribution'
configuration = 'Release'
end
rm_rf 'build'
args = ['clean', '-scheme', xcodetarget, '-configuration', configuration, '-sdk', sdk, '-project', xcodeproject]
additional_string = ' ARCHS="arm64 arm64e armv7 armv7s"'
if simulator
# args << '-arch'
# args << 'i386'
additional_string = ' ARCHS="i386 x86_64"'
end
require rootdir + '/lib/build/jake.rb'
if RUBY_PLATFORM =~ /(win|w)32$/
else
ret = IPhoneBuild.run_and_trace(xcodebuild,args,{:rootdir => rootdir, :string_for_add_to_command_line => additional_string})
end
Dir.chdir currentdir
end
def clean_extension_lib(extpath, sdk, xcodeproject, xcodetarget)
puts "clean extension START :" + extpath
if sdk =~ /iphonesimulator/
$sdkver = sdk.gsub(/iphonesimulator/,"")
$sdkroot = $devroot + "/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator" + $sdkver + ".sdk"
else
$sdkver = sdk.gsub(/iphoneos/,"")
$sdkroot = $devroot + "/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS" + $sdkver + ".sdk"
end
ENV['RHO_PLATFORM'] = 'iphone'
simulator = sdk =~ /iphonesimulator/
ENV["PLATFORM_DEVELOPER_BIN_DIR"] ||= $devroot + "/Platforms/" + ( simulator ? "iPhoneSimulator" : "iPhoneOS" ) +
".platform/Developer/usr/bin"
ENV["SDKROOT"] = $sdkroot
ENV["BUILD_DIR"] ||= $startdir + "/platform/iphone/build"
#ENV["TARGET_TEMP_DIR"] ||= target_dir
ENV["TEMP_FILES_DIR"] ||= ENV["TARGET_TEMP_DIR"]
ENV["ARCHS"] ||= simulator ? "i386 x86_64" : "arm64 arm64e armv7 armv7s"
ENV["RHO_ROOT"] = $startdir
# added by dmitrys
ENV["XCODEBUILD"] = $xcodebuild
ENV["CONFIGURATION"] ||= $configuration
ENV["SDK_NAME"] ||= sdk
build_script = File.join(extpath, 'clean')
if (xcodeproject != nil) and (xcodetarget != nil)
run_clean_for_extension(extpath, xcodeproject, xcodetarget)
else
# modify executable attribute
if File.exists? build_script
if !File.executable? build_script
#puts 'change executable attribute for build script in extension : '+build_script
begin
#File.chmod 0700, build_script
#puts 'executable attribute was writed for : '+build_script
rescue Exception => e
puts 'ERROR: can not change attribute for clean script in extension ! Try to run clean command with sudo: prefix.'
end
else
puts 'clean script in extension already executable : '+build_script
end
#puts '$$$$$$$$$$$$$$$$$$ START'
currentdir = Dir.pwd()
Dir.chdir extpath
sh %{$SHELL ./clean}
#Jake.run32("$SHELL "+build_script)
Dir.chdir currentdir
#puts '$$$$$$$$$$$$$$$$$$ FINISH'
#if File.executable? build_script
#puts Jake.run('./build', [], extpath)
#exit 1 unless $? == 0
#else
# puts 'ERROR: build script in extension is not executable !'
#end
else
puts 'clean script in extension not found => pure ruby extension or not supported clean'
end
end
puts "clean extension FINISH :" + extpath
end
task :extensions => ["config:iphone"] do
init_extensions(nil, 'get_ext_xml_paths')
#puts 'CLEAN ######################## ext='
puts "extpaths: #{$app_config["extpaths"].inspect.to_s}"
$stdout.flush
$app_extensions_list.each do |ext, commin_ext_path |
if commin_ext_path != nil
puts 'CLEAN ext='+ext.to_s+' path='+commin_ext_path.to_s
extpath = File.join( commin_ext_path, 'ext')
prebuilt_copy = false
xcodeproject = nil #xcodeproject
xcodetarget = nil #xcodetarget
extyml = File.join(commin_ext_path,"ext.yml")
if File.file? extyml
extconf = Jake.config(File.open(extyml))
extconf_iphone = extconf['iphone']
exttype = 'build'
exttype = extconf_iphone['exttype'] if extconf_iphone and extconf_iphone['exttype']
xcodeproject = extconf_iphone['xcodeproject'] if extconf_iphone and extconf_iphone['xcodeproject']
xcodetarget = extconf_iphone['xcodetarget'] if extconf_iphone and extconf_iphone['xcodetarget']
if exttype != 'prebuilt'
clean_extension_lib(extpath, $sdk, xcodeproject, xcodetarget)
end
end
#if ! prebuilt_copy
# build_extension_lib(extpath, sdk, target_dir, xcodeproject, xcodetarget, depfile)
#end
end
end
end
task :all => ["clean:iphone:rhodes", "clean:iphone:rhobundle", "clean:iphone:extensions"]
end
end
namespace "simulator" do
namespace "iphone" do
desc "build application package for simulator"
task :production => ["config:iphone"] do
Rake::Task['device:iphone:production'].invoke
end
desc "Builds and signs iphone for production, use prebuild binaries"
task :production_with_prebuild_binary => ["config:iphone"] do
Rake::Task['device:iphone:production_with_prebuild_binary'].invoke
end
end
end
namespace "device" do
namespace "iphone" do
# device:iphone:production
desc "Builds and signs iphone for production"
task :production, [:use_temp_keychain] do |t, args|
print_timestamp('device:iphone:production START')
#copy build results to app folder
args.with_defaults(:use_temp_keychain => "do_not_use_temp_keychain")
$use_temp_keychain = args[:use_temp_keychain] == "use_temp_keychain"
Rake::Task['config:iphone'].invoke
Rake::Task['build:iphone:rhodes'].invoke
app_path = File.join($app_path, 'bin', 'target', 'iOS', $sdk, $configuration)
iphone_path = File.join($app_path, "/project/iphone")
if $sdk =~ /iphonesimulator/
iphone_path = File.join(iphone_path, 'build', $configuration+'-iphonesimulator')
else
iphone_path = File.join(iphone_path, 'build', $configuration+'-iphoneos')
end
appname = $app_config["name"]
if appname == nil
appname = 'rhorunner'
end
# fix appname for remove restricted symbols
#appname = appname.downcase.split(/[^a-zA-Z0-9]/).map{|w| w.downcase}.join("_")
appname = appname.split(/[^a-zA-Z0-9\_\-]/).map{|w| w}.join("_")
src_file = File.join(iphone_path, 'rhorunner.app')
dst_file = File.join(app_path, appname+'.app')
rm_rf dst_file
rm_rf app_path
mkdir_p app_path
puts 'copy result build package to application target folder ...'
cp_r src_file, dst_file
make_app_info
ipapath = prepare_production_ipa(app_path, appname)
prepare_production_plist(app_path, appname)
copy_all_png_from_icon_folder_to_product(app_path)
print_timestamp('device:iphone:production FINISH')
puts '************************************'
puts '*'
puts "SUCCESS ! Production package built and placed into : "+ipapath
puts '*'
puts '************************************'
end
def determine_prebuild_path_iphone(config)
RhoPackages.request 'rhodes-containers'
require 'rhodes/containers'
Rhodes::Containers::get_container_path_prefix('iphone', config)
end
desc "Builds and signs iphone for production, use prebuild binaries"
task :production_with_prebuild_binary => ["config:iphone"] do
print_timestamp('device:iphone:production_with_prebuild_binary START')
#Support build.yml settings on cloud by copying to rhoconfig.txt
Rake::Task['config:common:ymlsetup'].invoke
currentdir = Dir.pwd()
$skip_build_rhodes_main = true
$skip_build_extensions = true
$skip_build_xmls = true
$use_prebuild_data = true
$skip_build_js_api_files = true
is_simulator = ($sdk =~ /iphonesimulator/)
parent_ipa_path = File.join(determine_prebuild_path_iphone($app_config), "prebuild.ipa")
puts '$ parent_ipa_path = '+parent_ipa_path
Rake::Task['build:iphone:rhodes'].invoke
chdir $app_path
print_timestamp('bundle was builded')
parent_app_bin = File.join($app_path, 'project/iphone/binp')
rm_rf parent_app_bin
mkdir_p parent_app_bin
#cp parent_ipa_path, File.join(parent_app_bin, parent_ipa_path)
chdir parent_app_bin
#cmd "%{unzip "+parent_ipa_path+" -d "+parent_app_bin+" }"
Jake.run('unzip', [parent_ipa_path, '-d', parent_app_bin])
print_timestamp('parent IPA was unzipped')
#copy bundle from bin to binp
src_bundle_folder = File.join($app_path, "/project/iphone/bin/RhoBundle/")
dst_bundle_folder = File.join($app_path, "/project/iphone/binp/Payload/prebuild.app/")
#resource_to_copy = ['apps', 'db', 'lib', 'hash', 'name', 'rhofilelist.txt']
# save container api folder
rm_rf File.join($app_path, "/project/iphone/binp/tmpapi")
mkdir_p File.join($app_path, "/project/iphone/binp/tmpapi")
cp_r File.join(dst_bundle_folder, "apps/public/api"),File.join($app_path, "/project/iphone/binp/tmpapi/api")
#apps
rm_rf File.join(dst_bundle_folder, "apps")
cp_r File.join(src_bundle_folder, "apps"),File.join(dst_bundle_folder, "apps")
#restore container api
rm_rf File.join(dst_bundle_folder, "apps/public/api")
cp_r File.join($app_path, "/project/iphone/binp/tmpapi/api"),File.join(dst_bundle_folder, "apps/public")
rm_rf File.join($app_path, "/project/iphone/binp/tmpapi")
#db
rm_rf File.join(dst_bundle_folder, "db")
cp_r File.join(src_bundle_folder, "db"),dst_bundle_folder
#hash
rm_rf File.join(dst_bundle_folder, "hash")
cp_r File.join(src_bundle_folder, "hash"),File.join(dst_bundle_folder, "hash")
#hash
rm_rf File.join(dst_bundle_folder, "name")
cp_r File.join(src_bundle_folder, "name"),File.join(dst_bundle_folder, "name")
#hash
rm_rf File.join(dst_bundle_folder, "rhofilelist.txt")
cp_r File.join(src_bundle_folder, "rhofilelist.txt"),File.join(dst_bundle_folder, "rhofilelist.txt")
#copy icons
src_app_icons_folder = File.join($app_path, "icon")
dst_bundle_icons_folder = dst_bundle_folder
ICONS.each do |pair|
name = pair[0]+'.png'
app_icon = File.join(src_app_icons_folder, name)
bundle_icon = File.join(dst_bundle_icons_folder, name)
if File.exists? app_icon
rm_rf bundle_icon
cp app_icon,bundle_icon
end
end
#copy loading
src_app_loading_folder = File.join($app_path, "app")
dst_bundle_loading_folder = dst_bundle_folder
LOADINGIMAGES.each do |name|
defname = name.sub('loading', 'Default')
app_loading = File.join(src_app_loading_folder, name)+'.png'
bundle_loading = File.join(dst_bundle_loading_folder, defname)+'.png'
rm_rf bundle_loading
if File.exists? app_loading
cp app_loading,bundle_loading
end
end
# fix plist
#rm_rf File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/Entitlements.plist')
#cp File.join($app_path, 'project/iphone/Entitlements.plist'),File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/Entitlements.plist')
#rm_rf File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/Info.plist')
#cp File.join($app_path, 'project/iphone/Info.plist'),File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/Info.plist')
chdir File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/')
#Jake.run('plutil', ['-convert', 'xml1', 'Entitlements.plist'])
Jake.run('plutil', ['-convert', 'xml1', 'Info.plist'])
prebuild_plist = File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/Info.plist')
app_plist = File.join($app_path, 'project/iphone/Info.plist')
rm_rf app_plist
cp prebuild_plist,app_plist
Rake::Task['build:iphone:update_plist'].reenable
Rake::Task['build:iphone:update_plist'].invoke
rm_rf prebuild_plist
cp app_plist,prebuild_plist
chdir File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/')
Jake.run('plutil', ['-convert', 'binary1', 'Info.plist'])
#iTunesArtwork
itunes_artwork_in_project = File.join(parent_app_bin, "Payload/prebuild.app/iTunesArtwork")
itunes_artwork_in_project_2 = File.join(parent_app_bin, "Payload/prebuild.app/iTunesArtwork@2x")
itunes_artwork_default = File.join($app_path, "/project/iphone/iTunesArtwork")
itunes_artwork = itunes_artwork_default
itunes_artwork_new = File.join($app_path, "resources","ios","iTunesArtwork.png")
if File.exists? itunes_artwork_new
itunes_artwork = itunes_artwork_new
end
if !$app_config["iphone"].nil?
if !$app_config["iphone"]["production"].nil?
if !$app_config["iphone"]["production"]["ipa_itunesartwork_image"].nil?
art_test_name = $app_config["iphone"]["production"]["ipa_itunesartwork_image"]
if File.exists? art_test_name
itunes_artwork = art_test_name
else
art_test_name = File.join($app_path,$app_config["iphone"]["production"]["ipa_itunesartwork_image"])
if File.exists? art_test_name
itunes_artwork = art_test_name
else
itunes_artwork = $app_config["iphone"]["production"]["ipa_itunesartwork_image"]
end
end
end
end
end
itunes_artwork_2 = itunes_artwork
itunes_artwork_2 = itunes_artwork_2.gsub(".png", "@2x.png")
if itunes_artwork_2.index('@2x') == nil
itunes_artwork_2 = itunes_artwork_2.gsub(".PNG", "@2x.PNG")
end
if itunes_artwork_2.index('@2x') == nil
itunes_artwork_2 = itunes_artwork_2 + '@2x'
end
rm_rf itunes_artwork_in_project
cp itunes_artwork,itunes_artwork_in_project
if itunes_artwork == itunes_artwork_default
BuildOutput.warning("iTunesArtwork (image required for iTunes) not found - use from XCode project, can be default !!!" )
end
rm_rf itunes_artwork_in_project_2
cp itunes_artwork_2,itunes_artwork_in_project_2
if itunes_artwork == itunes_artwork_default
BuildOutput.warning("iTunesArtwork@2x (image required for iTunes) not found - use from XCode project, can be default !!!" )
end
# copy to Payload root
rm_rf File.join(parent_app_bin, "iTunesArtwork")
#cp itunes_artwork, File.join(parent_app_bin, "iTunesArtwork")
#repack into IPA and sign
#zip -qr "Application.resigned.ipa" Payload
appname = $app_config["name"]
if appname == nil
appname = 'rhorunner'
end
appname = appname.split(/[^a-zA-Z0-9\_\-]/).map{|w| w}.join("_")
ipaname = appname + ".ipa"
app_path = File.join($app_path, 'bin', 'target', 'iOS', $sdk, $configuration)
#rename to new name
mv File.join($app_path, 'project/iphone/binp/Payload/prebuild.app/'),File.join($app_path, 'project/iphone/binp/Payload/'+appname+'.app/')
executable_file = File.join($app_path, 'project/iphone/binp/Payload/'+appname+'.app/', 'rhorunner')
if !File.executable? executable_file
begin
File.chmod 0700, executable_file
puts 'executable attribute was writed for : '+executable_file
rescue Exception => e
puts 'ERROR: can not change attribute for executable in application package ! Try to run build command with sudo: prefix.'
end
else
puts '$$$ executable is already have executable attribute !!! $$$'
end
print_timestamp('application bundle was updated')
chdir parent_app_bin
#sign
if !is_simulator
rm_rf File.join(parent_app_bin, "Payload/prebuild.app/_CodeSignature")
rm_rf File.join(parent_app_bin, "Payload/prebuild.app/CodeResources")
prov_file_path = File.join($app_path, 'production/embedded.mobileprovision')
entitlements = nil
if !$app_config["iphone"].nil?
entitlements = $app_config["iphone"]["entitlements"]
if entitlements == ""
entitlements = nil
end
if !$app_config["iphone"]["production"].nil?
if !$app_config["iphone"]["production"]["mobileprovision_file"].nil?
test_name = $app_config["iphone"]["production"]["mobileprovision_file"]
if File.exists? test_name
prov_file_path = test_name
else
test_name = File.join($app_path,$app_config["iphone"]["production"]["mobileprovision_file"])
if File.exists? test_name
prov_file_path = test_name
else
prov_file_path = $app_config["iphone"]["production"]["mobileprovision_file"]
end
end
end
end
end
cp prov_file_path, File.join(parent_app_bin, "Payload/"+appname+".app/embedded.mobileprovision")
#/usr/bin/codesign -f -s "iPhone Distribution: Certificate Name" --resource-rules "Payload/Application.app/ResourceRules.plist" "Payload/Application.app"
if entitlements == nil
if $ios_push_capability
#make fix file
tmp_ent_dir = File.join($app_path, "/project/iphone/push_fix_entitlements")
rm_rf tmp_ent_dir
mkdir_p tmp_ent_dir
entitlements = File.join(tmp_ent_dir, "Entitlements.plist")
File.open(entitlements, 'w') do |f|
f.puts "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
f.puts "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"https://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
f.puts "<plist version=\"1.0\">"
f.puts "<dict>"
f.puts "<key>aps-environment</key>"
if $configuration == "Distribution"
f.puts "<string>production</string>"
else
f.puts "<string>development</string>"
end
f.puts "<key>get-task-allow</key>"
f.puts "<true/>"
f.puts "</dict>"
f.puts "</plist>"
end
end
end
if entitlements != nil
tst_path = File.join($app_path, entitlements)
if File.exists? tst_path
entitlements = tst_path
end
end
if entitlements != nil
Jake.run('/usr/bin/codesign', ['-f', '-s', '"'+$signidentity+'"', '-i', '"'+$app_config["iphone"]["BundleIdentifier"]+'"', '--entitlements="'+entitlements+'"', 'Payload/'+appname+'.app'])
else
Jake.run('/usr/bin/codesign', ['-f', '-s', '"'+$signidentity+'"', '-i', '"'+$app_config["iphone"]["BundleIdentifier"]+'"', 'Payload/'+appname+'.app'])
end
#Jake.run('/usr/bin/codesign', ['-f', '-s', '"'+$signidentity+'"', '--resource-rules', 'Payload/prebuild.app/ResourceRules.plist', 'Payload/prebuild.app'])
unless $?.success?
raise "Error during signing of application package !"
end
end
print_timestamp('updated application was signed')
sh %{zip -r -y temporary_archive.zip .}
rm_rf app_path
mkdir_p app_path
puts 'copy result build package to application target folder ...'
cp File.join(parent_app_bin, "temporary_archive.zip"), File.join(app_path, ipaname)
rm_rf parent_app_bin
#chdir File.join($app_path, 'project/iphone/binp/Payload/'+appname+'.app/')
#Jake.run('plutil', ['-convert', 'xml1', 'Info.plist'])
#Jake.run('zip', ['-qr', ipaname, 'Payload'])
Dir.chdir currentdir
print_timestamp('device:iphone:production_with_prebuild_binary FINISH')
puts '************************************'
puts '*'
puts "SUCCESS ! Production package builded and placed into : "+File.join(app_path, ipaname)
puts '*'
puts '************************************'
end
task :make_container, [:container_prefix_path] => :production do |t, args|
container_prefix_path = args[:container_prefix_path]
appname = $app_config["name"]
if appname == nil
appname = 'rhorunner'
end
appname = appname.split(/[^a-zA-Z0-9\_\-]/).map{|w| w}.join("_")
ipaname = appname + ".ipa"
app_path = File.join($app_path, 'bin', 'target', 'iOS', $sdk, $configuration)
rm_rf container_prefix_path
mkdir_p container_prefix_path
cp File.join(app_path, ipaname), File.join(container_prefix_path, "prebuild.ipa")
end
task :production_with_prebuild_libs => ["config:iphone"] do
print_timestamp('device:iphone:production_with_prebuild_libs START')
rm_rf File.join($app_path, "project/iphone")
$use_prebuild_data = true
Rake::Task['build:iphone:rhodes'].invoke
#copy build results to app folder
app_path = File.join($app_path, 'bin', 'target', 'iOS', $sdk, $configuration)
iphone_path = File.join($app_path, "/project/iphone")
if $sdk =~ /iphonesimulator/
iphone_path = File.join(iphone_path, 'build', $configuration+'-iphonesimulator')
else
iphone_path = File.join(iphone_path, 'build', $configuration+'-iphoneos')
end
appname = $app_config["name"]
if appname == nil
appname = 'rhorunner'
end
# fix appname for remove restricted symbols
#appname = appname.downcase.split(/[^a-zA-Z0-9]/).map{|w| w.downcase}.join("_")
appname = appname.split(/[^a-zA-Z0-9\_\-]/).map{|w| w}.join("_")
src_file = File.join(iphone_path, 'rhorunner.app')
dst_file = File.join(app_path, appname+'.app')
rm_rf dst_file
rm_rf app_path
mkdir_p app_path
puts 'copy result build package to application target folder ...'
cp_r src_file, dst_file
make_app_info
prepare_production_ipa(app_path, appname)
prepare_production_plist(app_path, appname)
copy_all_png_from_icon_folder_to_product(app_path)
print_timestamp('device:iphone:production_with_prebuild_libs FINISH')
end
end
end
namespace :stop do
task :iphone do
kill_iphone_simulator
end
task "iphone:emulator" => :iphone
end
| 35.577273 | 313 | 0.610042 |
bbcad634880a8d82fc82acc2ae3bd7884fb64f7e | 1,112 | module Pione
module Location
class HTTPSLocation < HTTPLocation
set_scheme "https"
define(:need_caching, true)
define(:real_appendable, false)
define(:writable, false)
# Send a request HTTPS Get and evaluate the block with the response.
def http_get(&b)
http = Net::HTTP.new(@uri.host, @uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Get.new(@uri.path)
res = http.request(req)
if res.kind_of?(Net::HTTPSuccess)
return b.call(res)
else
raise NotFound.new(@uri)
end
end
# Send a request HTTPS Head and evaluate the block with the response.
def http_head(&b)
http = Net::HTTP.new(@uri.host, @uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Head.new(@uri.path)
res = http.request(req)
if res.kind_of?(Net::HTTPSuccess)
return b.call(res)
else
raise NotFound(@uri)
end
end
end
end
end
| 27.8 | 75 | 0.588129 |
6aba5a4c7dd95f50094f12f1d6b177cfac4c93f6 | 1,679 | module LogsHelper
def of_name
return if params[:name].blank? || params[:searching].blank?
thing = params[:searching].classify.constantize.find_by(name: params[:name])
' for '.html_safe <<
link_to(params[:name], controller: params[:searching], action: :show, id: thing.id)
end
def severity_class(severity)
{ info: '',
warn: 'text-warning',
error: 'text-danger',
fatal: 'text-danger danger' }[severity.to_sym]
end
def date_range
form_for :logs, url: { controller: :logs, action: "search" }, html: { method: :get, role: "search", class: "navbar-form navbar-left navbar-search", style: "padding-right: 0" } do
concat hidden_field_tag "query", params[:query] unless params[:query].blank?
concat hidden_field_tag "name", search_name unless search_name.blank?
concat(content_tag(:div, class: "form-group") {
concat label_tag :from, "From", class: "control-label", style: "margin-right: 5px"
concat date_field_tag :from, params[:from], class: 'form-control form-date'
})
concat(content_tag(:div, class: "form-group") {
concat label_tag :to, "To", class: "control-label", style: "margin-right: 5px"
concat date_field_tag :to, params[:to], class: 'form-control form-date'
})
concat button_tag "Filter", class: "btn btn-sm btn-default", name: ""
end
end
def time_to_complete(duration)
return unless duration
'Took ' << duration.human_time << ' to complete'
end
def time_format(time)
return unless time
I18n.l time.localtime, format: :human
end
def time_default(time)
I18n.l time.localtime, format: :default
end
end
| 34.979167 | 182 | 0.659917 |
61d09f4b2692b96cca3ef88af1aa5369e61d04f9 | 1,016 | module DataMapper
class Property
class Decimal < Numeric
load_as BigDecimal
dump_as BigDecimal
coercion_method :to_decimal
DEFAULT_PRECISION = 10
DEFAULT_SCALE = 0
precision(DEFAULT_PRECISION)
scale(DEFAULT_SCALE)
protected
def initialize(model, name, options = {})
super
[ :scale, :precision ].each do |key|
unless @options.key?(key)
warn "options[#{key.inspect}] should be set for #{self.class}, defaulting to #{send(key).inspect} (#{caller.first})"
end
end
unless @scale >= 0
raise ArgumentError, "scale must be equal to or greater than 0, but was #{@scale.inspect}"
end
unless @precision >= @scale
raise ArgumentError, "precision must be equal to or greater than scale, but was #{@precision.inspect} and scale was #{@scale.inspect}"
end
end
end # class Decimal
end # class Property
end # module DataMapper
| 27.459459 | 144 | 0.608268 |
0894f1cee64fc55273bf04c8875f013773cb5d94 | 1,193 | # frozen_string_literal: true
require File.join(File.expand_path('../../../../test', __dir__), 'test_helper')
module MasterfilesApp
class TestTreatmentTypePermission < Minitest::Test
include Crossbeams::Responses
def entity(attrs = {})
base_attrs = {
id: 1,
treatment_type_code: Faker::Lorem.unique.word,
description: 'ABC',
active: true
}
MasterfilesApp::TreatmentType.new(base_attrs.merge(attrs))
end
def test_create
res = MasterfilesApp::TaskPermissionCheck::TreatmentType.call(:create)
assert res.success, 'Should always be able to create a treatment_type'
end
def test_edit
MasterfilesApp::FruitRepo.any_instance.stubs(:find_treatment_type).returns(entity)
res = MasterfilesApp::TaskPermissionCheck::TreatmentType.call(:edit, 1)
assert res.success, 'Should be able to edit a treatment_type'
end
def test_delete
MasterfilesApp::FruitRepo.any_instance.stubs(:find_treatment_type).returns(entity)
res = MasterfilesApp::TaskPermissionCheck::TreatmentType.call(:delete, 1)
assert res.success, 'Should be able to delete a treatment_type'
end
end
end
| 32.243243 | 88 | 0.706622 |
39af561b7c0bac6c9d64754f30a5d6fb83a78b20 | 44 | module Heroku; end
require 'heroku/client'
| 11 | 23 | 0.772727 |
6142bfe56a968180e3d028f7c6d30143b76720a5 | 8,483 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# WorkRequestResource model.
class ObjectStorage::Models::WorkRequestResource
ACTION_TYPE_ENUM = [
ACTION_TYPE_CREATED = 'CREATED'.freeze,
ACTION_TYPE_UPDATED = 'UPDATED'.freeze,
ACTION_TYPE_DELETED = 'DELETED'.freeze,
ACTION_TYPE_RELATED = 'RELATED'.freeze,
ACTION_TYPE_IN_PROGRESS = 'IN_PROGRESS'.freeze,
ACTION_TYPE_READ = 'READ'.freeze,
ACTION_TYPE_WRITTEN = 'WRITTEN'.freeze,
ACTION_TYPE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
# The status of the work request.
# @return [String]
attr_reader :action_type
# The resource type the work request affects.
# @return [String]
attr_accessor :entity_type
# The resource type identifier.
# @return [String]
attr_accessor :identifier
# The URI path that you can use for a GET request to access the resource metadata.
# @return [String]
attr_accessor :entity_uri
# The metadata of the resource.
# @return [Hash<String, String>]
attr_accessor :metadata
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'action_type': :'actionType',
'entity_type': :'entityType',
'identifier': :'identifier',
'entity_uri': :'entityUri',
'metadata': :'metadata'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'action_type': :'String',
'entity_type': :'String',
'identifier': :'String',
'entity_uri': :'String',
'metadata': :'Hash<String, String>'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :action_type The value to assign to the {#action_type} property
# @option attributes [String] :entity_type The value to assign to the {#entity_type} property
# @option attributes [String] :identifier The value to assign to the {#identifier} property
# @option attributes [String] :entity_uri The value to assign to the {#entity_uri} property
# @option attributes [Hash<String, String>] :metadata The value to assign to the {#metadata} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.action_type = attributes[:'actionType'] if attributes[:'actionType']
raise 'You cannot provide both :actionType and :action_type' if attributes.key?(:'actionType') && attributes.key?(:'action_type')
self.action_type = attributes[:'action_type'] if attributes[:'action_type']
self.entity_type = attributes[:'entityType'] if attributes[:'entityType']
raise 'You cannot provide both :entityType and :entity_type' if attributes.key?(:'entityType') && attributes.key?(:'entity_type')
self.entity_type = attributes[:'entity_type'] if attributes[:'entity_type']
self.identifier = attributes[:'identifier'] if attributes[:'identifier']
self.entity_uri = attributes[:'entityUri'] if attributes[:'entityUri']
raise 'You cannot provide both :entityUri and :entity_uri' if attributes.key?(:'entityUri') && attributes.key?(:'entity_uri')
self.entity_uri = attributes[:'entity_uri'] if attributes[:'entity_uri']
self.metadata = attributes[:'metadata'] if attributes[:'metadata']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] action_type Object to be assigned
def action_type=(action_type)
# rubocop:disable Style/ConditionalAssignment
if action_type && !ACTION_TYPE_ENUM.include?(action_type)
OCI.logger.debug("Unknown value for 'action_type' [" + action_type + "]. Mapping to 'ACTION_TYPE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@action_type = ACTION_TYPE_UNKNOWN_ENUM_VALUE
else
@action_type = action_type
end
# rubocop:enable Style/ConditionalAssignment
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
action_type == other.action_type &&
entity_type == other.entity_type &&
identifier == other.identifier &&
entity_uri == other.entity_uri &&
metadata == other.metadata
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[action_type, entity_type, identifier, entity_uri, metadata].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 37.20614 | 245 | 0.677001 |
91d40978007bb77647c809f9dae7d4e53847ab4c | 2,920 | require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe CouchRest::WillPaginate do
class SomeModel < CouchRest::Model::Base
use_database SPEC_COUCH
property :name
paginated_view_by :name
end
[SomeModel].each do |klass|
describe klass do
before(:all) do
reset_test_db!
end
it "should respond to paginated_view_by class method" do
klass.should respond_to :paginated_view_by
end
it "should call view_by method when paginated view_by included" do
klass.should_receive(:view_by)
klass.paginated_view_by :name
end
it "should respond to the view and paginated method" do
klass.should respond_to :paginate_by_name
# @some_doc.stub(:id).and_return(123)
end
it "should accept request when no results" do
docs = klass.paginate_by_name(:per_page => 5)
docs.total_entries.should eql(0)
end
it "should accept request without page" do
docs = nil
lambda { docs = klass.paginate_by_name(:per_page => 5) }.should_not raise_error
docs.current_page.should eql(1)
end
it "should throw an exception when missing per_page parameter" do
lambda { klass.paginate_by_name() }.should raise_error
end
describe "performing pagination with lots of documents" do
before(:each) do
reset_test_db!
20.times do |i|
txt = "%02d" % i
klass.new(:name => "document #{txt}").save
end
end
it "should produce a will paginate collection" do
docs = klass.paginate_by_name( :page => 1, :per_page => 5 )
docs.should be_a_kind_of(::WillPaginate::Collection)
docs.total_pages.should eql(4)
docs.first.name.should eql('document 00')
docs.length.should eql(5)
docs.last.name.should eql('document 04')
end
it "should produce second page from paginate collection" do
docs = klass.paginate_by_name( :page => 2, :per_page => 5 )
docs.first.name.should eql('document 05')
docs.length.should eql(5)
docs.last.name.should eql('document 09')
end
it "should perform paginate on all entries" do
docs = klass.paginate_all(:page => 1, :per_page => 5)
docs.first.class.should eql(klass)
docs.total_pages.should eql(4)
docs.total_entries.should eql(20)
docs.length.should eql(5)
end
end
describe "using pagination via proxy class" do
before(:each) do
@proxy = klass.on(SPEC_COUCH)
end
it "should allow paginate call on proxy" do
klass.should_receive(:paginated_view).with('by_name', {:key => 'foo', :database => SPEC_COUCH})
@proxy.paginate_by_name :key => 'foo'
end
end
end
end
end
| 29.494949 | 105 | 0.618493 |
f746ebd8d4ab89f8902b34b0c8a08d39d3452647 | 614 | ENV['RAILS_ENV'] ||= 'test'
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'factory_girl_rails'
require 'database_cleaner'
require 'pry'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
config.mock_with :rspec
config.order = "random"
config.use_transactional_fixtures = false
DatabaseCleaner.strategy = :truncation
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end | 22.740741 | 71 | 0.742671 |
d5006575894aba74a1cdb9b04ff226d693b1ca5e | 11,602 | require_relative './miq_ae_service_model_legacy'
require_relative './miq_ae_service_vmdb'
require_relative './miq_ae_service_rbac'
module MiqAeMethodService
class MiqAeService
include Vmdb::Logging
include DRbUndumped
include MiqAeMethodService::MiqAeServiceModelLegacy
include MiqAeMethodService::MiqAeServiceVmdb
include MiqAeMethodService::MiqAeServiceRbac
attr_accessor :logger
@@id_hash = {}
@@current = []
def self.current
@@current.last
end
def self.find(id)
@@id_hash[id.to_i]
end
def self.add(obj)
@@id_hash[obj.object_id] = obj
@@current << obj
end
def self.destroy(obj)
@@id_hash.delete(obj.object_id)
@@current.delete(obj)
end
def initialize(workspace, inputs = {}, logger = $miq_ae_logger)
@tracking_label = Thread.current["tracking_label"]
@drb_server_references = []
@inputs = inputs
@workspace = workspace
@persist_state_hash = workspace.persist_state_hash
@logger = logger
self.class.add(self)
workspace.disable_rbac
end
delegate :enable_rbac, :disable_rbac, :rbac_enabled?, :to => :@workspace
def stdout
@stdout ||= Vmdb::Loggers::IoLogger.new(logger, :info, "Method STDOUT:")
end
def stderr
@stderr ||= Vmdb::Loggers::IoLogger.new(logger, :error, "Method STDERR:")
end
def destroy
self.class.destroy(self)
end
def disconnect_sql
ActiveRecord::Base.connection_pool.release_connection
end
attr_writer :inputs
attr_reader :inputs
####################################################
def log(level, msg)
Thread.current["tracking_label"] = @tracking_label
$miq_ae_logger.send(level, "<AEMethod #{current_method}> #{ManageIQ::Password.sanitize_string(msg)}")
end
def set_state_var(name, value)
@persist_state_hash[name] = value
end
def state_var_exist?(name)
@persist_state_hash.key?(name)
end
def get_state_var(name)
@persist_state_hash[name]
end
def delete_state_var(name)
@persist_state_hash.delete(name)
end
def get_state_vars
@persist_state_hash
end
def ansible_stats_vars
MiqAeEngine::MiqAeAnsibleMethodBase.ansible_stats_from_hash(@persist_state_hash)
end
def set_service_var(name, value)
if service_object.nil?
$miq_ae_logger.error("Service object not found in root object, set_service_var skipped for #{name} = #{value}")
return
end
service_object.root_service.set_service_vars_option(name, value)
end
def service_var_exists?(name)
return false unless service_object
service_object.root_service.service_vars_options.key?(name)
end
def get_service_var(name)
return unless service_var_exists?(name)
service_object.root_service.get_service_vars_option(name)
end
def delete_service_var(name)
return unless service_var_exists?(name)
service_object.root_service.delete_service_vars_option(name)
end
def prepend_namespace=(namespace)
@workspace.prepend_namespace = namespace
end
def instantiate(uri)
obj = @workspace.instantiate(uri, @workspace.ae_user, @workspace.current_object)
return nil if obj.nil?
MiqAeServiceObject.new(obj, self)
rescue StandardError => e
$miq_ae_logger.error("instantiate failed : #{e.message}")
nil
end
def object(path = nil)
obj = @workspace.get_obj_from_path(path)
return nil if obj.nil?
MiqAeServiceObject.new(obj, self)
end
def hash_to_query(hash)
MiqAeEngine::MiqAeUri.hash2query(hash)
end
def query_to_hash(query)
MiqAeEngine::MiqAeUri.query2hash(query)
end
def current_namespace
@workspace.current_namespace
end
def current_class
@workspace.current_class
end
def current_instance
@workspace.current_instance
end
def current_message
@workspace.current_message
end
def current_object
@current_object ||= MiqAeServiceObject.new(@workspace.current_object, self)
end
def current_method
@workspace.current_method
end
def current
current_object
end
def root
@root ||= object("/")
end
def parent
@parent ||= object("..")
end
def objects(aobj)
aobj.collect do |obj|
obj = MiqAeServiceObject.new(obj, self) unless obj.kind_of?(MiqAeServiceObject)
obj
end
end
def datastore
end
def ldap
end
def execute(method_name, *args)
User.with_user(@workspace.ae_user) { execute_with_user(method_name, *args) }
end
def execute_with_user(method_name, *args)
# Since each request from DRb client could run in a separate thread
# We have to set the current_user in every thread.
MiqAeServiceMethods.send(method_name, *args)
rescue NoMethodError => err
raise MiqAeException::MethodNotFound, err.message
end
def notification_subject(values_hash)
subject = values_hash[:subject] || @workspace.ae_user
(ar_object(subject) || subject).tap do |object|
raise ArgumentError, "Subject must be a valid Active Record object" unless object.kind_of?(ActiveRecord::Base)
end
end
def ar_object(svc_obj)
if svc_obj.kind_of?(MiqAeMethodService::MiqAeServiceModelBase)
svc_obj.instance_variable_get('@object')
end
end
def notification_type(values_hash)
type = values_hash[:type].present? ? values_hash[:type].to_sym : default_notification_type(values_hash)
type.tap do |t|
$miq_ae_logger.info("Validating Notification type: #{t}")
valid_type = NotificationType.find_by(:name => t)
raise ArgumentError, "Invalid notification type specified" unless valid_type
end
end
def create_notification(values_hash = {})
create_notification!(values_hash)
rescue StandardError
nil
end
def create_notification!(values_hash = {})
User.with_user(@workspace.ae_user) { create_notification_with_user!(values_hash) }
end
def create_notification_with_user!(values_hash)
options = {}
type = notification_type(values_hash)
subject = notification_subject(values_hash)
options[:message] = values_hash[:message] if values_hash[:message].present?
$miq_ae_logger.info("Calling Create Notification type: #{type} subject type: #{subject.class.base_class.name} id: #{subject.id} options: #{options.inspect}")
MiqAeServiceModelBase.wrap_results(Notification.create!(:type => type,
:subject => subject,
:options => options,
:initiator => @workspace.ae_user))
end
def instance_exists?(path)
_log.info("<< path=#{path.inspect}")
!!__find_instance_from_path(path)
end
def instance_create(path, values_hash = {})
_log.info("<< path=#{path.inspect}, values_hash=#{values_hash.inspect}")
return false unless editable_instance?(path)
ns, klass, instance = MiqAeEngine::MiqAePath.split(path)
$log.info("Instance Create for ns: #{ns} class #{klass} instance: #{instance}")
aec = MiqAeClass.lookup_by_namespace_and_name(ns, klass)
return false if aec.nil?
aei = aec.ae_instances.detect { |i| instance.casecmp(i.name).zero? }
return false unless aei.nil?
aei = MiqAeInstance.create(:name => instance, :class_id => aec.id)
values_hash.each { |key, value| aei.set_field_value(key, value) }
true
end
def instance_get_display_name(path)
_log.info("<< path=#{path.inspect}")
aei = __find_instance_from_path(path)
aei.try(:display_name)
end
def instance_set_display_name(path, display_name)
_log.info("<< path=#{path.inspect}, display_name=#{display_name.inspect}")
aei = __find_instance_from_path(path)
return false if aei.nil?
aei.update(:display_name => display_name)
true
end
def instance_update(path, values_hash)
_log.info("<< path=#{path.inspect}, values_hash=#{values_hash.inspect}")
return false unless editable_instance?(path)
aei = __find_instance_from_path(path)
return false if aei.nil?
values_hash.each { |key, value| aei.set_field_value(key, value) }
true
end
def instance_find(path, options = {})
_log.info("<< path=#{path.inspect}")
result = {}
ns, klass, instance = MiqAeEngine::MiqAePath.split(path)
aec = MiqAeClass.lookup_by_namespace_and_name(ns, klass)
unless aec.nil?
instance.gsub!(".", '\.')
instance.gsub!("*", ".*")
instance.gsub!("?", ".{1}")
instance_re = Regexp.new("^#{instance}$", Regexp::IGNORECASE)
aec.ae_instances.select { |i| instance_re =~ i.name }.each do |aei|
iname = if options[:path]
aei.fqname
else
aei.name
end
result[iname] = aei.field_attributes
end
end
result
end
def instance_get(path)
_log.info("<< path=#{path.inspect}")
aei = __find_instance_from_path(path)
return nil if aei.nil?
aei.field_attributes
end
def instance_delete(path)
_log.info("<< path=#{path.inspect}")
return false unless editable_instance?(path)
aei = __find_instance_from_path(path)
return false if aei.nil?
aei.destroy
true
end
def __find_instance_from_path(path)
dom, ns, klass, instance = MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(path)
return false unless visible_domain?(dom)
aec = MiqAeClass.lookup_by_namespace_and_name("#{dom}/#{ns}", klass)
return nil if aec.nil?
aec.ae_instances.detect { |i| instance.casecmp(i.name).zero? }
end
def field_timeout
raise _("ae_state_max_retries is not set in automate field") if root['ae_state_max_retries'].blank?
interval = root['ae_retry_interval'].present? ? root['ae_retry_interval'].to_i_with_method : 1
interval * root['ae_state_max_retries'].to_i
end
private
def service_object
current['service'] || root['service']
end
def editable_instance?(path)
dom, = MiqAeEngine::MiqAePath.get_domain_ns_klass_inst(path)
return false unless owned_domain?(dom)
domain = MiqAeDomain.lookup_by_fqname(dom, false)
return false unless domain
$log.warn "path=#{path.inspect} : is not editable" unless domain.editable?(@workspace.ae_user)
domain.editable?(@workspace.ae_user)
end
def owned_domain?(dom)
domains = @workspace.ae_user.current_tenant.ae_domains.collect(&:name).map(&:upcase)
return true if domains.include?(dom.upcase)
$log.warn "domain=#{dom} : is not editable"
false
end
def visible_domain?(dom)
domains = @workspace.ae_user.current_tenant.visible_domains.collect(&:name).map(&:upcase)
return true if domains.include?(dom.upcase)
$log.warn "domain=#{dom} : is not viewable"
false
end
def default_notification_type(values_hash)
level = values_hash[:level] || "info"
audience = values_hash[:audience] || "user"
"automate_#{audience}_#{level}".downcase.to_sym
end
end
end
| 28.09201 | 163 | 0.650577 |
386721a33ee35da8a07668ac9166c8ee5f3f7c88 | 144 | name 'build_cookbook'
maintainer 'eternaltyro'
maintainer_email '[email protected]'
license 'mit'
version '0.1.0'
depends 'delivery-truck'
| 18 | 40 | 0.791667 |
ac6498ec7aec43831aa46f8b5b96257c3a211588 | 1,522 | # frozen_string_literal: true
# Cookbook:: travis_build_environment
# Recipe:: ramfs
# Copyright:: 2017 Travis CI GmbH
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
directory node['travis_build_environment']['ramfs_dir'] do
owner 'root'
group 'root'
mode '755'
action :create
end
mount node['travis_build_environment']['ramfs_dir'] do
fstype 'tmpfs'
device 'none'
options %W(
defaults
size=#{node['travis_build_environment']['ramfs_size']}
noatime
)
action %i(mount enable)
end
| 36.238095 | 79 | 0.760841 |
f7cc7b839de0bd24d7f403d74cd9bbd9739ec0f2 | 363 | describe SectionPolicy do
let(:context) { { role: role, real_user: role.end_user } }
describe_rule :manage? do
succeed 'role is an instructor' do
let(:role) { create(:instructor) }
end
failed 'role is a ta' do
let(:role) { create(:ta) }
end
failed 'role is a student' do
let(:role) { create(:student) }
end
end
end
| 24.2 | 60 | 0.61157 |
ffbeac1a6248bd9d5fdd3828d398cf957892b424 | 331 | cask 'understand' do
version '5.0.972'
sha256 '19141b85f34cac4d0c2bc008b2bc44edea496a70320d6966e04f3402f5560ba0'
url "http://builds.scitools.com/all_builds/b#{version.patch}/Understand/Understand-#{version}-MacOSX-x86.dmg"
name 'SciTools Understand'
homepage 'https://scitools.com/features/'
app 'Understand.app'
end
| 30.090909 | 111 | 0.776435 |
187004c128b0b572192a151c90d281f72f285f75 | 2,830 | # Copyright 2011-2012 Rice University. Licensed under the Affero General Public
# License version 3 or later. See the COPYRIGHT file for details.
class QuestionPart < ActiveRecord::Base
belongs_to :multipart_question
belongs_to :child_question, :class_name => 'Question'
validates_presence_of :multipart_question_id, :child_question_id
validates_uniqueness_of :child_question_id, :scope => :multipart_question_id
validates_uniqueness_of :order, :scope => :multipart_question_id, :allow_nil => true
# nil is used as a temporary value to avoid conflicts when sorting
before_create :assign_order
attr_accessible :order
def content_copy
child_question_copy = child_question.is_published? ?
child_question :
child_question.content_copy
kopy = QuestionPart.new(:order => order)
kopy.multipart_question = multipart_question
kopy.child_question = child_question_copy
kopy
end
def unlock!(user)
return false if !child_question.is_published?
self.child_question = child_question.new_derivation!(user, multipart_question.list)
self.save!
multipart_question.check_and_unlock_setup!
true
end
def self.sort(sorted_ids)
QuestionPart.transaction do
next_position = 1
sorted_ids.each do |sorted_id|
part = QuestionPart.find(sorted_id)
if (part.order != next_position) && (
conflicting_part = QuestionPart.find_by_order_and_multipart_question_id(
next_position, part.multipart_question_id))
conflicting_part.order = nil
conflicting_part.save!
end
part.order = next_position
next_position += 1
part.save!
end
end
end
#############################################################################
# Access control methods
#############################################################################
# def can_be_read_by?(user)
# !user.is_anonymous? && ...
# end
#
# def can_be_created_by?(user)
# !user.is_anonymous?
# end
def can_be_updated_by?(user)
!user.is_anonymous? && multipart_question.can_be_updated_by?(user)
end
def can_be_destroyed_by?(user)
!user.is_anonymous? && multipart_question.can_be_updated_by?(user)
end
def can_be_sorted_by?(user)
!user.is_anonymous? && multipart_question.can_be_updated_by?(user)
end
protected
# Opting to go with 1-based indexing here; the first part will likely be
# referred to as part "1", so better for the order number to match
def assign_order
self.order ||= (QuestionPart.where{multipart_question_id == my{multipart_question_id}} \
.maximum('order') || 0) + 1
end
end
| 31.797753 | 92 | 0.640989 |
ff490c611355742ee514f9256e9f2b44f2c7d37b | 693 | require "spec_checkr/version"
class SpecCheckr
def initialize(target, spec_folder)
@target = target
@spec_folder = spec_folder
end
def check
@files_in_target = get_files(@target)
@files_in_spec = get_files(@spec_folder)
print(@files_in_spec)
compare_arrays
end
def get_files(directory)
begin
Dir.entries(directory).select { |f| !File.directory? f }
rescue Errno::ENOENT
print 'Directory not found'
end
end
def compare_arrays
return unless @files_in_target && @files_in_spec
@files_in_target.reject do |f|
sp = f.split('.')
name = sp.first+'_spec'+sp[1]
@files_in_spec.include?(name)
end
end
end
| 21 | 62 | 0.670996 |
263b767784ccd65c6306073f0f2fe7e305a3cc9a | 1,958 | Pod::Spec.new do |spec|
spec.name = 'module'
spec.version = '1.0'
spec.homepage = 'Link to the Shared Module homepage'
spec.source = { :git => "Not Published", :tag => "Cocoapods/#{spec.name}/#{spec.version}" }
spec.authors = ''
spec.license = ''
spec.summary = 'Modulo Compartilhado KMM'
spec.static_framework = true
spec.vendored_frameworks = "build/cocoapods/framework/Megazord_Poke_KMM.framework"
spec.libraries = "c++"
spec.module_name = "#{spec.name}_umbrella"
spec.ios.deployment_target = '14.1'
spec.pod_target_xcconfig = {
'KOTLIN_TARGET[sdk=iphonesimulator*]' => 'ios_x64',
'KOTLIN_TARGET[sdk=iphoneos*]' => 'ios_arm',
'KOTLIN_TARGET[sdk=watchsimulator*]' => 'watchos_x64',
'KOTLIN_TARGET[sdk=watchos*]' => 'watchos_arm',
'KOTLIN_TARGET[sdk=appletvsimulator*]' => 'tvos_x64',
'KOTLIN_TARGET[sdk=appletvos*]' => 'tvos_arm64',
'KOTLIN_TARGET[sdk=macosx*]' => 'macos_x64'
}
spec.script_phases = [
{
:name => 'Build module',
:execution_position => :before_compile,
:shell_path => '/bin/sh',
:script => <<-SCRIPT
set -ev
REPO_ROOT="$PODS_TARGET_SRCROOT"
"$REPO_ROOT/../gradlew" -p "$REPO_ROOT" :module:syncFramework \
-Pkotlin.native.cocoapods.target=$KOTLIN_TARGET \
-Pkotlin.native.cocoapods.configuration=$CONFIGURATION \
-Pkotlin.native.cocoapods.cflags="$OTHER_CFLAGS" \
-Pkotlin.native.cocoapods.paths.headers="$HEADER_SEARCH_PATHS" \
-Pkotlin.native.cocoapods.paths.frameworks="$FRAMEWORK_SEARCH_PATHS"
SCRIPT
}
]
end | 42.565217 | 113 | 0.539326 |
18aa3a23800e16473d63fd89a4f3bfced9a08f36 | 6,692 | # frozen_string_literal: true
module Alchemy
class Page < BaseRecord
module PageElements
extend ActiveSupport::Concern
included do
attr_accessor :autogenerate_elements
with_options(
class_name: "Alchemy::Element",
through: :public_version,
inverse_of: :page,
source: :elements,
) do
has_many :all_elements
has_many :elements, -> { not_nested.unfixed.available }
has_many :fixed_elements, -> { fixed.available }
end
has_many :contents, through: :elements
has_and_belongs_to_many :to_be_swept_elements, -> { distinct },
class_name: "Alchemy::Element",
join_table: ElementToPage.table_name
after_create :generate_elements,
unless: -> { autogenerate_elements == false }
end
module ClassMethods
# Copy page elements
#
# @param source [Alchemy::Page]
# @param target [Alchemy::Page]
# @return [Array]
#
def copy_elements(source, target)
source_elements = source.draft_version.elements.not_nested
source_elements.order(:position).map do |source_element|
Element.copy(source_element, {
page_version_id: target.draft_version.id,
}).tap(&:move_to_bottom)
end
end
end
# All available element definitions that can actually be placed on current page.
#
# It extracts all definitions that are unique or limited and already on page.
#
# == Example of unique element:
#
# - name: headline
# unique: true
# contents:
# - name: headline
# type: EssenceText
#
# == Example of limited element:
#
# - name: article
# amount: 2
# contents:
# - name: text
# type: EssenceRichtext
#
def available_element_definitions(only_element_named = nil)
@_element_definitions ||= if only_element_named
definition = Element.definition_by_name(only_element_named)
element_definitions_by_name(definition["nestable_elements"])
else
element_definitions
end
return [] if @_element_definitions.blank?
existing_elements = draft_version.elements.not_nested
@_existing_element_names = existing_elements.pluck(:name)
delete_unique_element_definitions!
delete_outnumbered_element_definitions!
@_element_definitions
end
# All names of elements that can actually be placed on current page.
#
def available_element_names
@_available_element_names ||= available_element_definitions.map { |e| e["name"] }
end
# Available element definitions excluding nested unique elements.
#
def available_elements_within_current_scope(parent)
@_available_elements = if parent
parents_unique_nested_elements = parent.nested_elements.where(unique: true).pluck(:name)
available_element_definitions(parent.name).reject do |e|
parents_unique_nested_elements.include? e["name"]
end
else
available_element_definitions
end
end
# All element definitions defined for page's page layout
#
# Warning: Since elements can be unique or limited in number,
# it is more safe to ask for +available_element_definitions+
#
def element_definitions
@_element_definitions ||= element_definitions_by_name(element_definition_names)
end
# All element definitions defined for page's page layout including nestable element definitions
#
def descendent_element_definitions
definitions = element_definitions_by_name(element_definition_names)
definitions.select { |d| d.key?("nestable_elements") }.each do |d|
definitions += element_definitions_by_name(d["nestable_elements"])
end
definitions.uniq { |d| d["name"] }
end
# All names of elements that are defined in the page definition.
#
# Assign elements to a page in +config/alchemy/page_layouts.yml+.
#
# == Example of page_layouts.yml:
#
# - name: contact
# elements: [headline, contactform]
#
def element_definition_names
definition["elements"] || []
end
# Element definitions with given name(s)
#
# @param [Array || String]
# one or many Alchemy::Element names. Pass +'all'+ to get all Element definitions
# @return [Array]
# An Array of element definitions
#
def element_definitions_by_name(names)
return [] if names.blank?
if names.to_s == "all"
Element.definitions
else
Element.definitions.select { |e| names.include? e["name"] }
end
end
# Returns all elements that should be feeded via rss.
#
# Define feedable elements in your +page_layouts.yml+:
#
# - name: news
# feed: true
# feed_elements: [element_name, element_2_name]
#
def feed_elements
elements.named(definition["feed_elements"])
end
# Returns an array of all EssenceRichtext contents ids from not folded elements
#
def richtext_contents_ids
Alchemy::Content.joins(:element)
.where(Element.table_name => { page_version_id: draft_version.id, folded: false })
.select(&:has_tinymce?)
.collect(&:id)
end
private
# Looks in the page_layout descripion, if there are elements to autogenerate.
#
# And if so, it generates them.
#
def generate_elements
definition.fetch("autogenerate", []).each do |element_name|
Element.create(page: self, page_version: draft_version, name: element_name)
end
end
# Deletes unique and already present definitions from @_element_definitions.
#
def delete_unique_element_definitions!
@_element_definitions.delete_if do |element|
element["unique"] && @_existing_element_names.include?(element["name"])
end
end
# Deletes limited and outnumbered definitions from @_element_definitions.
#
def delete_outnumbered_element_definitions!
@_element_definitions.delete_if do |element|
outnumbered = @_existing_element_names.select { |name| name == element["name"] }
element["amount"] && outnumbered.count >= element["amount"].to_i
end
end
end
end
end
| 32.485437 | 101 | 0.625224 |
6acf96f62a4d112ec32a888c2ead44edb97c852a | 1,084 | require 'spec_without_rails_helper'
require 'models/single_events_by_day'
describe SingleEventsByDay do
let(:date_one) { Date.new(2013, 12, 25) }
let(:date_two) { Date.new(2013, 12, 26) }
let(:event_on_date_one) { double('SingleEvent', date: date_one) }
let(:event_on_date_two) { double('SingleEvent', date: date_two) }
let(:another_event_on_date_one) { double('SingleEvent', date: date_one) }
let(:event_list) {[ event_on_date_one, event_on_date_two, another_event_on_date_one ]}
describe 'days' do
subject { SingleEventsByDay.new(event_list) }
let(:day_one) { double('Day') }
let(:day_two) { double('Day') }
let(:day_class) { double('DayClass') }
it 'should offer the sorted days with filtered events' do
allow(day_class).to receive(:new)
.with(date_one, [event_on_date_one, another_event_on_date_one])
.and_return(day_one)
allow(day_class).to receive(:new)
.with(date_two, [event_on_date_two])
.and_return(day_two)
expect(subject.days(day_class)).to eq [day_one, day_two]
end
end
end
| 32.848485 | 88 | 0.695572 |
33dc49a6f8aee6037d1ae0e755e78275e0cd1b3e | 2,389 | module Mongoid
module Association
module Referenced
module AutoSave
extend ActiveSupport::Concern
# Used to prevent infinite loops in associated autosaves.
#
# @example Is the document autosaved?
# document.autosaved?
#
# @return [ true, false ] Has the document already been autosaved?
#
# @since 3.0.0
def autosaved?
Threaded.autosaved?(self)
end
# Begin the associated autosave.
#
# @example Begin autosave.
# document.__autosaving__
#
# @since 3.1.3
def __autosaving__
Threaded.begin_autosave(self)
yield
ensure
Threaded.exit_autosave(self)
end
# Check if there is changes for auto-saving
#
# @example Return true if there is changes on self or in
# autosaved relations.
# document.changed_for_autosave?
#
# @since 3.1.3
def changed_for_autosave?(doc)
doc.new_record? || doc.changed? || doc.marked_for_destruction?
end
# Define the autosave method on an association's owning class for
# an associated object.
#
# @example Define the autosave method:
# Association::Referenced::Autosave.define_autosave!(association)
#
# @param [ Association ] association The association for which autosaving is enabled.
#
# @return [ Class ] The association's owner class.
#
# @since 7.0
def self.define_autosave!(association)
association.inverse_class.tap do |klass|
save_method = :"autosave_documents_for_#{association.name}"
klass.send(:define_method, save_method) do
if before_callback_halted?
self.before_callback_halted = false
else
__autosaving__ do
if relation = ivar(association.name)
Array(relation).each do |doc|
doc.with(persistence_context) do |d|
d.save
end
end
end
end
end
end
klass.after_save save_method, unless: :autosaved?
end
end
end
end
end
end
| 29.8625 | 93 | 0.541231 |
3883dffe294b7721a3d4e4ddfd3d9c91b46f9209 | 994 | ENV['DATABASE_ADAPTER'] = 'docker_postgres'
ENV['RACK_ENV'] = 'development'
require 'db'
require 'tasks/database'
require 'pact_broker/db'
PactBroker::DB.connection = PactBroker::Database.database = DB::PACT_BROKER_DB
Approvals.configure do |c|
c.approvals_path = 'regression/fixtures/approvals/'
end
RSpec.configure do | config |
config.before :each do
PactBroker.reset_configuration
PactBroker.configuration.seed_example_data = false
PactBroker.configuration.base_equality_only_on_content_that_affects_verification_results = false
end
config.include Rack::Test::Methods
config.define_derived_metadata do |meta|
meta[:aggregate_failures] = true unless meta.key?(:aggregate_failures)
end
config.example_status_persistence_file_path = "./regression/.examples.txt"
config.filter_run_excluding skip: true
def app
PactBroker::API
end
end
if ENV["DEBUG"] == "true"
SemanticLogger.add_appender(io: $stdout)
SemanticLogger.default_level = :info
end
| 26.157895 | 100 | 0.774648 |
4af72a157dcb301b2257c14f28d3c2c359a0fa71 | 2,908 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::SQL::Mgmt::V2017_03_01_preview
module Models
#
# Scheduling properties of a job.
#
class JobSchedule
include MsRestAzure
# @return [DateTime] Schedule start time. Default value:
# Date.parse('0001-01-01T00:00:00Z') .
attr_accessor :start_time
# @return [DateTime] Schedule end time. Default value:
# Date.parse('9999-12-31T11:59:59Z') .
attr_accessor :end_time
# @return [JobScheduleType] Schedule interval type. Possible values
# include: 'Once', 'Recurring'. Default value: 'Once' .
attr_accessor :type
# @return [Boolean] Whether or not the schedule is enabled.
attr_accessor :enabled
# @return [String] Value of the schedule's recurring interval, if the
# schedule type is recurring. ISO8601 duration format.
attr_accessor :interval
#
# Mapper for JobSchedule class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'JobSchedule',
type: {
name: 'Composite',
class_name: 'JobSchedule',
model_properties: {
start_time: {
client_side_validation: true,
required: false,
serialized_name: 'startTime',
default_value: Date.parse('0001-01-01T00:00:00Z'),
type: {
name: 'DateTime'
}
},
end_time: {
client_side_validation: true,
required: false,
serialized_name: 'endTime',
default_value: Date.parse('9999-12-31T11:59:59Z'),
type: {
name: 'DateTime'
}
},
type: {
client_side_validation: true,
required: false,
serialized_name: 'type',
default_value: 'Once',
type: {
name: 'Enum',
module: 'JobScheduleType'
}
},
enabled: {
client_side_validation: true,
required: false,
serialized_name: 'enabled',
type: {
name: 'Boolean'
}
},
interval: {
client_side_validation: true,
required: false,
serialized_name: 'interval',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 29.373737 | 75 | 0.500688 |
6a4917b2cc52acf5877cb1a19084202c7a6f4b88 | 684 | # Typographical attribute
#
# Indicates that this entity is used to render text.
#
define_attribute :typographical do
# The text to display
property :text
# Acts as a short-circuit for rendering
property :visible, default: true
# Property to store the `Ruby2D::Text` used to render the text
property :text_object
# A `Ruby2D::Font` or `Pixelometry::Font` to use
property :font, default: Font.default
# The font size in points
property :font_size, default: 20
# The angle of rotation
property :rotation, default: 0
# The opacity to render the text at
property :opacity, default: 1.0
# The color for the text
property :color, default: 'white'
end
| 22.8 | 64 | 0.719298 |
21a1d477a2bdd597d419fa4151a9585a33598c1b | 4,135 | require 'base64'
include_recipe 'bcpc-hadoop::hadoop_config'
::Chef::Recipe.send(:include, Bcpc_Hadoop::Helper)
::Chef::Resource::Bash.send(:include, Bcpc_Hadoop::Helper)
hdprel=node[:bcpc][:hadoop][:distribution][:active_release]
hdppath="/usr/hdp/#{hdprel}"
%w{hadoop-hdfs-namenode hadoop-hdfs-journalnode}.each do |pkg|
package hwx_pkg_str(pkg, hdprel) do
action :install
end
hdp_select(pkg, hdprel)
end
[node[:bcpc][:hadoop][:mounts].first].each do |d|
directory "/disk/#{d}/dfs/jn" do
owner "hdfs"
group "hdfs"
mode 0755
action :create
recursive true
end
directory "/disk/#{d}/dfs/jn/#{node.chef_environment}" do
owner "hdfs"
group "hdfs"
mode 0755
action :create
recursive true
end
end
jndisk="/disk/#{node[:bcpc][:hadoop][:mounts][0]}"
jnfile="/dfs/jn/#{node.chef_environment}/current/VERSION"
jncurrent="/dfs/jn/#{node.chef_environment}/current"
jnfile2chk=jndisk + jnfile
if get_config("jn_txn_fmt") then
file "#{Chef::Config[:file_cache_path]}/jn_fmt.tgz" do
user "hdfs"
group "hdfs"
user 0644
content Base64.decode64(get_config("jn_txn_fmt"))
not_if{File.exists?(jnfile2chk)}
end
end
bash "unpack-jn-fmt-image-to-disk-#{jndisk}" do
user "root"
cwd "#{jndisk}/dfs/"
code "tar xzvf #{Chef::Config[:file_cache_path]}/jn_fmt.tgz;"
notifies :restart, "service[hadoop-hdfs-journalnode]"
notifies :run, "bash[change-ownership-for-jnfile]", :immediate
only_if{not get_config("jn_txn_fmt").nil? and not
File.exists?(jnfile2chk)}
end
bash "change-ownership-for-jnfile" do
user "root"
cwd "#{jndisk}/dfs/jn"
code "chown -R hdfs:hdfs #{node.chef_environment}"
action :nothing
end
directory "#{jndisk}#{jncurrent}/paxos" do
owner "hdfs"
group "hdfs"
mode 0755
action :create
recursive true
only_if { File.exists?(jnfile2chk) }
end
# need to ensure hdfs user is in hadoop and hdfs
# groups. Packages will not add hdfs if it
# is already created at install time (e.g. if
# machine is using LDAP for users).
# Create all the resources to add them in resource collection
node[:bcpc][:hadoop][:os][:group].keys.each do |group_name|
node[:bcpc][:hadoop][:os][:group][group_name][:members].each do|user_name|
user user_name do
home "/var/lib/hadoop-#{user_name}"
shell '/bin/bash'
system true
action :create
not_if { user_exists?(user_name) }
end
end
group group_name do
append true
members node[:bcpc][:hadoop][:os][:group][group_name][:members]
action :nothing
end
end
# Take action on each group resource based on its existence
ruby_block 'create_or_manage_groups' do
block do
node[:bcpc][:hadoop][:os][:group].keys.each do |group_name|
res = run_context.resource_collection.find("group[#{group_name}]")
res.run_action(get_group_action(group_name))
end
end
end
link "/etc/init.d/hadoop-hdfs-journalnode" do
to "#{hdppath}/hadoop-hdfs/etc/init.d/hadoop-hdfs-journalnode"
notifies :run, 'bash[kill hdfs-journalnode]', :immediate
end
configure_kerberos 'namenode_kerb' do
service_name 'namenode'
end
configure_kerberos 'journalnode_kerb' do
service_name 'journalnode'
end
bash "kill hdfs-journalnode" do
code "pkill -u hdfs -f journalnode"
action :nothing
returns [0, 1]
end
jnKeytab = node[:bcpc][:hadoop][:kerberos][:data][:journalnode][:keytab]
nnKeytab = node[:bcpc][:hadoop][:kerberos][:data][:namenode][:keytab]
keyTabDir = node[:bcpc][:hadoop][:kerberos][:keytab][:dir]
service "hadoop-hdfs-journalnode" do
action [:start, :enable]
supports :status => true, :restart => true, :reload => false
subscribes :restart, "link[/etc/init.d/hadoop-hdfs-journalnode]", :delayed
subscribes :restart, "template[/etc/hadoop/conf/hdfs-site.xml]", :delayed
subscribes :restart, "template[/etc/hadoop/conf/hdfs-site_HA.xml]", :delayed
subscribes :restart, "template[/etc/hadoop/conf/hadoop-env.sh]", :delayed
subscribes :restart, "file[#{keyTabDir}/#{jnKeytab}]", :delayed
subscribes :restart, "file[#{keyTabDir}/#{nnKeytab}]", :delayed
subscribes :restart, "log[jdk-version-changed]", :delayed
end
| 28.715278 | 78 | 0.702539 |
d5a1caaaeeb85984be901bdf5d7de692c09060ad | 36 | module Eth
VERSION = "0.4.17"
end
| 9 | 20 | 0.638889 |
26e2402a18da9d3b2e9dc0666008276c6abfd3f7 | 2,644 | # Implementation class for Cancan gem. Instead of overriding this class, consider adding new permissions
# using the special +register_ability+ method which allows extensions to add their own abilities.
#
# See http://github.com/ryanb/cancan for more details on cancan.
require 'cancan'
module Spree
class Ability
include CanCan::Ability
class_attribute :abilities
self.abilities = Set.new
# Allows us to go beyond the standard cancan initialize method which makes it difficult for engines to
# modify the default +Ability+ of an application. The +ability+ argument must be a class that includes
# the +CanCan::Ability+ module. The registered ability should behave properly as a stand-alone class
# and therefore should be easy to test in isolation.
def self.register_ability(ability)
self.abilities.add(ability)
end
def self.remove_ability(ability)
self.abilities.delete(ability)
end
def initialize(user)
self.clear_aliased_actions
# override cancan default aliasing (we don't want to differentiate between read and index)
alias_action :delete, to: :destroy
alias_action :edit, to: :update
alias_action :new, to: :create
alias_action :new_action, to: :create
alias_action :show, to: :read
user ||= Spree.user_class.new
if user.respond_to?(:has_spree_role?) && user.has_spree_role?('admin')
can :manage, :all
else
can [:index, :read], Country
can [:index, :read], OptionType
can [:index, :read], OptionValue
can :create, Order
can :read, Order do |order, token|
order.user == user || order.token && token == order.token
end
can :update, Order do |order, token|
order.user == user || order.token && token == order.token
end
can [:create, :read], Address
can :update, Address do |address|
user.bill_address == address || user.ship_address == address
end
can [:index, :read], Product
can [:index, :read], ProductProperty
can [:index, :read], Property
can :create, Spree.user_class
can [:read, :update, :destroy], Spree.user_class, id: user.id
can [:index, :read], State
can [:index, :read], Taxon
can [:index, :read], Taxonomy
can [:index, :read], Variant
can [:index, :read], Zone
end
# Include any abilities registered by extensions, etc.
Ability.abilities.each do |clazz|
ability = clazz.send(:new, user)
@rules = rules + ability.send(:rules)
end
end
end
end
| 35.72973 | 107 | 0.645234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.