CombinedText stringlengths 4 3.42M |
|---|
# Encoding: utf-8
# Cloud Foundry Java Buildpack
# Copyright 2013-2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'java_buildpack/component/base_component'
require 'java_buildpack/framework'
require 'java_buildpack/util/dash_case'
module JavaBuildpack
module Framework
# Encapsulates the functionality for contributing Java JMX options to an application.
class Jmx < JavaBuildpack::Component::BaseComponent
# (see JavaBuildpack::Component::BaseComponent#detect)
def detect
enabled? ? "#{Jmx.to_s.dash_case}=#{port}" : nil
end
# (see JavaBuildpack::Component::BaseComponent#compile)
def compile
end
# (see JavaBuildpack::Component::BaseComponent#release)
def release
@droplet.java_opts
.add_system_property('java.rmi.server.hostname', '127.0.0.1')
.add_system_property('com.sun.management.jmxremote.authenticate', false)
.add_system_property('com.sun.management.jmxremote.port', port)
.add_system_property('com.sun.management.jmxremote.rmi.port', port)
end
private
def enabled?
@configuration['enabled']
end
def port
@configuration['port'] || 5000
end
end
end
end
JMX RMI Port Fix
This change updates the JMX framework to fix a problem where the port
number of the JMX RMI server overlapped with the JMX connector port.
# Encoding: utf-8
# Cloud Foundry Java Buildpack
# Copyright 2013-2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'java_buildpack/component/base_component'
require 'java_buildpack/framework'
require 'java_buildpack/util/dash_case'
module JavaBuildpack
module Framework
# Encapsulates the functionality for contributing Java JMX options to an application.
class Jmx < JavaBuildpack::Component::BaseComponent
# (see JavaBuildpack::Component::BaseComponent#detect)
def detect
enabled? ? "#{Jmx.to_s.dash_case}=#{port}" : nil
end
# (see JavaBuildpack::Component::BaseComponent#compile)
def compile
end
# (see JavaBuildpack::Component::BaseComponent#release)
def release
@droplet.java_opts
.add_system_property('java.rmi.server.hostname', '127.0.0.1')
.add_system_property('com.sun.management.jmxremote.authenticate', false)
.add_system_property('com.sun.management.jmxremote.port', port)
.add_system_property('com.sun.management.jmxremote.rmi.port', port + 1)
end
private
def enabled?
@configuration['enabled']
end
def port
@configuration['port'] || 5000
end
end
end
end
|
module Jekyll
module AssetsPlugin
VERSION = "0.10.0"
end
end
Release v0.10.1
module Jekyll
module AssetsPlugin
VERSION = "0.10.1"
end
end
|
module JqueryExpandAssets
VERSION = '0.0.5'
end
version 0.0.6
module JqueryExpandAssets
VERSION = '0.0.6'
end
|
require 'sinatra'
require 'sinatra/reloader' if development?
require 'sinatra/activerecord'
require 'redcarpet'
require 'sinatra/json'
require 'qiniu-rs'
require 'roo'
configure :development do
set :public_folder, File.dirname(__FILE__) + '/public/src/'
set :random, (Time.now.to_f * 1000).to_i.to_s
end
configure :production do
set :public_folder, File.dirname(__FILE__) + '/public/dist/'
set :random, (Time.now.to_f * 1000).to_i.to_s
set :static_cache_control, [:public, :max_age => 3600*24*30*12]
end
Qiniu::RS.establish_connection! :access_key => '4drJ2mqHlMuy1sXSfd7W9KYQj3Z9iBAWUZ5kC-9g',
:secret_key => '75lbFP5RQIjkZAlcnAGdKIOyxJlPuxVCsAoBLEXj'
class Song < ActiveRecord::Base
end
class Resource < ActiveRecord::Base
end
def encode_object(obj)
if obj
obj.attributes.each do |key, value|
if obj[key].is_a? String
obj[key].force_encoding("UTF-8")
end
end
end
obj
end
def encode_list(list)
list.each do |obj|
obj = encode_object(obj)
end
list
end
get '/dev-blog' do
markdown :dev_blog, :layout_engine => :erb, :layout => :dev_blog_layout
end
get '/songs' do
@etag = Song.maximum('updated_at').strftime('%Y%m%d%H%M%S') + '/' + Song.count.to_s
last_modified @etag
etag @etag
songs = Song.all.order('`index`')
json encode_list(songs)
end
get '/songs/:id' do
song = Song.find_by_id(params[:id].to_i)
resources = get_resources_by_song_id(params[:id].to_i)
if song
re = encode_object(song).attributes
re['resources'] = encode_list(resources)
json re
else
re = { :error => true }
json re
end
end
get '/songs_category/:category_name' do
songs = Song.where('category_big = ?', params[:category_name]).order('`index`')
json encode_list(songs)
end
def save_song(song, obj)
if song
song.attributes.each do |key, value|
if key != 'id'
if obj[key]
song[key] = obj[key]
end
end
end
song.save
end
end
def add_resources(resources, song_id)
if(resources.length>0)
resources.each do |obj|
current_resource = Resource.where('song_id = ? and file_name = ?', song_id, obj['file_name'])
if(current_resource.count==0)
new_resource = Resource.new
new_resource.attributes.each do |key, value|
if key != 'id'
if obj[key]
new_resource[key] = obj[key]
end
end
end
new_resource['song_id'] = song_id
new_resource['stars'] = 0
new_resource.save
end
end
end
get_resources_by_song_id(song_id)
end
def get_resources_by_song_id(song_id)
Resource.where('song_id = ?', song_id).order('stars desc')
end
put '/songs/:id' do
request.body.rewind # in case someone already read it
data = JSON.parse request.body.read
song = Song.find_by_id(params[:id].to_i)
if(song&&save_song(song, data))
resources = add_resources(data['resources'], song.id)
src = get_most_starred_resource_src_by_song_id(song.id)
update_song_src_by_song_id(src, song.id)
re = encode_object(song).attributes
re['resources'] = encode_list(resources)
json re
else
re = { :error => true }
json re
end
end
post '/songs' do
request.body.rewind # in case someone already read it
data = JSON.parse request.body.read
song = Song.new
if(song&&save_song(song, data))
resources = add_resources(data['resources'], song.id)
src = get_most_starred_resource_src_by_song_id(song.id)
update_song_src_by_song_id(src, song.id)
re = encode_object(song).attributes
re['resources'] = encode_list(resources)
json re
else
re = { :error => true }
json re
end
end
delete '/songs/:id' do
param = (params[:id]).to_i
resources = get_resources_by_song_id(param)
resources.each do |resource|
delete_resource_from_cloud_by_resource_key(resource['file_name'])
resource.delete
end
json Song.delete(param)
end
delete '/resources/:id' do
param = (params[:id]).to_i
resource = Resource.find_by_id(param)
delete_resource_from_cloud_by_resource_key(resource['file_name'])
if resource.delete
src = get_most_starred_resource_src_by_song_id(resource['song_id'])
update_song_src_by_song_id(src, resource['song_id'])
json true
end
end
patch '/resources/:id' do
request.body.rewind # in case someone already read it
data = JSON.parse request.body.read
obj = data
resource = Resource.find_by_id(params[:id].to_i)
if resource
resource.attributes.each do |key, value|
if key != 'id'
if obj[key]
resource[key] = obj[key]
end
end
end
if obj['plus']
resource['stars'] += obj['plus'].to_i
end
resource.save
src = get_most_starred_resource_src_by_song_id(resource['song_id'])
update_song_src_by_song_id(src, resource['song_id'])
re = encode_object(resource).attributes
json re
else
re = { :error => true }
json re
end
end
def get_most_starred_resource_src_by_song_id(song_id)
src = {}
resources = Resource.where('song_id = ?', song_id).order('stars desc')
t = encode_object(resources.where('file_type = ?', 'song').first)
src['song_src'] = t ? t['file_name'] : nil
t = encode_object(resources.where('file_type = ?', 'pic').first)
src['pic_src'] = t ? t['file_name'] : nil
src
end
def update_song_src_by_song_id(src, song_id)
song = Song.find_by_id(song_id)
if song
song['song_src'] = src['song_src']
song['pic_src'] = src['pic_src']
song.save
end
end
def delete_resource_from_cloud_by_resource_key(resource_key)
Qiniu::RS.delete('production-1050', resource_key)
end
### import start
get '/interface' do
erb :interface, :layout => :layout
end
post '/interface' do
msg = "请选择Excel文件!<a href='/interface'>返回重试</a>"
if(params[:song_file])
path = 'uploads/' + params[:song_file][:filename]
extension = path.slice(path.index('.'), path.length - path.index('.'))
if(extension == '.xlsx' || extension == '.xls')
File.open(path, "wb") do |f|
f.write(params[:song_file][:tempfile].read)
end
renamed_path = 'uploads/' + (Time.now.to_f * 1000).to_i.to_s + '_' + params[:song_file][:filename]
File.rename(path, renamed_path)
if import_songs_from_excel(renamed_path, extension)
msg = "恭喜,诗歌导入成功!<a href='/interface'>返回</a>"
else
"操作失败!<a href='/interface'>返回重试</a>"
end
else
msg = "只支持Excel文件!<a href='/interface'>返回重试</a>"
end
end
if(params[:resource_file])
path = 'uploads/' + params[:resource_file][:filename]
extension = path.slice(path.index('.'), path.length - path.index('.'))
if(extension == '.xlsx' || extension == '.xls')
File.open(path, "wb") do |f|
f.write(params[:resource_file][:tempfile].read)
end
renamed_path = 'uploads/' + (Time.now.to_f * 1000).to_i.to_s + '_' + params[:resource_file][:filename]
File.rename(path, renamed_path)
if import_resources_from_excel(renamed_path, extension)
msg = "恭喜,资源导入成功!<a href='/interface'>返回</a>"
else
"操作失败!<a href='/interface'>返回重试</a>"
end
else
msg = "只支持Excel文件!<a href='/interface'>返回重试</a>"
end
end
msg
end
def read_excel(path, extension)
if(extension == '.xlsx')
s = Roo::Excelx.new(path)
elsif(extension == '.xls')
s = Roo::Excel.new(path)
end
s.default_sheet = s.sheets.first
s
end
def convert_excel_to_list(s, attr_array)
list = []
2.upto(s.last_row) do |row|
obj = {}
attr_array.length.times do |i|
obj[attr_array[i]] = (s.cell(row, i+1)).to_s
end
obj = reset_obj_attr(obj)
if is_obj_pass_condition?(obj)
list.push(obj)
end
end
list
end
def reset_obj_attr(obj)
if(obj['index'])
obj['index'] = obj['index'].to_i
end
obj
end
def is_obj_pass_condition?(obj)
if(obj['index'])
if (obj['index'] > 0) && !(obj['name'].strip.empty?)
return true
end
return false
end
return true
end
def import_songs_from_excel(path, extension)
attr_array = ['index', 'name', 'first_sentence', 'category_big', 'category_small', 'song_src', 'pic_src']
s = read_excel(path, extension)
list = convert_excel_to_list(s, attr_array)
list.each do |obj|
song = Song.find_by_index(obj['index'].to_i)
if(!song)
song = Song.new
end
song.attributes.each do |key, value|
if obj[key]
song[key] = obj[key]
end
end
song.save
end
return true
end
def import_resources_from_excel(path, extension)
attr_array = ['name', 'file_name', 'file_size', 'file_type']
s = read_excel(path, extension)
list = convert_excel_to_list(s, attr_array)
list.each do |obj|
song = Song.find_by_name(obj['name'].force_encoding("UTF-8"))
if(song)
resource = Resource.where('song_id = ? and file_name = ?', song['id'], obj['file_name'].force_encoding("UTF-8"))
if(resource.count == 0)
resource = Resource.new
resource.attributes.each do |key, value|
if(obj[key] && obj[key] != 'name')
resource[key] = obj[key]
end
resource['song_id'] = song['id']
resource['stars'] = 0
end
resource.save
end
end
end
return true
end
### import end
get '/cache' do
cache_control :max_age => 10
"hello" + "**" + Time.now.to_s
end
get '*' do
@token = Qiniu::RS.generate_upload_token :scope => 'production-1050'
erb :index, :layout => :app_layout
end
fixbug_etag
require 'sinatra'
require 'sinatra/reloader' if development?
require 'sinatra/activerecord'
require 'redcarpet'
require 'sinatra/json'
require 'qiniu-rs'
require 'roo'
configure :development do
set :public_folder, File.dirname(__FILE__) + '/public/src/'
set :random, (Time.now.to_f * 1000).to_i.to_s
end
configure :production do
set :public_folder, File.dirname(__FILE__) + '/public/dist/'
set :random, (Time.now.to_f * 1000).to_i.to_s
set :static_cache_control, [:public, :max_age => 3600*24*30*12]
end
Qiniu::RS.establish_connection! :access_key => '4drJ2mqHlMuy1sXSfd7W9KYQj3Z9iBAWUZ5kC-9g',
:secret_key => '75lbFP5RQIjkZAlcnAGdKIOyxJlPuxVCsAoBLEXj'
class Song < ActiveRecord::Base
end
class Resource < ActiveRecord::Base
end
def encode_object(obj)
if obj
obj.attributes.each do |key, value|
if obj[key].is_a? String
obj[key].force_encoding("UTF-8")
end
end
end
obj
end
def encode_list(list)
list.each do |obj|
obj = encode_object(obj)
end
list
end
get '/dev-blog' do
markdown :dev_blog, :layout_engine => :erb, :layout => :dev_blog_layout
end
get '/songs' do
@etag = Song.maximum('updated_at').to_s + '/' + Song.count.to_s
last_modified @etag
etag @etag
songs = Song.all.order('`index`')
json encode_list(songs)
end
get '/songs/:id' do
song = Song.find_by_id(params[:id].to_i)
resources = get_resources_by_song_id(params[:id].to_i)
if song
re = encode_object(song).attributes
re['resources'] = encode_list(resources)
json re
else
re = { :error => true }
json re
end
end
get '/songs_category/:category_name' do
songs = Song.where('category_big = ?', params[:category_name]).order('`index`')
json encode_list(songs)
end
def save_song(song, obj)
if song
song.attributes.each do |key, value|
if key != 'id'
if obj[key]
song[key] = obj[key]
end
end
end
song.save
end
end
def add_resources(resources, song_id)
if(resources.length>0)
resources.each do |obj|
current_resource = Resource.where('song_id = ? and file_name = ?', song_id, obj['file_name'])
if(current_resource.count==0)
new_resource = Resource.new
new_resource.attributes.each do |key, value|
if key != 'id'
if obj[key]
new_resource[key] = obj[key]
end
end
end
new_resource['song_id'] = song_id
new_resource['stars'] = 0
new_resource.save
end
end
end
get_resources_by_song_id(song_id)
end
def get_resources_by_song_id(song_id)
Resource.where('song_id = ?', song_id).order('stars desc')
end
put '/songs/:id' do
request.body.rewind # in case someone already read it
data = JSON.parse request.body.read
song = Song.find_by_id(params[:id].to_i)
if(song&&save_song(song, data))
resources = add_resources(data['resources'], song.id)
src = get_most_starred_resource_src_by_song_id(song.id)
update_song_src_by_song_id(src, song.id)
re = encode_object(song).attributes
re['resources'] = encode_list(resources)
json re
else
re = { :error => true }
json re
end
end
post '/songs' do
request.body.rewind # in case someone already read it
data = JSON.parse request.body.read
song = Song.new
if(song&&save_song(song, data))
resources = add_resources(data['resources'], song.id)
src = get_most_starred_resource_src_by_song_id(song.id)
update_song_src_by_song_id(src, song.id)
re = encode_object(song).attributes
re['resources'] = encode_list(resources)
json re
else
re = { :error => true }
json re
end
end
delete '/songs/:id' do
param = (params[:id]).to_i
resources = get_resources_by_song_id(param)
resources.each do |resource|
delete_resource_from_cloud_by_resource_key(resource['file_name'])
resource.delete
end
json Song.delete(param)
end
delete '/resources/:id' do
param = (params[:id]).to_i
resource = Resource.find_by_id(param)
delete_resource_from_cloud_by_resource_key(resource['file_name'])
if resource.delete
src = get_most_starred_resource_src_by_song_id(resource['song_id'])
update_song_src_by_song_id(src, resource['song_id'])
json true
end
end
patch '/resources/:id' do
request.body.rewind # in case someone already read it
data = JSON.parse request.body.read
obj = data
resource = Resource.find_by_id(params[:id].to_i)
if resource
resource.attributes.each do |key, value|
if key != 'id'
if obj[key]
resource[key] = obj[key]
end
end
end
if obj['plus']
resource['stars'] += obj['plus'].to_i
end
resource.save
src = get_most_starred_resource_src_by_song_id(resource['song_id'])
update_song_src_by_song_id(src, resource['song_id'])
re = encode_object(resource).attributes
json re
else
re = { :error => true }
json re
end
end
def get_most_starred_resource_src_by_song_id(song_id)
src = {}
resources = Resource.where('song_id = ?', song_id).order('stars desc')
t = encode_object(resources.where('file_type = ?', 'song').first)
src['song_src'] = t ? t['file_name'] : nil
t = encode_object(resources.where('file_type = ?', 'pic').first)
src['pic_src'] = t ? t['file_name'] : nil
src
end
def update_song_src_by_song_id(src, song_id)
song = Song.find_by_id(song_id)
if song
song['song_src'] = src['song_src']
song['pic_src'] = src['pic_src']
song.save
end
end
def delete_resource_from_cloud_by_resource_key(resource_key)
Qiniu::RS.delete('production-1050', resource_key)
end
### import start
get '/interface' do
erb :interface, :layout => :layout
end
post '/interface' do
msg = "请选择Excel文件!<a href='/interface'>返回重试</a>"
if(params[:song_file])
path = 'uploads/' + params[:song_file][:filename]
extension = path.slice(path.index('.'), path.length - path.index('.'))
if(extension == '.xlsx' || extension == '.xls')
File.open(path, "wb") do |f|
f.write(params[:song_file][:tempfile].read)
end
renamed_path = 'uploads/' + (Time.now.to_f * 1000).to_i.to_s + '_' + params[:song_file][:filename]
File.rename(path, renamed_path)
if import_songs_from_excel(renamed_path, extension)
msg = "恭喜,诗歌导入成功!<a href='/interface'>返回</a>"
else
"操作失败!<a href='/interface'>返回重试</a>"
end
else
msg = "只支持Excel文件!<a href='/interface'>返回重试</a>"
end
end
if(params[:resource_file])
path = 'uploads/' + params[:resource_file][:filename]
extension = path.slice(path.index('.'), path.length - path.index('.'))
if(extension == '.xlsx' || extension == '.xls')
File.open(path, "wb") do |f|
f.write(params[:resource_file][:tempfile].read)
end
renamed_path = 'uploads/' + (Time.now.to_f * 1000).to_i.to_s + '_' + params[:resource_file][:filename]
File.rename(path, renamed_path)
if import_resources_from_excel(renamed_path, extension)
msg = "恭喜,资源导入成功!<a href='/interface'>返回</a>"
else
"操作失败!<a href='/interface'>返回重试</a>"
end
else
msg = "只支持Excel文件!<a href='/interface'>返回重试</a>"
end
end
msg
end
def read_excel(path, extension)
if(extension == '.xlsx')
s = Roo::Excelx.new(path)
elsif(extension == '.xls')
s = Roo::Excel.new(path)
end
s.default_sheet = s.sheets.first
s
end
def convert_excel_to_list(s, attr_array)
list = []
2.upto(s.last_row) do |row|
obj = {}
attr_array.length.times do |i|
obj[attr_array[i]] = (s.cell(row, i+1)).to_s
end
obj = reset_obj_attr(obj)
if is_obj_pass_condition?(obj)
list.push(obj)
end
end
list
end
def reset_obj_attr(obj)
if(obj['index'])
obj['index'] = obj['index'].to_i
end
obj
end
def is_obj_pass_condition?(obj)
if(obj['index'])
if (obj['index'] > 0) && !(obj['name'].strip.empty?)
return true
end
return false
end
return true
end
def import_songs_from_excel(path, extension)
attr_array = ['index', 'name', 'first_sentence', 'category_big', 'category_small', 'song_src', 'pic_src']
s = read_excel(path, extension)
list = convert_excel_to_list(s, attr_array)
list.each do |obj|
song = Song.find_by_index(obj['index'].to_i)
if(!song)
song = Song.new
end
song.attributes.each do |key, value|
if obj[key]
song[key] = obj[key]
end
end
song.save
end
return true
end
def import_resources_from_excel(path, extension)
attr_array = ['name', 'file_name', 'file_size', 'file_type']
s = read_excel(path, extension)
list = convert_excel_to_list(s, attr_array)
list.each do |obj|
song = Song.find_by_name(obj['name'].force_encoding("UTF-8"))
if(song)
resource = Resource.where('song_id = ? and file_name = ?', song['id'], obj['file_name'].force_encoding("UTF-8"))
if(resource.count == 0)
resource = Resource.new
resource.attributes.each do |key, value|
if(obj[key] && obj[key] != 'name')
resource[key] = obj[key]
end
resource['song_id'] = song['id']
resource['stars'] = 0
end
resource.save
end
end
end
return true
end
### import end
get '/cache' do
cache_control :max_age => 10
"hello" + "**" + Time.now.to_s
end
get '*' do
@token = Qiniu::RS.generate_upload_token :scope => 'production-1050'
erb :index, :layout => :app_layout
end
|
require 'sinatra'
require 'slim'
require 'sass'
require 'data_mapper'
require 'dm-postgres-adapter'
require 'pathname'
configure :development do
require 'dm-sqlite-adapter'
end
configure do
set :slim, pretty: true
APP_ROOT = Pathname.new(__FILE__).expand_path.dirname
DB_DIR = APP_ROOT + 'db'
DB_DIR.mkpath
DataMapper.setup(:default,
ENV['DATABASE_URL'] || "sqlite://#{DB_DIR}/tdrb.db")
end
class Task
include DataMapper::Resource
property :id, Serial
property :body, Text, required: true
property :done, Boolean, default: false
end
configure do
DataMapper.auto_upgrade!
end
get '/' do
@tasks = Task.all
slim :index
end
get '/new' do
slim :new
end
post '/create' do
Task.create(params[:task])
redirect('/')
end
get '*' do
redirect('/')
end
__END__
@@ layout
doctype 5
html
head
meta(charset='utf-8')
title = @title
sass:
body
font: 20px "Myriad Pro"
input
outline: none
border: none
background: #ccc
font: 20px "Myriad Pro"
padding: 2px
input:focus
outline: none
body
== yield
@@ index
ul
- @tasks.each do |task|
li = task.body
a href='/new' New
@@ new
h3 New task
form(action='/create' method='post' id='task')
label(for='body') body:
input(type='text' name='task[body]' id='body' value='description')
input(type='submit')
Add a 'delete' link to 'index'
require 'sinatra'
require 'slim'
require 'sass'
require 'data_mapper'
require 'dm-postgres-adapter'
require 'pathname'
configure :development do
require 'dm-sqlite-adapter'
end
configure do
set :slim, pretty: true
APP_ROOT = Pathname.new(__FILE__).expand_path.dirname
DB_DIR = APP_ROOT + 'db'
DB_DIR.mkpath
DataMapper.setup(:default,
ENV['DATABASE_URL'] || "sqlite://#{DB_DIR}/tdrb.db")
end
class Task
include DataMapper::Resource
property :id, Serial
property :body, Text, required: true
property :done, Boolean, default: false
end
configure do
DataMapper.auto_upgrade!
end
get '/' do
@tasks = Task.all
slim :index
end
get '/new' do
slim :new
end
post '/create' do
Task.create(params[:task])
redirect('/')
end
get '*' do
redirect('/')
end
__END__
@@ layout
doctype 5
html
head
meta(charset='utf-8')
title = @title
sass:
body
font: 20px "Myriad Pro"
input
outline: none
border: none
background: #ccc
font: 20px "Myriad Pro"
padding: 2px
input:focus
outline: none
body
== yield
@@ index
ul
- @tasks.each do |task|
li
= task.body + ' '
a href="/delete/#{task.id}" delete
a href='/new' New
@@ new
h3 New task
form(action='/create' method='post' id='task')
label(for='body') body:
input(type='text' name='task[body]' id='body' value='description')
input(type='submit')
|
#!/usr/bin/env ruby
require 'sinatra'
require 'sinatra/jsonp'
# GET /
get '/' do
"Welcome! You've reached the base endpoint of this terse API"
end
# GET /download
#
# Serve the update file
get '/download' do
major = params[:major]
minor = params[:minor]
patch = params[:patch]
'You are at the endpoint for downloading an update\n' <<
"You are trying to download #{major}.#{minor}.#{patch}"
end
# GET /update
#
# Reply with the JSON object of the most up-to-date version available.
#
# Example JSON response:
# {
# "publisher": "Distributed Interactive Mobile Gaming, Inc.",
# "publishDate": "2016-02-29",
# "version": "0.4.2",
# "size": 732087,
# "minFrameworkVer": "1.0.1",
# "download": "https://dimg.com/download?major=0&minor=4&patch=2"
# }
get '/update' do
json_resp = {
publisher: 'Distributed Interactive Mobile Gaming, Inc.',
publishDate: Time.now,
version: '0.50.1',
size: File.size('README.md'),
minFrameworkVer: '1.0.5',
download: 'https://dimg.com/download?major=0&minor=50&patch=1'
}
JSONP json_resp
end
Finish GET / and GET /update
#!/usr/bin/env ruby
require 'sinatra'
require 'sinatra/jsonp'
# GET /
get '/' do
body = "Sorry, all the coffee has been drunk. Please see Dr Urbain for\
recommendations, and buy him a cup while you're at it."
body.reverse! if params[:wumbo]
[418, body]
end
# GET /download /download?major=1 ...&minor=2 ...&patch=3
#
# Serve the update file
get '/download' do
major = params[:major] || 0
minor = params[:minor] || 0
patch = params[:patch] || 0
update_file = Dir.new "updates/#{major}/#{minor}/#{patch}"
puts update_file
'You are at the endpoint for downloading an update\n' <<
"You are trying to download #{major}.#{minor}.#{patch}"
end
# GET /update
#
# Reply with the JSON object of the most up-to-date version available.
#
# Example JSON response:
# {
# "publisher": "Distributed Interactive Mobile Gaming, Inc.",
# "publishDate": "2016-02-29",
# "version": "0.4.2",
# "size": 732087,
# "minFrameworkVer": "1.0.1",
# "download": "https://dimg.com/download?major=0&minor=4&patch=2"
# }
get '/update' do
prng = Random.new
upd_maj = prng.rand 10
upd_min = prng.rand 6
upd_pat = prng.rand 30
json_resp = {
publisher: 'Distributed Interactive Mobile Gaming, Inc.',
publishDate: Time.now + prng.rand(1...2000000),
version: "#{upd_maj}.#{upd_min}.#{upd_pat}",
size: prng.rand(1000000),
minFrameworkVer: "#{prng.rand(5)}.#{prng.rand(2)}.#{prng.rand(10)}",
download: "https://dimg.com/download?major=#{upd_maj}" <<
"&minor=#{upd_min}&patch=#{upd_pat}"
}
JSONP json_resp
end
|
require 'rubygems'
require 'sinatra'
require 'sinatra/activerecord'
require 'socket'
set :database, 'postgres://ip:ip@localhost/ips'
def hostname(ip)
begin
address_parts = ip.split(/\./).map(&:to_i)
hostname = Socket.gethostbyaddr(address_parts.pack('CCCC')).first
rescue SocketError
hostname = nil
end
hostname
end
class IP < ActiveRecord::Base
attr_accessible :name, :ip
end
get '/' do
@ip = env['REMOTE_ADDR']
@hostname = hostname(@ip) if @ip
@forwarded = env['HTTP_X_FORWARDED_FOR']
@forwarded_host = hostname(@forwarded) if @forwarded
erb :'index.html'
end
get '/:host' do |host|
@host = host
record = IP.find_by_host(host)
if record
@ip = record.ip
erb :'show.html'
else
erb :'unknown.html'
end
end
post '/:host' do |host|
record = IP.find_by_host(host)
unless record
record = IP.new
record.host = host
end
record.ip = env['REMOTE_ADDR']
record.save!
redirect "/#{host}"
end
Change get/set IP URLs to /host/:host
require 'rubygems'
require 'sinatra'
require 'sinatra/activerecord'
require 'socket'
set :database, 'postgres://ip:ip@localhost/ips'
def hostname(ip)
begin
address_parts = ip.split(/\./).map(&:to_i)
hostname = Socket.gethostbyaddr(address_parts.pack('CCCC')).first
rescue SocketError
hostname = nil
end
hostname
end
class IP < ActiveRecord::Base
attr_accessible :name, :ip
end
get '/' do
@ip = env['REMOTE_ADDR']
@hostname = hostname(@ip) if @ip
@forwarded = env['HTTP_X_FORWARDED_FOR']
@forwarded_host = hostname(@forwarded) if @forwarded
erb :'index.html'
end
get '/host/:host' do |host|
@host = host
record = IP.find_by_host(host)
if record
@ip = record.ip
erb :'show.html'
else
erb :'unknown.html'
end
end
post '/host/:host' do |host|
record = IP.find_by_host(host)
unless record
record = IP.new
record.host = host
end
record.ip = env['REMOTE_ADDR']
record.save!
redirect "/#{host}"
end
|
#!/usr/bin/env ruby
$LOAD_PATH.unshift File.dirname(__FILE__) + '/lib'
require 'sinatra'
require 'tweetstream'
require 'yaml'
require 'twitter'
require 'httparty'
require 'geo2gov'
require 'sinatra/activerecord'
require 'uri'
# If we're on Heroku use its database else use a local sqlite3 database. Nice and easy!
db = URI.parse(ENV['DATABASE_URL'] || 'sqlite3:///development.db')
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8'
)
# At this point, you can access the ActiveRecord::Base class using the
# "database" object:
#puts "the authorities table doesn't exist" if !database.table_exists?('authorities')
class Authority < ActiveRecord::Base
end
get "/" do
"Hello World!"
end
# Set config from local file for development (and use environment variables on Heroku)
if File.exists? 'configuration.yaml'
configuration = YAML.load_file('configuration.yaml')
ENV['CONSUMER_KEY'] = configuration['consumer']['key']
ENV['CONSUMER_SECRET'] = configuration['consumer']['secret']
ENV['OAUTH_TOKEN'] = configuration['oauth']['token']
ENV['OAUTH_TOKEN_SECRET'] = configuration['oauth']['token_secret']
end
EM.schedule do
TweetStream.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = ENV['OAUTH_TOKEN']
config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']
config.auth_method = :oauth
end
Twitter.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = ENV['OAUTH_TOKEN']
config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']
end
client = TweetStream::Client.new
client.track('#tmyc') do |status|
puts "Responding to tweet from @#{status.user.screen_name}"
if status.geo
puts "Found geo information: #{status.geo}"
geo2gov_response = Geo2gov.new(status.geo.coordinates[0], status.geo.coordinates[1])
lga_code = geo2gov_response.lga_code[3..-1] if geo2gov_response.lga_code
if lga_code
puts "Found LGA code #{lga_code}"
authority = Authority.find_by_lga_code(lga_code.to_i)
if authority
if authority.twitter_screen_name
response = "#{positive_response}: They are #{authority.twitter_screen_name}"
elsif authority.contact_email
response = "#{positive_response}: They are #{authority.contact_email}"
elsif authority.website_url
response = "#{positive_response}: They are #{authority.website_url}"
else
response = "#{positive_response}: They are #{authority.name}"
end
else
response = "#{positive_response}: #{lga_code}"
end
else
response = "#{positive_response}: #{status.geo.coordinates}"
end
else
response = no_geo_response
end
puts "Responding with \"@#{status.user.screen_name} #{response} (#{rand(500)})\""
Twitter.update("@#{status.user.screen_name} #{response} (#{rand(500)})", :in_reply_to_status_id => status.id.to_i)
end
client.on_error do |message|
p message
end
end
EM.error_handler{ |e|
puts "Error raised during event loop: #{e.message}"
}
def negative_response
responses = [
"I can't find where the bloody hell you are - you need to geotag your tweet",
"Can't find any location data on your tweet, mate",
"Strewth, you need to add location data to your tweet"
].sample
end
def positive_response
responses = [
"Crikey! I found your council",
"I've found your flamin council"
].sample
end
Better responses but still in test
#!/usr/bin/env ruby
$LOAD_PATH.unshift File.dirname(__FILE__) + '/lib'
require 'sinatra'
require 'tweetstream'
require 'yaml'
require 'twitter'
require 'httparty'
require 'geo2gov'
require 'sinatra/activerecord'
require 'uri'
# If we're on Heroku use its database else use a local sqlite3 database. Nice and easy!
db = URI.parse(ENV['DATABASE_URL'] || 'sqlite3:///development.db')
ActiveRecord::Base.establish_connection(
:adapter => db.scheme == 'postgres' ? 'postgresql' : db.scheme,
:host => db.host,
:username => db.user,
:password => db.password,
:database => db.path[1..-1],
:encoding => 'utf8'
)
# At this point, you can access the ActiveRecord::Base class using the
# "database" object:
#puts "the authorities table doesn't exist" if !database.table_exists?('authorities')
class Authority < ActiveRecord::Base
end
get "/" do
"Hello World!"
end
# Set config from local file for development (and use environment variables on Heroku)
if File.exists? 'configuration.yaml'
configuration = YAML.load_file('configuration.yaml')
ENV['CONSUMER_KEY'] = configuration['consumer']['key']
ENV['CONSUMER_SECRET'] = configuration['consumer']['secret']
ENV['OAUTH_TOKEN'] = configuration['oauth']['token']
ENV['OAUTH_TOKEN_SECRET'] = configuration['oauth']['token_secret']
end
EM.schedule do
TweetStream.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = ENV['OAUTH_TOKEN']
config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']
config.auth_method = :oauth
end
Twitter.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = ENV['OAUTH_TOKEN']
config.oauth_token_secret = ENV['OAUTH_TOKEN_SECRET']
end
client = TweetStream::Client.new
client.track('#tmyc') do |status|
puts "Responding to tweet from @#{status.user.screen_name}"
if status.geo
puts "Found geo information: #{status.geo}"
geo2gov_response = Geo2gov.new(status.geo.coordinates[0], status.geo.coordinates[1])
lga_code = geo2gov_response.lga_code[3..-1] if geo2gov_response.lga_code
if lga_code
puts "Found LGA code #{lga_code}"
authority = Authority.find_by_lga_code(lga_code.to_i)
if authority
if authority.twitter_screen_name
response = "#{positive_response}: They are #{authority.twitter_screen_name} on Twitter"
elsif authority.contact_email
response = "#{positive_response}: They're not on Twitter, try #{authority.contact_email}"
elsif authority.website_url
response = "#{positive_response}: They're not on Twitter, try #{authority.website_url}"
else
response = "#{positive_response}: #{authority.name} is not on twitter :("
end
else
response = "#{positive_response}: #{lga_code}"
end
else
response = "#{positive_response}: #{status.geo.coordinates}"
end
else
response = no_geo_response
end
puts "Responding with \"@#{status.user.screen_name} #{response} (#{rand(500)})\""
Twitter.update("@#{status.user.screen_name} #{response} (#{rand(500)})", :in_reply_to_status_id => status.id.to_i)
end
client.on_error do |message|
p message
end
end
EM.error_handler{ |e|
puts "Error raised during event loop: #{e.message}"
}
def negative_response
responses = [
"I can't find where the bloody hell you are - you need to geotag your tweet",
"Can't find any location data on your tweet, mate",
"Strewth, you need to add location data to your tweet"
].sample
end
def positive_response
responses = [
"Crikey! I found your council",
"I've found your flamin council"
].sample
end
|
# encoding=utf-8
require 'sinatra'
require 'net/http'
require 'logger'
require 'uri'
require 'json'
enable :sessions, :logging
set :protection, except: [:json_csrf]
before do
logger.level = Logger::DEBUG
headers({'Access-Control-Allow-Origin' => ENV['FRONT_END_URI']})
end
set :public_folder, 'dist'
use Rack::Static, urls: ['/styles', '/scripts/**/*.js', '/images',
'/bower_components'], root: settings.public_folder
get '/' do
send_file File.join(settings.public_folder, 'index.html')
end
get '/config.json' do
content_type 'application/json'
{
localStorageKey: ENV['LOCAL_STORAGE_KEY'],
serverUrl: ENV['FRONT_END_URI'],
instagram: {
clientId: ENV['INSTAGRAM_CLIENT_ID'],
redirectUri: ENV['FRONT_END_URI']
}
}.to_json
end
options '/image' do
''
end
get '/image' do
allowed_uri = URI.parse(ENV['FRONT_END_URI'])
unless request.host == allowed_uri.host
return "#{request.host} is not allowed to use this endpoint"
end
url = params[:url] || ''
unless url.start_with?('http://') || url.start_with?('https://')
return 'Invalid URL'
end
unless url.include?('cdninstagram.com')
return 'Only cdninstagram.com URLs are allowed'
end
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
begin
response = http.request(Net::HTTP::Get.new(uri.request_uri))
rescue SocketError => ex
status 404
return 'Could not load URL'
end
case response
when Net::HTTPOK
content_type response['content-type']
response.body
else
status 422
response.body
end
end
Allow igsonar Instagram thumbnails
# encoding=utf-8
require 'sinatra'
require 'net/http'
require 'logger'
require 'uri'
require 'json'
enable :sessions, :logging
set :protection, except: [:json_csrf]
before do
logger.level = Logger::DEBUG
headers({'Access-Control-Allow-Origin' => ENV['FRONT_END_URI']})
end
set :public_folder, 'dist'
use Rack::Static, urls: ['/styles', '/scripts/**/*.js', '/images',
'/bower_components'], root: settings.public_folder
get '/' do
send_file File.join(settings.public_folder, 'index.html')
end
get '/config.json' do
content_type 'application/json'
{
localStorageKey: ENV['LOCAL_STORAGE_KEY'],
serverUrl: ENV['FRONT_END_URI'],
instagram: {
clientId: ENV['INSTAGRAM_CLIENT_ID'],
redirectUri: ENV['FRONT_END_URI']
}
}.to_json
end
options '/image' do
''
end
get '/image' do
allowed_uri = URI.parse(ENV['FRONT_END_URI'])
unless request.host == allowed_uri.host
return "#{request.host} is not allowed to use this endpoint"
end
url = params[:url] || ''
unless url.start_with?('http://') || url.start_with?('https://')
return 'Invalid URL'
end
# Some of my Instagram image thumbnails were on igsonar.com
unless url.include?('cdninstagram.com') || url.include?('igsonar.com')
return "Only Instagram URLs are allowed, you gave #{url}"
end
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
begin
response = http.request(Net::HTTP::Get.new(uri.request_uri))
rescue SocketError => ex
status 404
return 'Could not load URL'
end
case response
when Net::HTTPOK
content_type response['content-type']
response.body
else
status 422
response.body
end
end
|
require 'bundler'
require 'bundler/setup'
require 'sinatra'
require 'slimmer'
require 'sass/plugin/rack'
Sass.load_paths << Gem.loaded_specs['govuk_frontend_toolkit'].full_gem_path + '/app/assets/stylesheets'
use Sass::Plugin::Rack
use Slimmer::App
get '/' do
erb :index
end
Add basic authentication
require 'bundler'
require 'bundler/setup'
require 'sinatra'
require 'slimmer'
require 'sass/plugin/rack'
Sass.load_paths << Gem.loaded_specs['govuk_frontend_toolkit'].full_gem_path + '/app/assets/stylesheets'
use Rack::Auth::Basic, 'Prototype' do |username, password|
[username, password] == [ENV['AUTH_USERNAME'], ENV['AUTH_PASSWORD']]
end if settings.production?
use Sass::Plugin::Rack
use Slimmer::App
get '/' do
erb :index
end
|
# coding: utf-8
require 'fileutils'
require_relative '../lxc-manager'
class LxcManager
class NginxController
def self.create config, reverse_proxy
logger = LxcManager::Logger.instance
logger.info "#{self}##{__method__}"
return if LxcManager::DRY_RUN
reverse_proxy_config_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf"
nginx_config = ""
nginx_config += "server {\n"
nginx_config += " listen #{reverse_proxy.listen_port};\n"
nginx_config += " server_name _;\n"
nginx_config += " proxy_set_header Host $http_host;\n"
nginx_config += " location #{reverse_proxy.location} {\n"
nginx_config += " proxy_pass http://#{reverse_proxy.container.interfaces.find_by_name( 'management' ).v4_address}:#{reverse_proxy.proxy_port}#{reverse_proxy.proxy_pass};\n"
nginx_config += " proxy_http_version 1.1;\n"
nginx_config += " proxy_set_header Upgrade $http_upgrade;\n"
nginx_config += " proxy_set_header Connection \"upgrade\";\n"
if reverse_proxy.reverse_proxy_substitutes.any?
nginx_config += " sub_filter_types '*';\n"
nginx_config += " sub_filter_once off;\n"
reverse_proxy.reverse_proxy_substitutes.each{ |reverse_proxy_substitute|
nginx_config += " sub_filter \"#{reverse_proxy_substitute.pattern}\" \"#{reverse_proxy_substitute.replacement}\";\n"
}
end
nginx_config += " }\n"
nginx_config += "}\n"
logger.debug "#{self}##{__method__}: " + "create nginx conf file: #{nginx_config}"
File.open( reverse_proxy_config_file, 'w' ){ |fo|
fo.puts nginx_config
}
logger.debug "#{self}##{__method__}: " + "cli-agent start"
CliAgent.open( config['local_shell'] ){ |s|
reload_nginx_success = false
begin
ret = s.run "systemctl reload nginx"
if s.exit_status == 0
reload_nginx_success = true
else
raise "Failed: reload nginx: #{ret}"
end
rescue
FileUtils.rm( reverse_proxy_config_file, force: true )
raise
end
}
logger.debug "#{self}##{__method__}: " + "cli-agent end"
end
def self.destroy config, reverse_proxy
logger = LxcManager::Logger.instance
logger.info "#{self}##{__method__}"
return if LxcManager::DRY_RUN
reverse_proxy_config_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf"
nginx_config = File.open( reverse_proxy_config_file ).read rescue ''
logger.debug "#{self}##{__method__}: " + "remove #{reverse_proxy_config_file}"
FileUtils.rm( reverse_proxy_config_file, force: true )
logger.debug "#{self}##{__method__}: " + "cli-agent start"
CliAgent.open( config['local_shell'] ){ |s|
reload_nginx_success = false
begin
ret = s.run "systemctl reload nginx"
if s.exit_status == 0
reload_nginx_success = true
else
raise "Failed: reload nginx: #{ret}"
end
rescue
logger.debug "#{self}##{__method__}: " + "create nginx conf file: #{nginx_config}"
File.open( reverse_proxy_config_file, 'w' ){ |fo|
fo.puts nginx_config
}
raise
end
}
logger.debug "#{self}##{__method__}: " + "cli-agent end"
end
def self.replace config, reverse_proxy
logger = LxcManager::Logger.instance
logger.info "#{self}##{__method__}"
return if LxcManager::DRY_RUN
reverse_proxy_config_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf"
reverse_proxy_config_backup_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf.bak"
logger.debug "#{self}##{__method__}: " + "copy #{reverse_proxy_config_file} to #{reverse_proxy_config_backup_file}"
FileUtils.copy( reverse_proxy_config_file, reverse_proxy_config_backup_file, preserve: true )
begin
nginx_config = ""
nginx_config += "server {\n"
nginx_config += " listen #{reverse_proxy.listen_port};\n"
nginx_config += " server_name _;\n"
nginx_config += " proxy_set_header Host $http_host;\n"
nginx_config += " location #{reverse_proxy.location} {\n"
nginx_config += " proxy_pass http://#{reverse_proxy.container.interfaces.find_by_name( 'management' ).v4_address}:#{reverse_proxy.proxy_port}#{reverse_proxy.proxy_pass};\n"
if reverse_proxy.reverse_proxy_substitutes.any?
nginx_config += " sub_filter_types '*';\n"
nginx_config += " sub_filter_once off;\n"
reverse_proxy.reverse_proxy_substitutes.each{ |reverse_proxy_substitute|
nginx_config += " sub_filter \"#{reverse_proxy_substitute.pattern}\" \"#{reverse_proxy_substitute.replacement}\";\n"
}
end
nginx_config += " }\n"
nginx_config += "}\n"
logger.debug "#{self}##{__method__}: " + "create nginx conf file: #{nginx_config}"
File.open( reverse_proxy_config_file, 'w' ){ |fo|
fo.puts nginx_config
}
rescue
logger.debug "#{self}##{__method__}: " + "move #{reverse_proxy_config_backup_file} to #{reverse_proxy_config_file}"
FileUtils.move( reverse_proxy_config_backup_file, reverse_proxy_config_file, force: true )
raise
end
logger.debug "#{self}##{__method__}: " + "cli-agent start"
CliAgent.open( config['local_shell'] ){ |s|
reload_nginx_success = false
begin
ret = s.run "systemctl reload nginx"
if s.exit_status == 0
reload_nginx_success = true
else
raise "Failed: reload nginx: #{ret}"
end
logger.debug "#{self}##{__method__}: " + "remove #{reverse_proxy_config_backup_file}"
FileUtils.rm( reverse_proxy_config_backup_file, force: true )
rescue
logger.debug "#{self}##{__method__}: " + "move #{reverse_proxy_config_backup_file} to #{reverse_proxy_config_file}"
FileUtils.move( reverse_proxy_config_backup_file, reverse_proxy_config_file, force: true )
raise
end
}
logger.debug "#{self}##{__method__}: " + "cli-agent end"
end
end
end
fix nginx-controller.rb #replace
# coding: utf-8
require 'fileutils'
require_relative '../lxc-manager'
class LxcManager
class NginxController
def self.create config, reverse_proxy
logger = LxcManager::Logger.instance
logger.info "#{self}##{__method__}"
return if LxcManager::DRY_RUN
reverse_proxy_config_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf"
nginx_config = ""
nginx_config += "server {\n"
nginx_config += " listen #{reverse_proxy.listen_port};\n"
nginx_config += " server_name _;\n"
nginx_config += " proxy_set_header Host $http_host;\n"
nginx_config += " location #{reverse_proxy.location} {\n"
nginx_config += " proxy_pass http://#{reverse_proxy.container.interfaces.find_by_name( 'management' ).v4_address}:#{reverse_proxy.proxy_port}#{reverse_proxy.proxy_pass};\n"
nginx_config += " proxy_http_version 1.1;\n"
nginx_config += " proxy_set_header Upgrade $http_upgrade;\n"
nginx_config += " proxy_set_header Connection \"upgrade\";\n"
if reverse_proxy.reverse_proxy_substitutes.any?
nginx_config += " sub_filter_types '*';\n"
nginx_config += " sub_filter_once off;\n"
reverse_proxy.reverse_proxy_substitutes.each{ |reverse_proxy_substitute|
nginx_config += " sub_filter \"#{reverse_proxy_substitute.pattern}\" \"#{reverse_proxy_substitute.replacement}\";\n"
}
end
nginx_config += " }\n"
nginx_config += "}\n"
logger.debug "#{self}##{__method__}: " + "create nginx conf file: #{nginx_config}"
File.open( reverse_proxy_config_file, 'w' ){ |fo|
fo.puts nginx_config
}
logger.debug "#{self}##{__method__}: " + "cli-agent start"
CliAgent.open( config['local_shell'] ){ |s|
reload_nginx_success = false
begin
ret = s.run "systemctl reload nginx"
if s.exit_status == 0
reload_nginx_success = true
else
raise "Failed: reload nginx: #{ret}"
end
rescue
FileUtils.rm( reverse_proxy_config_file, force: true )
raise
end
}
logger.debug "#{self}##{__method__}: " + "cli-agent end"
end
def self.destroy config, reverse_proxy
logger = LxcManager::Logger.instance
logger.info "#{self}##{__method__}"
return if LxcManager::DRY_RUN
reverse_proxy_config_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf"
nginx_config = File.open( reverse_proxy_config_file ).read rescue ''
logger.debug "#{self}##{__method__}: " + "remove #{reverse_proxy_config_file}"
FileUtils.rm( reverse_proxy_config_file, force: true )
logger.debug "#{self}##{__method__}: " + "cli-agent start"
CliAgent.open( config['local_shell'] ){ |s|
reload_nginx_success = false
begin
ret = s.run "systemctl reload nginx"
if s.exit_status == 0
reload_nginx_success = true
else
raise "Failed: reload nginx: #{ret}"
end
rescue
logger.debug "#{self}##{__method__}: " + "create nginx conf file: #{nginx_config}"
File.open( reverse_proxy_config_file, 'w' ){ |fo|
fo.puts nginx_config
}
raise
end
}
logger.debug "#{self}##{__method__}: " + "cli-agent end"
end
def self.replace config, reverse_proxy
logger = LxcManager::Logger.instance
logger.info "#{self}##{__method__}"
return if LxcManager::DRY_RUN
reverse_proxy_config_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf"
reverse_proxy_config_backup_file = "#{config['nginx_conf_dir']}/#{reverse_proxy.id}.conf.bak"
logger.debug "#{self}##{__method__}: " + "copy #{reverse_proxy_config_file} to #{reverse_proxy_config_backup_file}"
FileUtils.copy( reverse_proxy_config_file, reverse_proxy_config_backup_file, preserve: true )
begin
nginx_config = ""
nginx_config += "server {\n"
nginx_config += " listen #{reverse_proxy.listen_port};\n"
nginx_config += " server_name _;\n"
nginx_config += " proxy_set_header Host $http_host;\n"
nginx_config += " location #{reverse_proxy.location} {\n"
nginx_config += " proxy_pass http://#{reverse_proxy.container.interfaces.find_by_name( 'management' ).v4_address}:#{reverse_proxy.proxy_port}#{reverse_proxy.proxy_pass};\n"
nginx_config += " proxy_http_version 1.1;\n"
nginx_config += " proxy_set_header Upgrade $http_upgrade;\n"
nginx_config += " proxy_set_header Connection \"upgrade\";\n"
if reverse_proxy.reverse_proxy_substitutes.any?
nginx_config += " sub_filter_types '*';\n"
nginx_config += " sub_filter_once off;\n"
reverse_proxy.reverse_proxy_substitutes.each{ |reverse_proxy_substitute|
nginx_config += " sub_filter \"#{reverse_proxy_substitute.pattern}\" \"#{reverse_proxy_substitute.replacement}\";\n"
}
end
nginx_config += " }\n"
nginx_config += "}\n"
logger.debug "#{self}##{__method__}: " + "create nginx conf file: #{nginx_config}"
File.open( reverse_proxy_config_file, 'w' ){ |fo|
fo.puts nginx_config
}
rescue
logger.debug "#{self}##{__method__}: " + "move #{reverse_proxy_config_backup_file} to #{reverse_proxy_config_file}"
FileUtils.move( reverse_proxy_config_backup_file, reverse_proxy_config_file, force: true )
raise
end
logger.debug "#{self}##{__method__}: " + "cli-agent start"
CliAgent.open( config['local_shell'] ){ |s|
reload_nginx_success = false
begin
ret = s.run "systemctl reload nginx"
if s.exit_status == 0
reload_nginx_success = true
else
raise "Failed: reload nginx: #{ret}"
end
logger.debug "#{self}##{__method__}: " + "remove #{reverse_proxy_config_backup_file}"
FileUtils.rm( reverse_proxy_config_backup_file, force: true )
rescue
logger.debug "#{self}##{__method__}: " + "move #{reverse_proxy_config_backup_file} to #{reverse_proxy_config_file}"
FileUtils.move( reverse_proxy_config_backup_file, reverse_proxy_config_file, force: true )
raise
end
}
logger.debug "#{self}##{__method__}: " + "cli-agent end"
end
end
end
|
require 'active_record'
module Memdash
module ActiveRecord
class Report < ::ActiveRecord::Base
self.table_name = :memdash_reports
serialize :stats
end
end
end
Add a scope to grab the last days worth of reports
require 'active_record'
module Memdash
module ActiveRecord
class Report < ::ActiveRecord::Base
self.table_name = :memdash_reports
serialize :stats
scope :past_day, where('created_at >= :time', :time => Time.current - 1.day)
end
end
end
|
require "metadata/ingest/form"
module Metadata
module Ingest
class Form
VERSION = "2.0.0"
end
end
end
Bump version to 2.1.0
require "metadata/ingest/form"
module Metadata
module Ingest
class Form
VERSION = "2.1.0"
end
end
end
|
require 'optparse'
require 'morpheus/cli/cli_command'
require 'json'
class Morpheus::Cli::ReportsCommand
include Morpheus::Cli::CliCommand
set_command_name :reports
def initialize()
# @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end
def connect(opts)
@api_client = establish_remote_appliance_connection(opts)
@reports_interface = @api_client.reports
end
register_subcommands :list, :get, :run, :view, :export, :remove, :types
def default_refresh_interval
5
end
def handle(args)
handle_subcommand(args)
end
def list(args)
options = {}
params = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage()
opts.on( '--type CODE', String, "Report Type code(s)" ) do |val|
params['reportType'] = val.to_s.split(",").compact.collect {|it| it.strip }
end
build_common_options(opts, options, [:list, :query, :json, :dry_run, :remote])
opts.footer = "List report history."
end
optparse.parse!(args)
connect(options)
begin
params.merge!(parse_list_options(options))
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.list(params)
return
end
json_response = @reports_interface.list(params)
if options[:json]
puts as_json(json_response, options)
return 0
end
report_results = json_response['reportResults']
title = "Morpheus Report History"
subtitles = []
if params['type']
subtitles << "Type: #{params[:type]}".strip
end
subtitles += parse_list_subtitles(options)
print_h1 title, subtitles
if report_results.empty?
print cyan, "No report results found", reset, "\n"
else
columns = {
"ID" => 'id',
"TITLE" => lambda {|it| truncate_string(it['reportTitle'], 50) },
"FILTERS" => lambda {|it| truncate_string(it['filterTitle'], 30) },
"REPORT TYPE" => lambda {|it| it['type'].is_a?(Hash) ? it['type']['name'] : it['type'] },
"DATE RUN" => lambda {|it| format_local_dt(it['dateCreated']) },
"CREATED BY" => lambda {|it| it['createdBy'].is_a?(Hash) ? it['createdBy']['username'] : it['createdBy'] },
"STATUS" => lambda {|it| format_report_status(it) }
}
# custom pretty table columns ...
if options[:include_fields]
columns = options[:include_fields]
end
print as_pretty_table(report_results, columns, options)
print reset
print_results_pagination(json_response)
end
print reset,"\n"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def get(args)
original_args = args.dup
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
opts.on('--refresh [SECONDS]', String, "Refresh until status is ready,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
options[:refresh_until_status] ||= "ready,failed"
if !val.to_s.empty?
options[:refresh_interval] = val.to_f
end
end
opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
options[:refresh_until_status] = val.to_s.downcase
end
opts.on('--rows', '--rows', "Print Report Data rows too.") do
options[:show_data_rows] = true
end
opts.on('--view', '--view', "View report result in web browser too.") do
options[:view_report] = true
end
build_common_options(opts, options, [:json, :yaml, :csv, :fields, :outfile, :dry_run, :remote])
opts.footer = "Get details about a report result." + "\n"
+ "[id] is required. This is the id of the report result."
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} missing argument: [id]\n#{optparse}"
return 1
end
connect(options)
begin
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.get(args[0].to_i)
return 0
end
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
json_response = {'reportResult' => report_result} # skip redundant request
# json_response = @reports_interface.get(report['id'])
#report_result = json_response['reportResult']
# if options[:json]
# puts as_json(json_response, options)
# return 0
# end
# render_with_format() handles json,yaml,csv,outfile,etc
render_result = render_with_format(json_response, options, 'reportResult')
if render_result
#return render_result
else
print_h1 "Morpheus Report Details"
print cyan
description_cols = {
"ID" => 'id',
"Title" => lambda {|it| it['reportTitle'] },
"Filters" => lambda {|it| it['filterTitle'] },
"Report Type" => lambda {|it| it['type'].is_a?(Hash) ? it['type']['name'] : it['type'] },
"Date Run" => lambda {|it| format_local_dt(it['dateCreated']) },
"Created By" => lambda {|it| it['createdBy'].is_a?(Hash) ? it['createdBy']['username'] : it['createdBy'] },
"Status" => lambda {|it| format_report_status(it) }
}
print_description_list(description_cols, report_result)
# todo:
# 1. format raw output better.
# 2. write rendering methods for all the various types...
if options[:show_data_rows]
print_h2 "Report Data Rows"
print cyan
if report_result['rows']
# report_result['rows'].each_with_index do |row, index|
# print "#{index}: ", row, "\n"
# end
term_width = current_terminal_width()
data_width = term_width.to_i - 30
if data_width < 0
data_wdith = 10
end
puts as_pretty_table(report_result['rows'], options[:include_fields] || {
"ID" => lambda {|it| it['id'] },
"SECTION" => lambda {|it| it['section'] },
"DATA" => lambda {|it| truncate_string(it['data'], data_width) }
}, options.merge({:wrap => true}))
else
print yellow, "No report data found.", reset, "\n"
end
end
print reset,"\n"
end
# refresh until a status is reached
if options[:refresh_until_status]
if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
options[:refresh_interval] = default_refresh_interval
end
statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
if !statuses.include?(report_result['status'])
print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
sleep_with_dots(options[:refresh_interval])
print "\n"
get(original_args)
end
end
if options[:view_report]
view([report_result['id']])
end
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
return 1
end
end
def run(args)
params = {}
do_refresh = true
options = {:options => {}}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[type] [options]")
opts.on( '--type CODE', String, "Report Type code" ) do |val|
options[:options]['type'] = val
end
# opts.on( '--title TITLE', String, "Title for the report" ) do |val|
# options[:options]['reportTitle'] = val
# end
opts.on(nil, '--no-refresh', "Do not refresh until finished" ) do
do_refresh = false
end
opts.on('--rows', '--rows', "Print Report Data rows too.") do
options[:show_data_rows] = true
end
opts.on('--view', '--view', "View report result in web browser when it is finished.") do
options[:view_report] = true
end
build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
opts.footer = "Run a report to generate a new result." + "\n" +
"[type] is required. This is code of the report type."
end
optparse.parse!(args)
if args.count > 1
raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
if args[0]
options[:options]['type'] = args[0]
end
connect(options)
begin
# construct payload
passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
payload = nil
if options[:payload]
payload = options[:payload]
payload.deep_merge!({'report' => passed_options}) unless passed_options.empty?
else
# prompt for resource folder options
payload = {
'report' => {
}
}
# allow arbitrary -O options
payload.deep_merge!({'report' => passed_options}) unless passed_options.empty?
# Report Type
@all_report_types ||= @reports_interface.types({max: 1000})['reportTypes'] || []
report_types_dropdown = @all_report_types.collect {|it| {"name" => it["name"], "value" => it["code"]} }
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Report Type', 'type' => 'select', 'selectOptions' => report_types_dropdown, 'required' => true}], options[:options], @api_client)
payload['report']['type'] = v_prompt['type']
# convert name/code/id to code
report_type = find_report_type_by_name_or_code_id(payload['report']['type'])
return 1 if report_type.nil?
payload['report']['type'] = report_type['code']
# Report Types tell us what the available filters are...
report_option_types = report_type['optionTypes'] || []
report_option_types = report_option_types.collect {|it|
it['fieldContext'] = nil
it
}
# pluck out optionTypes like the UI does..
metadata_option_type = nil
if report_option_types.find {|it| it['fieldName'] == 'metadata' }
metadata_option_type = report_option_types.delete_if {|it| it['fieldName'] == 'metadata' }
end
v_prompt = Morpheus::Cli::OptionTypes.prompt(report_option_types, options[:options], @api_client)
payload.deep_merge!({'report' => v_prompt}) unless v_prompt.empty?
if metadata_option_type
if !options[:options]['metadata']
metadata_filter = prompt_metadata(options)
if metadata_filter && !metadata_filter.empty?
payload['report']['metadata'] = metadata_filter
end
end
end
end
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.create(payload)
return 0
end
json_response = @reports_interface.create(payload)
if options[:json]
puts as_json(json_response, options)
return 0
end
print_green_success "Created report result #{json_response['reportResult']['id']}"
print_args = [json_response['reportResult']['id']]
print_args << "--refresh" if do_refresh
print_args << "--rows" if options[:show_data_rows]
print_args << "--view" if options[:view_report]
get(print_args)
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def view(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
build_common_options(opts, options, [:dry_run, :remote])
opts.footer = "View a report result in a web browser" + "\n" +
"[id] is required. This is the id of the report result."
end
optparse.parse!(args)
if args.count != 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/operations/reports/#{report_result['type']['code']}/reportResults/#{report_result['id']}"
if options[:dry_run]
puts Morpheus::Util.open_url_command(link)
return 0
end
return Morpheus::Util.open_url(link)
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def export(args)
params = {}
report_format = 'json'
options = {}
outfile = nil
do_overwrite = false
do_mkdir = false
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id] [file]")
build_common_options(opts, options, [:dry_run, :remote])
opts.on( '--format VALUE', String, "Report Format for exported file, json or csv. Default is json." ) do |val|
report_format = val
end
opts.on( '-f', '--force', "Overwrite existing [local-file] if it exists." ) do
do_overwrite = true
# do_mkdir = true
end
opts.on( '-p', '--mkdir', "Create missing directories for [local-file] if they do not exist." ) do
do_mkdir = true
end
opts.footer = "Export a report result as json or csv." + "\n" +
"[id] is required. This is id of the report result." + "\n" +
"[file] is required. This is local destination for the downloaded file."
end
optparse.parse!(args)
if args.count != 2
raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
outfile = args[1]
outfile = File.expand_path(outfile)
if Dir.exists?(outfile)
print_red_alert "[file] is invalid. It is the name of an existing directory: #{outfile}"
return 1
end
destination_dir = File.dirname(outfile)
if !Dir.exists?(destination_dir)
if do_mkdir
print cyan,"Creating local directory #{destination_dir}",reset,"\n"
FileUtils.mkdir_p(destination_dir)
else
print_red_alert "[file] is invalid. Directory not found: #{destination_dir}"
return 1
end
end
if File.exists?(outfile)
if do_overwrite
# uhh need to be careful wih the passed filepath here..
# don't delete, just overwrite.
# File.delete(outfile)
else
print_error Morpheus::Terminal.angry_prompt
puts_error "[file] is invalid. File already exists: #{outfile}", "Use -f to overwrite the existing file."
# puts_error optparse
return 1
end
end
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.export(report_result['id'], outfile, params, report_format)
return 0
end
json_response = @reports_interface.export(report_result['id'], outfile, params, report_format)
print_green_success "Exported report result #{report_result['id']} to file #{outfile}"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def remove(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
opts.footer = "Delete a report result." + "\n" +
"[id] is required. This is id of the report result."
end
optparse.parse!(args)
if args.count != 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the report result: #{report_result['id']}?")
return 9, "aborted command"
end
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.destroy(report_result['id'])
return
end
json_response = @reports_interface.destroy(report_result['id'])
if options[:json]
puts as_json(json_response, options)
return 0
end
print_green_success "Deleted report result #{report_result['id']}"
#list([])
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def types(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage()
build_common_options(opts, options, [:list, :json, :dry_run, :remote])
opts.footer = "List report types."
end
optparse.parse!(args)
connect(options)
begin
params = {}
params.merge!(parse_list_options(options))
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.types(params)
return
end
json_response = @reports_interface.types(params)
if options[:json]
print JSON.pretty_generate(json_response)
print "\n"
return
end
title = "Morpheus Report Types"
subtitles = []
subtitles += parse_list_subtitles(options)
print_h1 title, subtitles
report_types = json_response['reportTypes']
if report_types.empty?
print cyan,"No report types found.",reset,"\n"
else
columns = {
"NAME" => 'name',
"CODE" => 'code'
}
# custom pretty table columns ...
if options[:include_fields]
columns = options[:include_fields]
end
print as_pretty_table(report_types, columns, options)
print reset
if json_response['meta']
print_results_pagination(json_response)
else
print_results_pagination({'meta'=>{'total'=>(report_types.size),'size'=>report_types.size,'max'=>(params['max']||25),'offset'=>(params['offset']||0)}})
end
end
print reset,"\n"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def find_report_result_by_id(id)
begin
json_response = @reports_interface.get(id.to_i)
return json_response['reportResult']
rescue RestClient::Exception => e
if e.response && e.response.code == 404
print_red_alert "Report Result not found by id #{id}"
return nil
else
raise e
end
end
end
def find_report_type_by_name_or_code_id(val)
if val.to_s =~ /\A\d{1,}\Z/
return find_report_type_by_id(val)
else
return find_report_type_by_name_or_code(val)
end
end
def find_report_type_by_id(id)
@all_report_types ||= @reports_interface.list({max: 1000})['reportTypes'] || []
report_types = @all_report_types.select { |it| id && it['id'] == id.to_i }
if report_types.empty?
print_red_alert "Report Type not found by id #{id}"
return nil
elsif report_types.size > 1
print_red_alert "#{report_types.size} report types found by id #{id}"
rows = report_types.collect do |it|
{id: it['id'], code: it['code'], name: it['name']}
end
print "\n"
puts as_pretty_table(rows, [:id, :code, :name], {color:red})
return nil
else
return report_types[0]
end
end
def find_report_type_by_name_or_code(name)
@all_report_types ||= @reports_interface.list({max: 1000})['reportTypes'] || []
report_types = @all_report_types.select { |it| name && it['code'] == name || it['name'] == name }
if report_types.empty?
print_red_alert "Report Type not found by code #{name}"
return nil
elsif report_types.size > 1
print_red_alert "#{report_types.size} report types found by code #{name}"
rows = report_types.collect do |it|
{id: it['id'], code: it['code'], name: it['name']}
end
print "\n"
puts as_pretty_table(rows, [:id, :code, :name], {color:red})
return nil
else
return report_types[0]
end
end
def format_report_status(report_result, return_color=cyan)
out = ""
status_string = report_result['status'].to_s
if status_string == 'ready'
out << "#{green}#{status_string.upcase}#{return_color}"
elsif status_string == 'requested'
out << "#{cyan}#{status_string.upcase}#{return_color}"
elsif status_string == 'generating'
out << "#{cyan}#{status_string.upcase}#{return_color}"
elsif status_string == 'failed'
out << "#{red}#{status_string.upcase}#{return_color}"
else
out << "#{yellow}#{status_string.upcase}#{return_color}"
end
out
end
# Prompts user for metadata for report filter
# returns array of metadata objects {id: null, name: "MYTAG", value: "myvalue"}
def prompt_metadata(options={})
#puts "Configure Environment Variables:"
no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
metadata_filter = {}
metadata_index = 0
has_another_metadata = options[:options] && options[:options]["metadata#{metadata_index}"]
add_another_metadata = has_another_metadata || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add a metadata tag filter?", {default: false}))
while add_another_metadata do
field_context = "metadata#{metadata_index}"
metadata = {}
metadata['id'] = nil
metadata_label = metadata_index == 0 ? "Metadata Tag" : "Metadata Tag [#{metadata_index+1}]"
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "#{metadata_label} Name", 'required' => true, 'description' => 'Metadata Tag Name.', 'defaultValue' => metadata['name']}], options[:options])
# todo: metadata.type ?
metadata['name'] = v_prompt[field_context]['name'].to_s
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'value', 'type' => 'text', 'fieldLabel' => "#{metadata_label} Value", 'required' => true, 'description' => 'Metadata Tag Value', 'defaultValue' => metadata['value']}], options[:options])
metadata['value'] = v_prompt[field_context]['value'].to_s
metadata_filter[metadata['name']] = metadata['value']
metadata_index += 1
has_another_metadata = options[:options] && options[:options]["metadata#{metadata_index}"]
add_another_metadata = has_another_metadata || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another metadata tag filter?", {default: false}))
end
return metadata_filter
end
end
reports can include the fieldContext when prompting for optionType filters
require 'optparse'
require 'morpheus/cli/cli_command'
require 'json'
class Morpheus::Cli::ReportsCommand
include Morpheus::Cli::CliCommand
set_command_name :reports
def initialize()
# @appliance_name, @appliance_url = Morpheus::Cli::Remote.active_appliance
end
def connect(opts)
@api_client = establish_remote_appliance_connection(opts)
@reports_interface = @api_client.reports
end
register_subcommands :list, :get, :run, :view, :export, :remove, :types
def default_refresh_interval
5
end
def handle(args)
handle_subcommand(args)
end
def list(args)
options = {}
params = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage()
opts.on( '--type CODE', String, "Report Type code(s)" ) do |val|
params['reportType'] = val.to_s.split(",").compact.collect {|it| it.strip }
end
build_common_options(opts, options, [:list, :query, :json, :dry_run, :remote])
opts.footer = "List report history."
end
optparse.parse!(args)
connect(options)
begin
params.merge!(parse_list_options(options))
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.list(params)
return
end
json_response = @reports_interface.list(params)
if options[:json]
puts as_json(json_response, options)
return 0
end
report_results = json_response['reportResults']
title = "Morpheus Report History"
subtitles = []
if params['type']
subtitles << "Type: #{params[:type]}".strip
end
subtitles += parse_list_subtitles(options)
print_h1 title, subtitles
if report_results.empty?
print cyan, "No report results found", reset, "\n"
else
columns = {
"ID" => 'id',
"TITLE" => lambda {|it| truncate_string(it['reportTitle'], 50) },
"FILTERS" => lambda {|it| truncate_string(it['filterTitle'], 30) },
"REPORT TYPE" => lambda {|it| it['type'].is_a?(Hash) ? it['type']['name'] : it['type'] },
"DATE RUN" => lambda {|it| format_local_dt(it['dateCreated']) },
"CREATED BY" => lambda {|it| it['createdBy'].is_a?(Hash) ? it['createdBy']['username'] : it['createdBy'] },
"STATUS" => lambda {|it| format_report_status(it) }
}
# custom pretty table columns ...
if options[:include_fields]
columns = options[:include_fields]
end
print as_pretty_table(report_results, columns, options)
print reset
print_results_pagination(json_response)
end
print reset,"\n"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def get(args)
original_args = args.dup
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
opts.on('--refresh [SECONDS]', String, "Refresh until status is ready,failed. Default interval is #{default_refresh_interval} seconds.") do |val|
options[:refresh_until_status] ||= "ready,failed"
if !val.to_s.empty?
options[:refresh_interval] = val.to_f
end
end
opts.on('--refresh-until STATUS', String, "Refresh until a specified status is reached.") do |val|
options[:refresh_until_status] = val.to_s.downcase
end
opts.on('--rows', '--rows', "Print Report Data rows too.") do
options[:show_data_rows] = true
end
opts.on('--view', '--view', "View report result in web browser too.") do
options[:view_report] = true
end
build_common_options(opts, options, [:json, :yaml, :csv, :fields, :outfile, :dry_run, :remote])
opts.footer = "Get details about a report result." + "\n"
+ "[id] is required. This is the id of the report result."
end
optparse.parse!(args)
if args.count != 1
print_error Morpheus::Terminal.angry_prompt
puts_error "#{command_name} missing argument: [id]\n#{optparse}"
return 1
end
connect(options)
begin
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.get(args[0].to_i)
return 0
end
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
json_response = {'reportResult' => report_result} # skip redundant request
# json_response = @reports_interface.get(report['id'])
#report_result = json_response['reportResult']
# if options[:json]
# puts as_json(json_response, options)
# return 0
# end
# render_with_format() handles json,yaml,csv,outfile,etc
render_result = render_with_format(json_response, options, 'reportResult')
if render_result
#return render_result
else
print_h1 "Morpheus Report Details"
print cyan
description_cols = {
"ID" => 'id',
"Title" => lambda {|it| it['reportTitle'] },
"Filters" => lambda {|it| it['filterTitle'] },
"Report Type" => lambda {|it| it['type'].is_a?(Hash) ? it['type']['name'] : it['type'] },
"Date Run" => lambda {|it| format_local_dt(it['dateCreated']) },
"Created By" => lambda {|it| it['createdBy'].is_a?(Hash) ? it['createdBy']['username'] : it['createdBy'] },
"Status" => lambda {|it| format_report_status(it) }
}
print_description_list(description_cols, report_result)
# todo:
# 1. format raw output better.
# 2. write rendering methods for all the various types...
if options[:show_data_rows]
print_h2 "Report Data Rows"
print cyan
if report_result['rows']
# report_result['rows'].each_with_index do |row, index|
# print "#{index}: ", row, "\n"
# end
term_width = current_terminal_width()
data_width = term_width.to_i - 30
if data_width < 0
data_wdith = 10
end
puts as_pretty_table(report_result['rows'], options[:include_fields] || {
"ID" => lambda {|it| it['id'] },
"SECTION" => lambda {|it| it['section'] },
"DATA" => lambda {|it| truncate_string(it['data'], data_width) }
}, options.merge({:wrap => true}))
else
print yellow, "No report data found.", reset, "\n"
end
end
print reset,"\n"
end
# refresh until a status is reached
if options[:refresh_until_status]
if options[:refresh_interval].nil? || options[:refresh_interval].to_f < 0
options[:refresh_interval] = default_refresh_interval
end
statuses = options[:refresh_until_status].to_s.downcase.split(",").collect {|s| s.strip }.select {|s| !s.to_s.empty? }
if !statuses.include?(report_result['status'])
print cyan, "Refreshing in #{options[:refresh_interval] > 1 ? options[:refresh_interval].to_i : options[:refresh_interval]} seconds"
sleep_with_dots(options[:refresh_interval])
print "\n"
get(original_args)
end
end
if options[:view_report]
view([report_result['id']])
end
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
return 1
end
end
def run(args)
params = {}
do_refresh = true
options = {:options => {}}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[type] [options]")
opts.on( '--type CODE', String, "Report Type code" ) do |val|
options[:options]['type'] = val
end
# opts.on( '--title TITLE', String, "Title for the report" ) do |val|
# options[:options]['reportTitle'] = val
# end
opts.on(nil, '--no-refresh', "Do not refresh until finished" ) do
do_refresh = false
end
opts.on('--rows', '--rows', "Print Report Data rows too.") do
options[:show_data_rows] = true
end
opts.on('--view', '--view', "View report result in web browser when it is finished.") do
options[:view_report] = true
end
build_common_options(opts, options, [:options, :payload, :json, :dry_run, :remote])
opts.footer = "Run a report to generate a new result." + "\n" +
"[type] is required. This is code of the report type."
end
optparse.parse!(args)
if args.count > 1
raise_command_error "wrong number of arguments, expected 0-1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
if args[0]
options[:options]['type'] = args[0]
end
connect(options)
begin
# construct payload
passed_options = options[:options] ? options[:options].reject {|k,v| k.is_a?(Symbol) } : {}
payload = nil
if options[:payload]
payload = options[:payload]
payload.deep_merge!({'report' => passed_options}) unless passed_options.empty?
else
# prompt for resource folder options
payload = {
'report' => {
}
}
# allow arbitrary -O options
payload.deep_merge!({'report' => passed_options}) unless passed_options.empty?
# Report Type
@all_report_types ||= @reports_interface.types({max: 1000})['reportTypes'] || []
report_types_dropdown = @all_report_types.collect {|it| {"name" => it["name"], "value" => it["code"]} }
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'fieldLabel' => 'Report Type', 'type' => 'select', 'selectOptions' => report_types_dropdown, 'required' => true}], options[:options], @api_client)
payload['report']['type'] = v_prompt['type']
# convert name/code/id to code
report_type = find_report_type_by_name_or_code_id(payload['report']['type'])
return 1 if report_type.nil?
payload['report']['type'] = report_type['code']
# Report Types tell us what the available filters are...
report_option_types = report_type['optionTypes'] || []
# report_option_types = report_option_types.collect {|it|
# it['fieldContext'] = nil
# it
# }
# pluck out optionTypes like the UI does..
metadata_option_type = nil
if report_option_types.find {|it| it['fieldName'] == 'metadata' }
metadata_option_type = report_option_types.delete_if {|it| it['fieldName'] == 'metadata' }
end
v_prompt = Morpheus::Cli::OptionTypes.prompt(report_option_types, options[:options], @api_client)
payload.deep_merge!({'report' => v_prompt}) unless v_prompt.empty?
if metadata_option_type
if !options[:options]['metadata']
metadata_filter = prompt_metadata(options)
if metadata_filter && !metadata_filter.empty?
payload['report']['metadata'] = metadata_filter
end
end
end
end
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.create(payload)
return 0
end
json_response = @reports_interface.create(payload)
if options[:json]
puts as_json(json_response, options)
return 0
end
print_green_success "Created report result #{json_response['reportResult']['id']}"
print_args = [json_response['reportResult']['id']]
print_args << "--refresh" if do_refresh
print_args << "--rows" if options[:show_data_rows]
print_args << "--view" if options[:view_report]
get(print_args)
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def view(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
build_common_options(opts, options, [:dry_run, :remote])
opts.footer = "View a report result in a web browser" + "\n" +
"[id] is required. This is the id of the report result."
end
optparse.parse!(args)
if args.count != 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
link = "#{@appliance_url}/login/oauth-redirect?access_token=#{@access_token}\\&redirectUri=/operations/reports/#{report_result['type']['code']}/reportResults/#{report_result['id']}"
if options[:dry_run]
puts Morpheus::Util.open_url_command(link)
return 0
end
return Morpheus::Util.open_url(link)
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def export(args)
params = {}
report_format = 'json'
options = {}
outfile = nil
do_overwrite = false
do_mkdir = false
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id] [file]")
build_common_options(opts, options, [:dry_run, :remote])
opts.on( '--format VALUE', String, "Report Format for exported file, json or csv. Default is json." ) do |val|
report_format = val
end
opts.on( '-f', '--force', "Overwrite existing [local-file] if it exists." ) do
do_overwrite = true
# do_mkdir = true
end
opts.on( '-p', '--mkdir', "Create missing directories for [local-file] if they do not exist." ) do
do_mkdir = true
end
opts.footer = "Export a report result as json or csv." + "\n" +
"[id] is required. This is id of the report result." + "\n" +
"[file] is required. This is local destination for the downloaded file."
end
optparse.parse!(args)
if args.count != 2
raise_command_error "wrong number of arguments, expected 2 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
outfile = args[1]
outfile = File.expand_path(outfile)
if Dir.exists?(outfile)
print_red_alert "[file] is invalid. It is the name of an existing directory: #{outfile}"
return 1
end
destination_dir = File.dirname(outfile)
if !Dir.exists?(destination_dir)
if do_mkdir
print cyan,"Creating local directory #{destination_dir}",reset,"\n"
FileUtils.mkdir_p(destination_dir)
else
print_red_alert "[file] is invalid. Directory not found: #{destination_dir}"
return 1
end
end
if File.exists?(outfile)
if do_overwrite
# uhh need to be careful wih the passed filepath here..
# don't delete, just overwrite.
# File.delete(outfile)
else
print_error Morpheus::Terminal.angry_prompt
puts_error "[file] is invalid. File already exists: #{outfile}", "Use -f to overwrite the existing file."
# puts_error optparse
return 1
end
end
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.export(report_result['id'], outfile, params, report_format)
return 0
end
json_response = @reports_interface.export(report_result['id'], outfile, params, report_format)
print_green_success "Exported report result #{report_result['id']} to file #{outfile}"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def remove(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage("[id]")
build_common_options(opts, options, [:auto_confirm, :json, :dry_run, :remote])
opts.footer = "Delete a report result." + "\n" +
"[id] is required. This is id of the report result."
end
optparse.parse!(args)
if args.count != 1
raise_command_error "wrong number of arguments, expected 1 and got (#{args.count}) #{args.join(' ')}\n#{optparse}"
end
connect(options)
begin
report_result = find_report_result_by_id(args[0])
return 1 if report_result.nil?
unless options[:yes] || Morpheus::Cli::OptionTypes.confirm("Are you sure you want to delete the report result: #{report_result['id']}?")
return 9, "aborted command"
end
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.destroy(report_result['id'])
return
end
json_response = @reports_interface.destroy(report_result['id'])
if options[:json]
puts as_json(json_response, options)
return 0
end
print_green_success "Deleted report result #{report_result['id']}"
#list([])
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def types(args)
options = {}
optparse = Morpheus::Cli::OptionParser.new do |opts|
opts.banner = subcommand_usage()
build_common_options(opts, options, [:list, :json, :dry_run, :remote])
opts.footer = "List report types."
end
optparse.parse!(args)
connect(options)
begin
params = {}
params.merge!(parse_list_options(options))
@reports_interface.setopts(options)
if options[:dry_run]
print_dry_run @reports_interface.dry.types(params)
return
end
json_response = @reports_interface.types(params)
if options[:json]
print JSON.pretty_generate(json_response)
print "\n"
return
end
title = "Morpheus Report Types"
subtitles = []
subtitles += parse_list_subtitles(options)
print_h1 title, subtitles
report_types = json_response['reportTypes']
if report_types.empty?
print cyan,"No report types found.",reset,"\n"
else
columns = {
"NAME" => 'name',
"CODE" => 'code'
}
# custom pretty table columns ...
if options[:include_fields]
columns = options[:include_fields]
end
print as_pretty_table(report_types, columns, options)
print reset
if json_response['meta']
print_results_pagination(json_response)
else
print_results_pagination({'meta'=>{'total'=>(report_types.size),'size'=>report_types.size,'max'=>(params['max']||25),'offset'=>(params['offset']||0)}})
end
end
print reset,"\n"
return 0
rescue RestClient::Exception => e
print_rest_exception(e, options)
exit 1
end
end
def find_report_result_by_id(id)
begin
json_response = @reports_interface.get(id.to_i)
return json_response['reportResult']
rescue RestClient::Exception => e
if e.response && e.response.code == 404
print_red_alert "Report Result not found by id #{id}"
return nil
else
raise e
end
end
end
def find_report_type_by_name_or_code_id(val)
if val.to_s =~ /\A\d{1,}\Z/
return find_report_type_by_id(val)
else
return find_report_type_by_name_or_code(val)
end
end
def find_report_type_by_id(id)
@all_report_types ||= @reports_interface.list({max: 1000})['reportTypes'] || []
report_types = @all_report_types.select { |it| id && it['id'] == id.to_i }
if report_types.empty?
print_red_alert "Report Type not found by id #{id}"
return nil
elsif report_types.size > 1
print_red_alert "#{report_types.size} report types found by id #{id}"
rows = report_types.collect do |it|
{id: it['id'], code: it['code'], name: it['name']}
end
print "\n"
puts as_pretty_table(rows, [:id, :code, :name], {color:red})
return nil
else
return report_types[0]
end
end
def find_report_type_by_name_or_code(name)
@all_report_types ||= @reports_interface.list({max: 1000})['reportTypes'] || []
report_types = @all_report_types.select { |it| name && it['code'] == name || it['name'] == name }
if report_types.empty?
print_red_alert "Report Type not found by code #{name}"
return nil
elsif report_types.size > 1
print_red_alert "#{report_types.size} report types found by code #{name}"
rows = report_types.collect do |it|
{id: it['id'], code: it['code'], name: it['name']}
end
print "\n"
puts as_pretty_table(rows, [:id, :code, :name], {color:red})
return nil
else
return report_types[0]
end
end
def format_report_status(report_result, return_color=cyan)
out = ""
status_string = report_result['status'].to_s
if status_string == 'ready'
out << "#{green}#{status_string.upcase}#{return_color}"
elsif status_string == 'requested'
out << "#{cyan}#{status_string.upcase}#{return_color}"
elsif status_string == 'generating'
out << "#{cyan}#{status_string.upcase}#{return_color}"
elsif status_string == 'failed'
out << "#{red}#{status_string.upcase}#{return_color}"
else
out << "#{yellow}#{status_string.upcase}#{return_color}"
end
out
end
# Prompts user for metadata for report filter
# returns array of metadata objects {id: null, name: "MYTAG", value: "myvalue"}
def prompt_metadata(options={})
#puts "Configure Environment Variables:"
no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
metadata_filter = {}
metadata_index = 0
has_another_metadata = options[:options] && options[:options]["metadata#{metadata_index}"]
add_another_metadata = has_another_metadata || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add a metadata tag filter?", {default: false}))
while add_another_metadata do
field_context = "metadata#{metadata_index}"
metadata = {}
metadata['id'] = nil
metadata_label = metadata_index == 0 ? "Metadata Tag" : "Metadata Tag [#{metadata_index+1}]"
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "#{metadata_label} Name", 'required' => true, 'description' => 'Metadata Tag Name.', 'defaultValue' => metadata['name']}], options[:options])
# todo: metadata.type ?
metadata['name'] = v_prompt[field_context]['name'].to_s
v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'value', 'type' => 'text', 'fieldLabel' => "#{metadata_label} Value", 'required' => true, 'description' => 'Metadata Tag Value', 'defaultValue' => metadata['value']}], options[:options])
metadata['value'] = v_prompt[field_context]['value'].to_s
metadata_filter[metadata['name']] = metadata['value']
metadata_index += 1
has_another_metadata = options[:options] && options[:options]["metadata#{metadata_index}"]
add_another_metadata = has_another_metadata || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another metadata tag filter?", {default: false}))
end
return metadata_filter
end
end
|
# frozen_string_literal: true
require "tempfile"
require "digest"
using Mournmail::MessageRendering
module Mournmail
class SearchResultMode < Mournmail::SummaryMode
SEARCH_RESULT_MODE_MAP = Keymap.new
SEARCH_RESULT_MODE_MAP.define_key(" ", :summary_read_command)
SEARCH_RESULT_MODE_MAP.define_key(:backspace, :summary_scroll_down_command)
SEARCH_RESULT_MODE_MAP.define_key("\C-h", :summary_scroll_down_command)
SEARCH_RESULT_MODE_MAP.define_key("\C-?", :summary_scroll_down_command)
SEARCH_RESULT_MODE_MAP.define_key("w", :summary_write_command)
SEARCH_RESULT_MODE_MAP.define_key("a", :summary_reply_command)
SEARCH_RESULT_MODE_MAP.define_key("A", :summary_reply_command)
# SEARCH_RESULT_MODE_MAP.define_key("f", :summary_forward_command)
SEARCH_RESULT_MODE_MAP.define_key("v", :summary_view_source_command)
SEARCH_RESULT_MODE_MAP.define_key("u", :search_result_close_command)
SEARCH_RESULT_MODE_MAP.define_key("k", :previous_line)
SEARCH_RESULT_MODE_MAP.define_key("j", :next_line)
SEARCH_RESULT_MODE_MAP.define_key("<", :previous_page_command)
SEARCH_RESULT_MODE_MAP.define_key(">", :next_page_command)
SEARCH_RESULT_MODE_MAP.define_key("/", :summary_search_command)
SEARCH_RESULT_MODE_MAP.define_key("t", :summary_show_thread_command)
def initialize(buffer)
super(buffer)
buffer.keymap = SEARCH_RESULT_MODE_MAP
end
define_local_command(:summary_read, doc: "Read a mail.") do
num = scroll_up_or_current_number
return if num.nil?
Mournmail.background do
message = @buffer[:messages][num]
if message.nil?
raise EditorError, "No message found"
end
mail = Mail.new(File.read(message.path))
next_tick do
show_message(mail)
@buffer[:message_number] = num
end
end
end
define_local_command(:summary_scroll_down,
doc: "Scroll down the current message.") do
num = @buffer.current_line
if num == @buffer[:message_number]
window = Mournmail.message_window
if window.buffer.name == "*message*"
old_window = Window.current
begin
Window.current = window
scroll_down
return
ensure
Window.current = old_window
end
end
end
end
define_local_command(:search_result_close,
doc: "Close the search result.") do
if @buffer.name == "*thread*"
buf = Buffer["*search result*"] || "*summary*"
else
buf = "*summary*"
end
kill_buffer(@buffer)
switch_to_buffer(buf)
end
define_local_command(:previous_page,
doc: "Show the previous page.") do
messages = @buffer[:messages]
page = messages.current_page - 1
if page < 1
raise EditorError, "No more page."
end
summary_search(@buffer[:query], page)
end
define_local_command(:next_page,
doc: "Show the next page.") do
messages = @buffer[:messages]
page = messages.current_page + 1
if page > messages.n_pages
raise EditorError, "No more page."
end
summary_search(@buffer[:query], page)
end
private
def scroll_up_or_current_number
begin
num = @buffer.current_line
if num == @buffer[:message_number]
window = Mournmail.message_window
if window.buffer.name == "*message*"
old_window = Window.current
begin
Window.current = window
scroll_up
return nil
ensure
Window.current = old_window
end
end
end
num
rescue RangeError # may be raised by scroll_up
next_message
retry
end
end
def read_current_mail
message = @buffer[:messages][@buffer.current_line]
if message.nil?
raise EditorError, "No message found"
end
[File.read(message.path), false]
end
def next_message
@buffer.end_of_line
if @buffer.end_of_buffer?
raise EditorError, "No more mail"
end
@buffer.forward_line
end
def current_message
message = @buffer[:messages][@buffer.current_line]
if message.nil?
raise EditorError, "No message found"
end
message
end
end
end
Change the key binding of search_result_close_command.
# frozen_string_literal: true
require "tempfile"
require "digest"
using Mournmail::MessageRendering
module Mournmail
class SearchResultMode < Mournmail::SummaryMode
SEARCH_RESULT_MODE_MAP = Keymap.new
SEARCH_RESULT_MODE_MAP.define_key(" ", :summary_read_command)
SEARCH_RESULT_MODE_MAP.define_key(:backspace, :summary_scroll_down_command)
SEARCH_RESULT_MODE_MAP.define_key("\C-h", :summary_scroll_down_command)
SEARCH_RESULT_MODE_MAP.define_key("\C-?", :summary_scroll_down_command)
SEARCH_RESULT_MODE_MAP.define_key("w", :summary_write_command)
SEARCH_RESULT_MODE_MAP.define_key("a", :summary_reply_command)
SEARCH_RESULT_MODE_MAP.define_key("A", :summary_reply_command)
# SEARCH_RESULT_MODE_MAP.define_key("f", :summary_forward_command)
SEARCH_RESULT_MODE_MAP.define_key("v", :summary_view_source_command)
SEARCH_RESULT_MODE_MAP.define_key("q", :search_result_close_command)
SEARCH_RESULT_MODE_MAP.define_key("k", :previous_line)
SEARCH_RESULT_MODE_MAP.define_key("j", :next_line)
SEARCH_RESULT_MODE_MAP.define_key("<", :previous_page_command)
SEARCH_RESULT_MODE_MAP.define_key(">", :next_page_command)
SEARCH_RESULT_MODE_MAP.define_key("/", :summary_search_command)
SEARCH_RESULT_MODE_MAP.define_key("t", :summary_show_thread_command)
def initialize(buffer)
super(buffer)
buffer.keymap = SEARCH_RESULT_MODE_MAP
end
define_local_command(:summary_read, doc: "Read a mail.") do
num = scroll_up_or_current_number
return if num.nil?
Mournmail.background do
message = @buffer[:messages][num]
if message.nil?
raise EditorError, "No message found"
end
mail = Mail.new(File.read(message.path))
next_tick do
show_message(mail)
@buffer[:message_number] = num
end
end
end
define_local_command(:summary_scroll_down,
doc: "Scroll down the current message.") do
num = @buffer.current_line
if num == @buffer[:message_number]
window = Mournmail.message_window
if window.buffer.name == "*message*"
old_window = Window.current
begin
Window.current = window
scroll_down
return
ensure
Window.current = old_window
end
end
end
end
define_local_command(:search_result_close,
doc: "Close the search result.") do
if @buffer.name == "*thread*"
buf = Buffer["*search result*"] || "*summary*"
else
buf = "*summary*"
end
kill_buffer(@buffer)
switch_to_buffer(buf)
end
define_local_command(:previous_page,
doc: "Show the previous page.") do
messages = @buffer[:messages]
page = messages.current_page - 1
if page < 1
raise EditorError, "No more page."
end
summary_search(@buffer[:query], page)
end
define_local_command(:next_page,
doc: "Show the next page.") do
messages = @buffer[:messages]
page = messages.current_page + 1
if page > messages.n_pages
raise EditorError, "No more page."
end
summary_search(@buffer[:query], page)
end
private
def scroll_up_or_current_number
begin
num = @buffer.current_line
if num == @buffer[:message_number]
window = Mournmail.message_window
if window.buffer.name == "*message*"
old_window = Window.current
begin
Window.current = window
scroll_up
return nil
ensure
Window.current = old_window
end
end
end
num
rescue RangeError # may be raised by scroll_up
next_message
retry
end
end
def read_current_mail
message = @buffer[:messages][@buffer.current_line]
if message.nil?
raise EditorError, "No message found"
end
[File.read(message.path), false]
end
def next_message
@buffer.end_of_line
if @buffer.end_of_buffer?
raise EditorError, "No more mail"
end
@buffer.forward_line
end
def current_message
message = @buffer[:messages][@buffer.current_line]
if message.nil?
raise EditorError, "No message found"
end
message
end
end
end
|
require 'action_mailer'
module Notify::Adapter
#
# Platform options
# - mailer - The name or class of the mailer to use. If a name is provided, only
# including the part of the name that doesn't include "Mailer" is
# necessary. Similar to Rails routing, the action can also be specified
# using a hash to separate the mailer name from the mailer method.
# Examples:
# - "foo". Calls: FooMailer.<strategy name>
# - "foo#bar". Calls: FooMailer.bar
class ActionMailer
# TODO: switch service adapters to receive the user and the notification
# (or a presenter) instead of the delivery object.
def deliver(delivery, strategy)
# TODO: move parsing out the mailer to the Strategy object.
# This will give us the ability to stay out of the notif object during
# adaptation, and allow us to raise an error early on if the mailer
# doesn't exist.
method_name = nil
mailer = case strategy.mailer
when Class then strategy.mailer
when String, Symbol
segments = strategy.mailer.to_s.split("#")
method_name = segments[1]
mailer_class(segments[0])
else
raise AdapterError, "#{strategy.mailer} is not a valid mailer"
end
method_name ||= delivery.notification.class.id
mail = mailer.send method_name, delivery.receiver, delivery.message
mail.deliver!
end
private def mailer_class(name)
name = name.to_s.classify
"#{name.classify}Mailer".safe_constantize ||
"#{name.classify}".safe_constantize
end
end
end
Fix private method declaration for Ruby 2.0.0
require 'action_mailer'
module Notify::Adapter
#
# Platform options
# - mailer - The name or class of the mailer to use. If a name is provided, only
# including the part of the name that doesn't include "Mailer" is
# necessary. Similar to Rails routing, the action can also be specified
# using a hash to separate the mailer name from the mailer method.
# Examples:
# - "foo". Calls: FooMailer.<strategy name>
# - "foo#bar". Calls: FooMailer.bar
class ActionMailer
# TODO: switch service adapters to receive the user and the notification
# (or a presenter) instead of the delivery object.
def deliver(delivery, strategy)
# TODO: move parsing out the mailer to the Strategy object.
# This will give us the ability to stay out of the notif object during
# adaptation, and allow us to raise an error early on if the mailer
# doesn't exist.
method_name = nil
mailer = case strategy.mailer
when Class then strategy.mailer
when String, Symbol
segments = strategy.mailer.to_s.split("#")
method_name = segments[1]
mailer_class(segments[0])
else
raise AdapterError, "#{strategy.mailer} is not a valid mailer"
end
method_name ||= delivery.notification.class.id
mail = mailer.send method_name, delivery.receiver, delivery.message
mail.deliver!
end
private
def mailer_class(name)
name = name.to_s.classify
"#{name.classify}Mailer".safe_constantize ||
"#{name.classify}".safe_constantize
end
end
end
|
module Octokit
class Client
# Methods for the Pull Requests API
#
# @see https://developer.github.com/v3/pulls/
module PullRequests
# List pull requests for a repository
#
# @overload pull_requests(repo, options)
# @param repo [String, Hash, Repository] A GitHub repository
# @param options [Hash] Method options
# @option options [String] :state `open` or `closed`.
# @overload pull_requests(repo, state, options)
# @deprecated
# @param repo [String, Hash, Repository] A GitHub repository
# @param state [String] `open` or `closed`.
# @param options [Hash] Method options
# @return [Array<Sawyer::Resource>] Array of pulls
# @see https://developer.github.com/v3/pulls/#list-pull-requests
# @example
# Octokit.pull_requests('rails/rails', :state => 'closed')
def pull_requests(*args)
arguments = Arguments.new(args)
opts = arguments.options
repo = arguments.shift
if state = arguments.shift
octokit_warn "DEPRECATED: Client#pull_requests: Passing state as positional argument is deprecated. Please use :state => '#{state}'"
opts[:state] = state if state
end
paginate "repos/#{Repository.new(repo)}/pulls", opts
end
alias :pulls :pull_requests
# Get a pull request
#
# @see https://developer.github.com/v3/pulls/#get-a-single-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of the pull request to fetch
# @return [Sawyer::Resource] Pull request info
def pull_request(repo, number, options = {})
get "repos/#{Repository.new(repo)}/pulls/#{number}", options
end
alias :pull :pull_request
# Create a pull request
#
# @see https://developer.github.com/v3/pulls/#create-a-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param title [String] Title for the pull request
# @param body [String] The body for the pull request. Supports GFM.
# @return [Sawyer::Resource] The newly created pull request
def create_pull_request(repo, base, head, title, body, options = {})
pull = {
:base => base,
:head => head,
:title => title,
:body => body,
}
post "repos/#{Repository.new(repo)}/pulls", options.merge(pull)
end
# Create a pull request from existing issue
#
# @see https://developer.github.com/v3/pulls/#alternative-input
# @param repo [String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param issue [Integer] Number of Issue on which to base this pull request
# @return [Sawyer::Resource] The newly created pull request
def create_pull_request_for_issue(repo, base, head, issue, options = {})
pull = {
:base => base,
:head => head,
:issue => issue
}
post "repos/#{Repository.new(repo)}/pulls", options.merge(pull)
end
# Update a pull request
# @overload update_pull_request(repo, id, title=nil, body=nil, state=nil, options = {})
# @deprecated
# @param repo [String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @param title [String] Title for the pull request.
# @param body [String] Body content for pull request. Supports GFM.
# @param state [String] State of the pull request. `open` or `closed`.
# @overload update_pull_request(repo, id, options = {})
# @param repo [String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @option options [String] :title Title for the pull request.
# @option options [String] :body Body for the pull request.
# @option options [String] :state State for the pull request.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.update_pull_request('octokit/octokit.rb', 67, 'new title', 'updated body', 'closed')
# @example Passing nil for optional attributes to update specific attributes.
# @client.update_pull_request('octokit/octokit.rb', 67, nil, nil, 'open')
# @example Empty body by passing empty string
# @client.update_pull_request('octokit/octokit.rb', 67, nil, '')
def update_pull_request(*args)
arguments = Octokit::Arguments.new(args)
repo = arguments.shift
number = arguments.shift
patch "repos/#{Repository.new(repo)}/pulls/#{number}", arguments.options
end
# Close a pull request
#
# @param repo [String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.close_pull_request('octokit/octokit.rb', 67)
def close_pull_request(repo, number, options = {})
options.merge! :state => 'closed'
update_pull_request(repo, number, options)
end
# List commits on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of commits
def pull_request_commits(repo, number, options = {})
get "repos/#{Repository.new(repo)}/pulls/#{number}/commits", options
end
alias :pull_commits :pull_request_commits
# List pull request comments for a repository
#
# By default, Review Comments are ordered by ascending ID.
#
# @param repo [String, Repository, Hash] A GitHub repository
# @param options [Hash] Optional parameters
# @option options [String] :sort created or updated
# @option options [String] :direction asc or desc. Ignored without sort
# parameter.
# @option options [String] :since Timestamp in ISO 8601
# format: YYYY-MM-DDTHH:MM:SSZ
#
# @return [Array] List of pull request review comments.
#
# @see https://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository
#
# @example Get the pull request review comments in the octokit repository
# @client.issues_comments("octokit/octokit.rb")
#
# @example Get review comments, sort by updated asc since a time
# @client.pull_requests_comments("octokit/octokit.rb", {
# :sort => 'asc',
# :direction => 'down',
# :since => '2010-05-04T23:45:02Z'
# })
def pull_requests_comments(repo, options = {})
get("repos/#{Repository.new(repo)}/pulls/comments", options)
end
alias :pulls_comments :pull_requests_comments
alias :reviews_comments :pull_requests_comments
# List comments on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-comments-on-a-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of comments
def pull_request_comments(repo, number, options = {})
# return the comments for a pull request
get "repos/#{Repository.new(repo)}/pulls/#{number}/comments", options
end
alias :pull_comments :pull_request_comments
alias :review_comments :pull_request_comments
# Get a pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of comment to get
# @return [Sawyer::Resource] Hash representing the comment
# @see https://developer.github.com/v3/pulls/comments/#get-a-single-comment
# @example
# @client.pull_request_comment("pengwynn/octkit", 1903950)
def pull_request_comment(repo, comment_id, options = {})
get "repos/#{Repository.new(repo)}/pulls/comments/#{comment_id}", options
end
alias :pull_comment :pull_request_comment
alias :review_comment :pull_request_comment
# Create a pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment content
# @param commit_id [String] Sha of the commit to comment on.
# @param path [String] Relative path of the file to comment on.
# @param position [Integer] Line index in the diff to comment on.
# @return [Sawyer::Resource] Hash representing the new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment("octokit/octokit.rb", 163, ":shipit:",
# "2d3201e4440903d8b04a5487842053ca4883e5f0", "lib/octokit/request.rb", 47)
def create_pull_request_comment(repo, pull_id, body, commit_id, path, position, options = {})
options.merge!({
:body => body,
:commit_id => commit_id,
:path => path,
:position => position
})
post "repos/#{Repository.new(repo)}/pulls/#{pull_id}/comments", options
end
alias :create_pull_comment :create_pull_request_comment
alias :create_view_comment :create_pull_request_comment
# Create reply to a pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment contents
# @param comment_id [Integer] Comment id to reply to
# @return [Sawyer::Resource] Hash representing new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment_reply("octokit/octokit.rb", 1903950, "done.")
def create_pull_request_comment_reply(repo, pull_id, body, comment_id, options = {})
options.merge!({
:body => body,
:in_reply_to => comment_id
})
post "repos/#{Repository.new(repo)}/pulls/#{pull_id}/comments", options
end
alias :create_pull_reply :create_pull_request_comment_reply
alias :create_review_reply :create_pull_request_comment_reply
# Update pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to update
# @param body [String] Updated comment content
# @return [Sawyer::Resource] Hash representing the updated comment
# @see https://developer.github.com/v3/pulls/comments/#edit-a-comment
# @example
# @client.update_pull_request_comment("octokit/octokit.rb", 1903950, ":shipit:")
def update_pull_request_comment(repo, comment_id, body, options = {})
options.merge! :body => body
patch("repos/#{Repository.new(repo)}/pulls/comments/#{comment_id}", options)
end
alias :update_pull_comment :update_pull_request_comment
alias :update_review_comment :update_pull_request_comment
# Delete pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to delete
# @return [Boolean] True if deleted, false otherwise
# @see https://developer.github.com/v3/pulls/comments/#delete-a-comment
# @example
# @client.delete_pull_request_comment("octokit/octokit.rb", 1902707)
def delete_pull_request_comment(repo, comment_id, options = {})
boolean_from_response(:delete, "repos/#{Repository.new(repo)}/pulls/comments/#{comment_id}", options)
end
alias :delete_pull_comment :delete_pull_request_comment
alias :delete_review_comment :delete_pull_request_comment
# List files on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-pull-requests-files
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of files
def pull_request_files(repo, number, options = {})
get "repos/#{Repository.new(repo)}/pulls/#{number}/files", options
end
alias :pull_files :pull_request_files
# Merge a pull request
#
# @see https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @param commit_message [String] Optional commit message for the merge commit
# @return [Array<Sawyer::Resource>] Merge commit info if successful
def merge_pull_request(repo, number, commit_message='', options = {})
put "repos/#{Repository.new(repo)}/pulls/#{number}/merge", options.merge({:commit_message => commit_message})
end
# Check pull request merge status
#
# @see https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Boolean] True if the pull request has been merged
def pull_merged?(repo, number, options = {})
boolean_from_response :get, "repos/#{Repository.new(repo)}/pulls/#{number}/merge", options
end
alias :pull_request_merged? :pull_merged?
end
end
end
Paginate GET /repos/:owner/:repo/pulls/:number/commits
module Octokit
class Client
# Methods for the Pull Requests API
#
# @see https://developer.github.com/v3/pulls/
module PullRequests
# List pull requests for a repository
#
# @overload pull_requests(repo, options)
# @param repo [String, Hash, Repository] A GitHub repository
# @param options [Hash] Method options
# @option options [String] :state `open` or `closed`.
# @overload pull_requests(repo, state, options)
# @deprecated
# @param repo [String, Hash, Repository] A GitHub repository
# @param state [String] `open` or `closed`.
# @param options [Hash] Method options
# @return [Array<Sawyer::Resource>] Array of pulls
# @see https://developer.github.com/v3/pulls/#list-pull-requests
# @example
# Octokit.pull_requests('rails/rails', :state => 'closed')
def pull_requests(*args)
arguments = Arguments.new(args)
opts = arguments.options
repo = arguments.shift
if state = arguments.shift
octokit_warn "DEPRECATED: Client#pull_requests: Passing state as positional argument is deprecated. Please use :state => '#{state}'"
opts[:state] = state if state
end
paginate "repos/#{Repository.new(repo)}/pulls", opts
end
alias :pulls :pull_requests
# Get a pull request
#
# @see https://developer.github.com/v3/pulls/#get-a-single-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of the pull request to fetch
# @return [Sawyer::Resource] Pull request info
def pull_request(repo, number, options = {})
get "repos/#{Repository.new(repo)}/pulls/#{number}", options
end
alias :pull :pull_request
# Create a pull request
#
# @see https://developer.github.com/v3/pulls/#create-a-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param title [String] Title for the pull request
# @param body [String] The body for the pull request. Supports GFM.
# @return [Sawyer::Resource] The newly created pull request
def create_pull_request(repo, base, head, title, body, options = {})
pull = {
:base => base,
:head => head,
:title => title,
:body => body,
}
post "repos/#{Repository.new(repo)}/pulls", options.merge(pull)
end
# Create a pull request from existing issue
#
# @see https://developer.github.com/v3/pulls/#alternative-input
# @param repo [String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param issue [Integer] Number of Issue on which to base this pull request
# @return [Sawyer::Resource] The newly created pull request
def create_pull_request_for_issue(repo, base, head, issue, options = {})
pull = {
:base => base,
:head => head,
:issue => issue
}
post "repos/#{Repository.new(repo)}/pulls", options.merge(pull)
end
# Update a pull request
# @overload update_pull_request(repo, id, title=nil, body=nil, state=nil, options = {})
# @deprecated
# @param repo [String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @param title [String] Title for the pull request.
# @param body [String] Body content for pull request. Supports GFM.
# @param state [String] State of the pull request. `open` or `closed`.
# @overload update_pull_request(repo, id, options = {})
# @param repo [String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @option options [String] :title Title for the pull request.
# @option options [String] :body Body for the pull request.
# @option options [String] :state State for the pull request.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.update_pull_request('octokit/octokit.rb', 67, 'new title', 'updated body', 'closed')
# @example Passing nil for optional attributes to update specific attributes.
# @client.update_pull_request('octokit/octokit.rb', 67, nil, nil, 'open')
# @example Empty body by passing empty string
# @client.update_pull_request('octokit/octokit.rb', 67, nil, '')
def update_pull_request(*args)
arguments = Octokit::Arguments.new(args)
repo = arguments.shift
number = arguments.shift
patch "repos/#{Repository.new(repo)}/pulls/#{number}", arguments.options
end
# Close a pull request
#
# @param repo [String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.close_pull_request('octokit/octokit.rb', 67)
def close_pull_request(repo, number, options = {})
options.merge! :state => 'closed'
update_pull_request(repo, number, options)
end
# List commits on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of commits
def pull_request_commits(repo, number, options = {})
paginate "repos/#{Repository.new(repo)}/pulls/#{number}/commits", options
end
alias :pull_commits :pull_request_commits
# List pull request comments for a repository
#
# By default, Review Comments are ordered by ascending ID.
#
# @param repo [String, Repository, Hash] A GitHub repository
# @param options [Hash] Optional parameters
# @option options [String] :sort created or updated
# @option options [String] :direction asc or desc. Ignored without sort
# parameter.
# @option options [String] :since Timestamp in ISO 8601
# format: YYYY-MM-DDTHH:MM:SSZ
#
# @return [Array] List of pull request review comments.
#
# @see https://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository
#
# @example Get the pull request review comments in the octokit repository
# @client.issues_comments("octokit/octokit.rb")
#
# @example Get review comments, sort by updated asc since a time
# @client.pull_requests_comments("octokit/octokit.rb", {
# :sort => 'asc',
# :direction => 'down',
# :since => '2010-05-04T23:45:02Z'
# })
def pull_requests_comments(repo, options = {})
get("repos/#{Repository.new(repo)}/pulls/comments", options)
end
alias :pulls_comments :pull_requests_comments
alias :reviews_comments :pull_requests_comments
# List comments on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-comments-on-a-pull-request
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of comments
def pull_request_comments(repo, number, options = {})
# return the comments for a pull request
get "repos/#{Repository.new(repo)}/pulls/#{number}/comments", options
end
alias :pull_comments :pull_request_comments
alias :review_comments :pull_request_comments
# Get a pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of comment to get
# @return [Sawyer::Resource] Hash representing the comment
# @see https://developer.github.com/v3/pulls/comments/#get-a-single-comment
# @example
# @client.pull_request_comment("pengwynn/octkit", 1903950)
def pull_request_comment(repo, comment_id, options = {})
get "repos/#{Repository.new(repo)}/pulls/comments/#{comment_id}", options
end
alias :pull_comment :pull_request_comment
alias :review_comment :pull_request_comment
# Create a pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment content
# @param commit_id [String] Sha of the commit to comment on.
# @param path [String] Relative path of the file to comment on.
# @param position [Integer] Line index in the diff to comment on.
# @return [Sawyer::Resource] Hash representing the new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment("octokit/octokit.rb", 163, ":shipit:",
# "2d3201e4440903d8b04a5487842053ca4883e5f0", "lib/octokit/request.rb", 47)
def create_pull_request_comment(repo, pull_id, body, commit_id, path, position, options = {})
options.merge!({
:body => body,
:commit_id => commit_id,
:path => path,
:position => position
})
post "repos/#{Repository.new(repo)}/pulls/#{pull_id}/comments", options
end
alias :create_pull_comment :create_pull_request_comment
alias :create_view_comment :create_pull_request_comment
# Create reply to a pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment contents
# @param comment_id [Integer] Comment id to reply to
# @return [Sawyer::Resource] Hash representing new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment_reply("octokit/octokit.rb", 1903950, "done.")
def create_pull_request_comment_reply(repo, pull_id, body, comment_id, options = {})
options.merge!({
:body => body,
:in_reply_to => comment_id
})
post "repos/#{Repository.new(repo)}/pulls/#{pull_id}/comments", options
end
alias :create_pull_reply :create_pull_request_comment_reply
alias :create_review_reply :create_pull_request_comment_reply
# Update pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to update
# @param body [String] Updated comment content
# @return [Sawyer::Resource] Hash representing the updated comment
# @see https://developer.github.com/v3/pulls/comments/#edit-a-comment
# @example
# @client.update_pull_request_comment("octokit/octokit.rb", 1903950, ":shipit:")
def update_pull_request_comment(repo, comment_id, body, options = {})
options.merge! :body => body
patch("repos/#{Repository.new(repo)}/pulls/comments/#{comment_id}", options)
end
alias :update_pull_comment :update_pull_request_comment
alias :update_review_comment :update_pull_request_comment
# Delete pull request comment
#
# @param repo [String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to delete
# @return [Boolean] True if deleted, false otherwise
# @see https://developer.github.com/v3/pulls/comments/#delete-a-comment
# @example
# @client.delete_pull_request_comment("octokit/octokit.rb", 1902707)
def delete_pull_request_comment(repo, comment_id, options = {})
boolean_from_response(:delete, "repos/#{Repository.new(repo)}/pulls/comments/#{comment_id}", options)
end
alias :delete_pull_comment :delete_pull_request_comment
alias :delete_review_comment :delete_pull_request_comment
# List files on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-pull-requests-files
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of files
def pull_request_files(repo, number, options = {})
get "repos/#{Repository.new(repo)}/pulls/#{number}/files", options
end
alias :pull_files :pull_request_files
# Merge a pull request
#
# @see https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @param commit_message [String] Optional commit message for the merge commit
# @return [Array<Sawyer::Resource>] Merge commit info if successful
def merge_pull_request(repo, number, commit_message='', options = {})
put "repos/#{Repository.new(repo)}/pulls/#{number}/merge", options.merge({:commit_message => commit_message})
end
# Check pull request merge status
#
# @see https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged
# @param repo [String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Boolean] True if the pull request has been merged
def pull_merged?(repo, number, options = {})
boolean_from_response :get, "repos/#{Repository.new(repo)}/pulls/#{number}/merge", options
end
alias :pull_request_merged? :pull_merged?
end
end
end
|
module Octokit
class Client
# Methods for the Pull Requests API
#
# @see https://developer.github.com/v3/pulls/
module PullRequests
# List pull requests for a repository
#
# @overload pull_requests(repo, options)
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param options [Hash] Method options
# @option options [String] :state `open` or `closed`.
# @return [Array<Sawyer::Resource>] Array of pulls
# @see https://developer.github.com/v3/pulls/#list-pull-requests
# @example
# Octokit.pull_requests('rails/rails', :state => 'closed')
def pull_requests(repo, options = {})
paginate "#{Repository.path repo}/pulls", options
end
alias :pulls :pull_requests
# Get a pull request
#
# @see https://developer.github.com/v3/pulls/#get-a-single-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of the pull request to fetch
# @return [Sawyer::Resource] Pull request info
# @example
# Octokit.pull_request('rails/rails', 42, :state => 'closed')
def pull_request(repo, number, options = {})
get "#{Repository.path repo}/pulls/#{number}", options
end
alias :pull :pull_request
# Create a pull request
#
# @see https://developer.github.com/v3/pulls/#create-a-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param title [String] Title for the pull request
# @param body [String] The body for the pull request (optional). Supports GFM.
# @return [Sawyer::Resource] The newly created pull request
# @example
# @client.create_pull_request("octokit/octokit.rb", "master", "feature-branch",
# "Pull Request title", "Pull Request body")
def create_pull_request(repo, base, head, title, body = nil, options = {})
pull = {
:base => base,
:head => head,
:title => title,
}
pull[:body] = body unless body.nil?
post "#{Repository.path repo}/pulls", options.merge(pull)
end
# Create a pull request from existing issue
#
# @see https://developer.github.com/v3/pulls/#alternative-input
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param issue [Integer] Number of Issue on which to base this pull request
# @return [Sawyer::Resource] The newly created pull request
def create_pull_request_for_issue(repo, base, head, issue, options = {})
pull = {
:base => base,
:head => head,
:issue => issue
}
post "#{Repository.path repo}/pulls", options.merge(pull)
end
# Update a pull request
# @overload update_pull_request(repo, number, title=nil, body=nil, state=nil, options = {})
# @deprecated
# @param repo [Integer, String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @param title [String] Title for the pull request.
# @param body [String] Body content for pull request. Supports GFM.
# @param state [String] State of the pull request. `open` or `closed`.
# @overload update_pull_request(repo, number, options = {})
# @param repo [Integer, String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @option options [String] :title Title for the pull request.
# @option options [String] :body Body for the pull request.
# @option options [String] :state State for the pull request.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.update_pull_request('octokit/octokit.rb', 67, 'new title', 'updated body', 'closed')
# @example Passing nil for optional attributes to update specific attributes.
# @client.update_pull_request('octokit/octokit.rb', 67, nil, nil, 'open')
# @example Empty body by passing empty string
# @client.update_pull_request('octokit/octokit.rb', 67, nil, '')
def update_pull_request(*args)
arguments = Octokit::Arguments.new(args)
repo = arguments.shift
number = arguments.shift
patch "#{Repository.path repo}/pulls/#{number}", arguments.options
end
# Close a pull request
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.close_pull_request('octokit/octokit.rb', 67)
def close_pull_request(repo, number, options = {})
options.merge! :state => 'closed'
update_pull_request(repo, number, options)
end
# List commits on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of commits
def pull_request_commits(repo, number, options = {})
paginate "#{Repository.path repo}/pulls/#{number}/commits", options
end
alias :pull_commits :pull_request_commits
# List pull request comments for a repository
#
# By default, Review Comments are ordered by ascending ID.
#
# @param repo [Integer, String, Repository, Hash] A GitHub repository
# @param options [Hash] Optional parameters
# @option options [String] :sort created or updated
# @option options [String] :direction asc or desc. Ignored without sort
# parameter.
# @option options [String] :since Timestamp in ISO 8601
# format: YYYY-MM-DDTHH:MM:SSZ
#
# @return [Array] List of pull request review comments.
#
# @see https://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository
#
# @example Get the pull request review comments in the octokit repository
# @client.issues_comments("octokit/octokit.rb")
#
# @example Get review comments, sort by updated asc since a time
# @client.pull_requests_comments("octokit/octokit.rb", {
# :sort => 'updated',
# :direction => 'asc',
# :since => '2010-05-04T23:45:02Z'
# })
def pull_requests_comments(repo, options = {})
paginate("#{Repository.path repo}/pulls/comments", options)
end
alias :pulls_comments :pull_requests_comments
alias :reviews_comments :pull_requests_comments
# List comments on a pull request
#
# @see https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of comments
def pull_request_comments(repo, number, options = {})
# return the comments for a pull request
paginate("#{Repository.path repo}/pulls/#{number}/comments", options)
end
alias :pull_comments :pull_request_comments
alias :review_comments :pull_request_comments
# Get a pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of comment to get
# @return [Sawyer::Resource] Hash representing the comment
# @see https://developer.github.com/v3/pulls/comments/#get-a-single-comment
# @example
# @client.pull_request_comment("pengwynn/octkit", 1903950)
def pull_request_comment(repo, comment_id, options = {})
get "#{Repository.path repo}/pulls/comments/#{comment_id}", options
end
alias :pull_comment :pull_request_comment
alias :review_comment :pull_request_comment
# Create a pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment content
# @param commit_id [String] Sha of the commit to comment on.
# @param path [String] Relative path of the file to comment on.
# @param position [Integer] Line index in the diff to comment on.
# @return [Sawyer::Resource] Hash representing the new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment("octokit/octokit.rb", 163, ":shipit:",
# "2d3201e4440903d8b04a5487842053ca4883e5f0", "lib/octokit/request.rb", 47)
def create_pull_request_comment(repo, pull_id, body, commit_id, path, position, options = {})
options.merge!({
:body => body,
:commit_id => commit_id,
:path => path,
:position => position
})
post "#{Repository.path repo}/pulls/#{pull_id}/comments", options
end
alias :create_pull_comment :create_pull_request_comment
alias :create_view_comment :create_pull_request_comment
# Create reply to a pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment contents
# @param comment_id [Integer] Comment id to reply to
# @return [Sawyer::Resource] Hash representing new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment_reply("octokit/octokit.rb", 163, "done.", 1903950)
def create_pull_request_comment_reply(repo, pull_id, body, comment_id, options = {})
options.merge!({
:body => body,
:in_reply_to => comment_id
})
post "#{Repository.path repo}/pulls/#{pull_id}/comments", options
end
alias :create_pull_reply :create_pull_request_comment_reply
alias :create_review_reply :create_pull_request_comment_reply
# Update pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to update
# @param body [String] Updated comment content
# @return [Sawyer::Resource] Hash representing the updated comment
# @see https://developer.github.com/v3/pulls/comments/#edit-a-comment
# @example
# @client.update_pull_request_comment("octokit/octokit.rb", 1903950, ":shipit:")
def update_pull_request_comment(repo, comment_id, body, options = {})
options.merge! :body => body
patch("#{Repository.path repo}/pulls/comments/#{comment_id}", options)
end
alias :update_pull_comment :update_pull_request_comment
alias :update_review_comment :update_pull_request_comment
# Delete pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to delete
# @return [Boolean] True if deleted, false otherwise
# @see https://developer.github.com/v3/pulls/comments/#delete-a-comment
# @example
# @client.delete_pull_request_comment("octokit/octokit.rb", 1902707)
def delete_pull_request_comment(repo, comment_id, options = {})
boolean_from_response(:delete, "#{Repository.path repo}/pulls/comments/#{comment_id}", options)
end
alias :delete_pull_comment :delete_pull_request_comment
alias :delete_review_comment :delete_pull_request_comment
# List files on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-pull-requests-files
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of files
def pull_request_files(repo, number, options = {})
paginate "#{Repository.path repo}/pulls/#{number}/files", options
end
alias :pull_files :pull_request_files
# Merge a pull request
#
# @see https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @param commit_message [String] Optional commit message for the merge commit
# @return [Array<Sawyer::Resource>] Merge commit info if successful
def merge_pull_request(repo, number, commit_message='', options = {})
put "#{Repository.path repo}/pulls/#{number}/merge", options.merge({:commit_message => commit_message})
end
# Check pull request merge status
#
# @see https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Boolean] True if the pull request has been merged
def pull_merged?(repo, number, options = {})
boolean_from_response :get, "#{Repository.path repo}/pulls/#{number}/merge", options
end
alias :pull_request_merged? :pull_merged?
end
end
end
update pull_requests.rb document
module Octokit
class Client
# Methods for the Pull Requests API
#
# @see https://developer.github.com/v3/pulls/
module PullRequests
# List pull requests for a repository
#
# @overload pull_requests(repo, options)
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param options [Hash] Method options
# @option options [String] :state `open` or `closed` or `all`.
# @return [Array<Sawyer::Resource>] Array of pulls
# @see https://developer.github.com/v3/pulls/#list-pull-requests
# @example
# Octokit.pull_requests('rails/rails', :state => 'closed')
def pull_requests(repo, options = {})
paginate "#{Repository.path repo}/pulls", options
end
alias :pulls :pull_requests
# Get a pull request
#
# @see https://developer.github.com/v3/pulls/#get-a-single-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of the pull request to fetch
# @return [Sawyer::Resource] Pull request info
# @example
# Octokit.pull_request('rails/rails', 42, :state => 'closed')
def pull_request(repo, number, options = {})
get "#{Repository.path repo}/pulls/#{number}", options
end
alias :pull :pull_request
# Create a pull request
#
# @see https://developer.github.com/v3/pulls/#create-a-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param title [String] Title for the pull request
# @param body [String] The body for the pull request (optional). Supports GFM.
# @return [Sawyer::Resource] The newly created pull request
# @example
# @client.create_pull_request("octokit/octokit.rb", "master", "feature-branch",
# "Pull Request title", "Pull Request body")
def create_pull_request(repo, base, head, title, body = nil, options = {})
pull = {
:base => base,
:head => head,
:title => title,
}
pull[:body] = body unless body.nil?
post "#{Repository.path repo}/pulls", options.merge(pull)
end
# Create a pull request from existing issue
#
# @see https://developer.github.com/v3/pulls/#alternative-input
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param base [String] The branch (or git ref) you want your changes
# pulled into. This should be an existing branch on the current
# repository. You cannot submit a pull request to one repo that requests
# a merge to a base of another repo.
# @param head [String] The branch (or git ref) where your changes are implemented.
# @param issue [Integer] Number of Issue on which to base this pull request
# @return [Sawyer::Resource] The newly created pull request
def create_pull_request_for_issue(repo, base, head, issue, options = {})
pull = {
:base => base,
:head => head,
:issue => issue
}
post "#{Repository.path repo}/pulls", options.merge(pull)
end
# Update a pull request
# @overload update_pull_request(repo, number, title=nil, body=nil, state=nil, options = {})
# @deprecated
# @param repo [Integer, String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @param title [String] Title for the pull request.
# @param body [String] Body content for pull request. Supports GFM.
# @param state [String] State of the pull request. `open` or `closed`.
# @overload update_pull_request(repo, number, options = {})
# @param repo [Integer, String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @option options [String] :title Title for the pull request.
# @option options [String] :body Body for the pull request.
# @option options [String] :state State for the pull request.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.update_pull_request('octokit/octokit.rb', 67, 'new title', 'updated body', 'closed')
# @example Passing nil for optional attributes to update specific attributes.
# @client.update_pull_request('octokit/octokit.rb', 67, nil, nil, 'open')
# @example Empty body by passing empty string
# @client.update_pull_request('octokit/octokit.rb', 67, nil, '')
def update_pull_request(*args)
arguments = Octokit::Arguments.new(args)
repo = arguments.shift
number = arguments.shift
patch "#{Repository.path repo}/pulls/#{number}", arguments.options
end
# Close a pull request
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository.
# @param number [Integer] Number of pull request to update.
# @return [Sawyer::Resource] Hash representing updated pull request.
# @see https://developer.github.com/v3/pulls/#update-a-pull-request
# @example
# @client.close_pull_request('octokit/octokit.rb', 67)
def close_pull_request(repo, number, options = {})
options.merge! :state => 'closed'
update_pull_request(repo, number, options)
end
# List commits on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of commits
def pull_request_commits(repo, number, options = {})
paginate "#{Repository.path repo}/pulls/#{number}/commits", options
end
alias :pull_commits :pull_request_commits
# List pull request comments for a repository
#
# By default, Review Comments are ordered by ascending ID.
#
# @param repo [Integer, String, Repository, Hash] A GitHub repository
# @param options [Hash] Optional parameters
# @option options [String] :sort created or updated
# @option options [String] :direction asc or desc. Ignored without sort
# parameter.
# @option options [String] :since Timestamp in ISO 8601
# format: YYYY-MM-DDTHH:MM:SSZ
#
# @return [Array] List of pull request review comments.
#
# @see https://developer.github.com/v3/pulls/comments/#list-comments-in-a-repository
#
# @example Get the pull request review comments in the octokit repository
# @client.issues_comments("octokit/octokit.rb")
#
# @example Get review comments, sort by updated asc since a time
# @client.pull_requests_comments("octokit/octokit.rb", {
# :sort => 'updated',
# :direction => 'asc',
# :since => '2010-05-04T23:45:02Z'
# })
def pull_requests_comments(repo, options = {})
paginate("#{Repository.path repo}/pulls/comments", options)
end
alias :pulls_comments :pull_requests_comments
alias :reviews_comments :pull_requests_comments
# List comments on a pull request
#
# @see https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of comments
def pull_request_comments(repo, number, options = {})
# return the comments for a pull request
paginate("#{Repository.path repo}/pulls/#{number}/comments", options)
end
alias :pull_comments :pull_request_comments
alias :review_comments :pull_request_comments
# Get a pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of comment to get
# @return [Sawyer::Resource] Hash representing the comment
# @see https://developer.github.com/v3/pulls/comments/#get-a-single-comment
# @example
# @client.pull_request_comment("pengwynn/octkit", 1903950)
def pull_request_comment(repo, comment_id, options = {})
get "#{Repository.path repo}/pulls/comments/#{comment_id}", options
end
alias :pull_comment :pull_request_comment
alias :review_comment :pull_request_comment
# Create a pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment content
# @param commit_id [String] Sha of the commit to comment on.
# @param path [String] Relative path of the file to comment on.
# @param position [Integer] Line index in the diff to comment on.
# @return [Sawyer::Resource] Hash representing the new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment("octokit/octokit.rb", 163, ":shipit:",
# "2d3201e4440903d8b04a5487842053ca4883e5f0", "lib/octokit/request.rb", 47)
def create_pull_request_comment(repo, pull_id, body, commit_id, path, position, options = {})
options.merge!({
:body => body,
:commit_id => commit_id,
:path => path,
:position => position
})
post "#{Repository.path repo}/pulls/#{pull_id}/comments", options
end
alias :create_pull_comment :create_pull_request_comment
alias :create_view_comment :create_pull_request_comment
# Create reply to a pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param pull_id [Integer] Pull request id
# @param body [String] Comment contents
# @param comment_id [Integer] Comment id to reply to
# @return [Sawyer::Resource] Hash representing new comment
# @see https://developer.github.com/v3/pulls/comments/#create-a-comment
# @example
# @client.create_pull_request_comment_reply("octokit/octokit.rb", 163, "done.", 1903950)
def create_pull_request_comment_reply(repo, pull_id, body, comment_id, options = {})
options.merge!({
:body => body,
:in_reply_to => comment_id
})
post "#{Repository.path repo}/pulls/#{pull_id}/comments", options
end
alias :create_pull_reply :create_pull_request_comment_reply
alias :create_review_reply :create_pull_request_comment_reply
# Update pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to update
# @param body [String] Updated comment content
# @return [Sawyer::Resource] Hash representing the updated comment
# @see https://developer.github.com/v3/pulls/comments/#edit-a-comment
# @example
# @client.update_pull_request_comment("octokit/octokit.rb", 1903950, ":shipit:")
def update_pull_request_comment(repo, comment_id, body, options = {})
options.merge! :body => body
patch("#{Repository.path repo}/pulls/comments/#{comment_id}", options)
end
alias :update_pull_comment :update_pull_request_comment
alias :update_review_comment :update_pull_request_comment
# Delete pull request comment
#
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param comment_id [Integer] Id of the comment to delete
# @return [Boolean] True if deleted, false otherwise
# @see https://developer.github.com/v3/pulls/comments/#delete-a-comment
# @example
# @client.delete_pull_request_comment("octokit/octokit.rb", 1902707)
def delete_pull_request_comment(repo, comment_id, options = {})
boolean_from_response(:delete, "#{Repository.path repo}/pulls/comments/#{comment_id}", options)
end
alias :delete_pull_comment :delete_pull_request_comment
alias :delete_review_comment :delete_pull_request_comment
# List files on a pull request
#
# @see https://developer.github.com/v3/pulls/#list-pull-requests-files
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Array<Sawyer::Resource>] List of files
def pull_request_files(repo, number, options = {})
paginate "#{Repository.path repo}/pulls/#{number}/files", options
end
alias :pull_files :pull_request_files
# Merge a pull request
#
# @see https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @param commit_message [String] Optional commit message for the merge commit
# @return [Array<Sawyer::Resource>] Merge commit info if successful
def merge_pull_request(repo, number, commit_message='', options = {})
put "#{Repository.path repo}/pulls/#{number}/merge", options.merge({:commit_message => commit_message})
end
# Check pull request merge status
#
# @see https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged
# @param repo [Integer, String, Hash, Repository] A GitHub repository
# @param number [Integer] Number of pull request
# @return [Boolean] True if the pull request has been merged
def pull_merged?(repo, number, options = {})
boolean_from_response :get, "#{Repository.path repo}/pulls/#{number}/merge", options
end
alias :pull_request_merged? :pull_merged?
end
end
end
|
require "omniauth"
module Omniauth
module Strategies
class Delivery
include Omniauth::Strategy
option :fields, [:name, :email]
end
end
end
added client options
require "omniauth"
module Omniauth
module Strategies
class Delivery < Omniauth::Strategies::OAuth2
option :fields, [:name, :email]
option :client_options, {
:site => "api.delivery.com",
:authorize_url => "/third_party/authorize",
:token_url => "/third_party/access_token"
}
end
end
end |
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'error_data'
s.version = '0.1.9'
s.summary = 'Representation of an error as a data structure'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/error-data'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'schema'
s.add_runtime_dependency 'casing'
s.add_development_dependency 'serialize'
s.add_development_dependency 'test_bench'
s.add_development_dependency 'pry'
end
Pry is removed
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'error_data'
s.version = '0.0.1.9'
s.summary = 'Representation of an error as a data structure'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/error-data'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'schema'
s.add_runtime_dependency 'casing'
s.add_development_dependency 'serialize'
s.add_development_dependency 'test_bench'
end
|
module Pacer
class Route
class << self
def property_filter_before(base, filters, block)
if filters and filters.any? or block
yield new(:back => base, :filter => :property, :filters => filters, :block => block)
else
yield base
end
end
def property_filter(base, filters, block)
if filters and filters.any? or block
new(:back => base, :filter => :property, :filters => filters, :block => block)
elsif Pacer.vertex? base
new(:back => base, :pipe_class => Pacer::Pipes::IdentityPipe)
elsif Pacer.edge? base
new(:back => base, :pipe_class => Pacer::Pipes::IdentityPipe)
else
base
end
end
end
end
module Filter
module PropertyFilter
module EdgeLabels
# Specialize filter_pipe for edge labels.
def filter_pipe(pipe, filters, block, expand_extensions)
pipe, filters = expand_extension_conditions(pipe, filters) if expand_extensions
labels = filters.select { |arg| arg.is_a? Symbol or arg.is_a? String }
if labels.empty?
super
else
label_pipe = Pacer::Pipes::LabelCollectionFilterPipe.new labels.collect { |l| l.to_s }, Pacer::Pipes::NOT_EQUAL
label_pipe.set_starts pipe
super(label_pipe, filters - labels, block, false)
end
end
end
def self.triggers
[:filters]
end
attr_accessor :block
def filters=(filter_array)
case filter_array
when Array
@filters = filter_array
when nil
@filters = []
else
@filters = [filter_array]
end
# Sometimes filters are modules. If they contain a Route submodule, extend this route with that module.
add_extensions @filters
end
# Return an array of filter options for the current route.
def filters
@filters ||= []
end
protected
def after_initialize
if element_type == graph.element_type(:edge)
extend EdgeLabels
end
end
def attach_pipe(end_pipe)
filter_pipe(end_pipe, @filters, @block, true)
end
# Appends the defined filter pipes to narrow the results passed through
# the pipes for this route object.
def filter_pipe(pipe, args_array, block, expand_extensions)
if args_array and args_array.any?
pipe, args_array = expand_extension_conditions(pipe, args_array) if expand_extensions
pipe = args_array.select { |arg| arg.is_a? Hash }.inject(pipe) do |p, hash|
hash.inject(p) do |p2, (key, value)|
new_pipe = Pacer::Pipes::PropertyFilterPipe.new(key.to_s, value.to_java, Pacer::Pipes::ComparisonFilterPipe::Filter::NOT_EQUAL)
new_pipe.set_starts p2 if p2
new_pipe
end
end
end
if block
block_pipe = Pacer::Pipes::BlockFilterPipe.new(self, block)
block_pipe.set_starts pipe
pipe = block_pipe
end
pipe
end
def expand_extension_conditions(pipe, args_array)
modules = args_array.select { |obj| obj.is_a? Module or obj.is_a? Class }
pipe = modules.inject(pipe) do |p, mod|
if mod.respond_to? :route_conditions
if mod.route_conditions.is_a? Array
args_array = args_array + mod.route_conditions
else
args_array = args_array + [mod.route_conditions]
end
p
elsif mod.respond_to? :route
route = mod.route(Pacer::Route.empty(self))
s, e = route.send :build_pipeline
s.setStarts(p)
e
else
p
end
end
[pipe, args_array]
end
def inspect_string
fs = filters.map do |f|
if f.is_a? Hash
f.map { |k, v| "#{ k }==#{ v.inspect }" }
else
f.inspect
end
end
fs << '&block' if @block
s = inspect_class_name
if fs or bs
s = "#{s}(#{ fs.join(', ') })"
end
s
end
end
end
end
'string'.to_java is called .to_java_string in jruby 1.4.
module Pacer
class Route
class << self
def property_filter_before(base, filters, block)
if filters and filters.any? or block
yield new(:back => base, :filter => :property, :filters => filters, :block => block)
else
yield base
end
end
def property_filter(base, filters, block)
if filters and filters.any? or block
new(:back => base, :filter => :property, :filters => filters, :block => block)
elsif Pacer.vertex? base
new(:back => base, :pipe_class => Pacer::Pipes::IdentityPipe)
elsif Pacer.edge? base
new(:back => base, :pipe_class => Pacer::Pipes::IdentityPipe)
else
base
end
end
end
end
module Filter
module PropertyFilter
module EdgeLabels
# Specialize filter_pipe for edge labels.
def filter_pipe(pipe, filters, block, expand_extensions)
pipe, filters = expand_extension_conditions(pipe, filters) if expand_extensions
labels = filters.select { |arg| arg.is_a? Symbol or arg.is_a? String }
if labels.empty?
super
else
label_pipe = Pacer::Pipes::LabelCollectionFilterPipe.new labels.collect { |l| l.to_s }, Pacer::Pipes::NOT_EQUAL
label_pipe.set_starts pipe
super(label_pipe, filters - labels, block, false)
end
end
end
def self.triggers
[:filters]
end
attr_accessor :block
def filters=(filter_array)
case filter_array
when Array
@filters = filter_array
when nil
@filters = []
else
@filters = [filter_array]
end
# Sometimes filters are modules. If they contain a Route submodule, extend this route with that module.
add_extensions @filters
end
# Return an array of filter options for the current route.
def filters
@filters ||= []
end
protected
def after_initialize
if element_type == graph.element_type(:edge)
extend EdgeLabels
end
end
def attach_pipe(end_pipe)
filter_pipe(end_pipe, @filters, @block, true)
end
# Appends the defined filter pipes to narrow the results passed through
# the pipes for this route object.
def filter_pipe(pipe, args_array, block, expand_extensions)
if args_array and args_array.any?
pipe, args_array = expand_extension_conditions(pipe, args_array) if expand_extensions
pipe = args_array.select { |arg| arg.is_a? Hash }.inject(pipe) do |p, hash|
hash.inject(p) do |p2, (key, value)|
if value.respond_to? :to_java
jvalue = value.to_java
elsif value.respond_to? :to_java_string
jvalue = value.to_java_string
else
jvalue = value
end
new_pipe = Pacer::Pipes::PropertyFilterPipe.new(key.to_s, jvalue, Pacer::Pipes::ComparisonFilterPipe::Filter::NOT_EQUAL)
new_pipe.set_starts p2 if p2
new_pipe
end
end
end
if block
block_pipe = Pacer::Pipes::BlockFilterPipe.new(self, block)
block_pipe.set_starts pipe
pipe = block_pipe
end
pipe
end
def expand_extension_conditions(pipe, args_array)
modules = args_array.select { |obj| obj.is_a? Module or obj.is_a? Class }
pipe = modules.inject(pipe) do |p, mod|
if mod.respond_to? :route_conditions
if mod.route_conditions.is_a? Array
args_array = args_array + mod.route_conditions
else
args_array = args_array + [mod.route_conditions]
end
p
elsif mod.respond_to? :route
route = mod.route(Pacer::Route.empty(self))
s, e = route.send :build_pipeline
s.setStarts(p)
e
else
p
end
end
[pipe, args_array]
end
def inspect_string
fs = filters.map do |f|
if f.is_a? Hash
f.map { |k, v| "#{ k }==#{ v.inspect }" }
else
f.inspect
end
end
fs << '&block' if @block
s = inspect_class_name
if fs or bs
s = "#{s}(#{ fs.join(', ') })"
end
s
end
end
end
end
|
module Phony
module NationalSplitters
# TODO
#
class DSL
#
#
def >> local_splitter
if local_splitter.respond_to? :split
country_for local_splitter, true
else
local_splitter.national_splitter = self
local_splitter
end
end
def country_for local_splitter, with_zero, trunk = '0'
Phony::Country.new Phony::NationalCode.new(self, local_splitter, with_zero, trunk)
end
end
end
end
Rename correctly.
module Phony
module NationalSplitters
# TODO
#
class DSL
#
#
def >> local_splitter
if local_splitter.respond_to? :split
country_for local_splitter, true
else
local_splitter.national_splitter = self
local_splitter
end
end
def country_for local_splitter, normalize, trunk = '0'
Phony::Country.new Phony::NationalCode.new(self, local_splitter, normalize, trunk)
end
end
end
end |
module Plivo
module Resources
include Plivo::Utils
class Application < Base::Resource
def initialize(client, options = nil)
@_name = 'Application'
@_identifier_string = 'app_id'
super
@_is_voice_request = true
end
# @param [Hash] options
# @option options [String] :answer_url - The URL invoked by Plivo when a call executes this application.
# @option options [String] :answer_method - The method used to call the answer_url. Defaults to POST.
# @option options [String] :hangup_url - The URL that will be notified by Plivo when the call hangs up. Defaults to answer_url.
# @option options [String] :hangup_method - The method used to call the hangup_url. Defaults to POST.
# @option options [String] :fallback_answer_url - Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
# @option options [String] :fallback_method - The method used to call the fallback_answer_url. Defaults to POST.
# @option options [String] :message_url - The URL that will be notified by Plivo when an inbound message is received. Defaults not set.
# @option options [String] :message_method - The method used to call the message_url. Defaults to POST.
# @option options [Boolean] :default_number_app - If set to true, this parameter ensures that newly created numbers, which don't have an app_id, point to this application.
# @option options [Boolean] :default_endpoint_app - If set to true, this parameter ensures that newly created endpoints, which don't have an app_id, point to this application.
# @option options [String] :subaccount - Id of the subaccount, in case only subaccount applications are needed.
# @option options [Boolean] :log_incoming_messages - If set to true, this parameter ensures that incoming messages are logged.
# @return [Application] Application
def update(options = nil)
return perform_update({}) if options.nil?
valid_param?(:options, options, Hash, true)
params = {}
%i[answer_url hangup_url fallback_answer_url message_url subaccount]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true)
params[param] = options[param]
end
end
%i[answer_method hangup_method fallback_method message_method]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true, %w[GET POST])
params[param] = options[param]
end
end
%i[default_number_app default_endpoint_app log_incoming_messages].each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [TrueClass, FalseClass], true)
params[param] = options[param]
end
end
perform_update(params)
end
# @param [Hash] options
# @option options [Boolean] :cascade - delete associated endpoints
# @option options [String] :new_endpoint_application - Link associated endpoints to this app
def delete(options = nil)
return perform_delete if options.nil?
params = {}
if options.key?(:cascade) && valid_param?(:cascade, options[:cascade], [TrueClass, FalseClass], false, [true, false])
params[:cascade] = options[:cascade]
end
if options.key?(:new_endpoint_application) && valid_param?(:new_endpoint_application, options[:new_endpoint_application], [String, Symbol])
params[:new_endpoint_application] = options[:new_endpoint_application]
end
perform_delete(params)
end
def to_s
{
answer_method: @answer_method,
answer_url: @answer_url,
app_id: @app_id,
api_id: @api_id,
app_name: @app_name,
default_app: @default_app,
default_endpoint_app: @default_endpoint_app,
enabled: @enabled,
fallback_answer_url: @fallback_answer_url,
fallback_method: @fallback_method,
hangup_method: @hangup_method,
hangup_url: @hangup_url,
message_method: @message_method,
message_url: @message_url,
public_uri: @public_uri,
resource_uri: @resource_uri,
sip_uri: @sip_uri,
sub_account: @sub_account,
log_incoming_messages: @log_incoming_messages
}.to_s
end
end
# @!method get
# @!method create
# @!method list
class ApplicationInterface < Base::ResourceInterface
def initialize(client, resource_list_json = nil)
@_name = 'Application'
@_resource_type = Application
@_identifier_string = 'app_id'
super
@_is_voice_request = true
end
# @param [String] app_id
# @return [Application] Application
def get(app_id)
valid_param?(:app_id, app_id, [String, Symbol], true)
perform_get(app_id)
end
# @param [String] app_name
# @param [Hash] options
# @option options [String] :answer_url - The URL invoked by Plivo when a call executes this application.
# @option options [String] :answer_method - The method used to call the answer_url. Defaults to POST.
# @option options [String] :hangup_url - The URL that will be notified by Plivo when the call hangs up. Defaults to answer_url.
# @option options [String] :hangup_method - The method used to call the hangup_url. Defaults to POST.
# @option options [String] :fallback_answer_url - Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
# @option options [String] :fallback_method - The method used to call the fallback_answer_url. Defaults to POST.
# @option options [String] :message_url - The URL that will be notified by Plivo when an inbound message is received. Defaults not set.
# @option options [String] :message_method - The method used to call the message_url. Defaults to POST.
# @option options [Boolean] :default_number_app - If set to true, this parameter ensures that newly created numbers, which don't have an app_id, point to this application.
# @option options [Boolean] :default_endpoint_app - If set to true, this parameter ensures that newly created endpoints, which don't have an app_id, point to this application.
# @option options [String] :subaccount - Id of the subaccount, in case only subaccount applications are needed.
# @option options [Boolean] :log_incoming_messages - If set to true, this parameter ensures that incoming messages are logged.
# @return [Application] Application
def create(app_name, options = nil)
valid_param?(:app_name, app_name, [String, Symbol], true)
valid_param?(:options, options, Hash, true) unless options.nil?
params = {
app_name: app_name
}
return perform_create(params) if options.nil?
%i[answer_url hangup_url fallback_answer_url message_url subaccount]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true)
params[param] = options[param]
end
end
%i[answer_method hangup_method fallback_method message_method]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true, %w[GET POST])
params[param] = options[param]
end
end
%i[default_number_app default_endpoint_app log_incoming_messages].each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [TrueClass, FalseClass], true)
params[param] = options[param]
end
end
perform_create(params)
end
##
# Lists all applications
# @param [Hash] options
# @option options [String] :subaccount
# @option options [Int] :offset
# @option options [Int] :limit
# @return [Hash]
def list(options = nil)
return perform_list if options.nil?
params = {}
if options.key?(:subaccount) &&
valid_param?(:subaccount, options[:subaccount], [String, Symbol], true)
params[:subaccount] = options[:subaccount]
end
%i[offset limit].each do |param|
if options.key?(param) && valid_param?(param, options[param],
[Integer, Integer], true)
params[param] = options[param]
end
end
if options.key?(:limit) && (options[:limit] > 20 || options[:limit] <= 0)
raise_invalid_request('The maximum number of results that can be '\
"fetched is 20. limit can't be more than 20 or less than 1")
end
if options.key?(:offset) && options[:offset] < 0
raise_invalid_request("Offset can't be negative")
end
perform_list(params)
end
def each
offset = 0
loop do
app_list = list(offset: offset)
app_list[:objects].each { |app| yield app }
offset += 20
return unless app_list.length == 20
end
end
##
# Modify an application
# @param [String] app_id
# @param [Hash] options
# @option options [String] :answer_url - The URL invoked by Plivo when a call executes this application.
# @option options [String] :answer_method - The method used to call the answer_url. Defaults to POST.
# @option options [String] :hangup_url - The URL that will be notified by Plivo when the call hangs up. Defaults to answer_url.
# @option options [String] :hangup_method - The method used to call the hangup_url. Defaults to POST.
# @option options [String] :fallback_answer_url - Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
# @option options [String] :fallback_method - The method used to call the fallback_answer_url. Defaults to POST.
# @option options [String] :message_url - The URL that will be notified by Plivo when an inbound message is received. Defaults not set.
# @option options [String] :message_method - The method used to call the message_url. Defaults to POST.
# @option options [Boolean] :default_number_app - If set to true, this parameter ensures that newly created numbers, which don't have an app_id, point to this application.
# @option options [Boolean] :default_endpoint_app - If set to true, this parameter ensures that newly created endpoints, which don't have an app_id, point to this application.
# @option options [String] :subaccount - Id of the subaccount, in case only subaccount applications are needed.
# @option options [Boolean] :log_incoming_messages - If set to true, this parameter ensures that incoming messages are logged.
# @return [Application] Application
def update(app_id, options = nil)
valid_param?(:app_id, app_id, [String, Symbol], true)
Application.new(@_client,
resource_id: app_id).update(options)
end
##
# Delete an application
# @param [String] app_id
# @param [Hash] options
# @option options [Boolean] :cascade - delete associated endpoints
# @option options [String] :new_endpoint_application - Link associated endpoints to this app
def delete(app_id, options = nil)
valid_param?(:app_id, app_id, [String, Symbol], true)
Application.new(@_client,
resource_id: app_id).delete(options)
end
end
end
end
[VT-2365] Adding public uri support
module Plivo
module Resources
include Plivo::Utils
class Application < Base::Resource
def initialize(client, options = nil)
@_name = 'Application'
@_identifier_string = 'app_id'
super
@_is_voice_request = true
end
# @param [Hash] options
# @option options [String] :answer_url - The URL invoked by Plivo when a call executes this application.
# @option options [String] :answer_method - The method used to call the answer_url. Defaults to POST.
# @option options [String] :hangup_url - The URL that will be notified by Plivo when the call hangs up. Defaults to answer_url.
# @option options [String] :hangup_method - The method used to call the hangup_url. Defaults to POST.
# @option options [String] :fallback_answer_url - Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
# @option options [String] :fallback_method - The method used to call the fallback_answer_url. Defaults to POST.
# @option options [String] :message_url - The URL that will be notified by Plivo when an inbound message is received. Defaults not set.
# @option options [String] :message_method - The method used to call the message_url. Defaults to POST.
# @option options [Boolean] :default_number_app - If set to true, this parameter ensures that newly created numbers, which don't have an app_id, point to this application.
# @option options [Boolean] :default_endpoint_app - If set to true, this parameter ensures that newly created endpoints, which don't have an app_id, point to this application.
# @option options [String] :subaccount - Id of the subaccount, in case only subaccount applications are needed.
# @option options [Boolean] :log_incoming_messages - If set to true, this parameter ensures that incoming messages are logged.
# @option options [Boolean] :public_uri - If set to true, this parameter enables public_uri.
# @return [Application] Application
def update(options = nil)
return perform_update({}) if options.nil?
valid_param?(:options, options, Hash, true)
params = {}
%i[answer_url hangup_url fallback_answer_url message_url subaccount]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true)
params[param] = options[param]
end
end
%i[answer_method hangup_method fallback_method message_method]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true, %w[GET POST])
params[param] = options[param]
end
end
%i[default_number_app default_endpoint_app log_incoming_messages public_uri].each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [TrueClass, FalseClass], true)
params[param] = options[param]
end
end
perform_update(params)
end
# @param [Hash] options
# @option options [Boolean] :cascade - delete associated endpoints
# @option options [String] :new_endpoint_application - Link associated endpoints to this app
def delete(options = nil)
return perform_delete if options.nil?
params = {}
if options.key?(:cascade) && valid_param?(:cascade, options[:cascade], [TrueClass, FalseClass], false, [true, false])
params[:cascade] = options[:cascade]
end
if options.key?(:new_endpoint_application) && valid_param?(:new_endpoint_application, options[:new_endpoint_application], [String, Symbol])
params[:new_endpoint_application] = options[:new_endpoint_application]
end
perform_delete(params)
end
def to_s
{
answer_method: @answer_method,
answer_url: @answer_url,
app_id: @app_id,
api_id: @api_id,
app_name: @app_name,
default_app: @default_app,
default_endpoint_app: @default_endpoint_app,
enabled: @enabled,
fallback_answer_url: @fallback_answer_url,
fallback_method: @fallback_method,
hangup_method: @hangup_method,
hangup_url: @hangup_url,
message_method: @message_method,
message_url: @message_url,
public_uri: @public_uri,
resource_uri: @resource_uri,
sip_uri: @sip_uri,
sub_account: @sub_account,
log_incoming_messages: @log_incoming_messages
}.to_s
end
end
# @!method get
# @!method create
# @!method list
class ApplicationInterface < Base::ResourceInterface
def initialize(client, resource_list_json = nil)
@_name = 'Application'
@_resource_type = Application
@_identifier_string = 'app_id'
super
@_is_voice_request = true
end
# @param [String] app_id
# @return [Application] Application
def get(app_id)
valid_param?(:app_id, app_id, [String, Symbol], true)
perform_get(app_id)
end
# @param [String] app_name
# @param [Hash] options
# @option options [String] :answer_url - The URL invoked by Plivo when a call executes this application.
# @option options [String] :answer_method - The method used to call the answer_url. Defaults to POST.
# @option options [String] :hangup_url - The URL that will be notified by Plivo when the call hangs up. Defaults to answer_url.
# @option options [String] :hangup_method - The method used to call the hangup_url. Defaults to POST.
# @option options [String] :fallback_answer_url - Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
# @option options [String] :fallback_method - The method used to call the fallback_answer_url. Defaults to POST.
# @option options [String] :message_url - The URL that will be notified by Plivo when an inbound message is received. Defaults not set.
# @option options [String] :message_method - The method used to call the message_url. Defaults to POST.
# @option options [Boolean] :default_number_app - If set to true, this parameter ensures that newly created numbers, which don't have an app_id, point to this application.
# @option options [Boolean] :default_endpoint_app - If set to true, this parameter ensures that newly created endpoints, which don't have an app_id, point to this application.
# @option options [String] :subaccount - Id of the subaccount, in case only subaccount applications are needed.
# @option options [Boolean] :log_incoming_messages - If set to true, this parameter ensures that incoming messages are logged.
# @option options [Boolean] :public_uri - If set to true, this parameter enables public_uri.
# @return [Application] Application
def create(app_name, options = nil)
valid_param?(:app_name, app_name, [String, Symbol], true)
valid_param?(:options, options, Hash, true) unless options.nil?
params = {
app_name: app_name
}
return perform_create(params) if options.nil?
%i[answer_url hangup_url fallback_answer_url message_url subaccount]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true)
params[param] = options[param]
end
end
%i[answer_method hangup_method fallback_method message_method]
.each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [String, Symbol], true, %w[GET POST])
params[param] = options[param]
end
end
%i[default_number_app default_endpoint_app log_incoming_messages public_uri].each do |param|
if options.key?(param) &&
valid_param?(param, options[param], [TrueClass, FalseClass], true)
params[param] = options[param]
end
end
perform_create(params)
end
##
# Lists all applications
# @param [Hash] options
# @option options [String] :subaccount
# @option options [Int] :offset
# @option options [Int] :limit
# @return [Hash]
def list(options = nil)
return perform_list if options.nil?
params = {}
if options.key?(:subaccount) &&
valid_param?(:subaccount, options[:subaccount], [String, Symbol], true)
params[:subaccount] = options[:subaccount]
end
%i[offset limit].each do |param|
if options.key?(param) && valid_param?(param, options[param],
[Integer, Integer], true)
params[param] = options[param]
end
end
if options.key?(:limit) && (options[:limit] > 20 || options[:limit] <= 0)
raise_invalid_request('The maximum number of results that can be '\
"fetched is 20. limit can't be more than 20 or less than 1")
end
if options.key?(:offset) && options[:offset] < 0
raise_invalid_request("Offset can't be negative")
end
perform_list(params)
end
def each
offset = 0
loop do
app_list = list(offset: offset)
app_list[:objects].each { |app| yield app }
offset += 20
return unless app_list.length == 20
end
end
##
# Modify an application
# @param [String] app_id
# @param [Hash] options
# @option options [String] :answer_url - The URL invoked by Plivo when a call executes this application.
# @option options [String] :answer_method - The method used to call the answer_url. Defaults to POST.
# @option options [String] :hangup_url - The URL that will be notified by Plivo when the call hangs up. Defaults to answer_url.
# @option options [String] :hangup_method - The method used to call the hangup_url. Defaults to POST.
# @option options [String] :fallback_answer_url - Invoked by Plivo only if answer_url is unavailable or the XML response is invalid. Should contain a XML response.
# @option options [String] :fallback_method - The method used to call the fallback_answer_url. Defaults to POST.
# @option options [String] :message_url - The URL that will be notified by Plivo when an inbound message is received. Defaults not set.
# @option options [String] :message_method - The method used to call the message_url. Defaults to POST.
# @option options [Boolean] :default_number_app - If set to true, this parameter ensures that newly created numbers, which don't have an app_id, point to this application.
# @option options [Boolean] :default_endpoint_app - If set to true, this parameter ensures that newly created endpoints, which don't have an app_id, point to this application.
# @option options [String] :subaccount - Id of the subaccount, in case only subaccount applications are needed.
# @option options [Boolean] :log_incoming_messages - If set to true, this parameter ensures that incoming messages are logged.
# @return [Application] Application
def update(app_id, options = nil)
valid_param?(:app_id, app_id, [String, Symbol], true)
Application.new(@_client,
resource_id: app_id).update(options)
end
##
# Delete an application
# @param [String] app_id
# @param [Hash] options
# @option options [Boolean] :cascade - delete associated endpoints
# @option options [String] :new_endpoint_application - Link associated endpoints to this app
def delete(app_id, options = nil)
valid_param?(:app_id, app_id, [String, Symbol], true)
Application.new(@_client,
resource_id: app_id).delete(options)
end
end
end
end
|
require 'hirb-unicode'
class Hirb::Helpers::VerticalTable < Hirb::Helpers::Table
# Method should return an Array
def render_rows
i = 0
rows = ''
longest_header = Hirb::String.size @headers.values.sort_by {|e| Hirb::String.size(e) }.last
delimiter = "-" * longest_header
@rows.map do |row|
row = "\n#{delimiter} #{i+1}. review #{delimiter}\n" +
@fields.map {|f|
if !@options[:hide_empty] || (@options[:hide_empty] && !row[f].empty?)
"#{Hirb::String.rjust(@headers[f], longest_header)}: #{row[f]}"
else
nil
end
}.compact.join("\n")
i+= 1
rows += row
end
rows = "#{@rows.size} review(s)" + rows
if @options[:system_less] && system("which less 2>&1 > /dev/null")
IO.popen('less', 'w') { |io| io.puts rows }
[]
else
[rows]
end
end
end
use hirb
require 'hirb'
class Hirb::Helpers::VerticalTable < Hirb::Helpers::Table
# Method should return an Array
def render_rows
i = 0
rows = ''
longest_header = Hirb::String.size @headers.values.sort_by {|e| Hirb::String.size(e) }.last
delimiter = "-" * longest_header
@rows.map do |row|
row = "\n#{delimiter} #{i+1}. review #{delimiter}\n" +
@fields.map {|f|
if !@options[:hide_empty] || (@options[:hide_empty] && !row[f].empty?)
"#{Hirb::String.rjust(@headers[f], longest_header)}: #{row[f]}"
else
nil
end
}.compact.join("\n")
i+= 1
rows += row
end
rows = "#{@rows.size} review(s)" + rows
if @options[:system_less] && system("which less 2>&1 > /dev/null")
IO.popen('less', 'w') { |io| io.puts rows }
[]
else
[rows]
end
end
end |
module NumbersAndWordsPl
VERSION = "0.0.1"
end
bumps version
module NumbersAndWordsPl
VERSION = "0.0.2"
end
|
module NutritionCalculator
VERSION = "1.0.0"
end
Version bump
module NutritionCalculator
VERSION = "1.0.1"
end
|
module OmniAuth
module Applicaster
VERSION = "1.5.2"
end
end
bump version 1.6.0
module OmniAuth
module Applicaster
VERSION = "1.6.0"
end
end
|
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Coinbase < OmniAuth::Strategies::OAuth2
# Give your strategy a name.
option :name, "coinbase"
# This is where you pass the options you would pass when
# initializing your consumer from the OAuth gem.
option :client_options, {
:site => 'https://coinbase.com',
:authorize_url => 'https://coinbase.com/oauth/authorize',
:token_url => 'https://coinbase.com/oauth/token'
}
# These are called after authentication has succeeded. If
# possible, you should try to set the UID without making
# additional calls (if the user id is returned with the token
# or as a URI parameter). This may not be possible with all
# providers.
uid{ raw_info['id'] }
info do
{
:name => raw_info['name'],
:email => raw_info['email']
}
end
extra do
{
'raw_info' => raw_info
}
end
def raw_info
@raw_info ||= access_token.get('/api/v1/users').parsed
end
end
end
end
Gettting the info correctly from hash
require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Coinbase < OmniAuth::Strategies::OAuth2
# Give your strategy a name.
option :name, "coinbase"
# This is where you pass the options you would pass when
# initializing your consumer from the OAuth gem.
option :client_options, {
:site => 'https://coinbase.com',
:authorize_url => 'https://coinbase.com/oauth/authorize',
:token_url => 'https://coinbase.com/oauth/token'
}
# These are called after authentication has succeeded. If
# possible, you should try to set the UID without making
# additional calls (if the user id is returned with the token
# or as a URI parameter). This may not be possible with all
# providers.
uid{ raw_info['id'] }
info do
{
:name => raw_info['name'],
:email => raw_info['email'],
:balance => raw_info['balance']
}
end
extra do
{
'raw_info' => raw_info
}
end
def raw_info
@raw_info ||= access_token.get('/api/v1/users').parsed['users'].first['user']
end
end
end
end |
module Onebox
module Engine
class YoutubeOnebox
include Engine
include StandardEmbed
matches_regexp(/^https?:\/\/(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/.+$/)
always_https
WIDTH ||= 480
HEIGHT ||= 360
def placeholder_html
if video_id
"<img src='https://i.ytimg.com/vi/#{video_id}/hqdefault.jpg' width='#{WIDTH}' height='#{HEIGHT}'>"
elsif list_id
"<img src='#{list_thumbnail_url}' width='#{WIDTH}' height='#{HEIGHT}'>"
else
to_html
end
end
def to_html
if video_id
<<-HTML
<iframe width="#{WIDTH}"
height="#{HEIGHT}"
src="https://www.youtube.com/embed/#{video_id}?#{embed_params}"
frameborder="0"
allowfullscreen>
</iframe>
HTML
elsif list_id
<<-HTML
<iframe width="#{WIDTH}"
height="#{HEIGHT}"
src="https://www.youtube.com/embed/videoseries?list=#{list_id}&wmode=transparent&rel=0&autohide=1&showinfo=1&enablejsapi=1"
frameborder="0"
allowfullscreen>
</iframe>
HTML
else
# for channel pages
html = Onebox::Engine::WhitelistedGenericOnebox.new(@url, @cache, @timeout).to_html
return if Onebox::Helpers.blank?(html)
html.gsub!("http:", "https:")
html.gsub!(/['"]\/\//, "https://")
html
end
end
def video_title
@video_title ||= begin
url = "https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/watch?v=#{video_id}"
data = Onebox::Helpers.symbolize_keys(::MultiJson.load(Onebox::Helpers.fetch_response(url).body))
data[:title]
rescue
nil
end
end
private
def video_id
@video_id ||= begin
# http://youtu.be/afyK1HSFfgw
if uri.host["youtu.be"]
id = uri.path[/\/([\w\-]+)\//, 1]
return id if id
end
# https://www.youtube.com/embed/vsF0K3Ou1v0
if uri.path["/embed/"]
id = uri.path[/\/embed\/([\w\-]+)/, 1]
return id if id
end
# https://www.youtube.com/watch?v=Z0UISCEe52Y
params['v']
end
end
def list_id
@list_id ||= params['list']
end
def list_thumbnail_url
@list_thumbnail_url ||= begin
url = "https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/playlist?list=#{list_id}"
data = Onebox::Helpers.symbolize_keys(::MultiJson.load(Onebox::Helpers.fetch_response(url).body))
data[:thumbnail_url]
rescue
nil
end
end
def embed_params
p = {'feature' => 'oembed', 'wmode' => 'opaque'}
p['list'] = list_id if list_id
# Parse timestrings, and assign the result as a start= parameter
start = if params['start']
params['start']
elsif params['t']
params['t']
elsif uri.fragment && uri.fragment.start_with?('t=')
# referencing uri is safe here because any throws were already caught by video_id returning nil
# remove the t= from the start
uri.fragment[2..-1]
end
p['start'] = parse_timestring(start) if start
p['end'] = parse_timestring params['end'] if params['end']
# Official workaround for looping videos
# https://developers.google.com/youtube/player_parameters#loop
# use params.include? so that you can just add "&loop"
if params.include?('loop')
p['loop'] = 1
p['playlist'] = video_id
end
URI.encode_www_form(p)
end
def parse_timestring(string)
if string =~ /(\d+h)?(\d+m)?(\d+s?)?/
($1.to_i * 3600) + ($2.to_i * 60) + $3.to_i
end
end
def params
return {} unless uri.query
# This mapping is necessary because CGI.parse returns a hash of keys to arrays.
# And *that* is necessary because querystrings support arrays, so they
# force you to deal with it to avoid security issues that would pop up
# if one day it suddenly gave you an array.
#
# However, we aren't interested. Just take the first one.
@params ||= begin
p = {}
CGI.parse(uri.query).each { |k, v| p[k] = v.first }
p
end
rescue
{}
end
end
end
end
FIX: youtu.be onebox was failing
module Onebox
module Engine
class YoutubeOnebox
include Engine
include StandardEmbed
matches_regexp(/^https?:\/\/(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/.+$/)
always_https
WIDTH ||= 480
HEIGHT ||= 360
def placeholder_html
if video_id
"<img src='https://i.ytimg.com/vi/#{video_id}/hqdefault.jpg' width='#{WIDTH}' height='#{HEIGHT}'>"
elsif list_id
"<img src='#{list_thumbnail_url}' width='#{WIDTH}' height='#{HEIGHT}'>"
else
to_html
end
end
def to_html
if video_id
<<-HTML
<iframe width="#{WIDTH}"
height="#{HEIGHT}"
src="https://www.youtube.com/embed/#{video_id}?#{embed_params}"
frameborder="0"
allowfullscreen>
</iframe>
HTML
elsif list_id
<<-HTML
<iframe width="#{WIDTH}"
height="#{HEIGHT}"
src="https://www.youtube.com/embed/videoseries?list=#{list_id}&wmode=transparent&rel=0&autohide=1&showinfo=1&enablejsapi=1"
frameborder="0"
allowfullscreen>
</iframe>
HTML
else
# for channel pages
html = Onebox::Engine::WhitelistedGenericOnebox.new(@url, @cache, @timeout).to_html
return if Onebox::Helpers.blank?(html)
html.gsub!("http:", "https:")
html.gsub!(/['"]\/\//, "https://")
html
end
end
def video_title
@video_title ||= begin
url = "https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/watch?v=#{video_id}"
data = Onebox::Helpers.symbolize_keys(::MultiJson.load(Onebox::Helpers.fetch_response(url).body))
data[:title]
rescue
nil
end
end
private
def video_id
@video_id ||= begin
# http://youtu.be/afyK1HSFfgw
if uri.host["youtu.be"]
id = uri.path[/\/([\w\-]+)/, 1]
return id if id
end
# https://www.youtube.com/embed/vsF0K3Ou1v0
if uri.path["/embed/"]
id = uri.path[/\/embed\/([\w\-]+)/, 1]
return id if id
end
# https://www.youtube.com/watch?v=Z0UISCEe52Y
params['v']
end
end
def list_id
@list_id ||= params['list']
end
def list_thumbnail_url
@list_thumbnail_url ||= begin
url = "https://www.youtube.com/oembed?format=json&url=https://www.youtube.com/playlist?list=#{list_id}"
data = Onebox::Helpers.symbolize_keys(::MultiJson.load(Onebox::Helpers.fetch_response(url).body))
data[:thumbnail_url]
rescue
nil
end
end
def embed_params
p = {'feature' => 'oembed', 'wmode' => 'opaque'}
p['list'] = list_id if list_id
# Parse timestrings, and assign the result as a start= parameter
start = if params['start']
params['start']
elsif params['t']
params['t']
elsif uri.fragment && uri.fragment.start_with?('t=')
# referencing uri is safe here because any throws were already caught by video_id returning nil
# remove the t= from the start
uri.fragment[2..-1]
end
p['start'] = parse_timestring(start) if start
p['end'] = parse_timestring params['end'] if params['end']
# Official workaround for looping videos
# https://developers.google.com/youtube/player_parameters#loop
# use params.include? so that you can just add "&loop"
if params.include?('loop')
p['loop'] = 1
p['playlist'] = video_id
end
URI.encode_www_form(p)
end
def parse_timestring(string)
if string =~ /(\d+h)?(\d+m)?(\d+s?)?/
($1.to_i * 3600) + ($2.to_i * 60) + $3.to_i
end
end
def params
return {} unless uri.query
# This mapping is necessary because CGI.parse returns a hash of keys to arrays.
# And *that* is necessary because querystrings support arrays, so they
# force you to deal with it to avoid security issues that would pop up
# if one day it suddenly gave you an array.
#
# However, we aren't interested. Just take the first one.
@params ||= begin
p = {}
CGI.parse(uri.query).each { |k, v| p[k] = v.first }
p
end
rescue
{}
end
end
end
end
|
module OpenStack
module Compute
class Connection
attr_accessor :connection
attr_accessor :extensions
def initialize(connection)
@extensions = nil
@connection = connection
OpenStack::Authentication.init(@connection)
end
# Returns true if the authentication was successful and returns false otherwise.
#
# cs.authok?
# => true
def authok?
@connection.authok
end
# Returns the OpenStack::Compute::Server object identified by the given id.
#
# >> server = cs.get_server(110917)
# => #<OpenStack::Compute::Server:0x101407ae8 ...>
# >> server.name
# => "MyServer"
def get_server(id)
OpenStack::Compute::Server.new(self,id)
end
alias :server :get_server
# Returns an array of hashes, one for each server that exists under this account. The hash keys are :name and :id.
#
# You can also provide :limit and :offset and :"changes-since" and :image and :flavor and :name and :status
# and :host and :limit and :marker parameters to handle pagination.
# http://developer.openstack.org/api-ref-compute-v2.1.html
#
# >> cs.list_servers
# => [{:name=>"MyServer", :id=>110917}]
#
# >> cs.list_servers(:limit => 2, :offset => 3, :name => "MyServer", :status => "ACTIVE")
# => [{:name=>"demo-standingcloud-lts", :id=>168867},
# {:name=>"demo-aicache1", :id=>187853}]
def list_servers(options = {})
anti_cache_param="cacheid=#{Time.now.to_i}"
path = options.empty? ? "#{@connection.service_path}/servers?#{anti_cache_param}" : "#{@connection.service_path}/servers?#{options.to_query}&#{anti_cache_param}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)["servers"])
end
alias :servers :list_servers
# Returns an array of hashes with more details about each server that exists under this account. Additional information
# includes public and private IP addresses, status, hostID, and more. All hash keys are symbols except for the metadata
# hash, which are verbatim strings.
#
# You can also provide :limit and :offset and :"changes-since" and :image and :flavor and :name and :status and :host
# and :limit and :marker parameters to handle pagination.
# http://developer.openstack.org/api-ref-compute-v2.1.html
# >> cs.list_servers_detail
# => [{:name=>"MyServer", :addresses=>{:public=>["67.23.42.37"], :private=>["10.176.241.237"]}, :metadata=>{"MyData" => "Valid"}, :imageRef=>10, :progress=>100, :hostId=>"36143b12e9e48998c2aef79b50e144d2", :flavorRef=>1, :id=>110917, :status=>"ACTIVE"}]
#
# >> cs.list_servers_detail(:limit => 2, :offset => 3, :name => "MyServer", :flavor => 1, :status => "ACTIVE")
# => [{:status=>"ACTIVE", :imageRef=>10, :progress=>100, :metadata=>{}, :addresses=>{:public=>["x.x.x.x"], :private=>["x.x.x.x"]}, :name=>"demo-standingcloud-lts", :id=>168867, :flavorRef=>1, :hostId=>"xxxxxx"},
# {:status=>"ACTIVE", :imageRef=>8, :progress=>100, :metadata=>{}, :addresses=>{:public=>["x.x.x.x"], :private=>["x.x.x.x"]}, :name=>"demo-aicache1", :id=>187853, :flavorRef=>3, :hostId=>"xxxxxx"}]
def list_servers_detail(options = {})
path = options.empty? ? "#{@connection.service_path}/servers/detail" : "#{@connection.service_path}/servers/detail?#{options.to_query}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
json_server_list = JSON.parse(response.body)["servers"]
json_server_list.each do |server|
server["addresses"] = OpenStack::Compute::Address.fix_labels(server["addresses"])
end
OpenStack.symbolize_keys(json_server_list)
end
alias :servers_detail :list_servers_detail
# Creates a new server instance on OpenStack Compute
#
# The argument is a hash of options. The keys :name, :flavorRef,
# and :imageRef are required; :metadata, :security_groups,
# :key_name and :personality are optional.
#
# :flavorRef and :imageRef are href strings identifying a particular
# server flavor and image to use when building the server. The :imageRef
# can either be a stock image, or one of your own created with the
# server.create_image method.
#
# The :metadata argument should be a hash of key/value pairs. This
# metadata will be applied to the server at the OpenStack Compute API level.
#
# The "Personality" option allows you to include up to five files, # of
# 10Kb or less in size, that will be placed on the created server.
# For :personality, pass a hash of the form {'local_path' => 'server_path'}.
# The file located at local_path will be base64-encoded and placed at the
# location identified by server_path on the new server.
#
# Returns a OpenStack::Compute::Server object. The root password is
# available in the adminPass instance method.
#
# >> server = cs.create_server(
# :name => 'NewServer',
# :imageRef => '3',
# :flavorRef => '1',
# :metadata => {'Racker' => 'Fanatical'},
# :personality => {'/home/bob/wedding.jpg' => '/root/wedding.jpg'},
# :key_name => "mykey",
# :security_groups => [ "devel", "test"])
# => #<OpenStack::Compute::Server:0x101229eb0 ...>
# >> server.name
# => "NewServer"
# >> server.status
# => "BUILD"
# >> server.adminPass
# => "NewServerSHMGpvI"
def create_server(options)
raise OpenStack::Exception::MissingArgument, "Server name, flavorRef, and imageRef, must be supplied" unless (options[:name] && options[:flavorRef] && options[:imageRef])
if options[:personality]
options[:personality] = Personalities.get_personality(options[:personality])
end
options[:security_groups] = (options[:security_groups] || []).inject([]){|res, c| res << {"name"=>c} ;res}
data = JSON.generate(:server => options)
response = @connection.csreq("POST",@connection.service_host,"#{@connection.service_path}/servers",@connection.service_port,@connection.service_scheme,{'content-type' => 'application/json'},data)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
server_info = JSON.parse(response.body)['server']
server = OpenStack::Compute::Server.new(self,server_info['id'])
server.adminPass = server_info['adminPass']
server
end
# Returns an array of hashes listing available server images that you have access too,
# including stock OpenStack Compute images and any that you have created. The "id" key
# in the hash can be used where imageRef is required. You can also provide :limit and
# :offset and :"changes-since" and :server and :name and :status :minDisk and :minRam
# and :type and :limit and :marker parameters to handle pagination.
#
# >> cs.list_images
# => [{:name=>"CentOS 5.2", :id=>2, :updated=>"2009-07-20T09:16:57-05:00", :status=>"ACTIVE", :created=>"2009-07-20T09:16:57-05:00"},
# {:name=>"Gentoo 2008.0", :id=>3, :updated=>"2009-07-20T09:16:57-05:00", :status=>"ACTIVE", :created=>"2009-07-20T09:16:57-05:00"},...
#
# >> cs.list_images(:limit => 3, :offset => 2, :status => "ACTIVE")
# => [{:status=>"ACTIVE", :name=>"Fedora 11 (Leonidas)", :updated=>"2009-12-08T13:50:45-06:00", :id=>13},
# {:status=>"ACTIVE", :name=>"CentOS 5.3", :updated=>"2009-08-26T14:59:52-05:00", :id=>7},
# {:status=>"ACTIVE", :name=>"CentOS 5.4", :updated=>"2009-12-16T01:02:17-06:00", :id=>187811}]
def list_images(options = {})
path = options.empty? ? "#{@connection.service_path}/images/detail" : "#{@connection.service_path}/images/detail?#{options.to_query}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)['images'])
end
alias :images :list_images
# Returns a OpenStack::Compute::Image object for the image identified by the provided id.
#
# >> image = cs.get_image(8)
# => #<OpenStack::Compute::Image:0x101659698 ...>
def get_image(id)
OpenStack::Compute::Image.new(self,id)
end
alias :image :get_image
# Returns an array of hashes listing all available server flavors. The :id key in the hash can be used when flavorRef is required.
#
# You can also provide :limit and :offset parameters to handle pagination.
# http://developer.openstack.org/api-ref-compute-v2.1.html
#
# >> cs.list_flavors
# => [{:name=>"256 server", :id=>1, :ram=>256, :disk=>10},
# {:name=>"512 server", :id=>2, :ram=>512, :disk=>20},...
#
# >> cs.list_flavors(:limit => 3, :offset => 2)
# => [{:ram=>1024, :disk=>40, :name=>"1GB server", :id=>3},
# {:ram=>2048, :disk=>80, :name=>"2GB server", :id=>4},
# {:ram=>4096, :disk=>160, :name=>"4GB server", :id=>5}]
def list_flavors(options = {})
path = options.empty? ? "#{@connection.service_path}/flavors/detail" : "#{@connection.service_path}/flavors/detail?#{options.to_query}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)['flavors'])
end
alias :flavors :list_flavors
# Returns a OpenStack::Compute::Flavor object for the flavor identified by the provided ID.
#
# >> flavor = cs.flavor(1)
# => #<OpenStack::Compute::Flavor:0x10156dcc0 @name="256 server", @disk=10, @id=1, @ram=256>
def get_flavor(id)
response = @connection.req('GET', "/flavors/#{id}")
flavor_info = JSON.parse(response.body)['flavor']
OpenStack::Compute::Flavor.new(flavor_info)
end
alias :flavor :get_flavor
# nova.create_flavor({name: 'small', vcpus: 2, ram: 1024, disk: 1}, true)
# :name - must be unique, :ram - MB, :disk - GB
# => #<OpenStack::Compute::Flavor:0x007ff95333e268 @id="0c0c393b-3acd-4569-baae-7a7afbe398f6", @name="small", @ram=1024, @disk=1, @vcpus=2>
def create_flavor(options, public = false)
raise OpenStack::Exception::MissingArgument, 'Flavor name, vcpus, ram and disk, must be supplied' unless (options[:name] && options[:vcpus] && options[:ram] && options[:disk])
data = JSON.generate(:flavor => options.merge!({'os-flavor-access:is_public' => public}))
response = @connection.req('POST', '/flavors', {data: data})
flavor_info = JSON.parse(response.body)['flavor']
OpenStack::Compute::Flavor.new(flavor_info)
end
def delete_flavor(id)
@connection.req('DELETE', "/flavors/#{id}")
true
end
def add_tenant_to_flavor(flavor_id, tenant_id)
data = JSON.generate({'addTenantAccess' => {'tenant' => tenant_id}})
response = @connection.req('POST', "/flavors/#{flavor_id}/action", {data: data})
JSON.parse(response.body)
end
def delete_tenant_from_flavor(flavor_id, tenant_id)
data = JSON.generate({'removeTenantAccess' => {'tenant' => tenant_id}})
response = @connection.req('POST', "/flavors/#{flavor_id}/action", {data: data})
JSON.parse(response.body)
end
# Returns the current state of the programatic API limits. Each account has certain limits on the number of resources
# allowed in the account, and a rate of API operations.
#
# The operation returns a hash. The :absolute hash key reveals the account resource limits, including the maxmimum
# amount of total RAM that can be allocated (combined among all servers), the maximum members of an IP group, and the
# maximum number of IP groups that can be created.
#
# The :rate hash key returns an array of hashes indicating the limits on the number of operations that can be performed in a
# given amount of time. An entry in this array looks like:
#
# {:regex=>"^/servers", :value=>50, :verb=>"POST", :remaining=>50, :unit=>"DAY", :resetTime=>1272399820, :URI=>"/servers*"}
#
# This indicates that you can only run 50 POST operations against URLs in the /servers URI space per day, we have not run
# any operations today (50 remaining), and gives the Unix time that the limits reset.
#
# Another example is:
#
# {:regex=>".*", :value=>10, :verb=>"PUT", :remaining=>10, :unit=>"MINUTE", :resetTime=>1272399820, :URI=>"*"}
#
# This says that you can run 10 PUT operations on all possible URLs per minute, and also gives the number remaining and the
# time that the limit resets.
#
# Use this information as you're building your applications to put in relevant pauses if you approach your API limitations.
def limits
response = @connection.csreq("GET",@connection.service_host,"#{@connection.service_path}/limits",@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)['limits'])
end
# ==============================
# API EXTENSIONS
#
# http://nova.openstack.org/api_ext/index.html
# http://api.openstack.org/ (grep 'Compute API Extensions')
#
#query the openstack provider for any implemented extensions to the compute API
#returns a hash with openstack service provider's returned details
#about the implemented extensions, e.g.:
#
# { :os-floating_ips => { :links=>[],
# :updated=>"2011-06-16T00:00:00+00:00",
# :description=>"Floating IPs support",
# :namespace=>"http://docs.openstack.org/ext/floating_ips/api/v1.1",
# :name=>"Floating_ips", :alias=>"os-floating-ips"},
# :os-keypairs => { :links=>[],
# :updated=>"2011-08-08T00:00:00+00:00",
# :description=>"Keypair Support",
# :namespace=>"http://docs.openstack.org/ext/keypairs/api/v1.1",
# :name=>"Keypairs",
# :alias=>"os-keypairs"}
# }
#
def api_extensions
if @extensions.nil?
response = @connection.req("GET", "/extensions")
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
res = OpenStack.symbolize_keys(JSON.parse(response.body))
@extensions = res[:extensions].inject({}){|result, c| result[c[:alias].to_sym] = c ; result}
end
@extensions
end
# Retrieve a list of key pairs associated with the current authenticated account
# Will return a hash:
# { :key_one => { :fingerprint => "3f:12:4d:d1:54:f1:f4:3f:fe:a8:12:ec:1a:fb:35:b2",
# :public_key => "ssh-rsa AAAAB3Nza923kJU123AADAQABAAAAg928JUwydszi029kIJudfOzQ7o160Ll1ItybDzYYcCAJ/N02loIKJU17264520bmXZFSsaZf2ErX3nSBNI3K+2zQzu832jkhkfdsa7GHH5hvNOxO7u800894312JKLJLHP/R91fdsajHKKJADSAgQ== nova@nv-zz2232-api0002\n",
# :name => "key_one"},
#
# :key_two => { :fingerprint => "6b:32:dd:d2:51:c1:f2:3a:fb:a2:52:3a:1a:bb:25:1b",
# :public_key => "ssh-rsa AKIJUuw71645kJU123AADAQABAAAAg928019oiUJY12765IJudfOzQ7o160Ll1ItybDzYYcCAJ/N80438012480321jhkhKJlfdsazu832jkhkfdsa7GHH5fdasfdsajlj2999789799987989894312JKLJLHP/R91fdsajHKKJADSAgQ== nova@bv-fdsa32-api0002\n",
# :name => "key_two"}
# }
#
# Raises OpenStack::Exception::NotImplemented if the current provider doesn't
# offer the os-keypairs extension
#
def keypairs
begin
response = @connection.req("GET", "/os-keypairs")
res = OpenStack.symbolize_keys(JSON.parse(response.body))
res[:keypairs].inject({}){|result, c| result[c[:keypair][:name].to_sym] = c[:keypair] ; result }
rescue OpenStack::Exception::ItemNotFound => not_found
msg = "The os-keypairs extension is not implemented for the provider you are talking to "+
"- #{@connection.http.keys.first}"
raise OpenStack::Exception::NotImplemented.new(msg, 501, "#{not_found.message}")
end
end
# Create a new keypair for use with launching servers. Raises
# a OpenStack::Exception::NotImplemented if os-keypairs extension
# is not implemented (or not advertised) by the OpenStack provider.
#
# The 'name' parameter MUST be supplied, otherwise a
# OpenStack::Exception::MissingArgument will be raised.
#
# Optionally requests can specify a 'public_key' parameter,
# with the full public ssh key (String) to be used to create the keypair
# (i.e. import a existing key).
#
# Returns a hash with details of the new key; the :private_key attribute
# must be saved must be saved by caller (not retrievable thereafter).
# NOTE: when the optional :public_key parameter is given, the response
# will obviously NOT contain the :private_key attribute.
#
# >> os.create_keypair({:name=>"test_key"})
# => { :name => "test_key",
# :fingerprint => "f1:f3:a2:d3:ca:75:da:f1:06:f4:f7:dc:cc:7d:e1:ca",
# :user_id => "dev_41247879706381",
# :public_key => "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDgGhDH3z9uMAvPV8ziE9BCEjHCPXGufy5bOgY5mY5jOSfdmKspdbl0z/LimHVKRDNX6HoL5qRg5V/tGH/NYP5sX2zF/XRKz16lfBxiUL1EONXA9fsTEBR3FGp8NcA7hW2+YiUxWafms4If3NFqttTQ11XqTU8JCMvms4D81lhbiQ== nova@use03147k5-eth0\n",
# :private_key => "-----BEGIN RSA PRIVATE KEY-----\nMIICXwIBAAKBgQDgGhDH3z9uMAvPV8ziE9BCEjHCPXGufy5bOgY5mY5jOSfdmKsp\ndbl0z/LimHVKRDNX6HoL5qRg5V/tGH/NYP5sX2zF/XRKz16lfBxiUL1EONXA9fsT\nEBR3FGp8NcA7hW2+YiUxWafms4If3NFqttTQ11XqTU8JCMvms4D81lhbiQIDAQAB\nAoGBAJ1akAfXwNEc2V4IV2sy4FtULS4nOKh+0szpjC9rm+gd3Nki9qQQ7lyQGwpy\nZID2LFsAeJnco/UJefaf6jUKcvnS7tlxMuQB8DBlepiDqnnec0EiEAVmmt9GWlYZ\nJgfGWqDzI1WtouDCIsOhx1Vq7Foue6pgOnibktg2kfYnH9IRAkEA9tKzhlr9rFui\nbVDkiRJK3VTIhKyk4davDjqPJFLJ+4+77wRW164sGxwReD7HtW6qVtJd1MFvqLDO\nqJJEsqDvXQJBAOhvGaWiAPSuP+/z6GE6VXB1pADQFTYIp2DXUa5DcStTGe7hGF1b\nDeAxpDNBbLO3YKYqi2L9vJcIsp5PkHlEVh0CQQCVLIkWBb5VQliryv0knuqiVFCQ\nZyuL1s2cQuYqZOLwaFGERtIZrom3pMImM4NN82F98cyF/pb2lE2CckyUzVF9AkEA\nqhwFjS9Pu8N7j8XWoLHsre2rJd0kaPNUbI+pe/xn6ula5XVgO5LUSOyL2+daAv2G\ngpZIhR5m07LN5wccGWRmEQJBALZRenXaSyX2R2C9ag9r2gaU8/h+aU9he5kjXIt8\n+B8wvpvfOkpOAVCQEMxtsDkEixUtI98YKZP60uw+Xzh40YU=\n-----END RSA PRIVATE KEY-----\n"
# }
#
# Will raise an OpenStack::Exception::BadRequest if an invalid public_key is provided:
# >> os.create_keypair({:name=>"marios_keypair_test_invalid", :public_key=>"derp"})
# => OpenStack::Exception::BadRequest: Unexpected error while running command.
# Stdout: '/tmp/tmp4kI12a/import.pub is not a public key file.\n'
#
def create_keypair(options)
raise OpenStack::Exception::NotImplemented.new("os-keypairs not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-keypairs"]
raise OpenStack::Exception::MissingArgument, "Keypair name must be supplied" unless (options[:name])
data = JSON.generate(:keypair => options)
response = @connection.req("POST", "/os-keypairs", {:data=>data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
res[:keypair]
end
# Delete an existing keypair. Raises OpenStack::Exception::NotImplemented
# if os-keypairs extension is not implemented (or not advertised) by the OpenStack provider.
#
# Returns true if succesful.
# >> os.delete_keypair("marios_keypair")
# => true
#
# Will raise OpenStack::Exception::ItemNotFound if specified keypair doesn't exist
#
def delete_keypair(keypair_name)
raise OpenStack::Exception::NotImplemented.new("os-keypairs not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-keypairs"]
@connection.req("DELETE", "/os-keypairs/#{keypair_name}")
true
end
#Security Groups:
#Returns a hash with the security group IDs as keys:
#=> { "1381" => { :tenant_id=>"12345678909876", :id=>1381, :name=>"default", :description=>"default",
# :rules=> [
# {:from_port=>22, :group=>{}, :ip_protocol=>"tcp", :to_port=>22,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4902},
# {:from_port=>80, :group=>{}, :ip_protocol=>"tcp", :to_port=>80,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4903},
# {:from_port=>443, :group=>{}, :ip_protocol=>"tcp", :to_port=>443,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4904},
# {:from_port=>-1, :group=>{}, :ip_protocol=>"icmp", :to_port=>-1,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4905}],
# ]
# },
# "1234" => { ... } }
#
def security_groups
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
response = @connection.req("GET", "/os-security-groups")
res = OpenStack.symbolize_keys(JSON.parse(response.body))
res[:security_groups].inject({}){|result, c| result[c[:id].to_s] = c ; result }
end
def security_group(id)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
response = @connection.req("GET", "/os-security-groups/#{id}")
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group][:id].to_s => res[:security_group]}
end
def create_security_group(name, description)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
data = JSON.generate(:security_group => { "name" => name, "description" => description})
response = @connection.req("POST", "/os-security-groups", {:data => data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group][:id].to_s => res[:security_group]}
end
def update_security_group(id, name, description)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
data = JSON.generate(:security_group => { "name" => name, "description" => description})
response = @connection.req("PUT", "/os-security-groups/#{id}", {:data => data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group][:id].to_s => res[:security_group]}
end
def delete_security_group(id)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
@connection.req("DELETE", "/os-security-groups/#{id}")
true
end
#params: { :ip_protocol=>"tcp", :from_port=>"123", :to_port=>"123", :cidr=>"192.168.0.1/16", :group_id:="123" }
#observed behaviour against Openstack@HP cloud - can specify either cidr OR group_id as source, but not both
#if both specified, the group is used and the cidr ignored.
def create_security_group_rule(security_group_id, params)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
params.merge!({:parent_group_id=>security_group_id.to_s})
data = JSON.generate(:security_group_rule => params)
response = @connection.req("POST", "/os-security-group-rules", {:data => data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group_rule][:id].to_s => res[:security_group_rule]}
end
def delete_security_group_rule(id)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
@connection.req("DELETE", "/os-security-group-rules/#{id}")
true
end
#VOLUMES - attach detach
def attach_volume(server_id, volume_id, device_id)
raise OpenStack::Exception::NotImplemented.new("os-volumes not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-volumes"]
data = JSON.generate(:volumeAttachment => {"volumeId" => volume_id, "device"=> device_id})
@connection.req("POST", "/servers/#{server_id}/os-volume_attachments", {:data=>data})
true
end
def list_attachments(server_id)
raise OpenStack::Exception::NotImplemented.new("os-volumes not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-volumes"]
response = @connection.req("GET", "/servers/#{server_id}/os-volume_attachments")
OpenStack.symbolize_keys(JSON.parse(response.body))
end
def detach_volume(server_id, attachment_id)
raise OpenStack::Exception::NotImplemented.new("os-volumes not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-volumes"]
@connection.req("DELETE", "/servers/#{server_id}/os-volume_attachments/#{attachment_id}")
true
end
#FLOATING IPs:
#list all float ips associated with tennant or account
def get_floating_ips
check_extension("os-floating-ips")
response = @connection.req("GET", "/os-floating-ips")
res = JSON.parse(response.body)["floating_ips"]
res.inject([]){|result, c| result<< OpenStack::Compute::FloatingIPAddress.new(c) ; result }
end
alias :floating_ips :get_floating_ips
#get details of a specific floating_ip by its id
def get_floating_ip(id)
check_extension("os-floating-ips")
response = @connection.req("GET", "/os-floating-ips/#{id}")
res = JSON.parse(response.body)["floating_ip"]
OpenStack::Compute::FloatingIPAddress.new(res)
end
alias :floating_ip :get_floating_ip
#can optionally pass the :pool parameter
def create_floating_ip(opts={})
check_extension("os-floating-ips")
data = opts[:pool] ? JSON.generate(opts) : JSON.generate({:pool=>nil})
response = @connection.req("POST", "/os-floating-ips",{:data=>data} )
res = JSON.parse(response.body)["floating_ip"]
OpenStack::Compute::FloatingIPAddress.new(res)
end
alias :allocate_floating_ip :create_floating_ip
#delete or deallocate a floating IP using its id
def delete_floating_ip(id)
check_extension("os-floating-ips")
@connection.req("DELETE", "/os-floating-ips/#{id}")
true
end
#add or attach a floating IP to a runnin g server
def attach_floating_ip(opts={:server_id=>"", :ip_id => ""})
check_extension("os-floating-ips")
#first get the address:
addr = get_floating_ip(opts[:ip_id]).ip
data = JSON.generate({:addFloatingIp=>{:address=>addr}})
@connection.req("POST", "/servers/#{opts[:server_id]}/action", {:data=>data})
true
end
def detach_floating_ip(opts={:server_id=>"", :ip_id => ""})
check_extension("os-floating-ips")
#first get the address:
addr = get_floating_ip(opts[:ip_id]).ip
data = JSON.generate({:removeFloatingIp=>{:address=>addr}})
@connection.req("POST", "/servers/#{opts[:server_id]}/action", {:data=>data})
true
end
def get_floating_ip_pools
check_extension 'os-floating-ip-pools'
response = @connection.req('GET', '/os-floating-ip-pools')
JSON.parse(response.body)['floating_ip_pools']
end
#deprecated - please do not use this typo method :)
def get_floating_ip_polls
puts "get_floating_ip_polls() is DEPRECATED: Please use get_floating_ip_pools() without typo!"
self.get_floating_ip_pools
end
def get_floating_ips_bulk
check_extension 'os-floating-ips-bulk'
response = @connection.req('GET', '/os-floating-ips-bulk')
res = JSON.parse(response.body)['floating_ip_info']
res.inject([]){|result, c| result << OpenStack::Compute::FloatingIPInfo.new(c); result}
end
def create_floating_ips_bulk(opts = {})
raise ArgumentError, 'Should not be empty' if opts.empty?
data = JSON.generate({:floating_ips_bulk_create => opts})
check_extension 'os-floating-ips-bulk'
response = @connection.req('POST', '/os-floating-ips-bulk', {:data => data})
JSON.parse(response.body)['floating_ips_bulk_create']
end
# Not working
# Nova does not supported deletion via API
def delete_floating_ips_bulk(opts = {})
raise ArgumentError, 'Should not be empty' if opts.empty?
data = JSON.generate(opts)
check_extension 'os-floating-ips-bulk'
response = @connection.req('POST', '/os-floating-ips-bulk/delete', {:data => data})
JSON.generate(response)
end
# Shows summary statistics for all hypervisors over all compute nodes
def get_hypervisor_stats
check_extension 'os-floating-ips-bulk'
response = @connection.req('GET', '/os-hypervisors/statistics')
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
JSON.parse(response.body)['hypervisor_statistics']
end
private
def check_extension(name)
raise OpenStack::Exception::NotImplemented.new("#{name} not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[name.to_sym]
true
end
end
end
end
Added summary statistics for all hypervisors over all compute nodes method
module OpenStack
module Compute
class Connection
attr_accessor :connection
attr_accessor :extensions
def initialize(connection)
@extensions = nil
@connection = connection
OpenStack::Authentication.init(@connection)
end
# Returns true if the authentication was successful and returns false otherwise.
#
# cs.authok?
# => true
def authok?
@connection.authok
end
# Returns the OpenStack::Compute::Server object identified by the given id.
#
# >> server = cs.get_server(110917)
# => #<OpenStack::Compute::Server:0x101407ae8 ...>
# >> server.name
# => "MyServer"
def get_server(id)
OpenStack::Compute::Server.new(self,id)
end
alias :server :get_server
# Returns an array of hashes, one for each server that exists under this account. The hash keys are :name and :id.
#
# You can also provide :limit and :offset and :"changes-since" and :image and :flavor and :name and :status
# and :host and :limit and :marker parameters to handle pagination.
# http://developer.openstack.org/api-ref-compute-v2.1.html
#
# >> cs.list_servers
# => [{:name=>"MyServer", :id=>110917}]
#
# >> cs.list_servers(:limit => 2, :offset => 3, :name => "MyServer", :status => "ACTIVE")
# => [{:name=>"demo-standingcloud-lts", :id=>168867},
# {:name=>"demo-aicache1", :id=>187853}]
def list_servers(options = {})
anti_cache_param="cacheid=#{Time.now.to_i}"
path = options.empty? ? "#{@connection.service_path}/servers?#{anti_cache_param}" : "#{@connection.service_path}/servers?#{options.to_query}&#{anti_cache_param}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)["servers"])
end
alias :servers :list_servers
# Returns an array of hashes with more details about each server that exists under this account. Additional information
# includes public and private IP addresses, status, hostID, and more. All hash keys are symbols except for the metadata
# hash, which are verbatim strings.
#
# You can also provide :limit and :offset and :"changes-since" and :image and :flavor and :name and :status and :host
# and :limit and :marker parameters to handle pagination.
# http://developer.openstack.org/api-ref-compute-v2.1.html
# >> cs.list_servers_detail
# => [{:name=>"MyServer", :addresses=>{:public=>["67.23.42.37"], :private=>["10.176.241.237"]}, :metadata=>{"MyData" => "Valid"}, :imageRef=>10, :progress=>100, :hostId=>"36143b12e9e48998c2aef79b50e144d2", :flavorRef=>1, :id=>110917, :status=>"ACTIVE"}]
#
# >> cs.list_servers_detail(:limit => 2, :offset => 3, :name => "MyServer", :flavor => 1, :status => "ACTIVE")
# => [{:status=>"ACTIVE", :imageRef=>10, :progress=>100, :metadata=>{}, :addresses=>{:public=>["x.x.x.x"], :private=>["x.x.x.x"]}, :name=>"demo-standingcloud-lts", :id=>168867, :flavorRef=>1, :hostId=>"xxxxxx"},
# {:status=>"ACTIVE", :imageRef=>8, :progress=>100, :metadata=>{}, :addresses=>{:public=>["x.x.x.x"], :private=>["x.x.x.x"]}, :name=>"demo-aicache1", :id=>187853, :flavorRef=>3, :hostId=>"xxxxxx"}]
def list_servers_detail(options = {})
path = options.empty? ? "#{@connection.service_path}/servers/detail" : "#{@connection.service_path}/servers/detail?#{options.to_query}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
json_server_list = JSON.parse(response.body)["servers"]
json_server_list.each do |server|
server["addresses"] = OpenStack::Compute::Address.fix_labels(server["addresses"])
end
OpenStack.symbolize_keys(json_server_list)
end
alias :servers_detail :list_servers_detail
# Creates a new server instance on OpenStack Compute
#
# The argument is a hash of options. The keys :name, :flavorRef,
# and :imageRef are required; :metadata, :security_groups,
# :key_name and :personality are optional.
#
# :flavorRef and :imageRef are href strings identifying a particular
# server flavor and image to use when building the server. The :imageRef
# can either be a stock image, or one of your own created with the
# server.create_image method.
#
# The :metadata argument should be a hash of key/value pairs. This
# metadata will be applied to the server at the OpenStack Compute API level.
#
# The "Personality" option allows you to include up to five files, # of
# 10Kb or less in size, that will be placed on the created server.
# For :personality, pass a hash of the form {'local_path' => 'server_path'}.
# The file located at local_path will be base64-encoded and placed at the
# location identified by server_path on the new server.
#
# Returns a OpenStack::Compute::Server object. The root password is
# available in the adminPass instance method.
#
# >> server = cs.create_server(
# :name => 'NewServer',
# :imageRef => '3',
# :flavorRef => '1',
# :metadata => {'Racker' => 'Fanatical'},
# :personality => {'/home/bob/wedding.jpg' => '/root/wedding.jpg'},
# :key_name => "mykey",
# :security_groups => [ "devel", "test"])
# => #<OpenStack::Compute::Server:0x101229eb0 ...>
# >> server.name
# => "NewServer"
# >> server.status
# => "BUILD"
# >> server.adminPass
# => "NewServerSHMGpvI"
def create_server(options)
raise OpenStack::Exception::MissingArgument, "Server name, flavorRef, and imageRef, must be supplied" unless (options[:name] && options[:flavorRef] && options[:imageRef])
if options[:personality]
options[:personality] = Personalities.get_personality(options[:personality])
end
options[:security_groups] = (options[:security_groups] || []).inject([]){|res, c| res << {"name"=>c} ;res}
data = JSON.generate(:server => options)
response = @connection.csreq("POST",@connection.service_host,"#{@connection.service_path}/servers",@connection.service_port,@connection.service_scheme,{'content-type' => 'application/json'},data)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
server_info = JSON.parse(response.body)['server']
server = OpenStack::Compute::Server.new(self,server_info['id'])
server.adminPass = server_info['adminPass']
server
end
# Returns an array of hashes listing available server images that you have access too,
# including stock OpenStack Compute images and any that you have created. The "id" key
# in the hash can be used where imageRef is required. You can also provide :limit and
# :offset and :"changes-since" and :server and :name and :status :minDisk and :minRam
# and :type and :limit and :marker parameters to handle pagination.
#
# >> cs.list_images
# => [{:name=>"CentOS 5.2", :id=>2, :updated=>"2009-07-20T09:16:57-05:00", :status=>"ACTIVE", :created=>"2009-07-20T09:16:57-05:00"},
# {:name=>"Gentoo 2008.0", :id=>3, :updated=>"2009-07-20T09:16:57-05:00", :status=>"ACTIVE", :created=>"2009-07-20T09:16:57-05:00"},...
#
# >> cs.list_images(:limit => 3, :offset => 2, :status => "ACTIVE")
# => [{:status=>"ACTIVE", :name=>"Fedora 11 (Leonidas)", :updated=>"2009-12-08T13:50:45-06:00", :id=>13},
# {:status=>"ACTIVE", :name=>"CentOS 5.3", :updated=>"2009-08-26T14:59:52-05:00", :id=>7},
# {:status=>"ACTIVE", :name=>"CentOS 5.4", :updated=>"2009-12-16T01:02:17-06:00", :id=>187811}]
def list_images(options = {})
path = options.empty? ? "#{@connection.service_path}/images/detail" : "#{@connection.service_path}/images/detail?#{options.to_query}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)['images'])
end
alias :images :list_images
# Returns a OpenStack::Compute::Image object for the image identified by the provided id.
#
# >> image = cs.get_image(8)
# => #<OpenStack::Compute::Image:0x101659698 ...>
def get_image(id)
OpenStack::Compute::Image.new(self,id)
end
alias :image :get_image
# Returns an array of hashes listing all available server flavors. The :id key in the hash can be used when flavorRef is required.
#
# You can also provide :limit and :offset parameters to handle pagination.
# http://developer.openstack.org/api-ref-compute-v2.1.html
#
# >> cs.list_flavors
# => [{:name=>"256 server", :id=>1, :ram=>256, :disk=>10},
# {:name=>"512 server", :id=>2, :ram=>512, :disk=>20},...
#
# >> cs.list_flavors(:limit => 3, :offset => 2)
# => [{:ram=>1024, :disk=>40, :name=>"1GB server", :id=>3},
# {:ram=>2048, :disk=>80, :name=>"2GB server", :id=>4},
# {:ram=>4096, :disk=>160, :name=>"4GB server", :id=>5}]
def list_flavors(options = {})
path = options.empty? ? "#{@connection.service_path}/flavors/detail" : "#{@connection.service_path}/flavors/detail?#{options.to_query}"
response = @connection.csreq("GET",@connection.service_host,path,@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)['flavors'])
end
alias :flavors :list_flavors
# Returns a OpenStack::Compute::Flavor object for the flavor identified by the provided ID.
#
# >> flavor = cs.flavor(1)
# => #<OpenStack::Compute::Flavor:0x10156dcc0 @name="256 server", @disk=10, @id=1, @ram=256>
def get_flavor(id)
response = @connection.req('GET', "/flavors/#{id}")
flavor_info = JSON.parse(response.body)['flavor']
OpenStack::Compute::Flavor.new(flavor_info)
end
alias :flavor :get_flavor
# nova.create_flavor({name: 'small', vcpus: 2, ram: 1024, disk: 1}, true)
# :name - must be unique, :ram - MB, :disk - GB
# => #<OpenStack::Compute::Flavor:0x007ff95333e268 @id="0c0c393b-3acd-4569-baae-7a7afbe398f6", @name="small", @ram=1024, @disk=1, @vcpus=2>
def create_flavor(options, public = false)
raise OpenStack::Exception::MissingArgument, 'Flavor name, vcpus, ram and disk, must be supplied' unless (options[:name] && options[:vcpus] && options[:ram] && options[:disk])
data = JSON.generate(:flavor => options.merge!({'os-flavor-access:is_public' => public}))
response = @connection.req('POST', '/flavors', {data: data})
flavor_info = JSON.parse(response.body)['flavor']
OpenStack::Compute::Flavor.new(flavor_info)
end
def delete_flavor(id)
@connection.req('DELETE', "/flavors/#{id}")
true
end
def add_tenant_to_flavor(flavor_id, tenant_id)
data = JSON.generate({'addTenantAccess' => {'tenant' => tenant_id}})
response = @connection.req('POST', "/flavors/#{flavor_id}/action", {data: data})
JSON.parse(response.body)
end
def delete_tenant_from_flavor(flavor_id, tenant_id)
data = JSON.generate({'removeTenantAccess' => {'tenant' => tenant_id}})
response = @connection.req('POST', "/flavors/#{flavor_id}/action", {data: data})
JSON.parse(response.body)
end
# Returns the current state of the programatic API limits. Each account has certain limits on the number of resources
# allowed in the account, and a rate of API operations.
#
# The operation returns a hash. The :absolute hash key reveals the account resource limits, including the maxmimum
# amount of total RAM that can be allocated (combined among all servers), the maximum members of an IP group, and the
# maximum number of IP groups that can be created.
#
# The :rate hash key returns an array of hashes indicating the limits on the number of operations that can be performed in a
# given amount of time. An entry in this array looks like:
#
# {:regex=>"^/servers", :value=>50, :verb=>"POST", :remaining=>50, :unit=>"DAY", :resetTime=>1272399820, :URI=>"/servers*"}
#
# This indicates that you can only run 50 POST operations against URLs in the /servers URI space per day, we have not run
# any operations today (50 remaining), and gives the Unix time that the limits reset.
#
# Another example is:
#
# {:regex=>".*", :value=>10, :verb=>"PUT", :remaining=>10, :unit=>"MINUTE", :resetTime=>1272399820, :URI=>"*"}
#
# This says that you can run 10 PUT operations on all possible URLs per minute, and also gives the number remaining and the
# time that the limit resets.
#
# Use this information as you're building your applications to put in relevant pauses if you approach your API limitations.
def limits
response = @connection.csreq("GET",@connection.service_host,"#{@connection.service_path}/limits",@connection.service_port,@connection.service_scheme)
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
OpenStack.symbolize_keys(JSON.parse(response.body)['limits'])
end
# ==============================
# API EXTENSIONS
#
# http://nova.openstack.org/api_ext/index.html
# http://api.openstack.org/ (grep 'Compute API Extensions')
#
#query the openstack provider for any implemented extensions to the compute API
#returns a hash with openstack service provider's returned details
#about the implemented extensions, e.g.:
#
# { :os-floating_ips => { :links=>[],
# :updated=>"2011-06-16T00:00:00+00:00",
# :description=>"Floating IPs support",
# :namespace=>"http://docs.openstack.org/ext/floating_ips/api/v1.1",
# :name=>"Floating_ips", :alias=>"os-floating-ips"},
# :os-keypairs => { :links=>[],
# :updated=>"2011-08-08T00:00:00+00:00",
# :description=>"Keypair Support",
# :namespace=>"http://docs.openstack.org/ext/keypairs/api/v1.1",
# :name=>"Keypairs",
# :alias=>"os-keypairs"}
# }
#
def api_extensions
if @extensions.nil?
response = @connection.req("GET", "/extensions")
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
res = OpenStack.symbolize_keys(JSON.parse(response.body))
@extensions = res[:extensions].inject({}){|result, c| result[c[:alias].to_sym] = c ; result}
end
@extensions
end
# Retrieve a list of key pairs associated with the current authenticated account
# Will return a hash:
# { :key_one => { :fingerprint => "3f:12:4d:d1:54:f1:f4:3f:fe:a8:12:ec:1a:fb:35:b2",
# :public_key => "ssh-rsa AAAAB3Nza923kJU123AADAQABAAAAg928JUwydszi029kIJudfOzQ7o160Ll1ItybDzYYcCAJ/N02loIKJU17264520bmXZFSsaZf2ErX3nSBNI3K+2zQzu832jkhkfdsa7GHH5hvNOxO7u800894312JKLJLHP/R91fdsajHKKJADSAgQ== nova@nv-zz2232-api0002\n",
# :name => "key_one"},
#
# :key_two => { :fingerprint => "6b:32:dd:d2:51:c1:f2:3a:fb:a2:52:3a:1a:bb:25:1b",
# :public_key => "ssh-rsa AKIJUuw71645kJU123AADAQABAAAAg928019oiUJY12765IJudfOzQ7o160Ll1ItybDzYYcCAJ/N80438012480321jhkhKJlfdsazu832jkhkfdsa7GHH5fdasfdsajlj2999789799987989894312JKLJLHP/R91fdsajHKKJADSAgQ== nova@bv-fdsa32-api0002\n",
# :name => "key_two"}
# }
#
# Raises OpenStack::Exception::NotImplemented if the current provider doesn't
# offer the os-keypairs extension
#
def keypairs
begin
response = @connection.req("GET", "/os-keypairs")
res = OpenStack.symbolize_keys(JSON.parse(response.body))
res[:keypairs].inject({}){|result, c| result[c[:keypair][:name].to_sym] = c[:keypair] ; result }
rescue OpenStack::Exception::ItemNotFound => not_found
msg = "The os-keypairs extension is not implemented for the provider you are talking to "+
"- #{@connection.http.keys.first}"
raise OpenStack::Exception::NotImplemented.new(msg, 501, "#{not_found.message}")
end
end
# Create a new keypair for use with launching servers. Raises
# a OpenStack::Exception::NotImplemented if os-keypairs extension
# is not implemented (or not advertised) by the OpenStack provider.
#
# The 'name' parameter MUST be supplied, otherwise a
# OpenStack::Exception::MissingArgument will be raised.
#
# Optionally requests can specify a 'public_key' parameter,
# with the full public ssh key (String) to be used to create the keypair
# (i.e. import a existing key).
#
# Returns a hash with details of the new key; the :private_key attribute
# must be saved must be saved by caller (not retrievable thereafter).
# NOTE: when the optional :public_key parameter is given, the response
# will obviously NOT contain the :private_key attribute.
#
# >> os.create_keypair({:name=>"test_key"})
# => { :name => "test_key",
# :fingerprint => "f1:f3:a2:d3:ca:75:da:f1:06:f4:f7:dc:cc:7d:e1:ca",
# :user_id => "dev_41247879706381",
# :public_key => "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDgGhDH3z9uMAvPV8ziE9BCEjHCPXGufy5bOgY5mY5jOSfdmKspdbl0z/LimHVKRDNX6HoL5qRg5V/tGH/NYP5sX2zF/XRKz16lfBxiUL1EONXA9fsTEBR3FGp8NcA7hW2+YiUxWafms4If3NFqttTQ11XqTU8JCMvms4D81lhbiQ== nova@use03147k5-eth0\n",
# :private_key => "-----BEGIN RSA PRIVATE KEY-----\nMIICXwIBAAKBgQDgGhDH3z9uMAvPV8ziE9BCEjHCPXGufy5bOgY5mY5jOSfdmKsp\ndbl0z/LimHVKRDNX6HoL5qRg5V/tGH/NYP5sX2zF/XRKz16lfBxiUL1EONXA9fsT\nEBR3FGp8NcA7hW2+YiUxWafms4If3NFqttTQ11XqTU8JCMvms4D81lhbiQIDAQAB\nAoGBAJ1akAfXwNEc2V4IV2sy4FtULS4nOKh+0szpjC9rm+gd3Nki9qQQ7lyQGwpy\nZID2LFsAeJnco/UJefaf6jUKcvnS7tlxMuQB8DBlepiDqnnec0EiEAVmmt9GWlYZ\nJgfGWqDzI1WtouDCIsOhx1Vq7Foue6pgOnibktg2kfYnH9IRAkEA9tKzhlr9rFui\nbVDkiRJK3VTIhKyk4davDjqPJFLJ+4+77wRW164sGxwReD7HtW6qVtJd1MFvqLDO\nqJJEsqDvXQJBAOhvGaWiAPSuP+/z6GE6VXB1pADQFTYIp2DXUa5DcStTGe7hGF1b\nDeAxpDNBbLO3YKYqi2L9vJcIsp5PkHlEVh0CQQCVLIkWBb5VQliryv0knuqiVFCQ\nZyuL1s2cQuYqZOLwaFGERtIZrom3pMImM4NN82F98cyF/pb2lE2CckyUzVF9AkEA\nqhwFjS9Pu8N7j8XWoLHsre2rJd0kaPNUbI+pe/xn6ula5XVgO5LUSOyL2+daAv2G\ngpZIhR5m07LN5wccGWRmEQJBALZRenXaSyX2R2C9ag9r2gaU8/h+aU9he5kjXIt8\n+B8wvpvfOkpOAVCQEMxtsDkEixUtI98YKZP60uw+Xzh40YU=\n-----END RSA PRIVATE KEY-----\n"
# }
#
# Will raise an OpenStack::Exception::BadRequest if an invalid public_key is provided:
# >> os.create_keypair({:name=>"marios_keypair_test_invalid", :public_key=>"derp"})
# => OpenStack::Exception::BadRequest: Unexpected error while running command.
# Stdout: '/tmp/tmp4kI12a/import.pub is not a public key file.\n'
#
def create_keypair(options)
raise OpenStack::Exception::NotImplemented.new("os-keypairs not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-keypairs"]
raise OpenStack::Exception::MissingArgument, "Keypair name must be supplied" unless (options[:name])
data = JSON.generate(:keypair => options)
response = @connection.req("POST", "/os-keypairs", {:data=>data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
res[:keypair]
end
# Delete an existing keypair. Raises OpenStack::Exception::NotImplemented
# if os-keypairs extension is not implemented (or not advertised) by the OpenStack provider.
#
# Returns true if succesful.
# >> os.delete_keypair("marios_keypair")
# => true
#
# Will raise OpenStack::Exception::ItemNotFound if specified keypair doesn't exist
#
def delete_keypair(keypair_name)
raise OpenStack::Exception::NotImplemented.new("os-keypairs not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-keypairs"]
@connection.req("DELETE", "/os-keypairs/#{keypair_name}")
true
end
#Security Groups:
#Returns a hash with the security group IDs as keys:
#=> { "1381" => { :tenant_id=>"12345678909876", :id=>1381, :name=>"default", :description=>"default",
# :rules=> [
# {:from_port=>22, :group=>{}, :ip_protocol=>"tcp", :to_port=>22,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4902},
# {:from_port=>80, :group=>{}, :ip_protocol=>"tcp", :to_port=>80,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4903},
# {:from_port=>443, :group=>{}, :ip_protocol=>"tcp", :to_port=>443,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4904},
# {:from_port=>-1, :group=>{}, :ip_protocol=>"icmp", :to_port=>-1,
# :parent_group_id=>1381, :ip_range=>{:cidr=>"0.0.0.0/0"}, :id=>4905}],
# ]
# },
# "1234" => { ... } }
#
def security_groups
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
response = @connection.req("GET", "/os-security-groups")
res = OpenStack.symbolize_keys(JSON.parse(response.body))
res[:security_groups].inject({}){|result, c| result[c[:id].to_s] = c ; result }
end
def security_group(id)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
response = @connection.req("GET", "/os-security-groups/#{id}")
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group][:id].to_s => res[:security_group]}
end
def create_security_group(name, description)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
data = JSON.generate(:security_group => { "name" => name, "description" => description})
response = @connection.req("POST", "/os-security-groups", {:data => data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group][:id].to_s => res[:security_group]}
end
def update_security_group(id, name, description)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
data = JSON.generate(:security_group => { "name" => name, "description" => description})
response = @connection.req("PUT", "/os-security-groups/#{id}", {:data => data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group][:id].to_s => res[:security_group]}
end
def delete_security_group(id)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
@connection.req("DELETE", "/os-security-groups/#{id}")
true
end
#params: { :ip_protocol=>"tcp", :from_port=>"123", :to_port=>"123", :cidr=>"192.168.0.1/16", :group_id:="123" }
#observed behaviour against Openstack@HP cloud - can specify either cidr OR group_id as source, but not both
#if both specified, the group is used and the cidr ignored.
def create_security_group_rule(security_group_id, params)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
params.merge!({:parent_group_id=>security_group_id.to_s})
data = JSON.generate(:security_group_rule => params)
response = @connection.req("POST", "/os-security-group-rules", {:data => data})
res = OpenStack.symbolize_keys(JSON.parse(response.body))
{res[:security_group_rule][:id].to_s => res[:security_group_rule]}
end
def delete_security_group_rule(id)
raise OpenStack::Exception::NotImplemented.new("os-security-groups not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-security-groups"] or api_extensions[:security_groups]
@connection.req("DELETE", "/os-security-group-rules/#{id}")
true
end
#VOLUMES - attach detach
def attach_volume(server_id, volume_id, device_id)
raise OpenStack::Exception::NotImplemented.new("os-volumes not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-volumes"]
data = JSON.generate(:volumeAttachment => {"volumeId" => volume_id, "device"=> device_id})
@connection.req("POST", "/servers/#{server_id}/os-volume_attachments", {:data=>data})
true
end
def list_attachments(server_id)
raise OpenStack::Exception::NotImplemented.new("os-volumes not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-volumes"]
response = @connection.req("GET", "/servers/#{server_id}/os-volume_attachments")
OpenStack.symbolize_keys(JSON.parse(response.body))
end
def detach_volume(server_id, attachment_id)
raise OpenStack::Exception::NotImplemented.new("os-volumes not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[:"os-volumes"]
@connection.req("DELETE", "/servers/#{server_id}/os-volume_attachments/#{attachment_id}")
true
end
#FLOATING IPs:
#list all float ips associated with tennant or account
def get_floating_ips
check_extension("os-floating-ips")
response = @connection.req("GET", "/os-floating-ips")
res = JSON.parse(response.body)["floating_ips"]
res.inject([]){|result, c| result<< OpenStack::Compute::FloatingIPAddress.new(c) ; result }
end
alias :floating_ips :get_floating_ips
#get details of a specific floating_ip by its id
def get_floating_ip(id)
check_extension("os-floating-ips")
response = @connection.req("GET", "/os-floating-ips/#{id}")
res = JSON.parse(response.body)["floating_ip"]
OpenStack::Compute::FloatingIPAddress.new(res)
end
alias :floating_ip :get_floating_ip
#can optionally pass the :pool parameter
def create_floating_ip(opts={})
check_extension("os-floating-ips")
data = opts[:pool] ? JSON.generate(opts) : JSON.generate({:pool=>nil})
response = @connection.req("POST", "/os-floating-ips",{:data=>data} )
res = JSON.parse(response.body)["floating_ip"]
OpenStack::Compute::FloatingIPAddress.new(res)
end
alias :allocate_floating_ip :create_floating_ip
#delete or deallocate a floating IP using its id
def delete_floating_ip(id)
check_extension("os-floating-ips")
@connection.req("DELETE", "/os-floating-ips/#{id}")
true
end
#add or attach a floating IP to a runnin g server
def attach_floating_ip(opts={:server_id=>"", :ip_id => ""})
check_extension("os-floating-ips")
#first get the address:
addr = get_floating_ip(opts[:ip_id]).ip
data = JSON.generate({:addFloatingIp=>{:address=>addr}})
@connection.req("POST", "/servers/#{opts[:server_id]}/action", {:data=>data})
true
end
def detach_floating_ip(opts={:server_id=>"", :ip_id => ""})
check_extension("os-floating-ips")
#first get the address:
addr = get_floating_ip(opts[:ip_id]).ip
data = JSON.generate({:removeFloatingIp=>{:address=>addr}})
@connection.req("POST", "/servers/#{opts[:server_id]}/action", {:data=>data})
true
end
def get_floating_ip_pools
check_extension 'os-floating-ip-pools'
response = @connection.req('GET', '/os-floating-ip-pools')
JSON.parse(response.body)['floating_ip_pools']
end
#deprecated - please do not use this typo method :)
def get_floating_ip_polls
puts "get_floating_ip_polls() is DEPRECATED: Please use get_floating_ip_pools() without typo!"
self.get_floating_ip_pools
end
def get_floating_ips_bulk
check_extension 'os-floating-ips-bulk'
response = @connection.req('GET', '/os-floating-ips-bulk')
res = JSON.parse(response.body)['floating_ip_info']
res.inject([]){|result, c| result << OpenStack::Compute::FloatingIPInfo.new(c); result}
end
def create_floating_ips_bulk(opts = {})
raise ArgumentError, 'Should not be empty' if opts.empty?
data = JSON.generate({:floating_ips_bulk_create => opts})
check_extension 'os-floating-ips-bulk'
response = @connection.req('POST', '/os-floating-ips-bulk', {:data => data})
JSON.parse(response.body)['floating_ips_bulk_create']
end
# Not working
# Nova does not supported deletion via API
def delete_floating_ips_bulk(opts = {})
raise ArgumentError, 'Should not be empty' if opts.empty?
data = JSON.generate(opts)
check_extension 'os-floating-ips-bulk'
response = @connection.req('POST', '/os-floating-ips-bulk/delete', {:data => data})
JSON.generate(response)
end
# Shows summary statistics for all hypervisors over all compute nodes
def get_hypervisor_stats
response = @connection.req('GET', '/os-hypervisors/statistics')
OpenStack::Exception.raise_exception(response) unless response.code.match(/^20.$/)
JSON.parse(response.body)['hypervisor_statistics']
end
private
def check_extension(name)
raise OpenStack::Exception::NotImplemented.new("#{name} not implemented by #{@connection.http.keys.first}", 501, "NOT IMPLEMENTED") unless api_extensions[name.to_sym]
true
end
end
end
end
|
module OpenStax
module RescueFrom
VERSION = "1.7.1"
end
end
Version bump
module OpenStax
module RescueFrom
VERSION = "1.7.2"
end
end
|
require 'origen_link/server/pin'
##################################################
# OrigenLink::Server::Sequencer Class
# Instance variables:
# pinmap: hash with ["pin name"] = pin object
# patternpinindex: hash with ["pin name"] =
# integer index into vector data
# patternpinorder: Array with pin names in
# the vector order
#
# This class processes messages targeted for
# pin sequencer interface (vector pattern
# execution).
#
# Supported messages:
# pin_assign (create pin mapping)
# ex: "pin_assign:tck,3,extal,23,tdo,5"
#
# pin_patternorder (define vector pin order)
# ex: "pin_patternorder:tdo,extal,tck"
#
# pin_cycle (execute vector data)
# ex: "pin_cycle:H11"
#
# pin_clear (clear all setup information)
# ex: "pin_clear:"
#
# pin_format (setup a pin with return format)
# first argument is the timeset
# ex: "pin_format:1,tck,rl"
#
# pin_timing (define when pin events happen)
# timing is stored in a timeset hash
# first argument is the timeset key
# ex: "pin_timing:1,tdi,0,tdo,1,tms,0
#
# version (check version of app server is
# running)
# ex: "version:"
# response ex: "P:0.2.0.pre0"
##################################################
module OrigenLink
module Server
def self.gpio_dir=(path)
@gpio_dir = path
end
def self.gpio_dir
@gpio_dir || '/sys/class/gpio'
end
class Sequencer
attr_accessor :version
attr_reader :pinmap
attr_reader :patternorder
attr_reader :cycletiming
attr_reader :patternpinindex
##################################################
# initialize method
# Create empty pinmap, pattern pin index
# and pattern order instance variables
##################################################
def initialize
@pinmap = Hash.new(-1)
@patternpinindex = Hash.new(-1)
@patternorder = []
@cycletiming = Hash.new(-1)
@version = ''
end
##################################################
# processmessage method
# arguments: message
# message format is <group>_<command>:<args>
# returns: message response
#
# This method splits a message into it's
# command and arguments and passes this
# information to the method that performs
# the requested command
##################################################
def processmessage(message)
command = message.split(':')
case command[0]
when 'pin_assign'
pin_assign(command[1])
when 'pin_patternorder'
pin_patternorder(command[1])
when 'pin_cycle'
pin_cycle(command[1])
when 'pin_clear'
pin_clear
when 'pin_format'
pin_format(command[1])
when 'pin_timing'
pin_timing(command[1])
when 'version'
"P:#{@version}"
else
'Error Invalid command: ' + command[0].to_s
end
end
##################################################
# pin_assign method
# arguments: <args> from the message request
# see "processmessage" method
# returns: "P:" or error message
#
# This method creates a pin instance for each
# pin in the pin map and builds the pinmap
# hash. Before the pinmap is created, any
# information from a previous pattern run is
# cleared.
##################################################
def pin_assign(args)
pin_clear
success = true
fail_message = ''
argarr = args.split(',')
0.step(argarr.length - 2, 2) do |index|
@pinmap[argarr[index]] = Pin.new(argarr[index + 1])
unless @pinmap[argarr[index]].gpio_valid
success = false
fail_message = fail_message + 'pin ' + argarr[index] + ' gpio' + argarr[index + 1] + ' is invalid'
end
end
if success
'P:'
else
'F:' + fail_message
end
end
##################################################
# new_timeset(tset)
# creates a new empty timeset hash
#
# timing format:
# ['events'] = [0, 5, 10, 35]
# ['drive_event_data'] = {
# 0: 'data'
# 10: 'data'
# 35: '0'
# }
# ['drive_event_pins'] = {
# 0: [pin_obj1, pin_obj2]
# etc.
# }
##################################################
def new_timeset(tset)
@cycletiming[tset] = {}
@cycletiming[tset]['timing'] = [[], [], []] # to be removed
# new format below
@cycletiming[tset]['events'] = []
@cycletiming[tset]['drive_event_data'] = {}
@cycletiming[tset]['drive_event_pins'] = {}
@cycletiming[tset]['compare_event_data'] = {}
@cycletiming[tset]['compare_event_pins'] = {}
end
##################################################
# pin_format method
# arguments: <args> from the message request
# Should be <timeset>,<pin>,rl or rh
# multi-clock not currently supported
#
# TODO: update to store timset in new format
##################################################
def pin_format(args)
argarr = args.split(',')
tset_key = argarr.delete_at(0).to_i
new_timeset(tset_key) unless @cycletiming.key?(tset_key)
@cycletiming[tset_key].delete('rl')
@cycletiming[tset_key].delete('rh')
0.step(argarr.length - 2, 2) do |index|
@cycletiming[tset_key][argarr[index + 1]] = [] unless @cycletiming[tset_key].key?(argarr[index + 1])
@cycletiming[tset_key][argarr[index + 1]] << argarr[index]
end
'P:'
end
##################################################
# pin_timing method
# arguments: <args> from the message request
# Should be '1,pin,-1,pin2,0,pin3,1'
# First integer is timeset number
# If argument is '', default timing is created
# Default timeset number is 0, this is used
# if no timeset is explicitly defined
#
# cycle arg: 0 1 2
# waveform : ___/***\___
#
# returns "P:" or error message
#
# This method sets up a time set. All retrun
# format pins are driven between 0 and 1 and
# return between 1 and 2. Non-return pins are
# acted upon during the 0, 1 or 2 time period.
#
# TODO: update to store timeset in new format
##################################################
def pin_timing(args)
argarr = args.split(',')
tset_key = argarr.delete_at(0).to_i
new_timeset(tset_key) unless @cycletiming.key?(tset_key)
@cycletiming[tset_key]['timing'].each do |index|
index.delete_if { true }
end
0.step(argarr.length - 2, 2) do |index|
@cycletiming[tset_key]['timing'][argarr[index + 1].to_i] << argarr[index]
end
'P:'
end
##################################################
# pin_patternorder method
# arguments: <args> from the message request
# returns: "P:" or error message
#
# This method is used to define the order
# for pin vector data.
##################################################
def pin_patternorder(args)
argarr = args.split(',')
index = 0
if @cycletiming.key?(0)
@cycletiming[0]['timing'][0].delete_if { true }
else
new_timeset(0)
end
argarr.each do |pin|
@patternorder << pin
@pinmap[pin].pattern_index = index # pattern index stored in pin object now
@patternpinindex[pin] = index # to be removed
# default timing will need to be updated to match new format
@cycletiming[0]['timing'][0] << pin
index += 1
end
'P:'
end
##################################################
# pin_cycle method
# arguments: <args> from the message request
# returns: "P:" or "F:" followed by results
#
# This method executes one cycle of pin vector
# data. The vector data is decomposed and
# sequenced. Each pin object and pin data
# is passed to the "process_pindata" method
# for decoding and execution
#
# TODO: re-write to use new timing format
##################################################
def pin_cycle(args)
# set default repeats and timeset
repeat_count = 1
tset = 0
if args =~ /,/
parsedargs = args.split(',')
args = parsedargs.pop
parsedargs.each do |arg|
if arg =~ /repeat/
repeat_count = arg.sub(/repeat/, '').to_i
elsif arg =~ /tset/
tset = arg.sub(/tset/, '').to_i
end
end
end
message = ''
pindata = args.split('')
@cycle_failure = false
0.upto(repeat_count - 1) do |count|
response = {}
# process time 0 events
response = process_events(@cycletiming[tset]['timing'][0], pindata)
# send drive data for return format pins
response = (process_events(@cycletiming[tset]['rl'], pindata)).merge(response)
response = (process_events(@cycletiming[tset]['rh'], pindata)).merge(response)
# process time 1 events
response = process_events(@cycletiming[tset]['timing'][1], pindata).merge(response)
# send return data
unless @cycletiming[tset]['rl'].nil?
@cycletiming[tset]['rl'].each do |pin|
process_pindata(@pinmap[pin], '0')
end
end
unless @cycletiming[tset]['rh'].nil?
@cycletiming[tset]['rh'].each do |pin|
process_pindata(@pinmap[pin], '1')
end
end
# process time 2 events
response = process_events(@cycletiming[tset]['timing'][2], pindata).merge(response)
# changing response format to return all data for easier debug, below is original method
# TODO: remove the commented code once return format and delay handling is finalized
# if (count == 0) || (@cycle_failure)
# message = ''
# @patternorder.each do |pin|
# message += response[pin]
# end
# end
message = message + ' ' unless count == 0
@patternorder.each do |pin|
message += response[pin]
end
end # end cycle through repeats
if @cycle_failure
rtnmsg = 'F:' + message + ' Expected:' + args
else
rtnmsg = 'P:' + message
end
# no need to return repeat count since all data is returned
# TODO: remove the commented code once return format and delay handling is finalized
# rtnmsg += ' Repeat ' + repeat_count.to_s if repeat_count > 1
rtnmsg
end
##################################################
# process_events
# used by pin_cycle to avoid duplicating code
#
# TODO: likely to remove after new pin_cycle
# method is implemented
##################################################
def process_events(events, pindata)
response = {}
unless events.nil?
events.each do |pin|
response[pin] = process_pindata(@pinmap[pin], pindata[@patternpinindex[pin]])
end
end
response
end
##################################################
# process_pindata method
# arguments:
# pin: the pin object to be operated on
# data: the pin data to be executed
# returns: the drive data or read data
#
# This method translates pin data into one
# of three possible events. Drive 0, drive 1
# or read. Supported character decode:
# drive 0: '0'
# drive 1: '1'
# read: anything else
#
# TODO: rewrite to suit new pin_cycle method
##################################################
def process_pindata(pin, data)
if data == '0' || data == '1'
pin.out(data)
data
else
case pin.in
when '0'
@cycle_failure = true if data == 'H'
if data == 'X'
'.'
else
'L'
end
when '1'
@cycle_failure = true if data == 'L'
if data == 'X'
'`'
else
'H'
end
else
'W'
end
end
end
##################################################
# pin_clear method
#
# This method clears all storage objects. It
# is called by the "pin_assign" method
##################################################
def pin_clear
@pinmap.each { |pin_name, pin| pin.destroy }
@pinmap.clear
@patternpinindex.clear
@patternorder.delete_if { true }
@cycletiming.clear
'P:'
end
end
end
end
updated legacy timing to use new format
require 'origen_link/server/pin'
##################################################
# OrigenLink::Server::Sequencer Class
# Instance variables:
# pinmap: hash with ["pin name"] = pin object
# patternpinindex: hash with ["pin name"] =
# integer index into vector data
# patternpinorder: Array with pin names in
# the vector order
#
# This class processes messages targeted for
# pin sequencer interface (vector pattern
# execution).
#
# Supported messages:
# pin_assign (create pin mapping)
# ex: "pin_assign:tck,3,extal,23,tdo,5"
#
# pin_patternorder (define vector pin order)
# ex: "pin_patternorder:tdo,extal,tck"
#
# pin_cycle (execute vector data)
# ex: "pin_cycle:H11"
#
# pin_clear (clear all setup information)
# ex: "pin_clear:"
#
# pin_format (setup a pin with return format)
# first argument is the timeset
# ex: "pin_format:1,tck,rl"
#
# pin_timing (define when pin events happen)
# timing is stored in a timeset hash
# first argument is the timeset key
# ex: "pin_timing:1,tdi,0,tdo,1,tms,0
#
# version (check version of app server is
# running)
# ex: "version:"
# response ex: "P:0.2.0.pre0"
##################################################
module OrigenLink
module Server
def self.gpio_dir=(path)
@gpio_dir = path
end
def self.gpio_dir
@gpio_dir || '/sys/class/gpio'
end
class Sequencer
attr_accessor :version
attr_reader :pinmap
attr_reader :patternorder
attr_reader :cycletiming
attr_reader :patternpinindex
##################################################
# initialize method
# Create empty pinmap, pattern pin index
# and pattern order instance variables
##################################################
def initialize
@pinmap = Hash.new(-1)
@patternpinindex = Hash.new(-1)
@patternorder = []
@cycletiming = Hash.new(-1)
@version = ''
end
##################################################
# processmessage method
# arguments: message
# message format is <group>_<command>:<args>
# returns: message response
#
# This method splits a message into it's
# command and arguments and passes this
# information to the method that performs
# the requested command
##################################################
def processmessage(message)
command = message.split(':')
case command[0]
when 'pin_assign'
pin_assign(command[1])
when 'pin_patternorder'
pin_patternorder(command[1])
when 'pin_cycle'
pin_cycle(command[1])
when 'pin_clear'
pin_clear
when 'pin_format'
pin_format(command[1])
when 'pin_timing'
pin_timing(command[1])
when 'version'
"P:#{@version}"
else
'Error Invalid command: ' + command[0].to_s
end
end
##################################################
# pin_assign method
# arguments: <args> from the message request
# see "processmessage" method
# returns: "P:" or error message
#
# This method creates a pin instance for each
# pin in the pin map and builds the pinmap
# hash. Before the pinmap is created, any
# information from a previous pattern run is
# cleared.
##################################################
def pin_assign(args)
pin_clear
success = true
fail_message = ''
argarr = args.split(',')
0.step(argarr.length - 2, 2) do |index|
@pinmap[argarr[index]] = Pin.new(argarr[index + 1])
unless @pinmap[argarr[index]].gpio_valid
success = false
fail_message = fail_message + 'pin ' + argarr[index] + ' gpio' + argarr[index + 1] + ' is invalid'
end
end
if success
'P:'
else
'F:' + fail_message
end
end
##################################################
# new_timeset(tset)
# creates a new empty timeset hash
#
# timing format:
# ['events'] = [0, 5, 10, 35]
# ['drive_event_data'] = {
# 0: 'data'
# 10: 'data'
# 35: '0'
# }
# ['drive_event_pins'] = {
# 0: [pin_obj1, pin_obj2]
# etc.
# }
##################################################
def new_timeset(tset)
@cycletiming[tset] = {}
@cycletiming[tset]['events'] = []
@cycletiming[tset]['drive_event_data'] = {}
@cycletiming[tset]['drive_event_pins'] = {}
@cycletiming[tset]['compare_event_data'] = {}
@cycletiming[tset]['compare_event_pins'] = {}
end
##################################################
# pin_format method
# arguments: <args> from the message request
# Should be <timeset>,<pin>,rl or rh
# multi-clock not currently supported
#
##################################################
def pin_format(args)
argarr = args.split(',')
tset_key = argarr.delete_at(0).to_i
new_timeset(tset_key) unless @cycletiming.key?(tset_key)
@cycletiming[tset_key]['events'] += [1, 3]
@cycletiming[tset_key]['events'].sort!
[1, 3].each do |event|
@cycletiming[tset_key]['drive_event_pins'][event] = []
end
0.step(argarr.length - 2, 2) do |index|
drive_type = argarr[index + 1]
pin_name = argarr[index]
@cycletiming[tset_key]['drive_event_data'][1] = 'data'
@cycletiming[tset-key]['drive_event_pins'][1] << @pinmap[pin_name]
@cycletiming[tset-key]['drive_event_pins'][3] << @pinmap[pin_name]
if drive_type = 'rl'
@cycletiming[tset_key]['drive_event_data'][3] = '0'
else
@cycletiming[tset_key]['drive_event_data'][3] = '1'
end
end
'P:'
end
##################################################
# pin_timing method
# arguments: <args> from the message request
# Should be '1,pin,-1,pin2,0,pin3,1'
# First integer is timeset number
# If argument is '', default timing is created
# Default timeset number is 0, this is used
# if no timeset is explicitly defined
#
# cycle arg: 0 1 2
# waveform : ___/***\___
#
# returns "P:" or error message
#
# This method sets up a time set. All retrun
# format pins are driven between 0 and 1 and
# return between 1 and 2. Non-return pins are
# acted upon during the 0, 1 or 2 time period.
#
##################################################
def pin_timing(args)
argarr = args.split(',')
tset_key = argarr.delete_at(0).to_i
new_timeset(tset_key) unless @cycletiming.key?(tset_key)
[0, 2, 4].each do |event|
@cycletiming[tset_key]['drive_event_pins'][event] = []
@cycletiming[tset_key]['compare_event_pins'][event] = []
end
#process the information received
0.step(argarr.length - 2, 2) do |index|
event = argarr[index + 1].to_i
# reorder event number to allow rising/falling edges
event *= 2
pin_name = argarr[index]
@cycletiming[tset_key]['events'] << event
@cycletiming[tset_key]['drive_event_data'][event] = 'data'
@cycletiming[tset_key]['drive_event_pins'][event] << @pinmap[pin_name]
@cycletiming[tset_key]['compare_event_data'][event] = 'data'
@cycletiming[tset_key]['compare_event_pins'][event] << @pinmap[pin_name]
end
# remove events with no associated pins
@cycletiming[tset_key]['events'].uniq!
@cycletiming[tset_key]['events'].sort!
[0, 2, 4].each do |event|
if @cycletiming[tset_key]['drive_event_pins'][event].size == 0
@cycletiming[tset_key]['events'] -= [event]
@cycletiming[tset_key]['drive_event_data'].delete(event)
@cycletiming[tset_key]['drive_event_pins'].delete(event)
@cycletiming[tset_key]['compare_event_data'].delete(event)
@cycletiming[tset_key]['compare_event_pins'].delete(event)
end
end
'P:'
end
##################################################
# pin_patternorder method
# arguments: <args> from the message request
# returns: "P:" or error message
#
# This method is used to define the order
# for pin vector data.
##################################################
def pin_patternorder(args)
argarr = args.split(',')
index = 0
new_timeset(0)
argarr.each do |pin|
@patternorder << pin
@pinmap[pin].pattern_index = index # pattern index stored in pin object now
@patternpinindex[pin] = index # to be removed
# define default timing
@cycletiming[0]['events'] << index
@cycletiming[0]['drive_event_data'][index] = 'data'
@cycletiming[0]['drive_event_pins'][index] = [@pinmap[pin]]
@cycletiming[0]['compare_event_data'][index] = 'data'
@cycletiming[0]['compare_event_pins'][index] = [@pinmap[pin]]
index += 1
end
'P:'
end
##################################################
# pin_cycle method
# arguments: <args> from the message request
# returns: "P:" or "F:" followed by results
#
# This method executes one cycle of pin vector
# data. The vector data is decomposed and
# sequenced. Each pin object and pin data
# is passed to the "process_pindata" method
# for decoding and execution
#
# TODO: re-write to use new timing format
##################################################
def pin_cycle(args)
# set default repeats and timeset
repeat_count = 1
tset = 0
if args =~ /,/
parsedargs = args.split(',')
args = parsedargs.pop
parsedargs.each do |arg|
if arg =~ /repeat/
repeat_count = arg.sub(/repeat/, '').to_i
elsif arg =~ /tset/
tset = arg.sub(/tset/, '').to_i
end
end
end
message = ''
pindata = args.split('')
@cycle_failure = false
0.upto(repeat_count - 1) do |count|
response = {}
# process time 0 events
response = process_events(@cycletiming[tset]['timing'][0], pindata)
# send drive data for return format pins
response = (process_events(@cycletiming[tset]['rl'], pindata)).merge(response)
response = (process_events(@cycletiming[tset]['rh'], pindata)).merge(response)
# process time 1 events
response = process_events(@cycletiming[tset]['timing'][1], pindata).merge(response)
# send return data
unless @cycletiming[tset]['rl'].nil?
@cycletiming[tset]['rl'].each do |pin|
process_pindata(@pinmap[pin], '0')
end
end
unless @cycletiming[tset]['rh'].nil?
@cycletiming[tset]['rh'].each do |pin|
process_pindata(@pinmap[pin], '1')
end
end
# process time 2 events
response = process_events(@cycletiming[tset]['timing'][2], pindata).merge(response)
# changing response format to return all data for easier debug, below is original method
# TODO: remove the commented code once return format and delay handling is finalized
# if (count == 0) || (@cycle_failure)
# message = ''
# @patternorder.each do |pin|
# message += response[pin]
# end
# end
message = message + ' ' unless count == 0
@patternorder.each do |pin|
message += response[pin]
end
end # end cycle through repeats
if @cycle_failure
rtnmsg = 'F:' + message + ' Expected:' + args
else
rtnmsg = 'P:' + message
end
# no need to return repeat count since all data is returned
# TODO: remove the commented code once return format and delay handling is finalized
# rtnmsg += ' Repeat ' + repeat_count.to_s if repeat_count > 1
rtnmsg
end
##################################################
# process_events
# used by pin_cycle to avoid duplicating code
#
# TODO: likely to remove after new pin_cycle
# method is implemented
##################################################
def process_events(events, pindata)
response = {}
unless events.nil?
events.each do |pin|
response[pin] = process_pindata(@pinmap[pin], pindata[@patternpinindex[pin]])
end
end
response
end
##################################################
# process_pindata method
# arguments:
# pin: the pin object to be operated on
# data: the pin data to be executed
# returns: the drive data or read data
#
# This method translates pin data into one
# of three possible events. Drive 0, drive 1
# or read. Supported character decode:
# drive 0: '0'
# drive 1: '1'
# read: anything else
#
# TODO: rewrite to suit new pin_cycle method
##################################################
def process_pindata(pin, data)
if data == '0' || data == '1'
pin.out(data)
data
else
case pin.in
when '0'
@cycle_failure = true if data == 'H'
if data == 'X'
'.'
else
'L'
end
when '1'
@cycle_failure = true if data == 'L'
if data == 'X'
'`'
else
'H'
end
else
'W'
end
end
end
##################################################
# pin_clear method
#
# This method clears all storage objects. It
# is called by the "pin_assign" method
##################################################
def pin_clear
@pinmap.each { |pin_name, pin| pin.destroy }
@pinmap.clear
@patternpinindex.clear
@patternorder.delete_if { true }
@cycletiming.clear
'P:'
end
end
end
end
|
module OscMacheteRails
# Methods that deal with pbs batch job status management
# within a Rails ActiveRecord model
module Statusable
delegate :not_submitted?, :submitted?, :completed?, :passed?, :failed?, :active?, to: :status
def status=(s)
super(OSC::Machete::Status.new(s).char)
end
# getter returns a Status value from CHAR or a Status value
def status
OSC::Machete::Status.new(super)
end
# delete the batch job and update status
# may raise PBS::Error as it is unhandled here!
def stop(update: true)
return unless status.active?
job.delete
update(status: OSC::Machete::Status.failed) if update
end
def self.included(obj)
# track the classes that include this module
self.classes << Kernel.const_get(obj.name) unless obj.name.nil?
# add class methods
obj.send(:extend, ClassMethods)
# Store job object info in a JSON column and replace old column methods
if obj.respond_to?(:column_names) && obj.column_names.include?('job_cache')
obj.store :job_cache, accessors: [ :script, :pbsid, :host ], coder: JSON
delegate :script_name, to: :job
define_method :job_path do
job.path
end
else
define_method(:job_cache) do
{
script: (job_path && script_name) ? Pathname.new(job_path).join(script_name) : nil,
pbsid: pbsid,
host: nil
}
end
end
end
def self.classes
@classes ||= []
end
# for each Statusable, call update_status! on active jobs
def self.update_status_of_all_active_jobs
Rails.logger.warn "Statusable.classes Array is empty. This should contain a list of all the classes that include Statusable." if self.classes.empty?
self.classes.each do |klass|
klass.active.to_a.each(&:update_status!) if klass.respond_to?(:active)
end
end
# class methods to extend a model with
module ClassMethods
# scope to get all of the jobs that are in an active state
# or have a pbsid
def active
# FIXME: what about OR i.e. where
#
# status in active_values OR (pbsid != null and status == null)
#
# will need to use STRING for the sql instead of this.
where(status: OSC::Machete::Status.active_values.map(&:char))
end
end
# Setter that accepts an OSC::Machete::Job instance
#
# @param [Job] new_job The Job object to be assigned to the Statusable instance.
def job=(new_job)
if self.has_attribute?(:job_cache)
job_cache[:script] = new_job.script_path.to_s
job_cache[:pbsid] = new_job.pbsid
job_cache[:host] = new_job.host if new_job.respond_to?(:host)
else
self.script_name = new_job.script_name
self.job_path = new_job.path.to_s
self.pbsid = new_job.pbsid
end
begin
self.status = new_job.status
rescue PBS::Error => e
# a safe default
self.status = OSC::Machete::Status.queued
# log the error
Rails.logger.error("After submitting the job with pbsid: #{pbsid}," \
" checking the status raised a PBS::Error: #{e.message}")
end
end
# Returns associated OSC::Machete::Job instance
def job
OSC::Machete::Job.new(job_cache.symbolize_keys)
end
# Build the results validation method name from script_name attr
# using ActiveSupport methods
#
# Call this using the Rails console to see what method you should implement
# to support results validation for that job.
#
# @return [String] A string representing a validation method name from script_name attr
# using ActiveSupport methods
def results_validation_method_name
File.basename(script_name, ".*").underscore.parameterize('_') + "_results_valid?"
end
# A hook that can be overidden with custom code
# also looks for default validation methods for existing
# WARNING: THIS USES ActiveSupport::Inflector methods underscore and parameterize
#
# @return [Boolean] true if the results script is present
def results_valid?
valid = true
if self.respond_to? :script_name && !script_name.nil?
if self.respond_to?(results_validation_method_name)
valid = self.send(results_validation_method_name)
end
end
valid
end
#FIXME: should have a unit test for this!
# job.update_status! will update and save object
# if submitted? and ! completed? and status changed from previous state
# force will cause status to update regardless of completion status,
# redoing the validations. This way, if you are fixing validation methods
# you can use the Rails console to update the status of a Workflow by doing this:
#
# Container.last.jobs.each {|j| j.update_status!(force: true) }
#
# Or for a single statusable such as job:
#
# job.update_status!(force: true)
#
# FIXME: should log whether a validation method was called or
# throw a warning that no validation method was found (the one that would have been called)
#
# @param [Boolean, nil] force Force the update. (Default: false)
def update_status!(force: false)
# this will make it easier to differentiate from current_status
cached_status = status
# by default only update if its an active job
if (cached_status.not_submitted? && pbsid) || cached_status.active? || force
# get the current status from the system
current_status = job.status
# if job is done, lets re-validate
if current_status.completed?
current_status = results_valid? ? OSC::Machete::Status.passed : OSC::Machete::Status.failed
end
if (current_status != cached_status) || force
self.status = current_status
self.save
end
end
rescue PBS::Error => e
# we log the error but we just don't update the status
Rails.logger.error("During update_status! call on job with pbsid #{pbsid} and id #{id}" \
" a PBS::Error was thrown: #{e.message}")
end
end
end
clarify issues with not eager loading classes
add comment and extend warning message for Statusable class list being
empty which can occur on the first request after an app is reloaded in
development when eager loading is turned off
module OscMacheteRails
# Methods that deal with pbs batch job status management
# within a Rails ActiveRecord model
module Statusable
delegate :not_submitted?, :submitted?, :completed?, :passed?, :failed?, :active?, to: :status
def status=(s)
super(OSC::Machete::Status.new(s).char)
end
# getter returns a Status value from CHAR or a Status value
def status
OSC::Machete::Status.new(super)
end
# delete the batch job and update status
# may raise PBS::Error as it is unhandled here!
def stop(update: true)
return unless status.active?
job.delete
update(status: OSC::Machete::Status.failed) if update
end
def self.included(obj)
# track the classes that include this module
self.classes << Kernel.const_get(obj.name) unless obj.name.nil?
# add class methods
obj.send(:extend, ClassMethods)
# Store job object info in a JSON column and replace old column methods
if obj.respond_to?(:column_names) && obj.column_names.include?('job_cache')
obj.store :job_cache, accessors: [ :script, :pbsid, :host ], coder: JSON
delegate :script_name, to: :job
define_method :job_path do
job.path
end
else
define_method(:job_cache) do
{
script: (job_path && script_name) ? Pathname.new(job_path).join(script_name) : nil,
pbsid: pbsid,
host: nil
}
end
end
end
def self.classes
@classes ||= []
end
# for each Statusable, call update_status! on active jobs
def self.update_status_of_all_active_jobs
# to eager load classes, set config.eager_load to true or execute Rails.application.eager_load!
Rails.logger.warn "Statusable.classes Array is empty. This should contain a list of all the classes that include Statusable. " \
"This could occur if the Rails app is not configured to eager load classes." if self.classes.empty?
self.classes.each do |klass|
klass.active.to_a.each(&:update_status!) if klass.respond_to?(:active)
end
end
# class methods to extend a model with
module ClassMethods
# scope to get all of the jobs that are in an active state
# or have a pbsid
def active
# FIXME: what about OR i.e. where
#
# status in active_values OR (pbsid != null and status == null)
#
# will need to use STRING for the sql instead of this.
where(status: OSC::Machete::Status.active_values.map(&:char))
end
end
# Setter that accepts an OSC::Machete::Job instance
#
# @param [Job] new_job The Job object to be assigned to the Statusable instance.
def job=(new_job)
if self.has_attribute?(:job_cache)
job_cache[:script] = new_job.script_path.to_s
job_cache[:pbsid] = new_job.pbsid
job_cache[:host] = new_job.host if new_job.respond_to?(:host)
else
self.script_name = new_job.script_name
self.job_path = new_job.path.to_s
self.pbsid = new_job.pbsid
end
begin
self.status = new_job.status
rescue PBS::Error => e
# a safe default
self.status = OSC::Machete::Status.queued
# log the error
Rails.logger.error("After submitting the job with pbsid: #{pbsid}," \
" checking the status raised a PBS::Error: #{e.message}")
end
end
# Returns associated OSC::Machete::Job instance
def job
OSC::Machete::Job.new(job_cache.symbolize_keys)
end
# Build the results validation method name from script_name attr
# using ActiveSupport methods
#
# Call this using the Rails console to see what method you should implement
# to support results validation for that job.
#
# @return [String] A string representing a validation method name from script_name attr
# using ActiveSupport methods
def results_validation_method_name
File.basename(script_name, ".*").underscore.parameterize('_') + "_results_valid?"
end
# A hook that can be overidden with custom code
# also looks for default validation methods for existing
# WARNING: THIS USES ActiveSupport::Inflector methods underscore and parameterize
#
# @return [Boolean] true if the results script is present
def results_valid?
valid = true
if self.respond_to? :script_name && !script_name.nil?
if self.respond_to?(results_validation_method_name)
valid = self.send(results_validation_method_name)
end
end
valid
end
#FIXME: should have a unit test for this!
# job.update_status! will update and save object
# if submitted? and ! completed? and status changed from previous state
# force will cause status to update regardless of completion status,
# redoing the validations. This way, if you are fixing validation methods
# you can use the Rails console to update the status of a Workflow by doing this:
#
# Container.last.jobs.each {|j| j.update_status!(force: true) }
#
# Or for a single statusable such as job:
#
# job.update_status!(force: true)
#
# FIXME: should log whether a validation method was called or
# throw a warning that no validation method was found (the one that would have been called)
#
# @param [Boolean, nil] force Force the update. (Default: false)
def update_status!(force: false)
# this will make it easier to differentiate from current_status
cached_status = status
# by default only update if its an active job
if (cached_status.not_submitted? && pbsid) || cached_status.active? || force
# get the current status from the system
current_status = job.status
# if job is done, lets re-validate
if current_status.completed?
current_status = results_valid? ? OSC::Machete::Status.passed : OSC::Machete::Status.failed
end
if (current_status != cached_status) || force
self.status = current_status
self.save
end
end
rescue PBS::Error => e
# we log the error but we just don't update the status
Rails.logger.error("During update_status! call on job with pbsid #{pbsid} and id #{id}" \
" a PBS::Error was thrown: #{e.message}")
end
end
end
|
module Paperclip
module Storage
# The default place to store attachments is in the filesystem. Files on the local
# filesystem can be very easily served by Apache without requiring a hit to your app.
# They also can be processed more easily after they've been saved, as they're just
# normal files. There is one Filesystem-specific option for has_attached_file.
# * +path+: The location of the repository of attachments on disk. This can (and, in
# almost all cases, should) be coordinated with the value of the +url+ option to
# allow files to be saved into a place where Apache can serve them without
# hitting your app. Defaults to
# ":rails_root/public/:attachment/:id/:style/:basename.:extension"
# By default this places the files in the app's public directory which can be served
# directly. If you are using capistrano for deployment, a good idea would be to
# make a symlink to the capistrano-created system directory from inside your app's
# public directory.
# See Paperclip::Attachment#interpolate for more information on variable interpolaton.
# :path => "/var/app/attachments/:class/:id/:style/:basename.:extension"
module Filesystem
def self.extended base
end
def exists?(style_name = default_style)
if original_filename
File.exist?(path(style_name))
else
false
end
end
def flush_writes #:nodoc:
@queued_for_write.each do |style_name, file|
FileUtils.mkdir_p(File.dirname(path(style_name)))
File.open(path(style_name), "wb") do |new_file|
while chunk = file.read(16 * 1024)
new_file.write(chunk)
end
end
unless @options[:override_file_permissions] == false
resolved_chmod = (@options[:override_file_permissions]&~0111) || (0666&~File.umask)
FileUtils.chmod( resolved_chmod, path(style_name) )
end
file.rewind
end
after_flush_writes # allows attachment to clean up temp files
@queued_for_write = {}
end
def flush_deletes #:nodoc:
@queued_for_delete.each do |path|
begin
log("deleting #{path}")
FileUtils.rm(path) if File.exist?(path)
rescue Errno::ENOENT => e
# ignore file-not-found, let everything else pass
end
begin
while(true)
path = File.dirname(path)
FileUtils.rmdir(path)
break if File.exists?(path) # Ruby 1.9.2 does not raise if the removal failed.
end
rescue Errno::EEXIST, Errno::ENOTEMPTY, Errno::ENOENT, Errno::EINVAL, Errno::ENOTDIR, Errno::EACCES
# Stop trying to remove parent directories
rescue SystemCallError => e
log("There was an unexpected error while deleting directories: #{e.class}")
# Ignore it
end
end
@queued_for_delete = []
end
def copy_to_local_file(style, local_dest_path)
FileUtils.cp(path(style), local_dest_path)
end
end
end
end
Documentation for new :override_file_permissions option
module Paperclip
module Storage
# The default place to store attachments is in the filesystem. Files on the local
# filesystem can be very easily served by Apache without requiring a hit to your app.
# They also can be processed more easily after they've been saved, as they're just
# normal files. There are two Filesystem-specific options for has_attached_file:
# * +path+: The location of the repository of attachments on disk. This can (and, in
# almost all cases, should) be coordinated with the value of the +url+ option to
# allow files to be saved into a place where Apache can serve them without
# hitting your app. Defaults to
# ":rails_root/public/:attachment/:id/:style/:basename.:extension"
# By default this places the files in the app's public directory which can be served
# directly. If you are using capistrano for deployment, a good idea would be to
# make a symlink to the capistrano-created system directory from inside your app's
# public directory.
# See Paperclip::Attachment#interpolate for more information on variable interpolaton.
# :path => "/var/app/attachments/:class/:id/:style/:basename.:extension"
# * +override_file_permissions+: This allows you to override the file permissions for files
# saved by paperclip. If you set this to an explicit octal value (0755, 0644, etc) then
# that value will be used to set the permissions for an uploaded file. The default is 0666.
# If you set :override_file_permissions to false, the chmod will be skipped. This allows
# you to use paperclip on filesystems that don't understand unix file permissions, and has the
# added benefit of using the storage directories default umask on those that do.
module Filesystem
def self.extended base
end
def exists?(style_name = default_style)
if original_filename
File.exist?(path(style_name))
else
false
end
end
def flush_writes #:nodoc:
@queued_for_write.each do |style_name, file|
FileUtils.mkdir_p(File.dirname(path(style_name)))
File.open(path(style_name), "wb") do |new_file|
while chunk = file.read(16 * 1024)
new_file.write(chunk)
end
end
unless @options[:override_file_permissions] == false
resolved_chmod = (@options[:override_file_permissions] &~ 0111) || (0666 &~ File.umask)
FileUtils.chmod( resolved_chmod, path(style_name) )
end
file.rewind
end
after_flush_writes # allows attachment to clean up temp files
@queued_for_write = {}
end
def flush_deletes #:nodoc:
@queued_for_delete.each do |path|
begin
log("deleting #{path}")
FileUtils.rm(path) if File.exist?(path)
rescue Errno::ENOENT => e
# ignore file-not-found, let everything else pass
end
begin
while(true)
path = File.dirname(path)
FileUtils.rmdir(path)
break if File.exists?(path) # Ruby 1.9.2 does not raise if the removal failed.
end
rescue Errno::EEXIST, Errno::ENOTEMPTY, Errno::ENOENT, Errno::EINVAL, Errno::ENOTDIR, Errno::EACCES
# Stop trying to remove parent directories
rescue SystemCallError => e
log("There was an unexpected error while deleting directories: #{e.class}")
# Ignore it
end
end
@queued_for_delete = []
end
def copy_to_local_file(style, local_dest_path)
FileUtils.cp(path(style), local_dest_path)
end
end
end
end
|
Pod::Spec.new do |s|
s.name = 'Countly'
s.version = '2.0.0'
s.license = {
:type => 'COMMUNITY',
:text => <<-LICENSE
COUNTLY MOBILE ANALYTICS COMMUNITY EDITION LICENSE
--------------------------------------------------
Copyright (c) 2012, 2014 Countly
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.
LICENSE
}
s.summary = 'Countly is an innovative, real-time, open source mobile analytics platform.'
s.homepage = 'https://github.com/Countly/countly-sdk-ios'
s.author = {'Countly' => 'hello@count.ly'}
s.source = { :git => 'https://github.com/Countly/countly-sdk-ios.git', :tag => s.version.to_s }
s.source_files = '*.{h,m}'
s.resources = '*.{xcdatamodeld}'
s.requires_arc = false
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.8'
s.ios.weak_framework = 'CoreTelephony', 'CoreData'
end
Updated Countly.podspec for 3.0.0
Pod::Spec.new do |s|
s.name = 'Countly'
s.version = '3.0.0'
s.license = {
:type => 'COMMUNITY',
:text => <<-LICENSE
COUNTLY MOBILE ANALYTICS COMMUNITY EDITION LICENSE
--------------------------------------------------
Copyright (c) 2012, 2015 Countly
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.
LICENSE
}
s.summary = 'Countly is an innovative, real-time, open source mobile analytics platform.'
s.homepage = 'https://github.com/Countly/countly-sdk-ios'
s.author = {'Countly' => 'hello@count.ly'}
s.source = { :git => 'https://github.com/Countly/countly-sdk-ios.git', :tag => s.version.to_s }
s.source_files = '*.{h,m}'
s.resources = '*.{xcdatamodeld}'
s.requires_arc = true
s.ios.deployment_target = '5.0'
s.osx.deployment_target = '10.8'
s.ios.weak_framework = 'CoreTelephony', 'CoreData'
end
|
# TO RUN THIS:
# $ rspec calculator_spec.rb
# YOU MAY NEED TO:
# $ gem install rspec # (and get v 2.14 or higher)
require_relative 'calculator'
describe Calculator do
let(:calculator) { Calculator.new }
describe "addition" do
it "puts two and two together" do
expect( calculator.add(2, 2) ).to eq(4)
end
it "puts two and two and two together" do
expect( calculator.add(2, 2, 2) ).to eq(6)
end
end
describe "subtraction" do
it "takes one from two" do
expect( calculator.subtract(2, 1) ).to eq(1)
end
it "subtracts all subsequent arguments from the first one" do
expect( calculator.subtract(13, 8, 5, 3, 2, 1, 1) ).to eq(-7)
end
end
describe "multiplication" do
it "multiplies six by nine (but does not get forty-two)" do
expect( calculator.multiply(6, 9) ).to eq(54)
end
it "does factorials the long way" do
expect( calculator.multiply(1, 2, 3, 4, 5, 6) ).to eq(720)
end
end
describe "division" do
it "halves" do
expect( calculator.divide(4, 2) ).to eq(2)
end
it "subdivides" do
expect( calculator.divide(128, 2, 2, 2) ).to eq(16)
end
end
# IF YOU'RE BORED...
describe "parsing for fun and profit", pending: true do
it "does simple addition" do
expect( calculator.evaluate("2+2") ).to eq(4)
end
it "copes well with spaces" do
expect( calculator.evaluate(" 2 + 2") ).to eq(4)
end
it "understands order of operations" do
expect( calculator.evaluate("2+2*5") ).to eq(12)
end
end
end
re-enable the first evaluate spec
# TO RUN THIS:
# $ rspec calculator_spec.rb
# YOU MAY NEED TO:
# $ gem install rspec # (and get v 2.14 or higher)
require_relative 'calculator'
describe Calculator do
let(:calculator) { Calculator.new }
describe "addition" do
it "puts two and two together" do
expect( calculator.add(2, 2) ).to eq(4)
end
it "puts two and two and two together" do
expect( calculator.add(2, 2, 2) ).to eq(6)
end
end
describe "subtraction" do
it "takes one from two" do
expect( calculator.subtract(2, 1) ).to eq(1)
end
it "subtracts all subsequent arguments from the first one" do
expect( calculator.subtract(13, 8, 5, 3, 2, 1, 1) ).to eq(-7)
end
end
describe "multiplication" do
it "multiplies six by nine (but does not get forty-two)" do
expect( calculator.multiply(6, 9) ).to eq(54)
end
it "does factorials the long way" do
expect( calculator.multiply(1, 2, 3, 4, 5, 6) ).to eq(720)
end
end
describe "division" do
it "halves" do
expect( calculator.divide(4, 2) ).to eq(2)
end
it "subdivides" do
expect( calculator.divide(128, 2, 2, 2) ).to eq(16)
end
end
# IF YOU'RE BORED...
describe "parsing for fun and profit" do
it "does simple addition" do
expect( calculator.evaluate("2+2") ).to eq(4)
end
xit "copes well with spaces" do
expect( calculator.evaluate(" 2 + 2") ).to eq(4)
end
xit "understands order of operations" do
expect( calculator.evaluate("2+2*5") ).to eq(12)
end
end
end
|
require '/Users/Albert/Repos/Scripts/ruby/lib/utilities.rb'
require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo.rb'
require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-maker.rb'
require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-rewriter.rb'
class NimzoCreateRemove
LIB = 'lib'
CREATE = 'create'
REMOVE = 'remove'
SCRIPT = 'script'
# The point of entry!
# @param route
# @param type
# @param action
def initialize(type, route, action, helper = nil)
@type = type.downcase
@route = route.sub(/^[\/]*/, '').sub(/(\/)+$/, '').squeeze('/')
@action = action.downcase
@helper = helper
@errors = false
@output = Array.new
@pathToRepo = $PATH_TO_REPO
@pathToPhp = "#{@pathToRepo}/httpdocs/private/#{@type}/"
@pathToDev = "#{@pathToRepo}/httpdocs/public/dev/#{@type}/"
@pathToMin = "#{@pathToRepo}/httpdocs/public/min/#{@type}/"
@pathToTest = "#{@pathToRepo}/tests-php/private/#{@type}/"
@paths = Array.new
@files = Array.new
self.validateParameters
if @type == LIB || @type == SCRIPT
self.createLibScript
else
if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type)
self.createHelper
else
self.createRoute
end
end
end
# Validate the input parameters
def validateParameters
# Make sure the particular controller type is valid.
# This error cannot be reached through incorrect user input.
unless inArray(%w(page pagehelper lib script modal modalhelper overlay overlayhelper system systemhelper widget widgethelper), @type)
self.error("\x1B[33m#{@type}\x1B[0m is not a valid type. There is an error in your bash script, not your input.")
end
# Make sure the particular action is valid.
# This error cannot be reached through incorrect user input.
unless inArray([CREATE, REMOVE], @action)
self.error("\x1B[33m#{@action}\x1B[0m is not a valid action. There is an error in your bash script, not your input.")
end
if @type == LIB || @type == SCRIPT
# Make sure the route consists of a parent directory and a classname
unless @route.include?('/')
self.error("You must specify a \x1B[33mfolder\x1B[0m and a \x1B[33mclassname\x1B[0m (IE: core/AjaxRequest)")
end
# Right now I'm only allowing the creation of scripts 1 folder deep.
# Although the PHP supports infinite folders, I want to keep it from getting too confusing.
#
# If more than 1 slash is present, this cuts it down to only 1. Everything after the 2nd will be ommited.
# Also capitalizes the 2nd part & removes file extension (if exists)
routeSplit = @route.split('/')
className = File.basename(routeSplit[1], File.extname(routeSplit[1]))
className[0] = className.upcase[0..0]
@route = "#{routeSplit[0].downcase}/#{className}"
# Make sure folder doesn't start with following values. These will just create confusion.
if inArray(%w(bin lib script scripts), routeSplit[0], true) &&
self.error("Namespace/preceeding folder shouldn't be \x1B[33m#{routeSplit[0]}\x1B[0m due to possible confusion.")
end
# Make sure that ALL characters within the route are AlphaNumeric.
unless isAlphaNumeric(@route.gsub('/', ''))
self.error("\x1B[33mFolder\x1B[0m and a \x1B[33mclassname\x1B[0m must be alphanumeric and seperated by a slash ('/'). You passed: \x1B[33m#{@route}\x1B[0m")
end
else
# Make sure route doesn't start with API or AJAX
routeSplit = @route.split('/')
if inArray(%w(api ajax script), routeSplit[0], true) &&
self.error("Request route cannot start with \x1B[33m#{routeSplit[0]}\x1B[0m as these are parameters the system uses.")
end
# Make sure that ALL characters within the route are AlphaNumeric.
unless isAlphaNumeric(@route.gsub('/', ''))
self.error("Route parameters must be alphanumeric and seperated by slashes ('/'). You passed: \x1B[33m#{@route}\x1B[0m")
end
# Make sure that the FIRST character of ANY route parameter is a letter, not a number.
@route.split('/').each { |routeParameter|
if (routeParameter[0, 1] =~ /[A-Za-z]/) != 0
self.error("Route parameters cannot start with a digit (IE: 0-9). You passed: \x1B[33m#{@route}\x1B[0m")
end
}
# Make sure the helper parameter is correct (if this is a 'helper' run)
if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type)
# Make sure @helper is not nil
if @helper.nil? || @helper == ''
self.error('@helper variable is nil or not set.')
end
@helper = File.basename(@helper, File.extname(@helper))
@helper[0] = @helper.upcase[0..0]
# Make sure helper is alphanumeric.
# Make sure that ALL characters within the route are AlphaNumeric.
unless isAlphaNumeric(@helper)
self.error("Helper name must be alphanumeric. You passed: \x1B[33m#{@helper}\x1B[0m")
end
end
end
end
# Creates a helper class.
def createHelper
case @type
when 'pagehelper'
@type = 'page'
when 'modalhelper'
@type = 'modal'
when 'overlayhelper'
@type = 'overlay'
when 'systemhelper'
@type = 'system'
when 'widgethelper'
@type = 'widget'
else
self.error('Type not supported.')
end
helperPath = "#{$PATH_TO_PHP}#{@type}/helpers/#{@route}/"
helperPathTest = "#{$PATH_TO_TESTS}#{@type}/helpers/#{@route}/"
helperFile = "#{helperPath}#{@helper}.php"
helperFileTest = "#{helperPathTest}#{@helper}Test.php"
if @action == CREATE
# Check that the helper paths even exist.
unless File.directory?(helperPath)
self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m")
end
unless File.directory?(helperPathTest)
self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m")
end
# Now check that the helper files DON'T exist.
if File.file?(helperFile)
self.error("The file \x1B[33m#{helperFile}\x1B[0m already exists.")
end
if File.file?(helperFileTest)
self.error("The file \x1B[33m#{helperFileTest}\x1B[0m already exists.")
end
@files.push(helperFile)
@files.push(helperFileTest)
@output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n")
@output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
@output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n")
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
puts
NimzoFileMaker.new(@type, @paths, @files, ' ')
puts
elsif @action == REMOVE
# @todo FINISH THIS!
puts 'REMOVE code goes here!'
exit
end
self.runUnitTests
end
# Creates a class within the /lib directory + also creates the UNIT Test boiler plate.
def createLibScript
routeSplit = @route.split('/')
if @type == LIB
filename = "#{$PATH_TO_PHP}lib/#{routeSplit[0]}/#{routeSplit[1]}.php"
filenameTest = "#{$PATH_TO_TESTS}lib/#{routeSplit[0]}/#{routeSplit[1]}Test.php"
elsif @type == SCRIPT
filename = "#{$PATH_TO_PHP}script/#{routeSplit[0]}/#{routeSplit[1]}.php"
filenameTest = "#{$PATH_TO_TESTS}script/#{routeSplit[0]}/#{routeSplit[1]}Test.php"
else
self.error('Type is not supported.')
end
if @action == CREATE
# Make sure the files don't already exist.
# The last thing we want to do is overwrite files.
if File.file?(filename)
self.error("File already exists: \x1B[33m#{filename}\x1B[0m")
exit
elsif File.file?(filenameTest)
self.error("File already exists: \x1B[33m#{filenameTest}\x1B[0m")
exit
end
@files.push(filename)
@files.push(filenameTest)
@output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n")
@output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
@output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n")
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
puts
NimzoFileMaker.new(@type, @paths, @files, ' ')
puts
elsif @action == REMOVE
# @todo FINISH THIS!
puts 'REMOVE code goes here!'
exit
end
self.runUnitTests
end
# IF CREATE: Scans the route and creates all the files (that don't exist yet) along the way.
# Has ability to create nested paths (IE: if only '/dashboard' exists you can still create '/dashboard/messages/new').
# IF REMOVE: Scans ONLY the last directory in the route and removes all the files recursively (if they exist).
def createRoute
baseDirs = Array[
"#{@pathToPhp}helpers/",
"#{@pathToTest}helpers/",
"#{@pathToTest}controllers/",
"#{@pathToPhp}controllers/",
"#{@pathToPhp}views/",
"#{@pathToDev}",
"#{@pathToMin}"
]
routeCount = 0
subDir = ''
subDirs = Array.new
filename = ''
@route.split('/').each { |routeParameter|
routeCount = routeCount + 1
subDir = "#{subDir}#{routeParameter}/"
filename = "#{filename}#{routeParameter.slice(0, 1).capitalize + routeParameter.slice(1..-1)}"
# If this is a 'remove' run, only spring to life once we're on the last loop (if that makes sense).
# We don't want to be deleting recursively..
if @action == REMOVE && routeCount < @route.split('/').size
next
end
pseudoOutput = Array.new
pseudoPaths = Array.new
pseudoFiles = Array.new
baseDirs.each { |dir|
dir = "#{dir}#{subDir}"
# If deleting, this checks if there are any FURTHER files/directories deeper in the 'route'.
# If so, adds them to an Array for later checking.
if @action == REMOVE
subFilesFound = Dir.glob("#{dir}**/*")
unless subFilesFound.empty?
subDirs.concat(subFilesFound)
end
end
if dir == "#{@pathToPhp}helpers/#{subDir}" || dir == "#{@pathToTest}helpers/#{subDir}"
if (@action == CREATE && !File.directory?(dir)) || (@action == REMOVE && File.directory?(dir))
pseudoOutput.push(" \x1B[32m#{dir.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
pseudoPaths.push(dir)
end
else
files = Array.new
case dir
when "#{@pathToPhp}controllers/#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.php")
when "#{@pathToPhp}views/#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.phtml")
when "#{@pathToDev}#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.less")
files.push("#{dir}#{@type.capitalize}_#{filename}.js")
when "#{@pathToMin}#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.min.js")
when "#{@pathToTest}controllers/#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}Test.php")
else
self.error('Path not found.')
end
files.each { |file|
if (@action == CREATE && !File.file?(file)) || ((@action == REMOVE && File.file?(file)) || (@action == REMOVE && File.directory?(File.dirname(file))))
pseudoFiles.push(file)
pseudoPaths.push(File.dirname(file))
fileCount = 0
fileDisplay = ''
file.split('/').each { |filePart|
fileCount = fileCount + 1
if fileCount < file.split('/').length
fileDisplay = "#{fileDisplay}/#{filePart}"
else
fileDisplay = "#{fileDisplay}/\x1B[36m#{filePart}\x1B[0m"
end
}
# Remove preceeding slash (/) as a result of above loop..
fileDisplay[0] = ''
pseudoOutput.push(" \x1B[33m#{fileDisplay.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
end
}
end
}
pseudoPaths.uniq
pseudoFiles.uniq
unless pseudoPaths.empty?
@paths.concat(pseudoPaths)
end
unless pseudoFiles.empty?
@files.concat(pseudoFiles)
end
unless pseudoPaths.empty? && pseudoFiles.empty?
pseudoOutput.unshift(" \x1B[90m#{@type.upcase}\x1B[0m => \x1B[35m#{subDir[0..-2]}\x1B[0m")
pseudoOutput.push('')
@output.concat(pseudoOutput)
end
}
if @paths.empty? && @files.empty?
if @action == CREATE
self.error("The route: \x1B[35m#{@route}\x1B[0m already exists..")
elsif @action == REMOVE
self.error("The route: \x1B[35m#{@route}\x1B[0m doesn't exist..")
end
else
if @action == CREATE
@output.unshift("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n")
elsif @action == REMOVE
@output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n")
end
end
# If we're deleting stuff, check if there are subPaths (past the point we're deleting from).
if @action == REMOVE && !subDirs.empty?
subFiles = Array.new
subPaths = Array.new
pseudoOutput = Array.new
subDirs.each { |subFile|
if File.directory?(subFile)
unless inArray(@paths, subFile)
subPaths.push(subFile)
end
elsif File.file?(subFile)
unless inArray(@files, subFile)
subFiles.push(subFile)
end
end
}
unless subPaths.empty? && subFiles.empty?
subPaths.each { |path| pseudoOutput.push(" \x1B[90m#{path.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") }
subFiles.each { |file| pseudoOutput.push(" \x1B[0m#{file.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") }
@paths.concat(subPaths)
@files.concat(subFiles)
@output.push("\x1B[41m NOTICE \x1B[0m\x1B[90m The following files/directories will also be removed:\n")
@output.concat(pseudoOutput)
@output.push('')
end
end
self.processRoute
end
# The final function which does all the processing. If errors are present, no processing will be done.
def processRoute
if @action == CREATE
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
puts
NimzoFileMaker.new(@type, @paths, @files, ' ')
puts
unless @files.empty? && @paths.empty?
NimzoRewriter.new(@type)
end
elsif @action == REMOVE
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
unless @files.empty?
@files.each { |file|
@output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m")
# Remove file from Git.
system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1")
FileUtils.rm_rf(file)
FileUtils.rm_rf(File.dirname(file))
}
end
unless @paths.empty?
@paths.each { |path|
@output.push("\x1B[31mRemoved: #{path.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m")
FileUtils.rm_rf(path)
}
end
@output.push('')
self.flushBuffer
unless @files.empty? && @paths.empty?
NimzoRewriter.new(@type)
end
end
self.runUnitTests
end
# Run (system) unit tests.
def runUnitTests
puts "\x1B[45m SYSTEM \x1B[0m Initializing tests...\n\n"
system('phpunit --bootstrap /Users/Albert/Repos/Nimzo/tests-php/bin/PHPUnit_Bootstrap.php --no-configuration --colors --group System /Users/Albert/Repos/Nimzo/tests-php')
end
# Aborts the script.
def abandonShip(abortTxt = " \x1B[90mScript aborted.\x1B[0m")
unless abortTxt.nil?
puts abortTxt
end
puts
exit
end
# Confirmation message. Returns and continues script on 'y' or 'Y'.. exits on anythng else.
def confirm(confirmTxt = "\x1B[90mContinue? [y/n]\x1B[0m => ?", abortTxt = nil)
STDOUT.flush
print confirmTxt
continue = STDIN.gets.chomp
if continue != 'y' && continue != 'Y'
self.abandonShip(abortTxt)
end
end
# If an error occurs, it's added to the @OUTPUT array and if 'exit' flag set to TRUE,
# the script goes straight to run & subsequently displays output & dies.
# @param text
def error(text = '')
@output.push("\x1B[41m ERROR \x1B[0m #{text}")
self.flushBuffer(true)
end
# Flushes the output buffer.
def flushBuffer(exit = false)
unless @output.empty?
puts
@output.each { |message| puts "#{message}\x1B[0m" }
if exit
self.abandonShip
end
@output = Array.new
end
end
# Log something to the output buffer.
def output(text = '')
@output.push(text)
end
end
NimzoCreateRemove.new(ARGV[0], ARGV[1], ARGV[2], ARGV[3])
Now able to delete 'helper' classes successfully. Also removes from git + runs unit tests straight after as a sanity check. All working flawlessly!
require '/Users/Albert/Repos/Scripts/ruby/lib/utilities.rb'
require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo.rb'
require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-maker.rb'
require '/Users/Albert/Repos/Scripts/ruby/nimzo/nimzo-file-rewriter.rb'
class NimzoCreateRemove
LIB = 'lib'
CREATE = 'create'
REMOVE = 'remove'
SCRIPT = 'script'
# The point of entry!
# @param route
# @param type
# @param action
def initialize(type, route, action, helper = nil)
@type = type.downcase
@route = route.sub(/^[\/]*/, '').sub(/(\/)+$/, '').squeeze('/')
@action = action.downcase
@helper = helper
@errors = false
@output = Array.new
@pathToRepo = $PATH_TO_REPO
@pathToPhp = "#{@pathToRepo}/httpdocs/private/#{@type}/"
@pathToDev = "#{@pathToRepo}/httpdocs/public/dev/#{@type}/"
@pathToMin = "#{@pathToRepo}/httpdocs/public/min/#{@type}/"
@pathToTest = "#{@pathToRepo}/tests-php/private/#{@type}/"
@paths = Array.new
@files = Array.new
self.validateParameters
if @type == LIB || @type == SCRIPT
self.createLibScript
else
if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type)
self.createHelper
else
self.createRoute
end
end
end
# Validate the input parameters
def validateParameters
# Make sure the particular controller type is valid.
# This error cannot be reached through incorrect user input.
unless inArray(%w(page pagehelper lib script modal modalhelper overlay overlayhelper system systemhelper widget widgethelper), @type)
self.error("\x1B[33m#{@type}\x1B[0m is not a valid type. There is an error in your bash script, not your input.")
end
# Make sure the particular action is valid.
# This error cannot be reached through incorrect user input.
unless inArray([CREATE, REMOVE], @action)
self.error("\x1B[33m#{@action}\x1B[0m is not a valid action. There is an error in your bash script, not your input.")
end
if @type == LIB || @type == SCRIPT
# Make sure the route consists of a parent directory and a classname
unless @route.include?('/')
self.error("You must specify a \x1B[33mfolder\x1B[0m and a \x1B[33mclassname\x1B[0m (IE: core/AjaxRequest)")
end
# Right now I'm only allowing the creation of scripts 1 folder deep.
# Although the PHP supports infinite folders, I want to keep it from getting too confusing.
#
# If more than 1 slash is present, this cuts it down to only 1. Everything after the 2nd will be ommited.
# Also capitalizes the 2nd part & removes file extension (if exists)
routeSplit = @route.split('/')
className = File.basename(routeSplit[1], File.extname(routeSplit[1]))
className[0] = className.upcase[0..0]
@route = "#{routeSplit[0].downcase}/#{className}"
# Make sure folder doesn't start with following values. These will just create confusion.
if inArray(%w(bin lib script scripts), routeSplit[0], true) &&
self.error("Namespace/preceeding folder shouldn't be \x1B[33m#{routeSplit[0]}\x1B[0m due to possible confusion.")
end
# Make sure that ALL characters within the route are AlphaNumeric.
unless isAlphaNumeric(@route.gsub('/', ''))
self.error("\x1B[33mFolder\x1B[0m and a \x1B[33mclassname\x1B[0m must be alphanumeric and seperated by a slash ('/'). You passed: \x1B[33m#{@route}\x1B[0m")
end
else
# Make sure route doesn't start with API or AJAX
routeSplit = @route.split('/')
if inArray(%w(api ajax script), routeSplit[0], true) &&
self.error("Request route cannot start with \x1B[33m#{routeSplit[0]}\x1B[0m as these are parameters the system uses.")
end
# Make sure that ALL characters within the route are AlphaNumeric.
unless isAlphaNumeric(@route.gsub('/', ''))
self.error("Route parameters must be alphanumeric and seperated by slashes ('/'). You passed: \x1B[33m#{@route}\x1B[0m")
end
# Make sure that the FIRST character of ANY route parameter is a letter, not a number.
@route.split('/').each { |routeParameter|
if (routeParameter[0, 1] =~ /[A-Za-z]/) != 0
self.error("Route parameters cannot start with a digit (IE: 0-9). You passed: \x1B[33m#{@route}\x1B[0m")
end
}
# Make sure the helper parameter is correct (if this is a 'helper' run)
if inArray(%w(pagehelper modalhelper overlayhelper systemhelper widgethelper), @type)
# Make sure @helper is not nil
if @helper.nil? || @helper == ''
self.error('@helper variable is nil or not set.')
end
@helper = File.basename(@helper, File.extname(@helper))
@helper[0] = @helper.upcase[0..0]
# Make sure helper is alphanumeric.
# Make sure that ALL characters within the route are AlphaNumeric.
unless isAlphaNumeric(@helper)
self.error("Helper name must be alphanumeric. You passed: \x1B[33m#{@helper}\x1B[0m")
end
end
end
end
# Creates a helper class.
def createHelper
case @type
when 'pagehelper'
@type = 'page'
when 'modalhelper'
@type = 'modal'
when 'overlayhelper'
@type = 'overlay'
when 'systemhelper'
@type = 'system'
when 'widgethelper'
@type = 'widget'
else
self.error('Type not supported.')
end
helperPath = "#{$PATH_TO_PHP}#{@type}/helpers/#{@route}/"
helperPathTest = "#{$PATH_TO_TESTS}#{@type}/helpers/#{@route}/"
helperFile = "#{helperPath}#{@helper}.php"
helperFileTest = "#{helperPathTest}#{@helper}Test.php"
if @action == CREATE
# Check that the helper paths even exist.
unless File.directory?(helperPath)
self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m")
end
unless File.directory?(helperPathTest)
self.error("The route \x1B[35m#{@route}\x1B[0m doesn't exist for content type: \x1B[44m #{@type.capitalize} \x1B[0m")
end
# Now check that the helper files DON'T exist.
if File.file?(helperFile)
self.error("The file \x1B[33m#{helperFile}\x1B[0m already exists.")
end
if File.file?(helperFileTest)
self.error("The file \x1B[33m#{helperFileTest}\x1B[0m already exists.")
end
@files.push(helperFile)
@files.push(helperFileTest)
@output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n")
@output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
@output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n")
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
puts
NimzoFileMaker.new(@type, @paths, @files, ' ')
puts
elsif @action == REMOVE
filesToDelete = Array.new
# Check that the helper files we're trying to delete exist.
if File.file?(helperFile)
filesToDelete.push(helperFile)
@output.push(" \x1B[33m#{helperFile.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
end
if File.file?(helperFileTest)
filesToDelete.push(helperFileTest)
@output.push(" \x1B[33m#{helperFileTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
end
# If helper files don't exist, abandon ship!
if filesToDelete.empty?
self.error("The helper \x1B[35m#{@helper}\x1B[0m doesn't exist for \x1B[44m #{@type.capitalize} \x1B[0m \x1B[35m#{@route}\x1B[0m")
end
@output.push('')
@output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n")
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
unless filesToDelete.empty?
filesToDelete.each { |file|
@output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m")
# Remove file from Git.
system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1")
FileUtils.rm_rf(file)
# When deleting the last file in a direcotry, Ruby for some stupid reason deletes
# the parent directory as well. This in turn crashed the unit tests so instead of trying to
# figure this out, I'm just going to check & re-create the directory if it's been wiped. Easy peasy.
dir = File.dirname(file)
unless File.directory?(dir)
FileUtils::mkdir_p(dir)
end
}
end
@output.push('')
self.flushBuffer
end
self.runUnitTests
end
# Creates a class within the /lib directory + also creates the UNIT Test boiler plate.
def createLibScript
routeSplit = @route.split('/')
if @type == LIB
filename = "#{$PATH_TO_PHP}lib/#{routeSplit[0]}/#{routeSplit[1]}.php"
filenameTest = "#{$PATH_TO_TESTS}lib/#{routeSplit[0]}/#{routeSplit[1]}Test.php"
elsif @type == SCRIPT
filename = "#{$PATH_TO_PHP}script/#{routeSplit[0]}/#{routeSplit[1]}.php"
filenameTest = "#{$PATH_TO_TESTS}script/#{routeSplit[0]}/#{routeSplit[1]}Test.php"
else
self.error('Type is not supported.')
end
if @action == CREATE
# Make sure the files don't already exist.
# The last thing we want to do is overwrite files.
if File.file?(filename)
self.error("File already exists: \x1B[33m#{filename}\x1B[0m")
exit
elsif File.file?(filenameTest)
self.error("File already exists: \x1B[33m#{filenameTest}\x1B[0m")
exit
end
@files.push(filename)
@files.push(filenameTest)
@output.push("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n")
@output.push(" \x1B[33m#{filename.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
@output.push(" \x1B[33m#{filenameTest.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m\n")
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
puts
NimzoFileMaker.new(@type, @paths, @files, ' ')
puts
elsif @action == REMOVE
# @todo FINISH THIS!
puts 'REMOVE code goes here!'
exit
end
self.runUnitTests
end
# IF CREATE: Scans the route and creates all the files (that don't exist yet) along the way.
# Has ability to create nested paths (IE: if only '/dashboard' exists you can still create '/dashboard/messages/new').
# IF REMOVE: Scans ONLY the last directory in the route and removes all the files recursively (if they exist).
def createRoute
baseDirs = Array[
"#{@pathToPhp}helpers/",
"#{@pathToTest}helpers/",
"#{@pathToTest}controllers/",
"#{@pathToPhp}controllers/",
"#{@pathToPhp}views/",
"#{@pathToDev}",
"#{@pathToMin}"
]
routeCount = 0
subDir = ''
subDirs = Array.new
filename = ''
@route.split('/').each { |routeParameter|
routeCount = routeCount + 1
subDir = "#{subDir}#{routeParameter}/"
filename = "#{filename}#{routeParameter.slice(0, 1).capitalize + routeParameter.slice(1..-1)}"
# If this is a 'remove' run, only spring to life once we're on the last loop (if that makes sense).
# We don't want to be deleting recursively..
if @action == REMOVE && routeCount < @route.split('/').size
next
end
pseudoOutput = Array.new
pseudoPaths = Array.new
pseudoFiles = Array.new
baseDirs.each { |dir|
dir = "#{dir}#{subDir}"
# If deleting, this checks if there are any FURTHER files/directories deeper in the 'route'.
# If so, adds them to an Array for later checking.
if @action == REMOVE
subFilesFound = Dir.glob("#{dir}**/*")
unless subFilesFound.empty?
subDirs.concat(subFilesFound)
end
end
if dir == "#{@pathToPhp}helpers/#{subDir}" || dir == "#{@pathToTest}helpers/#{subDir}"
if (@action == CREATE && !File.directory?(dir)) || (@action == REMOVE && File.directory?(dir))
pseudoOutput.push(" \x1B[32m#{dir.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
pseudoPaths.push(dir)
end
else
files = Array.new
case dir
when "#{@pathToPhp}controllers/#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.php")
when "#{@pathToPhp}views/#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.phtml")
when "#{@pathToDev}#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.less")
files.push("#{dir}#{@type.capitalize}_#{filename}.js")
when "#{@pathToMin}#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}.min.js")
when "#{@pathToTest}controllers/#{subDir}"
files.push("#{dir}#{@type.capitalize}_#{filename}Test.php")
else
self.error('Path not found.')
end
files.each { |file|
if (@action == CREATE && !File.file?(file)) || ((@action == REMOVE && File.file?(file)) || (@action == REMOVE && File.directory?(File.dirname(file))))
pseudoFiles.push(file)
pseudoPaths.push(File.dirname(file))
fileCount = 0
fileDisplay = ''
file.split('/').each { |filePart|
fileCount = fileCount + 1
if fileCount < file.split('/').length
fileDisplay = "#{fileDisplay}/#{filePart}"
else
fileDisplay = "#{fileDisplay}/\x1B[36m#{filePart}\x1B[0m"
end
}
# Remove preceeding slash (/) as a result of above loop..
fileDisplay[0] = ''
pseudoOutput.push(" \x1B[33m#{fileDisplay.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m")
end
}
end
}
pseudoPaths.uniq
pseudoFiles.uniq
unless pseudoPaths.empty?
@paths.concat(pseudoPaths)
end
unless pseudoFiles.empty?
@files.concat(pseudoFiles)
end
unless pseudoPaths.empty? && pseudoFiles.empty?
pseudoOutput.unshift(" \x1B[90m#{@type.upcase}\x1B[0m => \x1B[35m#{subDir[0..-2]}\x1B[0m")
pseudoOutput.push('')
@output.concat(pseudoOutput)
end
}
if @paths.empty? && @files.empty?
if @action == CREATE
self.error("The route: \x1B[35m#{@route}\x1B[0m already exists..")
elsif @action == REMOVE
self.error("The route: \x1B[35m#{@route}\x1B[0m doesn't exist..")
end
else
if @action == CREATE
@output.unshift("\x1B[42m CREATE \x1B[0m Determining files/directories which need to be created:\n")
elsif @action == REMOVE
@output.unshift("\x1B[41m REMOVE \x1B[0m Gathering files/directories for removal:\n")
end
end
# If we're deleting stuff, check if there are subPaths (past the point we're deleting from).
if @action == REMOVE && !subDirs.empty?
subFiles = Array.new
subPaths = Array.new
pseudoOutput = Array.new
subDirs.each { |subFile|
if File.directory?(subFile)
unless inArray(@paths, subFile)
subPaths.push(subFile)
end
elsif File.file?(subFile)
unless inArray(@files, subFile)
subFiles.push(subFile)
end
end
}
unless subPaths.empty? && subFiles.empty?
subPaths.each { |path| pseudoOutput.push(" \x1B[90m#{path.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") }
subFiles.each { |file| pseudoOutput.push(" \x1B[0m#{file.sub("#{@pathToRepo}/", '')[0..-1]}\x1B[0m") }
@paths.concat(subPaths)
@files.concat(subFiles)
@output.push("\x1B[41m NOTICE \x1B[0m\x1B[90m The following files/directories will also be removed:\n")
@output.concat(pseudoOutput)
@output.push('')
end
end
self.processRoute
end
# The final function which does all the processing. If errors are present, no processing will be done.
def processRoute
if @action == CREATE
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[42m CREATE \x1B[0m\x1B[90m these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
puts
NimzoFileMaker.new(@type, @paths, @files, ' ')
puts
unless @files.empty? && @paths.empty?
NimzoRewriter.new(@type)
end
elsif @action == REMOVE
system ('clear')
self.flushBuffer
self.confirm(" \x1B[90mYou're about to \x1B[0m\x1B[41m PERMANENTLY REMOVE \x1B[0m\x1B[90m all of these files/directories. Continue? [y/n]\x1B[0m => ", " \x1B[90mScript aborted.\x1B[0m")
unless @files.empty?
@files.each { |file|
@output.push("\x1B[31mRemoved: #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m")
# Remove file from Git.
system ("git rm -f #{file.sub("#{$PATH_TO_REPO}", '')[1..-1]} > /dev/null 2>&1")
FileUtils.rm_rf(file)
FileUtils.rm_rf(File.dirname(file))
}
end
unless @paths.empty?
@paths.each { |path|
@output.push("\x1B[31mRemoved: #{path.sub("#{$PATH_TO_REPO}", '')[1..-1]}\x1B[0m")
FileUtils.rm_rf(path)
}
end
@output.push('')
self.flushBuffer
unless @files.empty? && @paths.empty?
NimzoRewriter.new(@type)
end
end
self.runUnitTests
end
# Run (system) unit tests.
def runUnitTests
puts "\x1B[45m SYSTEM \x1B[0m Initializing tests...\n\n"
system('phpunit --bootstrap /Users/Albert/Repos/Nimzo/tests-php/bin/PHPUnit_Bootstrap.php --no-configuration --colors --group System /Users/Albert/Repos/Nimzo/tests-php')
end
# Aborts the script.
def abandonShip(abortTxt = " \x1B[90mScript aborted.\x1B[0m")
unless abortTxt.nil?
puts abortTxt
end
puts
exit
end
# Confirmation message. Returns and continues script on 'y' or 'Y'.. exits on anythng else.
def confirm(confirmTxt = "\x1B[90mContinue? [y/n]\x1B[0m => ?", abortTxt = nil)
STDOUT.flush
print confirmTxt
continue = STDIN.gets.chomp
if continue != 'y' && continue != 'Y'
self.abandonShip(abortTxt)
end
end
# If an error occurs, it's added to the @OUTPUT array and if 'exit' flag set to TRUE,
# the script goes straight to run & subsequently displays output & dies.
# @param text
def error(text = '')
@output.push("\x1B[41m ERROR \x1B[0m #{text}")
self.flushBuffer(true)
end
# Flushes the output buffer.
def flushBuffer(exit = false)
unless @output.empty?
puts
@output.each { |message| puts "#{message}\x1B[0m" }
if exit
self.abandonShip
end
@output = Array.new
end
end
# Log something to the output buffer.
def output(text = '')
@output.push(text)
end
end
NimzoCreateRemove.new(ARGV[0], ARGV[1], ARGV[2], ARGV[3]) |
# frozen_string_literal: true
module Pragma
module Decorator
# Adds association expansion to decorators.
#
# @author Alessandro Desantis
module Association
def self.included(klass)
klass.extend ClassMethods
klass.class_eval do
@associations = {}
def self.associations
@associations
end
end
end
# Inizializes the decorator and bindings for all the associations.
#
# @see Association::Binding
def initialize(*)
super
@association_bindings = {}
self.class.associations.each_pair do |property, reflection|
@association_bindings[property] = Binding.new(reflection: reflection, decorator: self)
end
end
module ClassMethods # rubocop:disable Style/Documentation
# Defines a +belongs_to+ association.
#
# See {Association::Reflection#initialize} for the list of available options.
#
# @param property [Symbol] the property containing the associated object
# @param options [Hash] the options of the association
def belongs_to(property, options = {})
define_association :belongs_to, property, options
end
# Defines a +has_one+ association.
#
# See {Association::Reflection#initialize} for the list of available options.
#
# @param property [Symbol] the property containing the associated object
# @param options [Hash] the options of the association
def has_one(property, options = {}) # rubocop:disable Style/PredicateName
define_association :has_one, property, options
end
private
def define_association(type, property, options = {})
create_association_definition(type, property, options)
create_association_getter(property)
create_association_property(property)
end
def create_association_definition(type, property, options)
@associations[property.to_sym] = Reflection.new(type, property, options)
end
def create_association_getter(property)
class_eval <<~RUBY
private def _#{property}_association
@association_bindings[:#{property}].render(user_options[:expand])
end
RUBY
end
def create_association_property(property_name)
options = {
exec_context: :decorator,
as: property_name
}.tap do |opts|
if @associations[property_name].options.key?(:render_nil)
opts[:render_nil] = @associations[property_name].options[:render_nil]
end
end
property("_#{property_name}_association", options)
end
end
end
end
end
Fix Association module with Representable 3.0.2
# frozen_string_literal: true
module Pragma
module Decorator
# Adds association expansion to decorators.
#
# @author Alessandro Desantis
module Association
def self.included(klass)
klass.extend ClassMethods
klass.class_eval do
@associations = {}
def self.associations
@associations
end
end
end
# Inizializes the decorator and bindings for all the associations.
#
# @see Association::Binding
def initialize(*)
super
@association_bindings = {}
self.class.associations.each_pair do |property, reflection|
@association_bindings[property] = Binding.new(reflection: reflection, decorator: self)
end
end
module ClassMethods # rubocop:disable Style/Documentation
# Defines a +belongs_to+ association.
#
# See {Association::Reflection#initialize} for the list of available options.
#
# @param property [Symbol] the property containing the associated object
# @param options [Hash] the options of the association
def belongs_to(property, options = {})
define_association :belongs_to, property, options
end
# Defines a +has_one+ association.
#
# See {Association::Reflection#initialize} for the list of available options.
#
# @param property [Symbol] the property containing the associated object
# @param options [Hash] the options of the association
def has_one(property, options = {}) # rubocop:disable Style/PredicateName
define_association :has_one, property, options
end
private
def define_association(type, property, options = {})
create_association_definition(type, property, options)
create_association_getter(property)
create_association_property(property)
end
def create_association_definition(type, property, options)
@associations[property.to_sym] = Reflection.new(type, property, options)
end
def create_association_getter(property)
class_eval <<~RUBY
def _#{property}_association
@association_bindings[:#{property}].render(user_options[:expand])
end
RUBY
end
def create_association_property(property_name)
options = {
exec_context: :decorator,
as: property_name
}.tap do |opts|
if @associations[property_name].options.key?(:render_nil)
opts[:render_nil] = @associations[property_name].options[:render_nil]
end
end
property("_#{property_name}_association", options)
end
end
end
end
end
|
class Preseason::Recipe::Initializer < Preseason::Recipe
def prepare
initialize_assets
end
private
def initialize_assets
old_line = '# Rails.application.config.assets.precompile += %w( search.js )'
new_line = 'Rails.application.config.assets.precompile += %w( screen.css )'
gsub_file 'config/initializers/assets.rb', old_line, new_line
end
end
Added ie8.js to precompile list.
class Preseason::Recipe::Initializer < Preseason::Recipe
attr_accessor :assets
def prepare
precompile_assets
initialize_assets
end
private
def precompile_assets
@assets = %w(screen.css)
@assets << 'ie8.js' if config.ie8.enabled?
end
def initialize_assets
old_line = '# Rails.application.config.assets.precompile += %w( search.js )'
new_line = "Rails.application.config.assets.precompile += #{@assets}"
gsub_file 'config/initializers/assets.rb', old_line, new_line
end
end
|
add mar ssl cli commands
require 'base64'
require_relative 'base'
module Qtc
module Cli
class Mar::SslCertificates < Mar::Base
def create(options)
raise ArgumentError.new("--key=#{opts.key} is not a file") unless File.exists(opts.key)
raise ArgumentError.new("--cert=#{opts.cert} is not a file") unless File.exists(opts.cert)
instance_id = resolve_instance_id(options)
instance_data = instance_info(instance_id)
if instance_data
token = instance_data['authorizations'][0]['access_token']
data = {
name: instance_id,
privateKey: File.read(opts.key),
certificateBody: File.read(opts.cert)
}
client.post("/apps/#{instance_id}/ssl_certificate", data, {}, {'Authorization' => "Bearer #{token}"})
end
end
def destroy(options)
instance_id = resolve_instance_id(options)
instance_data = instance_info(instance_id)
if instance_data
token = instance_data['authorizations'][0]['access_token']
client.delete("/apps/#{instance_id}/ssl_certificate", {}, {}, {'Authorization' => "Bearer #{token}"})
end
end
end
end
end
|
# encoding: utf-8
require 'optparse'
require 'progressbar'
require 'colored'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: rails_best_practices [options]"
opts.on("-d", "--debug", "Debug mode") do
options['debug'] = true
end
['vendor', 'spec', 'test', 'stories'].each do |pattern|
opts.on("--#{pattern}", "include #{pattern} files") do
options[pattern] = true
end
end
opts.on_tail('-v', '--version', 'Show this version') do
require 'rails_best_practices/version'
puts RailsBestPractices::VERSION
exit
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on("-x", "--exclude PATTERNS", "Don't analyze files matching a pattern", "(comma-separated regexp list)") do |list|
begin
options[:exclude] = list.split(/,/).map{|x| Regexp.new x}
rescue RegexpError => e
raise OptionParser::InvalidArgument, e.message
end
end
opts.parse!
end
runner = RailsBestPractices::Core::Runner.new
runner.set_debug if options['debug']
files = RailsBestPractices::analyze_files(ARGV, options)
bar = ProgressBar.new('Analyzing', files.size)
files.each { |file| runner.check_file(file); bar.inc }
bar.finish
runner.errors.each {|error| puts error.to_s.red}
puts "\nPlease go to http://rails-bestpractices.com to see more useful Rails Best Practices.".green
if runner.errors.size > 0
puts "\nFound #{runner.errors.size} errors.".red
end
exit runner.errors.size
do not display progressbar in debug mode
# encoding: utf-8
require 'optparse'
require 'progressbar'
require 'colored'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: rails_best_practices [options]"
opts.on("-d", "--debug", "Debug mode") do
options['debug'] = true
end
['vendor', 'spec', 'test', 'stories'].each do |pattern|
opts.on("--#{pattern}", "include #{pattern} files") do
options[pattern] = true
end
end
opts.on_tail('-v', '--version', 'Show this version') do
require 'rails_best_practices/version'
puts RailsBestPractices::VERSION
exit
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts.on("-x", "--exclude PATTERNS", "Don't analyze files matching a pattern", "(comma-separated regexp list)") do |list|
begin
options[:exclude] = list.split(/,/).map{|x| Regexp.new x}
rescue RegexpError => e
raise OptionParser::InvalidArgument, e.message
end
end
opts.parse!
end
runner = RailsBestPractices::Core::Runner.new
runner.set_debug if options['debug']
files = RailsBestPractices::analyze_files(ARGV, options)
bar = ProgressBar.new('Analyzing', files.size)
files.each do |file|
runner.check_file(file)
bar.inc unless options['debug']
end
bar.finish
runner.errors.each {|error| puts error.to_s.red}
puts "\nPlease go to http://rails-bestpractices.com to see more useful Rails Best Practices.".green
if runner.errors.size > 0
puts "\nFound #{runner.errors.size} errors.".red
end
exit runner.errors.size
|
module RailsServerTimings
VERSION = "1.0.2".freeze
end
v1.0.3
module RailsServerTimings
VERSION = "1.0.3".freeze
end
|
an (more?) accurate version fo Float#to_s, for 1.8
class Float
SIZE=[1.1].pack("d").size
BITSIZE=SIZE*8
BASE10_DIGITS=(2**BITSIZE-1).to_s.size
def accurate_to_s
return "#{'-' if self<0}Infinity" if infinite?
return "NaN" if nan?
return "0.0e0" if zero?
as_str=sprintf("%.#{BASE10_DIGITS+2}e",self)
return to_s if as_str.to_f.zero? #hopeless
#decompose self into sign, mantissa, and exponent (in string form)
all,sign,first,digits,exp=*as_str.match(/^([+-]?)(\d)\.(\d+)e(.*)$/)
digits=first<<digits
exp=exp.to_i+1
lead=sign<<"0."
#recompose back to a float
result=[lead,digits,"e",exp].join
result_f=result.to_f
delta=result_f - self
return result if delta.zero? #if representation is exact, return here
#figure out which direction to go to get toward the right answer
if delta<0
incr=1
else #delta>0
incr=-1
end
#keep adding increasing increments to mantissa
#until we get to a value on the other side of the correct answer
while true
while true
try_digits=digits.to_i.+(incr).to_s
if try_digits.size>digits.size
exp+=1
digits="0"+digits
end
fail if try_digits[0]==?- #can't happen... I think?
trying=[lead,try_digits,"e",exp].join
trying_f=trying.to_f
break unless trying_f.zero?
digits[-1,1]='' #workaround 1.8 bug
end
return trying if trying_f==self
break if self.between?(*[trying_f,result_f].sort) #(trying_f-self)*delta<0
incr*=2
end
#we now have lower and upper bounds on the correct answer
lower,upper=*[digits.to_i, digits.to_i.+(incr)].sort
#maybe one of the bounds is already the correct answer?
result=[lead,lower,"e",exp].join
return result if result.to_f==self
result=[lead,upper,"e",exp].join
return result if result.to_f==self
#binary search between lower and upper bounds til we find a correct answer
while true
return to_s if upper-lower <= 1 #hopeless
mid=(lower+upper)/2
mid_s=[lead,mid,"e",exp].join
mid_f=mid_s.to_f
return mid_s if mid_f==self
if mid_f<self
lower=mid
else #mid_f>self
upper=mid
end
end
end
end
eval DATA.read if __FILE__==$0
__END__
require 'test/unit'
class FloatRoundTripTest<Test::Unit::TestCase
def float_round_trip f
str=f.accurate_to_s
if str=="Infinity"
return 1.0/0
elsif str=="-Infinity"
return -1.0/0
elsif str=="NaN"
return 0.0/0.0
else
str.to_f
end
end
alias frt float_round_trip
def rand_float
base=rand
range=Float::MIN_10_EXP..Float::MAX_10_EXP
extent=range.last-range.first
offset=rand(extent+1)
exp=range.first+offset
base*=10**exp
end
def test_frt
data=[0.399891415240566, 0.198188037200931, 0.90302699802093,
7.48121345153454520016e-01, 4.11408313999083175005e-02,
2.68070684698467065488e-02, 3.85029229764812574999e-01,
"\327\237vY\343n\342?".unpack("d")[0],
1.0/0, -1.0/0, 0.0/0.0,
"\333\211>4\253Atu".unpack("d")[0],
"\2461\220\253\214\267e\021".unpack("d")[0],
"\r\032N\f'\336\243\003".unpack("d")[0],
"B[\226\001\2175f\021".unpack("d")[0],
"%\217\336\362\326\272\026\001".unpack("d")[0],
"\312\342\344\206\237\024\"\003".unpack("d")[0],
]
1_000_000.times{|i|
f=data.shift||rand_float
p sprintf("%.#{Float::BASE10_DIGITS}e",f)
p [f].pack"d"
p f.accurate_to_s
f2=frt f
warn "failed with i=#{i} f=#{f}, #{[f].pack("d").inspect}; f2=#{f2}, #{[f2].pack("d").inspect}" unless [f].pack("d")==[f2].pack("d")
}
end
end
|
#!/usr/bin/env ruby
# encoding: UTF-8
#
# Copyright © 2012-2015 Cask Data, 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.
#
require_relative '../logging'
require_relative 'utils'
module Coopr
module Plugin
# Base class for all automator plugins. This should be extended, not modified
class Automator
include Coopr::Logging
include Coopr::Plugin::Utils
attr_accessor :task, :flavor, :image, :hostname, :providerid, :result
attr_reader :env
def initialize(env, task)
@task = task
@env = env
@result = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
end
def runTask
sshauth = @task['config']['ssh-auth']
hostname = @task['config']['hostname']
ipaddress = @task['config']['ipaddresses']['access_v4']
fields = @task['config']['service']['action']['fields'] rescue nil
case task['taskName'].downcase
when 'bootstrap'
bootstrap('hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth)
return @result
when 'install'
install({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'configure'
configure({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'initialize'
init({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'start'
start({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'stop'
stop({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'remove'
remove({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
else
fail "unhandled automator task type: #{task['taskName']}"
end
end
def bootstrap(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task bootstrap in class #{self.class.name}"
fail "Unimplemented task bootstrap in class #{self.class.name}"
end
def install(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task install in class #{self.class.name}"
fail "Unimplemented task install in class #{self.class.name}"
end
def configure(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task configure in class #{self.class.name}"
fail "Unimplemented task configure in class #{self.class.name}"
end
def init(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task initialize in class #{self.class.name}"
fail "Unimplemented task initialize in class #{self.class.name}"
end
def start(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task start in class #{self.class.name}"
fail "Unimplemented task start in class #{self.class.name}"
end
def stop(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task stop in class #{self.class.name}"
fail "Unimplemented task stop in class #{self.class.name}"
end
def remove(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task remove in class #{self.class.name}"
fail "Unimplemented task remove in class #{self.class.name}"
end
end
end
end
Verify SSH host key... WARN if missing
#!/usr/bin/env ruby
# encoding: UTF-8
#
# Copyright © 2012-2015 Cask Data, 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.
#
require_relative '../logging'
require_relative 'utils'
module Coopr
module Plugin
# Base class for all automator plugins. This should be extended, not modified
class Automator
include Coopr::Logging
include Coopr::Plugin::Utils
attr_accessor :task, :flavor, :image, :hostname, :providerid, :result
attr_reader :env
def initialize(env, task)
@task = task
@env = env
@result = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
end
def runTask
sshauth = @task['config']['ssh-auth']
hostname = @task['config']['hostname']
ipaddress = @task['config']['ipaddresses']['access_v4']
fields = @task['config']['service']['action']['fields'] rescue nil
verify_ssh_host_key(ipaddress, 'rsa')
case task['taskName'].downcase
when 'bootstrap'
bootstrap('hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth)
return @result
when 'install'
install({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'configure'
configure({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'initialize'
init({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'start'
start({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'stop'
stop({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
when 'remove'
remove({'hostname' => hostname, 'ipaddress' => ipaddress, 'sshauth' => sshauth, 'fields' => fields})
return @result
else
fail "unhandled automator task type: #{task['taskName']}"
end
end
def verify_ssh_host_key(host, type = 'rsa')
log.debug "Verifying SSH host key for #{@task['config']['hostname']}/#{host}"
if @task['config']['keys'][type]
message = "SSH host key verification failed for #{@task['config']['hostname']}/#{host}"
fail message unless @task['config']['keys'][type] == ssh_keyscan(host, type)
return true
else
message = "SSH Host key not stored for #{@task['config']['hostname']}... Skipping verification"
log.warn message
return true
end
return false
end
def bootstrap(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task bootstrap in class #{self.class.name}"
fail "Unimplemented task bootstrap in class #{self.class.name}"
end
def install(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task install in class #{self.class.name}"
fail "Unimplemented task install in class #{self.class.name}"
end
def configure(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task configure in class #{self.class.name}"
fail "Unimplemented task configure in class #{self.class.name}"
end
def init(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task initialize in class #{self.class.name}"
fail "Unimplemented task initialize in class #{self.class.name}"
end
def start(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task start in class #{self.class.name}"
fail "Unimplemented task start in class #{self.class.name}"
end
def stop(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task stop in class #{self.class.name}"
fail "Unimplemented task stop in class #{self.class.name}"
end
def remove(inputmap)
@result['status'] = 1
@result['message'] = "Unimplemented task remove in class #{self.class.name}"
fail "Unimplemented task remove in class #{self.class.name}"
end
end
end
end
|
#encoding: UTF-8
require 'puppet/provider'
class SecurityPolicy
attr_reader :wmic_cmd
EVENT_TYPES = ["Success,Failure", "Success", "Failure", "No Auditing", 0, 1, 2, 3]
def initialize
# suppose to make an instance method for wmic
@wmic_cmd = Puppet::Provider::CommandDefiner.define('wmic', 'wmic', Puppet::Provider)
end
def wmic(args=[])
case args[0]
when 'useraccount'
@@useraccount ||= wmic_cmd.execute(args).force_encoding('utf-16le').encode('utf-8', :universal_newline => true).gsub("\xEF\xBB\xBF", '')
when 'group'
@@groupaccount ||= wmic_cmd.execute(args).force_encoding('utf-16le').encode('utf-8', :universal_newline => true).gsub("\xEF\xBB\xBF", '')
else
# will not cache
wmic_cmd.execute(args).force_encoding('utf-16le').encode('utf-8', :universal_newline => true).gsub("\xEF\xBB\xBF", '')
end
end
# collect all the local accounts using wmic
def local_accounts
ary = []
["useraccount","group"].each do |lu|
wmic([lu,'get', 'name,sid', '/format:csv']).split("\n").each do |line|
next if line =~ /Node/
if line.include? ","
ary << line.strip.split(",")
end
end
end
ary
end
def user_sid_array
@user_sid_array ||= local_accounts + builtin_accounts
end
def user_to_sid(value)
sid = user_sid_array.find do |home,user,sid|
user == value
end
unless sid.nil?
'*' + sid[2]
else
value
end
end
# convert the sid to a user
def sid_to_user(value)
value = value.gsub(/(^\*)/ , '')
user = user_sid_array.find do |home,user,sid|
value == sid
end
unless user.nil?
user[1]
else
value
end
end
def convert_privilege_right(ensure_value, policy_value)
# we need to convert users to sids first
if ensure_value.to_s == 'absent'
pv = ''
else
sids = Array.new
policy_value.split(",").sort.each do |suser|
suser.strip!
sids << user_to_sid(suser)
end
pv = sids.sort.join(",")
end
end
# converts the policy value inside the policy hash to conform to the secedit standards
def convert_policy_hash(policy_hash)
case policy_hash[:policy_type]
when 'Privilege Rights'
value = convert_privilege_right(policy_hash[:ensure], policy_hash[:policy_value])
when 'Event Audit'
value = event_to_audit_id(policy_hash[:policy_value])
when 'Registry Values'
value = SecurityPolicy.convert_registry_value(policy_hash[:name], policy_hash[:policy_value])
else
value = policy_hash[:policy_value]
end
policy_hash[:policy_value] = value
policy_hash
end
def builtin_accounts
# more accounts and SIDs can be found at https://support.microsoft.com/en-us/kb/243330
ary = [
["","NULL","S-1-0"],
["","NOBODY","S-1-0-0"],
["","EVERYONE","S-1-1-0"],
["","LOCAL","S-1-2-0"],
["","CONSOLE_LOGON","S-1-2-1"],
["","CREATOR_OWNER","S-1-3-0"],
["","CREATER_GROUP","S-1-3-1"],
["","OWNER_SERVER","S-1-3-2"],
["","GROUP_SERVER","S-1-3-3"],
["","OWNER_RIGHTS","S-1-3-4"],
["","NT_AUTHORITY","S-1-5"],
["","DIALUP","S-1-5-1"],
["","NETWORK","S-1-5-2"],
["","BATCH","S-1-5-3"],
["","INTERACTIVE","S-1-5-4"],
["","SERVICE","S-1-5-6"],
["","ANONYMOUS","S-1-5-7"],
["","PROXY","S-1-5-8"],
["","ENTERPRISE_DOMAIN_CONTROLLERS","S-1-5-9"],
["","PRINCIPAAL_SELF","S-1-5-10"],
["","AUTHENTICATED_USERS","S-1-5-11"],
["","RESTRICTED_CODE","S-1-5-12"],
["","TERMINAL_SERVER_USER","S-1-5-13"],
["","REMOTE_INTERACTIVE_LOGON","S-1-5-14"],
["","THIS_ORGANIZATION","S-1-5-15"],
["","IUSER","S-1-5-17"],
["","LOCAL_SYSTEM","S-1-5-18"],
["","LOCAL_SERVICE","S-1-5-19"],
["","NETWORK_SERVICE","S-1-5-20"],
["","COMPOUNDED_AUTHENTICATION","S-1-5-21-0-0-0-496"],
["","CLAIMS_VALID","S-1-5-21-0-0-0-497"],
["","BUILTIN_ADMINISTRATORS","S-1-5-32-544"],
["","BUILTIN_USERS","S-1-5-32-545"],
["","BUILTIN_GUESTS","S-1-5-32-546"],
["","POWER_USERS","S-1-5-32-547"],
["","ACCOUNT_OPERATORS","S-1-5-32-548"],
["","SERVER_OPERATORS","S-1-5-32-549"],
["","PRINTER_OPERATORS","S-1-5-32-550"],
["","BACKUP_OPERATORS","S-1-5-32-551"],
["","REPLICATOR","S-1-5-32-552"],
["","ALIAS_PREW2KCOMPACC","S-1-5-32-554"],
["","REMOTE_DESKTOP","S-1-5-32-555"],
["","NETWORK_CONFIGURATION_OPS","S-1-5-32-556"],
["","INCOMING_FOREST_TRUST_BUILDERS","S-1-5-32-557"],
["","PERMON_USERS","S-1-5-32-558"],
["","PERFLOG_USERS","S-1-5-32-559"],
["","WINDOWS_AUTHORIZATION_ACCESS_GROUP","S-1-5-32-560"],
["","TERMINAL_SERVER_LICENSE_SERVERS","S-1-5-32-561"],
["","DISTRIBUTED_COM_USERS","S-1-5-32-562"],
["","IIS_USERS","S-1-5-32-568"],
["","CRYPTOGRAPHIC_OPERATORS","S-1-5-32-569"],
["","EVENT_LOG_READERS","S-1-5-32-573"],
["","CERTIFICATE_SERVICE_DCOM_ACCESS","S-1-5-32-574"],
["","RDS_REMOTE_ACCESS_SERVERS","S-1-5-32-575"],
["","RDS_ENDPOINT_SERVERS","S-1-5-32-576"],
["","RDS_MANAGEMENT_SERVERS","S-1-5-32-577"],
["","HYPER_V_ADMINS","S-1-5-32-578"],
["","ACCESS_CONTROL_ASSISTANCE_OPS","S-1-5-32-579"],
["","REMOTE_MANAGEMENT_USERS","S-1-5-32-580"],
["","WRITE_RESTRICTED_CODE","S-1-5-32-558"],
["","NTLM_AUTHENTICATION","S-1-5-64-10"],
["","SCHANNEL_AUTHENTICATION","S-1-5-64-14"],
["","DIGEST_AUTHENTICATION","S-1-5-64-21"],
["","THIS_ORGANIZATION_CERTIFICATE","S-1-5-65-1"],
["","NT_SERVICE","S-1-5-80"],
["","NT_SERVICE\\ALL_SERVICES","S-1-5-80-0"],
["","NT_SERVICE\\WdiServiceHost","S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420"],
["","USER_MODE_DRIVERS","S-1-5-84-0-0-0-0-0"],
["","LOCAL_ACCOUNT","S-1-5-113"],
["","LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP","S-1-5-114"],
["","OTHER_ORGANIZATION","S-1-5-1000"],
["","ALL_APP_PACKAGES","S-1-15-2-1"],
["","ML_UNTRUSTED","S-1-16-0"],
["","ML_LOW","S-1-16-4096"],
["","ML_MEDIUM","S-1-16-8192"],
["","ML_MEDIUM_PLUS","S-1-16-8448"],
["","ML_HIGH","S-1-15-12288"],
["","ML_SYSTEM","S-1-16-16384"],
["","ML_PROTECTED_PROCESS","S-1-16-20480"],
["","AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY","S-1-18-1"],
["","SERVICE_ASSERTED_IDENTITY","S-1-18-2"]
]
ary
end
# Converts a event number to a word
def self.event_audit_mapper(policy_value)
case policy_value.to_s
when 3
return "Success,Failure"
when 2
return "Failure"
when 1
return "Success"
else
return "No auditing"
end
end
# Converts a event number to a word
def self.event_to_audit_id(event_audit_name)
case event_audit_name
when "Success,Failure"
return 3
when "Failure"
return 2
when "Success"
return 1
when 'No auditing'
return 0
else
return event_audit_name
end
end
# returns the key and hash value given the policy name
def self.find_mapping_from_policy_name(name)
key, value = lsp_mapping.find do |key,hash|
hash[:name] == name
end
unless key && value
raise KeyError, "#{name} is not a valid policy"
end
return key, value
end
# returns the key and hash value given the policy desc
def self.find_mapping_from_policy_desc(desc)
name = desc.downcase
value = nil
key, value = lsp_mapping.find do |key, hash|
key.downcase == name
end
unless value
raise KeyError, "#{desc} is not a valid policy"
end
return value
end
def self.valid_lsp?(name)
lsp_mapping.keys.include?(name)
end
def self.convert_registry_value(name, value)
value = value.to_s
return value if value.split(',').count > 1
policy_hash = find_mapping_from_policy_desc(name)
"#{policy_hash[:reg_type]},#{value}"
end
# converts the policy value to machine values
def self.convert_policy_value(policy_hash, value)
sp = SecurityPolicy.new
# I would rather not have to look this info up, but the type code will not always have this info handy
# without knowing the policy type we can't figure out what to convert
policy_type = find_mapping_from_policy_desc(policy_hash[:name])[:policy_type]
case policy_type.to_s
when 'Privilege Rights'
sp.convert_privilege_right(policy_hash[:ensure], value)
when 'Event Audit'
event_to_audit_id(value)
when 'Registry Values'
# convert the value to a datatype/value
convert_registry_value(policy_hash[:name], value)
else
value
end
end
def self.lsp_mapping
@lsp_mapping ||= {
# Password policy Mappings
'Enforce password history' => {
:name => 'PasswordHistorySize',
:policy_type => 'System Access',
},
'Maximum password age' => {
:name => 'MaximumPasswordAge',
:policy_type => 'System Access',
},
'Minimum password age' => {
:name => 'MinimumPasswordAge',
:policy_type => 'System Access',
},
'Minimum password length' => {
:name => 'MinimumPasswordLength',
:policy_type => 'System Access',
},
'Password must meet complexity requirements' => {
:name => 'PasswordComplexity',
:policy_type => 'System Access',
},
'Store passwords using reversible encryption' => {
:name => 'ClearTextPassword',
:policy_type => 'System Access',
},
'Account lockout threshold' => {
:name => 'LockoutBadCount',
:policy_type => 'System Access',
},
'Account lockout duration' => {
:name => 'LockoutDuration',
:policy_type => 'System Access',
},
'Reset account lockout counter after' => {
:name => 'ResetLockoutCount',
:policy_type => 'System Access',
},
'Accounts: Rename administrator account' => {
:name => 'NewAdministratorName',
:policy_type => 'System Access',
:data_type => :quoted_string
},
'Accounts: Rename guest account' => {
:name => 'NewGuestName',
:policy_type => 'System Access',
:data_type => :quoted_string
},
'Accounts: Require Login to Change Password' => {
:name => 'RequireLogonToChangePassword',
:policy_type => 'System Access'
},
'Network security: Force logoff when logon hours expire' => {
:name => 'ForceLogoffWhenHourExpire',
:policy_type => 'System Access'
},
'Network access: Allow anonymous SID/name translation' => {
:name => 'LSAAnonymousNameLookup',
:policy_type => 'System Access'
},
'EnableAdminAccount' => {
:name => 'EnableAdminAccount',
:policy_type => 'System Access'
},
"EnableGuestAccount"=>{
:name=>"EnableGuestAccount",
:policy_type => 'System Access'
},
# Audit Policy Mappings
'Audit account logon events' => {
:name => 'AuditAccountLogon',
:policy_type => 'Event Audit',
},
'Audit account management' => {
:name => 'AuditAccountManage',
:policy_type => 'Event Audit',
},
'Audit directory service access' => {
:name => 'AuditDSAccess',
:policy_type => 'Event Audit',
},
'Audit logon events' => {
:name => 'AuditLogonEvents',
:policy_type => 'Event Audit',
},
'Audit object access' => {
:name => 'AuditObjectAccess',
:policy_type => 'Event Audit',
},
'Audit policy change' => {
:name => 'AuditPolicyChange',
:policy_type => 'Event Audit',
},
'Audit privilege use' => {
:name => 'AuditPrivilegeUse',
:policy_type => 'Event Audit',
},
'Audit process tracking' => {
:name => 'AuditProcessTracking',
:policy_type => 'Event Audit',
},
'Audit system events' => {
:name => 'AuditSystemEvents',
:policy_type => 'Event Audit',
},
'Audit: Force audit policy subcategory settings (Windows Vista or later) to override audit policy category settings' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\SCENoApplyLegacyAuditPolicy',
:reg_type => '4',
:policy_type => 'Registry Values',
},
#User rights mapping
'Access Credential Manager as a trusted caller' => {
:name => 'SeTrustedCredManAccessPrivilege',
:policy_type => 'Privilege Rights',
},
'Access this computer from the network' => {
:name => 'SeNetworkLogonRight',
:policy_type => 'Privilege Rights',
},
'Act as part of the operating system' => {
:name => 'SeTcbPrivilege',
:policy_type => 'Privilege Rights',
},
'Add workstations to domain' => {
:name => 'SeMachineAccountPrivilege',
:policy_type => 'Privilege Rights',
},
'Adjust memory quotas for a process' => {
:name => 'SeIncreaseQuotaPrivilege',
:policy_type => 'Privilege Rights',
},
'Allow log on locally' => {
:name => 'SeInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Allow log on through Remote Desktop Services' => {
:name => 'SeRemoteInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Back up files and directories' => {
:name => 'SeBackupPrivilege',
:policy_type => 'Privilege Rights',
},
'Bypass traverse checking' => {
:name => 'SeChangeNotifyPrivilege',
:policy_type => 'Privilege Rights',
},
'Change the system time' => {
:name => 'SeSystemtimePrivilege',
:policy_type => 'Privilege Rights',
},
'Change the time zone' => {
:name => 'SeTimeZonePrivilege',
:policy_type => 'Privilege Rights',
},
'Create a pagefile' => {
:name => 'SeCreatePagefilePrivilege',
:policy_type => 'Privilege Rights',
},
'Create a token object' => {
:name => 'SeCreateTokenPrivilege',
:policy_type => 'Privilege Rights',
},
'Create global objects' => {
:name => 'SeCreateGlobalPrivilege',
:policy_type => 'Privilege Rights',
},
'Create permanent shared objects' => {
:name => 'SeCreatePermanentPrivilege',
:policy_type => 'Privilege Rights',
},
'Create symbolic links' => {
:name => 'SeCreateSymbolicLinkPrivilege',
:policy_type => 'Privilege Rights',
},
'Debug programs' => {
:name => 'SeDebugPrivilege',
:policy_type => 'Privilege Rights',
},
'Deny access to this computer from the network' => {
:name => 'SeDenyNetworkLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on as a batch job' => {
:name => 'SeDenyBatchLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on as a service' => {
:name => 'SeDenyServiceLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on locally' => {
:name => 'SeDenyInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on through Remote Desktop Services' => {
:name => 'SeDenyRemoteInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Enable computer and user accounts to be trusted for delegation' => {
:name => 'SeEnableDelegationPrivilege',
:policy_type => 'Privilege Rights',
},
'Force shutdown from a remote system' => {
:name => 'SeRemoteShutdownPrivilege',
:policy_type => 'Privilege Rights',
},
'Generate security audits' => {
:name => 'SeAuditPrivilege',
:policy_type => 'Privilege Rights',
},
'Impersonate a client after authentication' => {
:name => 'SeImpersonatePrivilege',
:policy_type => 'Privilege Rights',
},
'Increase a process working set' => {
:name => 'SeIncreaseWorkingSetPrivilege',
:policy_type => 'Privilege Rights',
},
'Increase scheduling priority' => {
:name => 'SeIncreaseBasePriorityPrivilege',
:policy_type => 'Privilege Rights',
},
'Load and unload device drivers' => {
:name => 'SeLoadDriverPrivilege',
:policy_type => 'Privilege Rights',
},
'Lock pages in memory' => {
:name => 'SeLockMemoryPrivilege',
:policy_type => 'Privilege Rights',
},
'Log on as a batch job' => {
:name => 'SeBatchLogonRight',
:policy_type => 'Privilege Rights',
},
'Log on as a service' => {
:name => 'SeServiceLogonRight',
:policy_type => 'Privilege Rights',
},
'Manage auditing and security log' => {
:name => 'SeSecurityPrivilege',
:policy_type => 'Privilege Rights',
},
'Modify an object label' => {
:name => 'SeRelabelPrivilege',
:policy_type => 'Privilege Rights',
},
'Modify firmware environment values' => {
:name => 'SeSystemEnvironmentPrivilege',
:policy_type => 'Privilege Rights',
},
'Perform volume maintenance tasks' => {
:name => 'SeManageVolumePrivilege',
:policy_type => 'Privilege Rights',
},
'Profile single process' => {
:name => 'SeProfileSingleProcessPrivilege',
:policy_type => 'Privilege Rights',
},
'Profile system performance' => {
:name => 'SeSystemProfilePrivilege',
:policy_type => 'Privilege Rights',
},
'Remove computer from docking station' => {
:name => 'SeUndockPrivilege',
:policy_type => 'Privilege Rights',
},
'Replace a process level token' => {
:name => 'SeAssignPrimaryTokenPrivilege',
:policy_type => 'Privilege Rights',
},
'Restore files and directories' => {
:name => 'SeRestorePrivilege',
:policy_type => 'Privilege Rights',
},
'Shut down the system' => {
:name => 'SeShutdownPrivilege',
:policy_type => 'Privilege Rights',
},
'Synchronize directory service data' => {
:name => 'SeSyncAgentPrivilege',
:policy_type => 'Privilege Rights',
},
'Take ownership of files or other objects' => {
:name => 'SeTakeOwnershipPrivilege',
:policy_type => 'Privilege Rights',
},
#Registry Keys
'Recovery console: Allow automatic administrative logon' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Recovery console: Allow floppy copy and access to all drives and all folders' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Number of previous logons to cache (in case domain controller is not available)' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\CachedLogonsCount',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Interactive logon: Require Domain Controller authentication to unlock workstation' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ForceUnlockLogon',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Prompt user to change password before expiration' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Smart card removal behavior' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorAdmin',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Behavior of the elevation prompt for standard users' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorUser',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Do not require CTRL+ALT+DEL' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableCAD',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Do not display last user name' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Detect application installations and prompt for elevation' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableInstallerDetection',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Run all administrators in Admin Approval Mode' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Only elevate UIAccess applications that are installed in secure locations' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableSecureUIAPaths',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktop' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableUIADesktopToggle',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Virtualize file and registry write failures to per-user locations' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableVirtualization',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Admin Approval Mode for the Built-in Administrator account' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Message title for users attempting to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeCaption',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Interactive logon: Message text for users attempting to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeText',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'User Account Control: Switch to the secure desktop when prompting for elevation' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\PromptOnSecureDesktop',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Require smart card' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ScForceOption',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Shutdown: Allow system to be shut down without having to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ShutdownWithoutLogon',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Devices: Allow undock without having to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\UndockWithoutLogon',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Only elevate executables that are signed and validated' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ValidateAdminCodeSignatures',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'System settings: Use Certificate Rules on Windows Executables for Software Restriction Policies' => {
:name => 'MACHINE\Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\AuthenticodeEnabled',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Audit: Audit the access of global system objects' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\AuditBaseObjects',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Audit: Shut down system immediately if unable to log security audits' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\CrashOnAuditFail',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Do not allow storage of passwords and credentials for network authentication' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\DisableDomainCreds',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Let Everyone permissions apply to anonymous users' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\EveryoneIncludesAnonymous',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Sharing and security model for local accounts' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'System cryptography: Force strong key protection for user keys stored on the computer' => {
:name => 'MACHINE\Software\Policies\Microsoft\Cryptography\ForceKeyProtection',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Audit: Audit the use of Backup and Restore privilege' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\FullPrivilegeAuditing',
:reg_type => '3',
:policy_type => 'Registry Values',
},
'Accounts: Block Microsoft accounts' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\NoConnectedUser',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Accounts: Limit local account use of blank passwords to console logon only' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\LimitBlankPasswordUse',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: All Local System to use computer identity for NTLM' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\UseMachineId',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Remotely accessible registry paths' => {
:name => 'MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedExactPaths\Machine',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Devices: Restrict CD-ROM access to locally logged-on user only' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AllocateCDRoms',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Devices: Restrict floppy access to locally logged-on user only' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AllocateFloppies',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Devices: Allowed to format and eject removable media' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AllocateDASD',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Devices: Prevent users from installing printer drivers' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Print\Providers\LanMan Print Services\Servers\AddPrinterDrivers',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Digitally encrypt or sign secure channel data (always)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireSignOrSeal',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Digitally encrypt secure channel data (when possible)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SealSecureChannel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Digitally sign secure channel data (when possible)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SignSecureChannel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Disable machine account password changes' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Maximum machine account password age' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\MaximumPasswordAge',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Require strong (Windows 2000 or later) session key' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireStrongKey',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Display user information when the session is locked' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLockedUserId',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Machine inactivity limit' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\InactivityTimeoutSecs',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Machine account lockout threshold' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\MaxDevicePasswordFailedAttempts',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network client: Digitally sign communications (always)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\RequireSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network client: Digitally sign communications (if server agrees)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnableSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network client: Send unencrypted password to third-party SMB servers' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnablePlainTextPassword',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Server SPN target name validation level' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters\SmbServerNameHardeningLevel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Amount of idle time required before suspending session' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\AutoDisconnect',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Digitally sign communications (always)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RequireSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Digitally sign communications (if client agrees)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Disconnect clients when logon hours expire' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableForcedLogOff',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Named Pipes that can be accessed anonymously' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionPipes',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Network access: Shares that can be accessed anonymously' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionShares',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Network access: Do not allow anonymous enumeration of SAM accounts and shares' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymous',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Do not allow anonymous enumeration of SAM accounts' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Remotely accessible registry paths and sub-paths' => {
:name => 'MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedPaths\Machine',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Network access: Restrict anonymous access to Named Pipes and Shares' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RestrictNullSessAccess',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: Do not store LAN Manager hash value on next password change' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\NoLMHash',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: LAN Manager authentication level' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\LmCompatibilityLevel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: Minimum session security for NTLM SSP based (including secure RPC) clients' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinClientSec',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: Minimum session security for NTLM SSP based (including secure RPC) servers' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinServerSec',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: LDAP client signing requirements' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LDAP\LDAPClientIntegrity',
:reg_type => "4",
:policy_type => "Registry Values",
},
'System objects: Require case insensitivity for non-Windows subsystems' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\Kernel\ObCaseInsensitive',
:policy_type => "Registry Values",
:reg_type => "4"
},
'System objects: Strengthen default permissions of internal system objects (e.g., Symbolic Links)' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\ProtectionMode',
:policy_type => "Registry Values",
:reg_type => "4"
},
'System settings: Optional subsystems' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\optional',
:policy_type => "Registry Values",
:reg_type => "7"
},
'Shutdown: Clear virtual memory pagefile' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management\ClearPageFileAtShutdown',
:policy_type => "Registry Values",
:reg_type => "4"
},
}
end
end
Constrain WMIC query for local users
Without this commit, the WMIC command that pulls SIDs for mapping will
pull every SID from a Domain if the node is joined. For large domains,
this can be a very lengthy and expensive operation. According to the
comments and method name, this WMIC query is meant to obtain only the
mapping used for local users.
This commit constrains the WMIC query to the domain of `%computername%`
and thus only the local users. This should significantly speed up the
runtime of this module.
#encoding: UTF-8
require 'puppet/provider'
class SecurityPolicy
attr_reader :wmic_cmd
EVENT_TYPES = ["Success,Failure", "Success", "Failure", "No Auditing", 0, 1, 2, 3]
def initialize
# suppose to make an instance method for wmic
@wmic_cmd = Puppet::Provider::CommandDefiner.define('wmic', 'wmic', Puppet::Provider)
end
def wmic(args=[])
case args[0]
when 'useraccount'
@@useraccount ||= wmic_cmd.execute(args).force_encoding('utf-16le').encode('utf-8', :universal_newline => true).gsub("\xEF\xBB\xBF", '')
when 'group'
@@groupaccount ||= wmic_cmd.execute(args).force_encoding('utf-16le').encode('utf-8', :universal_newline => true).gsub("\xEF\xBB\xBF", '')
else
# will not cache
wmic_cmd.execute(args).force_encoding('utf-16le').encode('utf-8', :universal_newline => true).gsub("\xEF\xBB\xBF", '')
end
end
# collect all the local accounts using wmic
def local_accounts
ary = []
["useraccount","group"].each do |lu|
wmic([lu,'where (domain=\'%computername%\')','get', 'name,sid', '/format:csv']).split("\n").each do |line|
next if line =~ /Node/
if line.include? ","
ary << line.strip.split(",")
end
end
end
ary
end
def user_sid_array
@user_sid_array ||= local_accounts + builtin_accounts
end
def user_to_sid(value)
sid = user_sid_array.find do |home,user,sid|
user == value
end
unless sid.nil?
'*' + sid[2]
else
value
end
end
# convert the sid to a user
def sid_to_user(value)
value = value.gsub(/(^\*)/ , '')
user = user_sid_array.find do |home,user,sid|
value == sid
end
unless user.nil?
user[1]
else
value
end
end
def convert_privilege_right(ensure_value, policy_value)
# we need to convert users to sids first
if ensure_value.to_s == 'absent'
pv = ''
else
sids = Array.new
policy_value.split(",").sort.each do |suser|
suser.strip!
sids << user_to_sid(suser)
end
pv = sids.sort.join(",")
end
end
# converts the policy value inside the policy hash to conform to the secedit standards
def convert_policy_hash(policy_hash)
case policy_hash[:policy_type]
when 'Privilege Rights'
value = convert_privilege_right(policy_hash[:ensure], policy_hash[:policy_value])
when 'Event Audit'
value = event_to_audit_id(policy_hash[:policy_value])
when 'Registry Values'
value = SecurityPolicy.convert_registry_value(policy_hash[:name], policy_hash[:policy_value])
else
value = policy_hash[:policy_value]
end
policy_hash[:policy_value] = value
policy_hash
end
def builtin_accounts
# more accounts and SIDs can be found at https://support.microsoft.com/en-us/kb/243330
ary = [
["","NULL","S-1-0"],
["","NOBODY","S-1-0-0"],
["","EVERYONE","S-1-1-0"],
["","LOCAL","S-1-2-0"],
["","CONSOLE_LOGON","S-1-2-1"],
["","CREATOR_OWNER","S-1-3-0"],
["","CREATER_GROUP","S-1-3-1"],
["","OWNER_SERVER","S-1-3-2"],
["","GROUP_SERVER","S-1-3-3"],
["","OWNER_RIGHTS","S-1-3-4"],
["","NT_AUTHORITY","S-1-5"],
["","DIALUP","S-1-5-1"],
["","NETWORK","S-1-5-2"],
["","BATCH","S-1-5-3"],
["","INTERACTIVE","S-1-5-4"],
["","SERVICE","S-1-5-6"],
["","ANONYMOUS","S-1-5-7"],
["","PROXY","S-1-5-8"],
["","ENTERPRISE_DOMAIN_CONTROLLERS","S-1-5-9"],
["","PRINCIPAAL_SELF","S-1-5-10"],
["","AUTHENTICATED_USERS","S-1-5-11"],
["","RESTRICTED_CODE","S-1-5-12"],
["","TERMINAL_SERVER_USER","S-1-5-13"],
["","REMOTE_INTERACTIVE_LOGON","S-1-5-14"],
["","THIS_ORGANIZATION","S-1-5-15"],
["","IUSER","S-1-5-17"],
["","LOCAL_SYSTEM","S-1-5-18"],
["","LOCAL_SERVICE","S-1-5-19"],
["","NETWORK_SERVICE","S-1-5-20"],
["","COMPOUNDED_AUTHENTICATION","S-1-5-21-0-0-0-496"],
["","CLAIMS_VALID","S-1-5-21-0-0-0-497"],
["","BUILTIN_ADMINISTRATORS","S-1-5-32-544"],
["","BUILTIN_USERS","S-1-5-32-545"],
["","BUILTIN_GUESTS","S-1-5-32-546"],
["","POWER_USERS","S-1-5-32-547"],
["","ACCOUNT_OPERATORS","S-1-5-32-548"],
["","SERVER_OPERATORS","S-1-5-32-549"],
["","PRINTER_OPERATORS","S-1-5-32-550"],
["","BACKUP_OPERATORS","S-1-5-32-551"],
["","REPLICATOR","S-1-5-32-552"],
["","ALIAS_PREW2KCOMPACC","S-1-5-32-554"],
["","REMOTE_DESKTOP","S-1-5-32-555"],
["","NETWORK_CONFIGURATION_OPS","S-1-5-32-556"],
["","INCOMING_FOREST_TRUST_BUILDERS","S-1-5-32-557"],
["","PERMON_USERS","S-1-5-32-558"],
["","PERFLOG_USERS","S-1-5-32-559"],
["","WINDOWS_AUTHORIZATION_ACCESS_GROUP","S-1-5-32-560"],
["","TERMINAL_SERVER_LICENSE_SERVERS","S-1-5-32-561"],
["","DISTRIBUTED_COM_USERS","S-1-5-32-562"],
["","IIS_USERS","S-1-5-32-568"],
["","CRYPTOGRAPHIC_OPERATORS","S-1-5-32-569"],
["","EVENT_LOG_READERS","S-1-5-32-573"],
["","CERTIFICATE_SERVICE_DCOM_ACCESS","S-1-5-32-574"],
["","RDS_REMOTE_ACCESS_SERVERS","S-1-5-32-575"],
["","RDS_ENDPOINT_SERVERS","S-1-5-32-576"],
["","RDS_MANAGEMENT_SERVERS","S-1-5-32-577"],
["","HYPER_V_ADMINS","S-1-5-32-578"],
["","ACCESS_CONTROL_ASSISTANCE_OPS","S-1-5-32-579"],
["","REMOTE_MANAGEMENT_USERS","S-1-5-32-580"],
["","WRITE_RESTRICTED_CODE","S-1-5-32-558"],
["","NTLM_AUTHENTICATION","S-1-5-64-10"],
["","SCHANNEL_AUTHENTICATION","S-1-5-64-14"],
["","DIGEST_AUTHENTICATION","S-1-5-64-21"],
["","THIS_ORGANIZATION_CERTIFICATE","S-1-5-65-1"],
["","NT_SERVICE","S-1-5-80"],
["","NT_SERVICE\\ALL_SERVICES","S-1-5-80-0"],
["","NT_SERVICE\\WdiServiceHost","S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420"],
["","USER_MODE_DRIVERS","S-1-5-84-0-0-0-0-0"],
["","LOCAL_ACCOUNT","S-1-5-113"],
["","LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP","S-1-5-114"],
["","OTHER_ORGANIZATION","S-1-5-1000"],
["","ALL_APP_PACKAGES","S-1-15-2-1"],
["","ML_UNTRUSTED","S-1-16-0"],
["","ML_LOW","S-1-16-4096"],
["","ML_MEDIUM","S-1-16-8192"],
["","ML_MEDIUM_PLUS","S-1-16-8448"],
["","ML_HIGH","S-1-15-12288"],
["","ML_SYSTEM","S-1-16-16384"],
["","ML_PROTECTED_PROCESS","S-1-16-20480"],
["","AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY","S-1-18-1"],
["","SERVICE_ASSERTED_IDENTITY","S-1-18-2"]
]
ary
end
# Converts a event number to a word
def self.event_audit_mapper(policy_value)
case policy_value.to_s
when 3
return "Success,Failure"
when 2
return "Failure"
when 1
return "Success"
else
return "No auditing"
end
end
# Converts a event number to a word
def self.event_to_audit_id(event_audit_name)
case event_audit_name
when "Success,Failure"
return 3
when "Failure"
return 2
when "Success"
return 1
when 'No auditing'
return 0
else
return event_audit_name
end
end
# returns the key and hash value given the policy name
def self.find_mapping_from_policy_name(name)
key, value = lsp_mapping.find do |key,hash|
hash[:name] == name
end
unless key && value
raise KeyError, "#{name} is not a valid policy"
end
return key, value
end
# returns the key and hash value given the policy desc
def self.find_mapping_from_policy_desc(desc)
name = desc.downcase
value = nil
key, value = lsp_mapping.find do |key, hash|
key.downcase == name
end
unless value
raise KeyError, "#{desc} is not a valid policy"
end
return value
end
def self.valid_lsp?(name)
lsp_mapping.keys.include?(name)
end
def self.convert_registry_value(name, value)
value = value.to_s
return value if value.split(',').count > 1
policy_hash = find_mapping_from_policy_desc(name)
"#{policy_hash[:reg_type]},#{value}"
end
# converts the policy value to machine values
def self.convert_policy_value(policy_hash, value)
sp = SecurityPolicy.new
# I would rather not have to look this info up, but the type code will not always have this info handy
# without knowing the policy type we can't figure out what to convert
policy_type = find_mapping_from_policy_desc(policy_hash[:name])[:policy_type]
case policy_type.to_s
when 'Privilege Rights'
sp.convert_privilege_right(policy_hash[:ensure], value)
when 'Event Audit'
event_to_audit_id(value)
when 'Registry Values'
# convert the value to a datatype/value
convert_registry_value(policy_hash[:name], value)
else
value
end
end
def self.lsp_mapping
@lsp_mapping ||= {
# Password policy Mappings
'Enforce password history' => {
:name => 'PasswordHistorySize',
:policy_type => 'System Access',
},
'Maximum password age' => {
:name => 'MaximumPasswordAge',
:policy_type => 'System Access',
},
'Minimum password age' => {
:name => 'MinimumPasswordAge',
:policy_type => 'System Access',
},
'Minimum password length' => {
:name => 'MinimumPasswordLength',
:policy_type => 'System Access',
},
'Password must meet complexity requirements' => {
:name => 'PasswordComplexity',
:policy_type => 'System Access',
},
'Store passwords using reversible encryption' => {
:name => 'ClearTextPassword',
:policy_type => 'System Access',
},
'Account lockout threshold' => {
:name => 'LockoutBadCount',
:policy_type => 'System Access',
},
'Account lockout duration' => {
:name => 'LockoutDuration',
:policy_type => 'System Access',
},
'Reset account lockout counter after' => {
:name => 'ResetLockoutCount',
:policy_type => 'System Access',
},
'Accounts: Rename administrator account' => {
:name => 'NewAdministratorName',
:policy_type => 'System Access',
:data_type => :quoted_string
},
'Accounts: Rename guest account' => {
:name => 'NewGuestName',
:policy_type => 'System Access',
:data_type => :quoted_string
},
'Accounts: Require Login to Change Password' => {
:name => 'RequireLogonToChangePassword',
:policy_type => 'System Access'
},
'Network security: Force logoff when logon hours expire' => {
:name => 'ForceLogoffWhenHourExpire',
:policy_type => 'System Access'
},
'Network access: Allow anonymous SID/name translation' => {
:name => 'LSAAnonymousNameLookup',
:policy_type => 'System Access'
},
'EnableAdminAccount' => {
:name => 'EnableAdminAccount',
:policy_type => 'System Access'
},
"EnableGuestAccount"=>{
:name=>"EnableGuestAccount",
:policy_type => 'System Access'
},
# Audit Policy Mappings
'Audit account logon events' => {
:name => 'AuditAccountLogon',
:policy_type => 'Event Audit',
},
'Audit account management' => {
:name => 'AuditAccountManage',
:policy_type => 'Event Audit',
},
'Audit directory service access' => {
:name => 'AuditDSAccess',
:policy_type => 'Event Audit',
},
'Audit logon events' => {
:name => 'AuditLogonEvents',
:policy_type => 'Event Audit',
},
'Audit object access' => {
:name => 'AuditObjectAccess',
:policy_type => 'Event Audit',
},
'Audit policy change' => {
:name => 'AuditPolicyChange',
:policy_type => 'Event Audit',
},
'Audit privilege use' => {
:name => 'AuditPrivilegeUse',
:policy_type => 'Event Audit',
},
'Audit process tracking' => {
:name => 'AuditProcessTracking',
:policy_type => 'Event Audit',
},
'Audit system events' => {
:name => 'AuditSystemEvents',
:policy_type => 'Event Audit',
},
'Audit: Force audit policy subcategory settings (Windows Vista or later) to override audit policy category settings' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\SCENoApplyLegacyAuditPolicy',
:reg_type => '4',
:policy_type => 'Registry Values',
},
#User rights mapping
'Access Credential Manager as a trusted caller' => {
:name => 'SeTrustedCredManAccessPrivilege',
:policy_type => 'Privilege Rights',
},
'Access this computer from the network' => {
:name => 'SeNetworkLogonRight',
:policy_type => 'Privilege Rights',
},
'Act as part of the operating system' => {
:name => 'SeTcbPrivilege',
:policy_type => 'Privilege Rights',
},
'Add workstations to domain' => {
:name => 'SeMachineAccountPrivilege',
:policy_type => 'Privilege Rights',
},
'Adjust memory quotas for a process' => {
:name => 'SeIncreaseQuotaPrivilege',
:policy_type => 'Privilege Rights',
},
'Allow log on locally' => {
:name => 'SeInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Allow log on through Remote Desktop Services' => {
:name => 'SeRemoteInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Back up files and directories' => {
:name => 'SeBackupPrivilege',
:policy_type => 'Privilege Rights',
},
'Bypass traverse checking' => {
:name => 'SeChangeNotifyPrivilege',
:policy_type => 'Privilege Rights',
},
'Change the system time' => {
:name => 'SeSystemtimePrivilege',
:policy_type => 'Privilege Rights',
},
'Change the time zone' => {
:name => 'SeTimeZonePrivilege',
:policy_type => 'Privilege Rights',
},
'Create a pagefile' => {
:name => 'SeCreatePagefilePrivilege',
:policy_type => 'Privilege Rights',
},
'Create a token object' => {
:name => 'SeCreateTokenPrivilege',
:policy_type => 'Privilege Rights',
},
'Create global objects' => {
:name => 'SeCreateGlobalPrivilege',
:policy_type => 'Privilege Rights',
},
'Create permanent shared objects' => {
:name => 'SeCreatePermanentPrivilege',
:policy_type => 'Privilege Rights',
},
'Create symbolic links' => {
:name => 'SeCreateSymbolicLinkPrivilege',
:policy_type => 'Privilege Rights',
},
'Debug programs' => {
:name => 'SeDebugPrivilege',
:policy_type => 'Privilege Rights',
},
'Deny access to this computer from the network' => {
:name => 'SeDenyNetworkLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on as a batch job' => {
:name => 'SeDenyBatchLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on as a service' => {
:name => 'SeDenyServiceLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on locally' => {
:name => 'SeDenyInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Deny log on through Remote Desktop Services' => {
:name => 'SeDenyRemoteInteractiveLogonRight',
:policy_type => 'Privilege Rights',
},
'Enable computer and user accounts to be trusted for delegation' => {
:name => 'SeEnableDelegationPrivilege',
:policy_type => 'Privilege Rights',
},
'Force shutdown from a remote system' => {
:name => 'SeRemoteShutdownPrivilege',
:policy_type => 'Privilege Rights',
},
'Generate security audits' => {
:name => 'SeAuditPrivilege',
:policy_type => 'Privilege Rights',
},
'Impersonate a client after authentication' => {
:name => 'SeImpersonatePrivilege',
:policy_type => 'Privilege Rights',
},
'Increase a process working set' => {
:name => 'SeIncreaseWorkingSetPrivilege',
:policy_type => 'Privilege Rights',
},
'Increase scheduling priority' => {
:name => 'SeIncreaseBasePriorityPrivilege',
:policy_type => 'Privilege Rights',
},
'Load and unload device drivers' => {
:name => 'SeLoadDriverPrivilege',
:policy_type => 'Privilege Rights',
},
'Lock pages in memory' => {
:name => 'SeLockMemoryPrivilege',
:policy_type => 'Privilege Rights',
},
'Log on as a batch job' => {
:name => 'SeBatchLogonRight',
:policy_type => 'Privilege Rights',
},
'Log on as a service' => {
:name => 'SeServiceLogonRight',
:policy_type => 'Privilege Rights',
},
'Manage auditing and security log' => {
:name => 'SeSecurityPrivilege',
:policy_type => 'Privilege Rights',
},
'Modify an object label' => {
:name => 'SeRelabelPrivilege',
:policy_type => 'Privilege Rights',
},
'Modify firmware environment values' => {
:name => 'SeSystemEnvironmentPrivilege',
:policy_type => 'Privilege Rights',
},
'Perform volume maintenance tasks' => {
:name => 'SeManageVolumePrivilege',
:policy_type => 'Privilege Rights',
},
'Profile single process' => {
:name => 'SeProfileSingleProcessPrivilege',
:policy_type => 'Privilege Rights',
},
'Profile system performance' => {
:name => 'SeSystemProfilePrivilege',
:policy_type => 'Privilege Rights',
},
'Remove computer from docking station' => {
:name => 'SeUndockPrivilege',
:policy_type => 'Privilege Rights',
},
'Replace a process level token' => {
:name => 'SeAssignPrimaryTokenPrivilege',
:policy_type => 'Privilege Rights',
},
'Restore files and directories' => {
:name => 'SeRestorePrivilege',
:policy_type => 'Privilege Rights',
},
'Shut down the system' => {
:name => 'SeShutdownPrivilege',
:policy_type => 'Privilege Rights',
},
'Synchronize directory service data' => {
:name => 'SeSyncAgentPrivilege',
:policy_type => 'Privilege Rights',
},
'Take ownership of files or other objects' => {
:name => 'SeTakeOwnershipPrivilege',
:policy_type => 'Privilege Rights',
},
#Registry Keys
'Recovery console: Allow automatic administrative logon' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SecurityLevel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Recovery console: Allow floppy copy and access to all drives and all folders' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Setup\RecoveryConsole\SetCommand',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Number of previous logons to cache (in case domain controller is not available)' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\CachedLogonsCount',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Interactive logon: Require Domain Controller authentication to unlock workstation' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ForceUnlockLogon',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Prompt user to change password before expiration' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\PasswordExpiryWarning',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Smart card removal behavior' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\ScRemoveOption',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorAdmin',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Behavior of the elevation prompt for standard users' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ConsentPromptBehaviorUser',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Do not require CTRL+ALT+DEL' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DisableCAD',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Do not display last user name' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLastUserName',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Detect application installations and prompt for elevation' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableInstallerDetection',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Run all administrators in Admin Approval Mode' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUA',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Only elevate UIAccess applications that are installed in secure locations' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableSecureUIAPaths',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Allow UIAccess applications to prompt for elevation without using the secure desktop' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableUIADesktopToggle',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Virtualize file and registry write failures to per-user locations' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\EnableVirtualization',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Admin Approval Mode for the Built-in Administrator account' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\FilterAdministratorToken',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Message title for users attempting to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeCaption',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Interactive logon: Message text for users attempting to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\LegalNoticeText',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'User Account Control: Switch to the secure desktop when prompting for elevation' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\PromptOnSecureDesktop',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Require smart card' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ScForceOption',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Shutdown: Allow system to be shut down without having to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ShutdownWithoutLogon',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Devices: Allow undock without having to log on' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\UndockWithoutLogon',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'User Account Control: Only elevate executables that are signed and validated' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ValidateAdminCodeSignatures',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'System settings: Use Certificate Rules on Windows Executables for Software Restriction Policies' => {
:name => 'MACHINE\Software\Policies\Microsoft\Windows\Safer\CodeIdentifiers\AuthenticodeEnabled',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Audit: Audit the access of global system objects' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\AuditBaseObjects',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Audit: Shut down system immediately if unable to log security audits' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\CrashOnAuditFail',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Do not allow storage of passwords and credentials for network authentication' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\DisableDomainCreds',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Let Everyone permissions apply to anonymous users' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\EveryoneIncludesAnonymous',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Sharing and security model for local accounts' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\ForceGuest',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'System cryptography: Use FIPS compliant algorithms for encryption, hashing, and signing' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'System cryptography: Force strong key protection for user keys stored on the computer' => {
:name => 'MACHINE\Software\Policies\Microsoft\Cryptography\ForceKeyProtection',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Audit: Audit the use of Backup and Restore privilege' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\FullPrivilegeAuditing',
:reg_type => '3',
:policy_type => 'Registry Values',
},
'Accounts: Block Microsoft accounts' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\NoConnectedUser',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Accounts: Limit local account use of blank passwords to console logon only' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\LimitBlankPasswordUse',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: All Local System to use computer identity for NTLM' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\UseMachineId',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Remotely accessible registry paths' => {
:name => 'MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedExactPaths\Machine',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Devices: Restrict CD-ROM access to locally logged-on user only' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AllocateCDRoms',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Devices: Restrict floppy access to locally logged-on user only' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AllocateFloppies',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Devices: Allowed to format and eject removable media' => {
:name => 'MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\AllocateDASD',
:reg_type => '1',
:policy_type => 'Registry Values',
},
'Devices: Prevent users from installing printer drivers' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Print\Providers\LanMan Print Services\Servers\AddPrinterDrivers',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Digitally encrypt or sign secure channel data (always)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireSignOrSeal',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Digitally encrypt secure channel data (when possible)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SealSecureChannel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Digitally sign secure channel data (when possible)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\SignSecureChannel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Disable machine account password changes' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\DisablePasswordChange',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Maximum machine account password age' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\MaximumPasswordAge',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Domain member: Require strong (Windows 2000 or later) session key' => {
:name => 'MACHINE\System\CurrentControlSet\Services\Netlogon\Parameters\RequireStrongKey',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Display user information when the session is locked' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\DontDisplayLockedUserId',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Machine inactivity limit' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\InactivityTimeoutSecs',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Interactive logon: Machine account lockout threshold' => {
:name => 'MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\MaxDevicePasswordFailedAttempts',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network client: Digitally sign communications (always)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\RequireSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network client: Digitally sign communications (if server agrees)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnableSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network client: Send unencrypted password to third-party SMB servers' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanWorkstation\Parameters\EnablePlainTextPassword',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Server SPN target name validation level' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters\SmbServerNameHardeningLevel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Amount of idle time required before suspending session' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\AutoDisconnect',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Digitally sign communications (always)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RequireSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Digitally sign communications (if client agrees)' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableSecuritySignature',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Microsoft network server: Disconnect clients when logon hours expire' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\EnableForcedLogOff',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Named Pipes that can be accessed anonymously' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionPipes',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Network access: Shares that can be accessed anonymously' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\NullSessionShares',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Network access: Do not allow anonymous enumeration of SAM accounts and shares' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymous',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Do not allow anonymous enumeration of SAM accounts' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\RestrictAnonymousSAM',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network access: Remotely accessible registry paths and sub-paths' => {
:name => 'MACHINE\System\CurrentControlSet\Control\SecurePipeServers\Winreg\AllowedPaths\Machine',
:reg_type => '7',
:policy_type => 'Registry Values',
},
'Network access: Restrict anonymous access to Named Pipes and Shares' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LanManServer\Parameters\RestrictNullSessAccess',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: Do not store LAN Manager hash value on next password change' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\NoLMHash',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: LAN Manager authentication level' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\LmCompatibilityLevel',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: Minimum session security for NTLM SSP based (including secure RPC) clients' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinClientSec',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: Minimum session security for NTLM SSP based (including secure RPC) servers' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Lsa\MSV1_0\NTLMMinServerSec',
:reg_type => '4',
:policy_type => 'Registry Values',
},
'Network security: LDAP client signing requirements' => {
:name => 'MACHINE\System\CurrentControlSet\Services\LDAP\LDAPClientIntegrity',
:reg_type => "4",
:policy_type => "Registry Values",
},
'System objects: Require case insensitivity for non-Windows subsystems' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\Kernel\ObCaseInsensitive',
:policy_type => "Registry Values",
:reg_type => "4"
},
'System objects: Strengthen default permissions of internal system objects (e.g., Symbolic Links)' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\ProtectionMode',
:policy_type => "Registry Values",
:reg_type => "4"
},
'System settings: Optional subsystems' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\SubSystems\optional',
:policy_type => "Registry Values",
:reg_type => "7"
},
'Shutdown: Clear virtual memory pagefile' => {
:name => 'MACHINE\System\CurrentControlSet\Control\Session Manager\Memory Management\ClearPageFileAtShutdown',
:policy_type => "Registry Values",
:reg_type => "4"
},
}
end
end
|
module PuppetX
module Puppetlabs
module Registry
# For 64-bit OS, use 64-bit view. Ignored on 32-bit OS
KEY_WOW64_64KEY = 0x100
# For 64-bit OS, use 32-bit view. Ignored on 32-bit OS
KEY_WOW64_32KEY = 0x200 unless defined? KEY_WOW64_32KEY
def self.hkeys
{
:hkcr => Win32::Registry::HKEY_CLASSES_ROOT,
:hklm => Win32::Registry::HKEY_LOCAL_MACHINE,
:hku => Win32::Registry::HKEY_USERS,
}
end
def self.hive
hkeys[root]
end
def self.type2name_map
{
Win32::Registry::REG_NONE => :none,
Win32::Registry::REG_SZ => :string,
Win32::Registry::REG_EXPAND_SZ => :expand,
Win32::Registry::REG_BINARY => :binary,
Win32::Registry::REG_DWORD => :dword,
Win32::Registry::REG_QWORD => :qword,
Win32::Registry::REG_MULTI_SZ => :array
}
end
def self.type2name(type)
type2name_map[type]
end
def self.name2type(name)
name2type = {}
type2name_map.each_pair {|k,v| name2type[v] = k}
name2type[name]
end
# This is the base class for Path manipulation. This class is meant to be
# abstract, RegistryKeyPath and RegistryValuePath will customize and override
# this class.
class RegistryPathBase < String
attr_reader :path
def initialize(path)
@filter_path_memo = nil
@path ||= path
super(path)
end
# The path is valid if we're able to parse it without exceptions.
def valid?
(filter_path and true) rescue false
end
def canonical
filter_path[:canonical]
end
# This method is meant to help setup aliases so autorequire can sort itself
# out in a case insensitive but preserving manner. It returns an array of
# resource identifiers.
def aliases
[canonical.downcase]
end
def access
filter_path[:access]
end
def root
filter_path[:root]
end
def subkey
filter_path[:trailing_path]
end
def ascend(&block)
p = canonical
while idx = p.rindex('\\')
p = p[0, idx]
yield p
end
end
private
def filter_path
if @filter_path_memo
return @filter_path_memo
end
result = {}
path = @path
# Strip off any trailing slash.
path = path.gsub(/\\*$/, '')
unless captures = /^(32:)?([h|H][^\\]*)((?:\\[^\\]{1,255})*)$/.match(path)
raise ArgumentError, "Invalid registry key: #{path}"
end
case captures[1]
when '32:'
result[:access] = PuppetX::Puppetlabs::Registry::KEY_WOW64_32KEY
result[:prefix] = '32:'
else
result[:access] = PuppetX::Puppetlabs::Registry::KEY_WOW64_64KEY
result[:prefix] = ''
end
# canonical root key symbol
result[:root] = case captures[2].to_s.downcase
when /hkey_local_machine/, /hklm/
:hklm
when /hkey_classes_root/, /hkcr/
:hkcr
when /hkey_users/, /hku/
:hku
when /hkey_current_user/, /hkcu/,
/hkey_current_config/, /hkcc/,
/hkey_performance_data/,
/hkey_performance_text/,
/hkey_performance_nlstext/,
/hkey_dyn_data/
raise ArgumentError, "Unsupported predefined key: #{path}"
else
raise ArgumentError, "Invalid registry key: #{path}"
end
result[:trailing_path] = captures[3]
result[:trailing_path].gsub!(/^\\/, '')
if result[:trailing_path].empty?
result[:canonical] = "#{result[:prefix]}#{result[:root].to_s}"
else
# Leading backslash is not part of the subkey name
result[:canonical] = "#{result[:prefix]}#{result[:root].to_s}\\#{result[:trailing_path]}"
end
@filter_path_memo = result
end
end
class RegistryKeyPath < RegistryPathBase
end
class RegistryValuePath < RegistryPathBase
attr_reader :valuename
# Combines a registry key path and valuename into a resource title for
# registry_value resource.
#
# To maintain backwards compatibility, only use the double backslash
# delimiter if the valuename actually contains a backslash
def self.combine_path_and_value(keypath, valuename)
if valuename.include?('\\')
keypath + '\\\\' + valuename
else
keypath + '\\' + valuename
end
end
# Extract the valuename from the path and then munge the actual path
def initialize(path)
# valuename appears after the the first double backslash
path, @valuename = path.split('\\\\', 2)
# found \\ so nearly done parsing
if !@valuename.nil?
@is_default = @valuename.empty?
# no \\ but there is at least a single \
elsif path.include?('\\')
path, _, @valuename = path.rpartition('\\')
@is_default = @valuename.empty?
# a hive name that contains no \
else
@valuename = ''
@is_default = false
end
super(path)
end
def canonical
# Because we extracted the valuename in the initializer we
# need to add it back in when canonical is called.
if valuename.include?('\\')
filter_path[:canonical] + '\\\\' + valuename
else
filter_path[:canonical] + '\\' + valuename
end
end
def default?
@is_default
end
def filter_path
result = super
# It's possible to pass in a path of 'hklm' which can still be parsed, but is not valid registry key. Only the default value 'hklm\'
# and named values 'hklm\something' are allowed
raise ArgumentError, "Invalid registry key: #{path}" if result[:trailing_path].empty? && valuename.empty? && !default?
result
end
end
end
end
end
(MODULES-2957) RegistryValuePath missing \ error
- Previous code entered a flow that made little sense, given paths
without at least a single \ are unsupported.
For instance, `hklm` is invalid, but `hklm\` is considered valid
per the documentation inside specs of type\registry_value_spec.rb
Raising an error was deferred unnecessarily to the valid? check
implemented on the base class, but is fixed here to make the code
easier to understand.
module PuppetX
module Puppetlabs
module Registry
# For 64-bit OS, use 64-bit view. Ignored on 32-bit OS
KEY_WOW64_64KEY = 0x100
# For 64-bit OS, use 32-bit view. Ignored on 32-bit OS
KEY_WOW64_32KEY = 0x200 unless defined? KEY_WOW64_32KEY
def self.hkeys
{
:hkcr => Win32::Registry::HKEY_CLASSES_ROOT,
:hklm => Win32::Registry::HKEY_LOCAL_MACHINE,
:hku => Win32::Registry::HKEY_USERS,
}
end
def self.hive
hkeys[root]
end
def self.type2name_map
{
Win32::Registry::REG_NONE => :none,
Win32::Registry::REG_SZ => :string,
Win32::Registry::REG_EXPAND_SZ => :expand,
Win32::Registry::REG_BINARY => :binary,
Win32::Registry::REG_DWORD => :dword,
Win32::Registry::REG_QWORD => :qword,
Win32::Registry::REG_MULTI_SZ => :array
}
end
def self.type2name(type)
type2name_map[type]
end
def self.name2type(name)
name2type = {}
type2name_map.each_pair {|k,v| name2type[v] = k}
name2type[name]
end
# This is the base class for Path manipulation. This class is meant to be
# abstract, RegistryKeyPath and RegistryValuePath will customize and override
# this class.
class RegistryPathBase < String
attr_reader :path
def initialize(path)
@filter_path_memo = nil
@path ||= path
super(path)
end
# The path is valid if we're able to parse it without exceptions.
def valid?
(filter_path and true) rescue false
end
def canonical
filter_path[:canonical]
end
# This method is meant to help setup aliases so autorequire can sort itself
# out in a case insensitive but preserving manner. It returns an array of
# resource identifiers.
def aliases
[canonical.downcase]
end
def access
filter_path[:access]
end
def root
filter_path[:root]
end
def subkey
filter_path[:trailing_path]
end
def ascend(&block)
p = canonical
while idx = p.rindex('\\')
p = p[0, idx]
yield p
end
end
private
def filter_path
if @filter_path_memo
return @filter_path_memo
end
result = {}
path = @path
# Strip off any trailing slash.
path = path.gsub(/\\*$/, '')
unless captures = /^(32:)?([h|H][^\\]*)((?:\\[^\\]{1,255})*)$/.match(path)
raise ArgumentError, "Invalid registry key: #{path}"
end
case captures[1]
when '32:'
result[:access] = PuppetX::Puppetlabs::Registry::KEY_WOW64_32KEY
result[:prefix] = '32:'
else
result[:access] = PuppetX::Puppetlabs::Registry::KEY_WOW64_64KEY
result[:prefix] = ''
end
# canonical root key symbol
result[:root] = case captures[2].to_s.downcase
when /hkey_local_machine/, /hklm/
:hklm
when /hkey_classes_root/, /hkcr/
:hkcr
when /hkey_users/, /hku/
:hku
when /hkey_current_user/, /hkcu/,
/hkey_current_config/, /hkcc/,
/hkey_performance_data/,
/hkey_performance_text/,
/hkey_performance_nlstext/,
/hkey_dyn_data/
raise ArgumentError, "Unsupported predefined key: #{path}"
else
raise ArgumentError, "Invalid registry key: #{path}"
end
result[:trailing_path] = captures[3]
result[:trailing_path].gsub!(/^\\/, '')
if result[:trailing_path].empty?
result[:canonical] = "#{result[:prefix]}#{result[:root].to_s}"
else
# Leading backslash is not part of the subkey name
result[:canonical] = "#{result[:prefix]}#{result[:root].to_s}\\#{result[:trailing_path]}"
end
@filter_path_memo = result
end
end
class RegistryKeyPath < RegistryPathBase
end
class RegistryValuePath < RegistryPathBase
attr_reader :valuename
# Combines a registry key path and valuename into a resource title for
# registry_value resource.
#
# To maintain backwards compatibility, only use the double backslash
# delimiter if the valuename actually contains a backslash
def self.combine_path_and_value(keypath, valuename)
if valuename.include?('\\')
keypath + '\\\\' + valuename
else
keypath + '\\' + valuename
end
end
# Extract the valuename from the path and then munge the actual path
def initialize(path)
raise ArgumentError, "Invalid registry key: #{path}" if !path.include?('\\')
# valuename appears after the the first double backslash
path, @valuename = path.split('\\\\', 2)
# found \\ so nearly done parsing
if !@valuename.nil?
@is_default = @valuename.empty?
# no \\ but there is at least a single \
else
path, _, @valuename = path.rpartition('\\')
@is_default = @valuename.empty?
end
super(path)
end
def canonical
# Because we extracted the valuename in the initializer we
# need to add it back in when canonical is called.
if valuename.include?('\\')
filter_path[:canonical] + '\\\\' + valuename
else
filter_path[:canonical] + '\\' + valuename
end
end
def default?
@is_default
end
def filter_path
result = super
# It's possible to pass in a path of 'hklm' which can still be parsed, but is not valid registry key. Only the default value 'hklm\'
# and named values 'hklm\something' are allowed
raise ArgumentError, "Invalid registry key: #{path}" if result[:trailing_path].empty? && valuename.empty? && !default?
result
end
end
end
end
end
|
require 'parallel'
require 'fileutils'
require 'json'
module Quanto
class Records
class Summary
#
# Merge tsv
#
def merge(format, outdir, metadata_dir, experiment_metadata, biosample_metadata, ow)
@format = format
@outdir = outdir
@exp_metadata = experiment_metadata
@bs_metadata = biosample_metadata
@overwrite = ow
if @format == "tsv"
# data object to merge, method defined in sumamry.rb
@objects = create_fastqc_data_objects(@list_fastqc_zip_path)
# sra metadata location
@metadata_dir = metadata_dir
# data to each type
assemble
# link annotation to each samples
annotate_samples
end
end
def assemble
puts "==> #{Time.now} Assembling Reads..."
merge_reads
puts "==> #{Time.now} Assembling Run..."
create_run_summary
puts "==> #{Time.now} Assembling Experiments..."
create_exp_summary
puts "==> #{Time.now} Assembling Samples..."
create_sample_summary
end
#
# Merge single read summary file to one tsv
#
def merge_reads
@reads_fpath = output_fpath("quanto.reads.tsv")
if !output_exist?(@reads_fpath)
File.open(@reads_fpath, 'w') do |file|
file.puts(tsv_header[0..-1].join("\t"))
@objects.each do |obj|
file.puts(open(obj[:summary_path]).read.chomp)
end
end
end
end
#
# Merge data
#
def create_run_summary
@runs_fpath = output_fpath("quanto.runs.tsv")
if !output_exist?(@runs_fpath)
merge_dataset(
@runs_fpath,
:read_to_run,
tsv_header.drop(1).insert(0, "run_id"),
reads_by_runid
)
end
end
def create_exp_summary
@experiments_fpath = output_fpath("quanto.exp.tsv")
if !output_exist?(@experiments_fpath)
merge_dataset(
@experiments_fpath,
:run_to_exp,
tsv_header.drop(1).insert(0, "experiment_id", "run_id"),
runs_by_expid
)
end
end
def create_sample_summary
@samples_fpath = output_fpath("quanto.sample.tsv")
if !output_exist?(@samples_fpath)
merge_dataset(
@samples_fpath,
:exp_to_sample,
tsv_header.drop(1).insert(0, "sample_id", "experiment_id", "run_id"),
exps_by_sampleid
)
end
end
def merge_dataset(outpath, type, header, id_data_pairs)
File.open(outpath, 'w') do |file|
file.puts(header.join("\t"))
id_data_pairs.each_pair do |id, data|
file.puts(merge_data_by_type(type, id, data))
end
end
end
def merge_data_by_type(type, id, data)
case type
when :read_to_run
merge_read_to_run(id, data)
when :run_to_exp
merge_run_to_exp(id, data)
when :exp_to_sample
merge_exp_to_sample(id, data)
end
end
#
# Merge reads to run
#
def merge_read_to_run(runid, reads)
if reads.size == 1
(reads[0].drop(1).insert(0, runid) << "SINGLE").join("\t")
else
pairs = remove_nonpair(reads)
if pairs.size == 2
merge_data(remove_nonpair(reads)).join("\t")
else
"IMPERFECT PAIR DETECTED"
end
end
end
def remove_nonpair(reads)
reads.select{|read| read[0] =~ /_._/ }
end
def reads_by_runid
hash = {}
reads = open(@reads_fpath).readlines.drop(1)
reads.each do |read|
runid = read.split("_")[0]
hash[runid] ||= []
hash[runid] << read.chomp.split("\t")
end
hash
end
#
# Merge reads to experiment
#
def merge_run_to_exp(expid, runs)
if runs.size == 1
([expid] + runs[0]).join("\t")
else
data = merge_data(runs)
([expid] + data).join("\t")
end
end
def runs_by_expid
run_data = data_by_id(@runs_fpath)
exp_run = `cat #{run_members_path} | awk -F '\t' '$8 == "live" { print $3 "\t" $1 }'`.split("\n")
hash = {}
exp_run.each do |e_r|
er = e_r.split("\t")
run = run_data[er[1]]
if run
hash[er[0]] ||= []
hash[er[0]] << run
end
end
hash
end
#
# Merge experiments to sample
#
def merge_exp_to_sample(sampleid, exps)
exps.map{|exp| ([sampleid] + exp).join("\t") }.join("\n")
end
# return hash like { "DRS000001" => ["DRX000001"], ... }
# key: SRA sample ID, value: array of SRA experiment ID
def exps_by_sampleid
exp_data = data_by_id(@experiments_fpath)
sample_exp = `cat #{run_members_path} | awk -F '\t' '$8 == "live" { print $4 "\t" $3 }' | sort -u`.split("\n")
hash = {}
sample_exp.each do |s_e|
se = s_e.split("\t")
exp = exp_data[se[1]]
if exp
hash[se[0]] ||= []
hash[se[0]] << exp
end
end
hash
end
#
# annotate tsv with metadata
#
def metadata_header
[
"biosample_id",
"taxonomy_id",
"taxonomy_scientific_name",
"genome_size",
"coverage",
"library_strategy",
"library_source",
"library_selection",
"instrument_model",
]
end
def annotate_samples
exp_hash = create_metadata_hash(@exp_metadata, 0)
bs_hash = create_metadata_hash(@bs_metadata, 1)
sample_data = open(@samples_fpath).readlines
header = [sample_data.shift.chomp].push(metadata_header).join("\t")
annotated = Parallel.map(sample_data, :in_threads => @@nop) do |line|
data = line.chomp.split("\t")
bsm = bs_hash[data[0]]
coverage = if bsm[3] != "NA"
data[7].to_f / bsm[3].to_f * 1_000_000
else
"NA"
end
[
data,
bsm,
coverage,
exp_hash[data[1]],
].flatten.join("\t")
end
open(output_fpath("quanto.annotated.tsv"), 'w'){|f| f.puts([header, annotated]) }
end
def sample_by_experiment
`cat #{run_members_path} | awk -F '\t' '$8 == "live" { print $3 "\t" $4 "\t" $9 }' | sort -u`.split("\n").map{|line| l = line.split("\t"); [l[0], [l[1], l[2]]] }.to_h
end
def create_metadata_hash(path, id_col)
hash = {}
open(path).readlines.each do |line|
data = line.chomp.split("\t")
id = data.delete_at(id_col)
hash[id] = data
end
hash
end
#
# Protected methods for data merge
#
protected
def run_members_path
File.join(@metadata_dir, "SRA_Run_Members")
end
def output_fpath(fname)
File.join(@outdir, fname)
end
def output_exist?(fpath) # true to skip creation
if File.exist?(fpath)
if @overwrite
backup_dir = File.join(@outdir, "backup", Time.now.strftime("%Y%m%d"))
FileUtils.mkdir_p(backup_dir)
FileUtils.mv(fpath, backup_dir)
false
else
true
end
end
end
def data_by_id(data_fpath)
data = open(data_fpath).readlines.drop(1)
hash = {}
data.each do |d|
id = d.split("\t")[0]
hash[id] = d.chomp.split("\t")
end
hash
end
def merge_data(data_list)
data_scheme.map.with_index do |method, i|
self.send(method, i, data_list)
end
end
def data_scheme
[
:join_ids, # Run id
:join_literals, # fastqc version
:join_literals, # filename
:join_literals, # file type
:join_literals, # encoding
:sum_floats, # total sequences
:sum_floats, # filtered sequences
:mean_floats, # sequence length
:mean_floats, # min seq length
:mean_floats, # max seq length
:mean_floats, # mean sequence length
:mean_floats, # median sequence length
:sum_reads_percent, # percent gc
:sum_reads_percent, # total duplication percentage
:mean_floats, # overall mean quality
:mean_floats, # overall median quality
:mean_floats, # overall n content
:layout_paired, # layout
]
end
def join_ids(i, data)
data.map{|d| d[i].split("_")[0] }.uniq.join(",")
end
def join_literals(i, data)
data.map{|d| d[i] }.uniq.join(",")
end
def sum_floats(i, data)
data.map{|d| d[i].to_f }.reduce(:+)
end
def mean_floats(i, data)
sum_floats(i, data) / 2
end
def sum_reads_percent(i, data)
total_reads = data.map{|d| d[5].to_f }.reduce(:+)
total_count = data.map{|d| percent_to_read_count(i, d) }.reduce(:+)
(total_count / total_reads) * 100
end
def percent_to_read_count(i, data)
data[5].to_f * (data[i].to_f / 100)
end
def layout_paired(i, data)
"PAIRED"
end
def tsv_header
[
"ID",
"fastqc_version",
"filename",
"file_type",
"encoding",
"total_sequences",
"filtered_sequences",
"sequence_length",
"min_sequence_length",
"max_sequence_length",
"mean_sequence_length",
"median_sequence_length",
"percent_gc",
"total_duplicate_percentage",
"overall_mean_quality_score",
"overall_median_quality_score",
"overall_n_content",
"read_layout",
]
end
end
end
end
fixed a bug on handling invalid sampleid
require 'parallel'
require 'fileutils'
require 'json'
module Quanto
class Records
class Summary
#
# Merge tsv
#
def merge(format, outdir, metadata_dir, experiment_metadata, biosample_metadata, ow)
@format = format
@outdir = outdir
@exp_metadata = experiment_metadata
@bs_metadata = biosample_metadata
@overwrite = ow
if @format == "tsv"
# data object to merge, method defined in sumamry.rb
@objects = create_fastqc_data_objects(@list_fastqc_zip_path)
# sra metadata location
@metadata_dir = metadata_dir
# data to each type
assemble
# link annotation to each samples
annotate_samples
end
end
def assemble
puts "==> #{Time.now} Assembling Reads..."
merge_reads
puts "==> #{Time.now} Assembling Run..."
create_run_summary
puts "==> #{Time.now} Assembling Experiments..."
create_exp_summary
puts "==> #{Time.now} Assembling Samples..."
create_sample_summary
end
#
# Merge single read summary file to one tsv
#
def merge_reads
@reads_fpath = output_fpath("quanto.reads.tsv")
if !output_exist?(@reads_fpath)
File.open(@reads_fpath, 'w') do |file|
file.puts(tsv_header[0..-1].join("\t"))
@objects.each do |obj|
file.puts(open(obj[:summary_path]).read.chomp)
end
end
end
end
#
# Merge data
#
def create_run_summary
@runs_fpath = output_fpath("quanto.runs.tsv")
if !output_exist?(@runs_fpath)
merge_dataset(
@runs_fpath,
:read_to_run,
tsv_header.drop(1).insert(0, "run_id"),
reads_by_runid
)
end
end
def create_exp_summary
@experiments_fpath = output_fpath("quanto.exp.tsv")
if !output_exist?(@experiments_fpath)
merge_dataset(
@experiments_fpath,
:run_to_exp,
tsv_header.drop(1).insert(0, "experiment_id", "run_id"),
runs_by_expid
)
end
end
def create_sample_summary
@samples_fpath = output_fpath("quanto.sample.tsv")
if !output_exist?(@samples_fpath)
merge_dataset(
@samples_fpath,
:exp_to_sample,
tsv_header.drop(1).insert(0, "biosample_id", "experiment_id", "run_id"),
exps_by_sampleid
)
end
end
def merge_dataset(outpath, type, header, id_data_pairs)
File.open(outpath, 'w') do |file|
file.puts(header.join("\t"))
id_data_pairs.each_pair do |id, data|
file.puts(merge_data_by_type(type, id, data))
end
end
end
def merge_data_by_type(type, id, data)
case type
when :read_to_run
merge_read_to_run(id, data)
when :run_to_exp
merge_run_to_exp(id, data)
when :exp_to_sample
merge_exp_to_sample(id, data)
end
end
#
# Merge reads to run
#
def merge_read_to_run(runid, reads)
if reads.size == 1
(reads[0].drop(1).insert(0, runid) << "SINGLE").join("\t")
else
pairs = remove_nonpair(reads)
if pairs.size == 2
merge_data(remove_nonpair(reads)).join("\t")
else
"IMPERFECT PAIR DETECTED"
end
end
end
def remove_nonpair(reads)
reads.select{|read| read[0] =~ /_._/ }
end
def reads_by_runid
hash = {}
reads = open(@reads_fpath).readlines.drop(1)
reads.each do |read|
runid = read.split("_")[0]
hash[runid] ||= []
hash[runid] << read.chomp.split("\t")
end
hash
end
#
# Merge reads to experiment
#
def merge_run_to_exp(expid, runs)
if runs.size == 1
([expid] + runs[0]).join("\t")
else
data = merge_data(runs)
([expid] + data).join("\t")
end
end
def runs_by_expid
run_data = data_by_id(@runs_fpath)
exp_run = `cat #{run_members_path} | awk -F '\t' '$8 == "live" { print $3 "\t" $1 }'`.split("\n")
hash = {}
exp_run.each do |e_r|
er = e_r.split("\t")
run = run_data[er[1]]
if run
hash[er[0]] ||= []
hash[er[0]] << run
end
end
hash
end
#
# Merge experiments to sample
#
def merge_exp_to_sample(sampleid, exps)
exps.map{|exp| ([sampleid] + exp).join("\t") }.join("\n")
end
# return hash { "SAMD00016353" => ["DRX000001"], ... }
# key: BioSample ID (can be SRS ID), value: array of SRA experiment ID
def exps_by_sampleid
exp_data = data_by_id(@experiments_fpath)
sample_exp = `cat #{run_members_path} | awk -F '\t' '$8 == "live" { print $9 "\t" $3 "\t" $4 }' | sort -u`.split("\n")
hash = {}
sample_exp.each do |s_e|
se = s_e.split("\t")
samid = select_sampleid(se[0], se[2])
exp = exp_data[se[1]]
if exp
hash[samid] ||= []
hash[samid] << exp
end
end
hash
end
def select_sampleid(biosample_id, srs_id)
if biosample_id == "-"
srs_id
elsif biosampleid =~ /^[0-9]+$/
numbers_to_biosampleid(biosample_id, srs_id)
else
biosample_id
end
end
def numbers_to_biosampleid(num, srs_id)
pfx = case srs_id[0]
when "S"
"SAMN"
when "E"
"SAME"
when "D"
"SAMD"
end
pfx + num.to_s
end
#
# annotate tsv with metadata
#
def metadata_header
[
"secondary_sample_id",
"taxonomy_id",
"taxonomy_scientific_name",
"genome_size",
"coverage",
"library_strategy",
"library_source",
"library_selection",
"instrument_model",
]
end
def annotate_samples
# hash to connect metadata
exp_hash = create_metadata_hash(@exp_metadata, 0) # { expid => [metadata] }
bs_hash = create_metadata_hash(@bs_metadata, 0) # { biosampleid => [metadata] }
srs_hash = create_metadata_hash(@bs_metadata, 1) # { sampleid => [metadata] }
sample_data = open(@samples_fpath).readlines
header = [sample_data.shift.chomp].push(metadata_header).join("\t")
annotated = Parallel.map(sample_data, :in_threads => @@nop) do |line|
data = line.chomp.split("\t")
sample_md = bs_hash[data[0]] || srs_hash[data[0]]
sample_info = if sample_md
coverage = if sample_md[3] != "NA"
data[7].to_f / sample_md[3].to_f * 1_000_000
else
"NA"
end
[
sample_md,
coverage,
]
end
[
data,
sample_info,
exp_hash[data[1]],
].flatten.join("\t")
end
open(output_fpath("quanto.annotated.tsv"), 'w'){|f| f.puts([header, annotated.compact]) }
end
def sample_by_experiment
`cat #{run_members_path} | awk -F '\t' '$8 == "live" { print $3 "\t" $4 "\t" $9 }' | sort -u`.split("\n").map{|line| l = line.split("\t"); [l[0], [l[1], l[2]]] }.to_h
end
def create_metadata_hash(path, id_col)
hash = {}
open(path).readlines.each do |line|
data = line.chomp.split("\t")
id = data.delete_at(id_col)
hash[id] = data
end
hash
end
#
# Protected methods for data merge
#
protected
def run_members_path
File.join(@metadata_dir, "SRA_Run_Members")
end
def output_fpath(fname)
File.join(@outdir, fname)
end
def output_exist?(fpath) # true to skip creation
if File.exist?(fpath)
if @overwrite
backup_dir = File.join(@outdir, "backup", Time.now.strftime("%Y%m%d"))
FileUtils.mkdir_p(backup_dir)
FileUtils.mv(fpath, backup_dir)
false
else
true
end
end
end
def data_by_id(data_fpath)
data = open(data_fpath).readlines.drop(1)
hash = {}
data.each do |d|
id = d.split("\t")[0]
hash[id] = d.chomp.split("\t")
end
hash
end
def merge_data(data_list)
data_scheme.map.with_index do |method, i|
self.send(method, i, data_list)
end
end
def data_scheme
[
:join_ids, # Run id
:join_literals, # fastqc version
:join_literals, # filename
:join_literals, # file type
:join_literals, # encoding
:sum_floats, # total sequences
:sum_floats, # filtered sequences
:mean_floats, # sequence length
:mean_floats, # min seq length
:mean_floats, # max seq length
:mean_floats, # mean sequence length
:mean_floats, # median sequence length
:sum_reads_percent, # percent gc
:sum_reads_percent, # total duplication percentage
:mean_floats, # overall mean quality
:mean_floats, # overall median quality
:mean_floats, # overall n content
:layout_paired, # layout
]
end
def join_ids(i, data)
data.map{|d| d[i].split("_")[0] }.uniq.join(",")
end
def join_literals(i, data)
data.map{|d| d[i] }.uniq.join(",")
end
def sum_floats(i, data)
data.map{|d| d[i].to_f }.reduce(:+)
end
def mean_floats(i, data)
sum_floats(i, data) / 2
end
def sum_reads_percent(i, data)
total_reads = data.map{|d| d[5].to_f }.reduce(:+)
total_count = data.map{|d| percent_to_read_count(i, d) }.reduce(:+)
(total_count / total_reads) * 100
end
def percent_to_read_count(i, data)
data[5].to_f * (data[i].to_f / 100)
end
def layout_paired(i, data)
"PAIRED"
end
def tsv_header
[
"ID",
"fastqc_version",
"filename",
"file_type",
"encoding",
"total_sequences",
"filtered_sequences",
"sequence_length",
"min_sequence_length",
"max_sequence_length",
"mean_sequence_length",
"median_sequence_length",
"percent_gc",
"total_duplicate_percentage",
"overall_mean_quality_score",
"overall_median_quality_score",
"overall_n_content",
"read_layout",
]
end
end
end
end
|
require 'rack/camel_snake/formatter'
module Rack
class CamelSnake
module Refinements
refine Oj.singleton_class do
def camelize(input)
to_camel = lambda do |key|
key.is_a?(String) ? key.to_camel : key
end
dump(Rack::CamelSnake::Formatter.formatter(load(input), to_camel))
end
def snakify(input)
to_snake = lambda do |key|
key.is_a?(String) ? key.to_snake : key
end
dump(Rack::CamelSnake::Formatter.formatter(load(input), to_snake))
end
end
refine String do
def to_camel
gsub(/_+([a-z])/){ |matched| matched.tr('_', '').upcase }
.sub(/^(.)/){ |matched| matched.downcase }
.sub(/_$/, '')
end
def to_snake
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr('-', '_')
.downcase
end
end
end
end
end
Update refinements.rb
require 'rack/camel_snake/formatter'
module Rack
class CamelSnake
module Refinements
class Oj
def self.camelize(input)
to_camel = lambda do |key|
key.is_a?(String) ? key.to_camel : key
end
dump(Rack::CamelSnake::Formatter.formatter(load(input), to_camel))
end
def def.snakify(input)
to_snake = lambda do |key|
key.is_a?(String) ? key.to_snake : key
end
dump(Rack::CamelSnake::Formatter.formatter(load(input), to_snake))
end
end
class String
def to_camel
gsub(/_+([a-z])/){ |matched| matched.tr('_', '').upcase }
.sub(/^(.)/){ |matched| matched.downcase }
.sub(/_$/, '')
end
def to_snake
gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr('-', '_')
.downcase
end
end
end
end
end
|
require 'mongoid'
require 'rails_admin/config/sections/list'
require 'rails_admin/abstract_object'
require 'rails_admin/adapters/abstract_object_mongoid'
module RailsAdmin
module Adapters
module Mongoid
def self.can_handle_model(model)
return false unless model.is_a?(Class)
# calling colletion on an embedded collection just bombs, be a bit more verbose to avoid exception
is_embedded = model.respond_to?(:embedded) && model.embedded?
return false if is_embedded
# check if it's backed by a Mongoid collection
model.respond_to?(:collection) && model.collection.is_a?(::Mongoid::Collection)
end
def get(id)
if object = model.where(:_id=>BSON::ObjectId(id)).first
RailsAdmin::Adapters::AbstractObjectMongoid.new object
else
nil
end
end
def get_bulk(ids)
ids = ids.map{|i| BSON::ObjectId(i)}
Array(model.where(:_id.in=>ids))
end
def keys
[:_id]
end
def count(options = {})
criteria_for_options(options).count
end
def first(options = {})
criteria_for_options(options).first
end
def all(options = {})
Array(criteria_for_options(options))
end
def paginated(options = {})
page = options.delete(:page) || 1
per_page = options.delete(:per_page) || RailsAdmin::Config::Sections::List.default_items_per_page
criteria = criteria_for_options(options)
page_count = (criteria.count.to_f / per_page).ceil
[page_count, Array(criteria.limit(per_page).offset((page-1)*per_page))]
end
def create(params = {})
model.create(params)
end
def new(params = {})
RailsAdmin::AbstractObject.new(model.new)
end
def destroy(ids)
ids = ids.map{|i| BSON::ObjectId(i)}
destroyed = Array(model.where(:_id.in=>ids))
model.destroy_all(:conditions=>{:_id.in=>ids})
destroyed
end
def destroy_all!
model.destroy_all
end
def has_and_belongs_to_many_associations
associations.select do |association|
association[:type] == :has_and_belongs_to_many
end
end
def has_many_associations
associations.select do |association|
association[:type] == :has_many
end
end
def has_one_associations
associations.select do |association|
association[:type] == :has_one
end
end
def belongs_to_associations
associations.select do |association|
association[:type] == :belongs_to
end
end
def model_name
"todo"
end
def table_name
model.collection.name
end
def associations
if true
[]
else
model.reflect_on_all_associations.select { |association| not association.options[:polymorphic] }.map do |association|
{
:name => association.name,
:pretty_name => association.name.to_s.gsub('_', ' ').capitalize,
:type => association.macro,
:parent_model => association_parent_model_lookup(association),
:parent_key => association_parent_key_lookup(association),
:child_model => association_child_model_lookup(association),
:child_key => association_child_key_lookup(association),
}
end
end
end
def properties
model.fields.map do |name,field|
ar_type = case field.type.to_s
when "String"
:string
when "Integer"
:integer
when "Time"
:datetime
when "Float"
:float
when "Array"
:string
else
# this will likely bomb, will fix as it does
field.type
end
{
:name => field.name.to_sym,
:pretty_name => field.name.to_s.gsub('_', ' ').capitalize,
:type => ar_type,
:length => 255,
:nullable? => true,
:serial? => false,
}
end
end
def model_store_exists?
# Collections are created on demand, so they always 'exist'.
# If need to know if pre-exist we can do something like
# model.db.collection_names.include?(model.collection.name)
true
end
private
def association_parent_model_lookup(association)
puts "association_parent_model_lookup(#{association})"
case association.macro
when :belongs_to
association.klass
when :has_one, :has_many, :has_and_belongs_to_many
association.active_record
else
raise "Unknown association type: #{association.macro.inspect}"
end
end
def association_parent_key_lookup(association)
[:_id]
end
def association_child_model_lookup(association)
puts "association_child_model_lookup(#{association})"
case association.macro
when :belongs_to
association.active_record
when :has_one, :has_many, :has_and_belongs_to_many
association.klass
else
raise "Unknown association type: #{association.macro.inspect}"
end
end
def association_child_key_lookup(association)
puts "association_child_key_lookup(#{association})"
case association.macro
when :belongs_to
[association.options[:foreign_key] || "#{association.name}_id".to_sym]
when :has_one, :has_many, :has_and_belongs_to_many
[association.primary_key_name.to_sym]
else
raise "Unknown association type: #{association.macro.inspect}"
end
end
private
def criteria_for_options(options)
puts "criteria_for_options #{options.inspect}"
sort = options.delete(:sort)
sort_reverse = options.delete(:sort_reverse)
criteria = if sort && sort_reverse
model.where(options).desc(sort)
elsif sort
model.where(options).asc(sort)
else
model.where(options)
end
end
end
end
end
Remove debugging.
require 'mongoid'
require 'rails_admin/config/sections/list'
require 'rails_admin/abstract_object'
require 'rails_admin/adapters/abstract_object_mongoid'
module RailsAdmin
module Adapters
module Mongoid
def self.can_handle_model(model)
return false unless model.is_a?(Class)
# calling colletion on an embedded collection just bombs, be a bit more verbose to avoid exception
is_embedded = model.respond_to?(:embedded) && model.embedded?
return false if is_embedded
# check if it's backed by a Mongoid collection
model.respond_to?(:collection) && model.collection.is_a?(::Mongoid::Collection)
end
def get(id)
if object = model.where(:_id=>BSON::ObjectId(id)).first
RailsAdmin::Adapters::AbstractObjectMongoid.new object
else
nil
end
end
def get_bulk(ids)
ids = ids.map{|i| BSON::ObjectId(i)}
Array(model.where(:_id.in=>ids))
end
def keys
[:_id]
end
def count(options = {})
criteria_for_options(options).count
end
def first(options = {})
criteria_for_options(options).first
end
def all(options = {})
Array(criteria_for_options(options))
end
def paginated(options = {})
page = options.delete(:page) || 1
per_page = options.delete(:per_page) || RailsAdmin::Config::Sections::List.default_items_per_page
criteria = criteria_for_options(options)
page_count = (criteria.count.to_f / per_page).ceil
[page_count, Array(criteria.limit(per_page).offset((page-1)*per_page))]
end
def create(params = {})
model.create(params)
end
def new(params = {})
RailsAdmin::AbstractObject.new(model.new)
end
def destroy(ids)
ids = ids.map{|i| BSON::ObjectId(i)}
destroyed = Array(model.where(:_id.in=>ids))
model.destroy_all(:conditions=>{:_id.in=>ids})
destroyed
end
def destroy_all!
model.destroy_all
end
def has_and_belongs_to_many_associations
associations.select do |association|
association[:type] == :has_and_belongs_to_many
end
end
def has_many_associations
associations.select do |association|
association[:type] == :has_many
end
end
def has_one_associations
associations.select do |association|
association[:type] == :has_one
end
end
def belongs_to_associations
associations.select do |association|
association[:type] == :belongs_to
end
end
def model_name
"todo"
end
def table_name
model.collection.name
end
def associations
if true
[]
else
model.reflect_on_all_associations.select { |association| not association.options[:polymorphic] }.map do |association|
{
:name => association.name,
:pretty_name => association.name.to_s.gsub('_', ' ').capitalize,
:type => association.macro,
:parent_model => association_parent_model_lookup(association),
:parent_key => association_parent_key_lookup(association),
:child_model => association_child_model_lookup(association),
:child_key => association_child_key_lookup(association),
}
end
end
end
def properties
model.fields.map do |name,field|
ar_type = case field.type.to_s
when "String"
:string
when "Integer"
:integer
when "Time"
:datetime
when "Float"
:float
when "Array"
:string
else
# this will likely bomb, will fix as it does
field.type
end
{
:name => field.name.to_sym,
:pretty_name => field.name.to_s.gsub('_', ' ').capitalize,
:type => ar_type,
:length => 255,
:nullable? => true,
:serial? => false,
}
end
end
def model_store_exists?
# Collections are created on demand, so they always 'exist'.
# If need to know if pre-exist we can do something like
# model.db.collection_names.include?(model.collection.name)
true
end
private
def association_parent_model_lookup(association)
puts "association_parent_model_lookup(#{association})"
case association.macro
when :belongs_to
association.klass
when :has_one, :has_many, :has_and_belongs_to_many
association.active_record
else
raise "Unknown association type: #{association.macro.inspect}"
end
end
def association_parent_key_lookup(association)
[:_id]
end
def association_child_model_lookup(association)
puts "association_child_model_lookup(#{association})"
case association.macro
when :belongs_to
association.active_record
when :has_one, :has_many, :has_and_belongs_to_many
association.klass
else
raise "Unknown association type: #{association.macro.inspect}"
end
end
def association_child_key_lookup(association)
puts "association_child_key_lookup(#{association})"
case association.macro
when :belongs_to
[association.options[:foreign_key] || "#{association.name}_id".to_sym]
when :has_one, :has_many, :has_and_belongs_to_many
[association.primary_key_name.to_sym]
else
raise "Unknown association type: #{association.macro.inspect}"
end
end
private
def criteria_for_options(options)
sort = options.delete(:sort)
sort_reverse = options.delete(:sort_reverse)
criteria = if sort && sort_reverse
model.where(options).desc(sort)
elsif sort
model.where(options).asc(sort)
else
model.where(options)
end
end
end
end
end
|
module RailsAdmin
module RestApi
###
# Generate jQuery code for api service.
module JQuery
###
# Returns jQuery command for service with given method and path.
def api_jquery_code(method, path, with_auth_vars=false)
# Get vars definition.
data, uri, vars = api_data('jquery', method, path, with_auth_vars)
# Generate uri and command.
command = ""
command << "var #{api_vars('jquery', vars).gsub(/\n/, ",\n ")};\n\n" unless vars.empty?
command << "jQuery.ajax({\n"
command << " url: '#{uri}',\n"
command << " method: '#{method.upcase}',\n"
command << " dataType: 'json',\n"
command << " headers: {\n"
command << " 'Content-Type': 'application/json',\n"
command << " 'X-Tenant-Access-Key': tenent_access_key,\n"
command << " 'X-Tenant-Access-Token': tenent_access_token\n"
command << " },\n"
command << " data: #{data.to_json},\n" unless data.empty?
command << " success: function(data, textStatus, jqXHR) {\n"
command << " console.log(data);\n"
command << " }\n"
command << "});\n"
command
end
end
end
end
update rest-api for jquery
module RailsAdmin
module RestApi
###
# Generate jQuery code for api service.
module JQuery
###
# Returns jQuery command for service with given method and path.
def api_jquery_code(method, path, with_auth_vars=false)
# Get vars definition.
data, uri, vars = api_data('jquery', method, path, with_auth_vars)
method = method.to_s.upcase
# Generate uri and command.
command = ""
command << "var #{api_vars('jquery', vars).gsub(/\n/, ",\n ")};\n\n" unless vars.empty?
command << "jQuery.ajax({\n"
command << " url: '#{uri}',\n"
command << " method: '#{method}',\n"
command << " dataType: 'json',\n"
command << " crossOrigin: true,\n"
command << " headers: {\n"
command << " 'Content-Type': 'application/json',\n"
command << " 'X-Tenant-Access-Key': tenent_access_key,\n"
command << " 'X-Tenant-Access-Token': tenent_access_token\n"
command << " },\n"
command << " data: #{data.to_json},\n" if data.any? && method == 'GET'
command << " data: JSON.stringify(#{data.to_json}),\n" if data.any? && method != 'GET'
command << " success: function(data, textStatus, jqXHR) {\n"
command << " console.log(data);\n"
command << " }\n"
command << "});\n"
command
end
end
end
end |
Add CommandRunner for running a shell command which raises when exitstatus > 0
require 'pty'
module CommandRunner
def self.run_command_and_print(cmd, output)
output.puts "[1mExecuting #{cmd}[0m\n\n"
PTY.spawn(cmd) do |read_stream, write_stream, pid|
begin
while chars = read_stream.read(1)
output.print chars
end
rescue Errno::EIO
end
Process.wait(pid)
end
output.puts "\n\n\n"
if $?
exit 1 if $?.exitstatus > 0
else
raise "Huh?! We didn't get an exit status from that last one: #{cmd}"
end
end
end |
module RailsAdminNestable
VERSION = "0.0.6"
end
version 0.0.7
module RailsAdminNestable
VERSION = "0.0.7"
end
|
module Ruboty
module JapanWeather
VERSION = "0.0.1"
end
end
Bump version 0.0.2
module Ruboty
module JapanWeather
VERSION = "0.0.2"
end
end
|
class Repositext
class Cli
module Copy
private
# Copies subtitle_marker csv files to content for subtitle import. Also renames files like so:
# 59-0125_0547.markers.txt => eng59-0125_0547.subtitle_markers.csv
# @param options [Hash]
# @option options [String] 'base-dir': (required) one of 'subtitle_tagging_import_dir' or 'subtitle_import_dir'
# @option options [String] 'file-pattern': defaults to 'txt_files', can be custom pattern
def copy_subtitle_marker_csv_files_to_content(options)
input_base_dir = config.compute_base_dir(options['base-dir'])
input_file_selector = config.compute_file_selector(options['file-selector'] || :all_files)
input_file_extension = config.compute_file_extension(options['file-extension'] || :txt_extension)
output_base_dir = options['output'] || config.base_dir(:content_dir)
Repositext::Cli::Utils.copy_files(
input_base_dir,
input_file_selector,
input_file_extension,
output_base_dir,
options['file_filter'] || /\.markers\.txt\z/,
"Copying subtitle marker CSV files from subtitle_tagging_import_dir to content_dir",
options.merge(
:output_path_lambda => lambda { |input_filename|
input_filename.gsub(input_base_dir, output_base_dir)
.gsub(
/\/([^\/\.]+)\.markers\.txt/,
'/' + config.setting(:language_code_3_chars) + '\1.subtitle_markers.csv'
)
}
)
)
end
# Copies subtitle_marker csv files from content to subtitle export.
# Also renames files like so:
# eng59-0125_0547.subtitle_markers.csv => 59-0125_0547.markers.txt
def copy_subtitle_marker_csv_files_to_subtitle_export(options)
input_base_dir = config.compute_base_dir(options['base-dir'] || :content_dir)
input_file_selector = config.compute_file_selector(options['file-selector'] || :all_files)
input_file_extension = config.compute_file_extension(options['file-extension'] || :csv_extension)
# grab source marker_csv file from primary repo
primary_repo_input_base_dir = input_base_dir.sub(
config.base_dir(:rtfile_dir), config.primary_repo_base_dir
)
output_base_dir = options['output'] || config.base_dir(:subtitle_export_dir)
Repositext::Cli::Utils.copy_files(
primary_repo_input_base_dir,
input_file_selector,
input_file_extension,
output_base_dir,
options['file_filter'] || /\.subtitle_markers\.csv\z/,
"Copying subtitle marker CSV files from content_dir to subtitle_export_dir",
options.merge(
:output_path_lambda => lambda { |input_filename|
input_filename.gsub(input_base_dir, output_base_dir)
.gsub(
/\/[[:alpha:]]{3}([^\/\.]+)\.subtitle_markers\.csv/,
'/\1.markers.txt'
)
}
)
)
end
end
end
end
Fixed bug when copying subtitle marker CSV files
class Repositext
class Cli
module Copy
private
# Copies subtitle_marker csv files to content for subtitle import. Also renames files like so:
# 59-0125_0547.markers.txt => eng59-0125_0547.subtitle_markers.csv
# @param options [Hash]
# @option options [String] 'base-dir': (required) one of 'subtitle_tagging_import_dir' or 'subtitle_import_dir'
# @option options [String] 'file-pattern': defaults to 'txt_files', can be custom pattern
def copy_subtitle_marker_csv_files_to_content(options)
input_base_dir = config.compute_base_dir(options['base-dir'])
input_file_selector = config.compute_file_selector(options['file-selector'] || :all_files)
input_file_extension = config.compute_file_extension(options['file-extension'] || :txt_extension)
output_base_dir = options['output'] || config.base_dir(:content_dir)
Repositext::Cli::Utils.copy_files(
input_base_dir,
input_file_selector,
input_file_extension,
output_base_dir,
options['file_filter'] || /\.markers\.txt\z/,
"Copying subtitle marker CSV files from subtitle_tagging_import_dir to content_dir",
options.merge(
:output_path_lambda => lambda { |input_filename|
input_filename.gsub(input_base_dir, output_base_dir)
.gsub(
/\/([^\/\.]+)\.markers\.txt/,
'/' + config.setting(:language_code_3_chars) + '\1.subtitle_markers.csv'
)
}
)
)
end
# Copies subtitle_marker csv files from content to subtitle export.
# Also renames files like so:
# eng59-0125_0547.subtitle_markers.csv => 59-0125_0547.markers.txt
def copy_subtitle_marker_csv_files_to_subtitle_export(options)
input_base_dir = config.compute_base_dir(options['base-dir'] || :content_dir)
input_file_selector = config.compute_file_selector(options['file-selector'] || :all_files)
input_file_extension = config.compute_file_extension(options['file-extension'] || :csv_extension)
# grab source marker_csv file from primary repo
primary_repo_input_base_dir = input_base_dir.sub(
config.base_dir(:rtfile_dir), config.primary_repo_base_dir
)
output_base_dir = options['output'] || config.base_dir(:subtitle_export_dir)
Repositext::Cli::Utils.copy_files(
primary_repo_input_base_dir,
input_file_selector,
input_file_extension,
output_base_dir,
options['file_filter'] || /\.subtitle_markers\.csv\z/,
"Copying subtitle marker CSV files from content_dir to subtitle_export_dir",
options.merge(
:output_path_lambda => lambda { |input_filename|
input_filename.gsub(primary_repo_input_base_dir, output_base_dir)
.gsub(
/\/[[:alpha:]]{3}([^\/\.]+)\.subtitle_markers\.csv/,
'/\1.markers.txt'
)
}
)
)
end
end
end
end
|
class ProgressBar
module Format
class Base
attr_reader :molecules
def initialize(format_string)
@format_string = format_string
@molecules = parse(format_string)
end
def process(environment)
processed_string = @format_string.dup
non_bar_molecules.each do |molecule|
processed_string.gsub!("%#{molecule.key}", environment.send(molecule.method_name).to_s)
end
remaining_molecules = bar_molecules.size
placeholder_length = remaining_molecules * 2
processed_string.gsub! '%%', '%'
leftover_bar_length = environment.send(:length) - processed_string.length + placeholder_length
leftover_bar_length = leftover_bar_length < 0 ? 0 : leftover_bar_length
bar_molecules.each do |molecule|
processed_string.gsub!("%#{molecule.key}", environment.send(molecule.method_name, leftover_bar_length).to_s)
end
processed_string
end
private
def non_bar_molecules
@non_bar_molecules ||= molecules.select { |molecule| !molecule.bar_molecule? }
end
def bar_molecules
@bar_molecules ||= molecules.select { |molecule| molecule.bar_molecule? }
end
def parse(format_string)
molecules = []
format_string.scan(/%[a-zA-Z]/) do |match|
molecules << Molecule.new(match[1,1])
end
molecules
end
end
end
end
allows to inclue ANSI SGR codes into molecules, preserving the printable length
class ProgressBar
module Format
class Base
attr_reader :molecules
def initialize(format_string)
@format_string = format_string
@molecules = parse(format_string)
end
def process(environment)
processed_string = @format_string.dup
non_bar_molecules.each do |molecule|
processed_string.gsub!("%#{molecule.key}", environment.send(molecule.method_name).to_s)
end
remaining_molecules = bar_molecules.size
placeholder_length = remaining_molecules * 2
processed_string.gsub! '%%', '%'
# lenght calculated without eventual ANSI SGR codes
processed_string_length = processed_string.gsub(/\e\[[\d;]+m/, '').length
leftover_bar_length = environment.send(:length) - processed_string_length + placeholder_length
leftover_bar_length = leftover_bar_length < 0 ? 0 : leftover_bar_length
bar_molecules.each do |molecule|
processed_string.gsub!("%#{molecule.key}", environment.send(molecule.method_name, leftover_bar_length).to_s)
end
processed_string
end
private
def non_bar_molecules
@non_bar_molecules ||= molecules.select { |molecule| !molecule.bar_molecule? }
end
def bar_molecules
@bar_molecules ||= molecules.select { |molecule| molecule.bar_molecule? }
end
def parse(format_string)
molecules = []
format_string.scan(/%[a-zA-Z]/) do |match|
molecules << Molecule.new(match[1,1])
end
molecules
end
end
end
end
|
# Formatter for ruby cucumber
require 'fileutils'
require 'res/ir'
require 'cucumber/formatter/io'
module Res
module Formatters
class RubyCucumber
include FileUtils
include ::Cucumber::Formatter::Io
def initialize(runtime, path_or_io, options)
@runtime = runtime
@io = ensure_io(path_or_io, "reporter")
@options = options
@exceptions = []
@indent = 0
@prefixes = options[:prefixes] || {}
@delayed_messages = []
@_start_time = Time.now
end
def before_features(features)
@_features = []
end
# Once everything has run -- whack it in a ResultIR object and
# dump it as json
def after_features(features)
results = @_features
ir = ::Res::IR.new( :started => @_start_time,
:finished => Time.now(),
:results => results,
:type => 'Cucumber' )
@io.puts ir.json
end
def before_feature(feature)
@_feature = {}
@_context = {}
@_feature[:started] = Time.now()
begin
hash = split_uri( feature.location.to_s )
@_feature[:file] = hash[:file]
@_feature[:line] = hash[:line]
@_feature[:urn] = hash[:urn]
rescue
@_feature[:uri] = 'unknown'
end
@_features << @_feature
@_context = @_feature
end
def comment_line(comment_line)
@_context[:comments] = [] if !@_context[:comments]
@_context[:comments] << comment_line
end
def after_tags(tags)
end
def tag_name(tag_name)
@_context[:tags] = [] if !@_context[:tag]
# Strip @ from tags
@_context[:tags] << tag_name[1..-1]
end
# { :type => 'Feature',
# :name => 'Feature name',
# :description => "As a blah\nAs a blah\n" }
def feature_name(keyword, name)
@_feature[:type] = "Cucumber::" + keyword.gsub(/\s+/, "")
lines = name.split("\n")
lines = lines.collect { |l| l.strip }
@_feature[:name] = lines.shift
@_feature[:description] = lines.join("\n")
end
def after_feature(feature)
@_feature[:finished] = Time.now()
end
def before_feature_element(feature_element)
@_feature_element = {}
@_context = {}
@_feature_element[:started] = Time.now
begin
hash = split_uri( feature_element.location.to_s )
@_feature_element[:file] = hash[:file]
@_feature_element[:line] = hash[:line]
@_feature_element[:urn] = hash[:urn]
rescue => e
@_feature_element[:error] = e.message
@_feature_element[:file] = 'unknown'
end
@_feature[:children] = [] if ! @_feature[:children]
@_feature[:children] << @_feature_element
@_context = @_feature_element
end
# After a scenario
def after_feature_element(feature_element)
@_context = {}
if feature_element.respond_to? :status
@_feature_element[:status] = feature_element.status
end
@_feature_element[:finished] = Time.now
end
def before_background(background)
#@_context[:background] = background
end
def after_background(background)
end
def background_name(keyword, name, file_colon_line, source_indent)
end
# def before_examples_array(examples_array)
# @indent = 4
# @io.puts
# @visiting_first_example_name = true
# end
#
def examples_name(keyword, name)
# @io.puts unless @visiting_first_example_name
# @visiting_first_example_name = false
# names = name.strip.empty? ? [name.strip] : name.split("\n")
# @io.puts(" #{keyword}: #{names[0]}")
# names[1..-1].each {|s| @io.puts " #{s}" } unless names.empty?
# @io.flush
# @indent = 6
# @scenario_indent = 6
end
#
def scenario_name(keyword, name, file_colon_line, source_indent)
@_context[:type] = "Cucumber::" + keyword.gsub(/\s+/, "")
@_context[:name] = name || ''
end
def before_step(step)
@_step = {}
# Background steps can appear totally divorced from scenerios (feature
# elements). Need to make sure we're not including them as children
# to scenario that don't exist
return if @_feature_element && @_feature_element[:finished]
@_feature_element = {} if !@_feature_element
@_feature_element[:children] = [] if !@_feature_element[:children]
@_feature_element[:children] << @_step
@_context = @_step
end
# def before_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line)
# @hide_this_step = false
# if exception
# if @exceptions.include?(exception)
# @hide_this_step = true
# return
# end
# @exceptions << exception
# end
# if status != :failed && @in_background ^ background
# @hide_this_step = true
# return
# end
# @status = status
# end
# Argument list changed after cucumber 1.4, hence the *args
def step_name(keyword, step_match, status, source_indent, background, *args)
file_colon_line = args[0] if args[0]
@_step[:type] = "Cucumber::Step"
name = keyword + step_match.format_args(lambda{|param| %{#{param}}})
@_step[:name] = name
@_step[:status] = status
#@_step[:background] = background
@_step[:type] = "Cucumber::Step"
end
# def doc_string(string)
# return if @options[:no_multiline] || @hide_this_step
# s = %{"""\n#{string}\n"""}.indent(@indent)
# s = s.split("\n").map{|l| l =~ /^\s+$/ ? '' : l}.join("\n")
# @io.puts(format_string(s, @current_step.status))
# @io.flush
# end
#
def exception(exception, status)
@_context[:message] = exception.to_s
end
def before_multiline_arg(multiline_arg)
# return if @options[:no_multiline] || @hide_this_step
# @table = multiline_arg
end
def after_multiline_arg(multiline_arg)
@_context[:args] = multiline_arg.to_s.gsub(/\e\[(\d+)m/, '')
@_table = nil
end
# Before a scenario outline is encountered
def before_outline_table(outline_table)
# Scenario outlines appear as children like normal scenarios,
# but really we just want to construct normal-looking children
# from them
@_outlines = @_feature_element[:children]
@_table = []
end
def after_outline_table(outline_table)
headings = @_table.shift
description = @_outlines.collect{ |o| o[:name] }.join("\n") + "\n" + headings[:name]
@_feature_element[:children] = @_table
@_feature_element[:description] = description
end
def before_table_row(table_row)
@_current_table_row = { :type => 'Cucumber::ScenarioOutline::Example' }
@_table = [] if !@_table
end
def after_table_row(table_row)
if table_row.class == Cucumber::Ast::OutlineTable::ExampleRow
@_current_table_row[:name] = table_row.name
if table_row.exception
@_current_table_row[:message] = table_row.exception.to_s
end
if table_row.scenario_outline
@_current_table_row[:status] = table_row.status
end
@_current_table_row[:line] = table_row.line
@_current_table_row[:urn] = @_feature_element[:file] + ":" + table_row.line.to_s
@_table << @_current_table_row
end
end
def after_table_cell(cell)
end
def table_cell_value(value, status)
@_current_table_row[:children] = [] if !@_current_table_row[:children]
@_current_table_row[:children] << { :type => "Cucumber::ScenarioOutline::Parameter",
:name => value, :status => status }
end
def split_uri(uri)
strings = uri.rpartition(/:/)
{ :file => strings[0], :line => strings[2].to_i, :urn => uri }
end
end
end
end
Make split_uri back into function
# Formatter for ruby cucumber
require 'fileutils'
require 'res/ir'
require 'cucumber/formatter/io'
module Res
module Formatters
class RubyCucumber
include FileUtils
include ::Cucumber::Formatter::Io
def initialize(runtime, path_or_io, options)
@runtime = runtime
@io = ensure_io(path_or_io, "reporter")
@options = options
@exceptions = []
@indent = 0
@prefixes = options[:prefixes] || {}
@delayed_messages = []
@_start_time = Time.now
end
def before_features(features)
@_features = []
end
# Once everything has run -- whack it in a ResultIR object and
# dump it as json
def after_features(features)
results = @_features
ir = ::Res::IR.new( :started => @_start_time,
:finished => Time.now(),
:results => results,
:type => 'Cucumber' )
@io.puts ir.json
end
def before_feature(feature)
@_feature = {}
@_context = {}
@_feature[:started] = Time.now()
begin
hash = RubyCucumber.split_uri( feature.location.to_s )
@_feature[:file] = hash[:file]
@_feature[:line] = hash[:line]
@_feature[:urn] = hash[:urn]
rescue
@_feature[:uri] = 'unknown'
end
@_features << @_feature
@_context = @_feature
end
def comment_line(comment_line)
@_context[:comments] = [] if !@_context[:comments]
@_context[:comments] << comment_line
end
def after_tags(tags)
end
def tag_name(tag_name)
@_context[:tags] = [] if !@_context[:tag]
# Strip @ from tags
@_context[:tags] << tag_name[1..-1]
end
# { :type => 'Feature',
# :name => 'Feature name',
# :description => "As a blah\nAs a blah\n" }
def feature_name(keyword, name)
@_feature[:type] = "Cucumber::" + keyword.gsub(/\s+/, "")
lines = name.split("\n")
lines = lines.collect { |l| l.strip }
@_feature[:name] = lines.shift
@_feature[:description] = lines.join("\n")
end
def after_feature(feature)
@_feature[:finished] = Time.now()
end
def before_feature_element(feature_element)
@_feature_element = {}
@_context = {}
@_feature_element[:started] = Time.now
begin
hash = RubyCucumber.split_uri( feature_element.location.to_s )
@_feature_element[:file] = hash[:file]
@_feature_element[:line] = hash[:line]
@_feature_element[:urn] = hash[:urn]
rescue => e
@_feature_element[:error] = e.message
@_feature_element[:file] = 'unknown'
end
@_feature[:children] = [] if ! @_feature[:children]
@_feature[:children] << @_feature_element
@_context = @_feature_element
end
# After a scenario
def after_feature_element(feature_element)
@_context = {}
if feature_element.respond_to? :status
@_feature_element[:status] = feature_element.status
end
@_feature_element[:finished] = Time.now
end
def before_background(background)
#@_context[:background] = background
end
def after_background(background)
end
def background_name(keyword, name, file_colon_line, source_indent)
end
# def before_examples_array(examples_array)
# @indent = 4
# @io.puts
# @visiting_first_example_name = true
# end
#
def examples_name(keyword, name)
# @io.puts unless @visiting_first_example_name
# @visiting_first_example_name = false
# names = name.strip.empty? ? [name.strip] : name.split("\n")
# @io.puts(" #{keyword}: #{names[0]}")
# names[1..-1].each {|s| @io.puts " #{s}" } unless names.empty?
# @io.flush
# @indent = 6
# @scenario_indent = 6
end
#
def scenario_name(keyword, name, file_colon_line, source_indent)
@_context[:type] = "Cucumber::" + keyword.gsub(/\s+/, "")
@_context[:name] = name || ''
end
def before_step(step)
@_step = {}
# Background steps can appear totally divorced from scenerios (feature
# elements). Need to make sure we're not including them as children
# to scenario that don't exist
return if @_feature_element && @_feature_element[:finished]
@_feature_element = {} if !@_feature_element
@_feature_element[:children] = [] if !@_feature_element[:children]
@_feature_element[:children] << @_step
@_context = @_step
end
# def before_step_result(keyword, step_match, multiline_arg, status, exception, source_indent, background, file_colon_line)
# @hide_this_step = false
# if exception
# if @exceptions.include?(exception)
# @hide_this_step = true
# return
# end
# @exceptions << exception
# end
# if status != :failed && @in_background ^ background
# @hide_this_step = true
# return
# end
# @status = status
# end
# Argument list changed after cucumber 1.4, hence the *args
def step_name(keyword, step_match, status, source_indent, background, *args)
file_colon_line = args[0] if args[0]
@_step[:type] = "Cucumber::Step"
name = keyword + step_match.format_args(lambda{|param| %{#{param}}})
@_step[:name] = name
@_step[:status] = status
#@_step[:background] = background
@_step[:type] = "Cucumber::Step"
end
# def doc_string(string)
# return if @options[:no_multiline] || @hide_this_step
# s = %{"""\n#{string}\n"""}.indent(@indent)
# s = s.split("\n").map{|l| l =~ /^\s+$/ ? '' : l}.join("\n")
# @io.puts(format_string(s, @current_step.status))
# @io.flush
# end
#
def exception(exception, status)
@_context[:message] = exception.to_s
end
def before_multiline_arg(multiline_arg)
# return if @options[:no_multiline] || @hide_this_step
# @table = multiline_arg
end
def after_multiline_arg(multiline_arg)
@_context[:args] = multiline_arg.to_s.gsub(/\e\[(\d+)m/, '')
@_table = nil
end
# Before a scenario outline is encountered
def before_outline_table(outline_table)
# Scenario outlines appear as children like normal scenarios,
# but really we just want to construct normal-looking children
# from them
@_outlines = @_feature_element[:children]
@_table = []
end
def after_outline_table(outline_table)
headings = @_table.shift
description = @_outlines.collect{ |o| o[:name] }.join("\n") + "\n" + headings[:name]
@_feature_element[:children] = @_table
@_feature_element[:description] = description
end
def before_table_row(table_row)
@_current_table_row = { :type => 'Cucumber::ScenarioOutline::Example' }
@_table = [] if !@_table
end
def after_table_row(table_row)
if table_row.class == Cucumber::Ast::OutlineTable::ExampleRow
@_current_table_row[:name] = table_row.name
if table_row.exception
@_current_table_row[:message] = table_row.exception.to_s
end
if table_row.scenario_outline
@_current_table_row[:status] = table_row.status
end
@_current_table_row[:line] = table_row.line
@_current_table_row[:urn] = @_feature_element[:file] + ":" + table_row.line.to_s
@_table << @_current_table_row
end
end
def after_table_cell(cell)
end
def table_cell_value(value, status)
@_current_table_row[:children] = [] if !@_current_table_row[:children]
@_current_table_row[:children] << { :type => "Cucumber::ScenarioOutline::Parameter",
:name => value, :status => status }
end
def self.split_uri(uri)
strings = uri.rpartition(/:/)
{ :file => strings[0], :line => strings[2].to_i, :urn => uri }
end
end
end
end
|
module SalesforceDeployTool
VERSION = "1.0.0"
end
bump version to 1.0.1
module SalesforceDeployTool
VERSION = "1.0.1"
end
|
require 'rgitflow/tasks/task'
module RGitFlow
module Tasks
class Feature
class Start < RGitFlow::Tasks::Task
def initialize(git)
super(git, 'start', 'Start a feature branch', ['rgitflow', 'feature'])
end
protected
def run
status 'Starting feature branch...'
branch = ENV['BRANCH']
while branch.blank?
error 'Cannot create a branch with an empty name!'
prompt 'Please enter a name for your feature branch:'
branch = STDIN.gets.chomp
end
branch = [RGitFlow::Config.options[:feature], branch].join('/')
if @git.is_local_branch? branch
error 'Cannot create a branch that already exists locally'
abort
end
if @git.is_remote_branch? branch
error 'Cannot create a branch that already exists remotely'
abort
end
@git.branch(branch).create
@git.branch(branch).checkout
status "Started feature branch #{branch}!"
end
end
end
end
end
controlling feature branch creation
require 'rgitflow/tasks/task'
module RGitFlow
module Tasks
class Feature
class Start < RGitFlow::Tasks::Task
def initialize(git)
super(git, 'start', 'Start a feature branch', ['rgitflow', 'feature'])
end
protected
def run
status 'Starting feature branch...'
unless @git.current_branch == RGitFlow::Config.options[:develop]
error 'Cannot create feature branch unless on development branch'
abort
end
branch = ENV['BRANCH']
while branch.blank?
error 'Cannot create a branch with an empty name!'
prompt 'Please enter a name for your feature branch:'
branch = STDIN.gets.chomp
end
branch = [RGitFlow::Config.options[:feature], branch].join('/')
if @git.is_local_branch? branch
error 'Cannot create a branch that already exists locally'
abort
end
if @git.is_remote_branch? branch
error 'Cannot create a branch that already exists remotely'
abort
end
@git.branch(branch).create
@git.branch(branch).checkout
status "Started feature branch #{branch}!"
end
end
end
end
end |
require 'builder'
module SamlIdp
class SignedInfoBuilder
attr_accessor :reference_id
attr_accessor :digest_value
attr_accessor :raw_algorithm
def initialize(reference_id, digest_value, raw_algorithm)
self.reference_id = reference_id
self.digest_value = digest_value
self.raw_algorithm = raw_algorithm
end
def raw
build
end
def signed
encoded.gsub(/\n/, "")
end
def secret_key
SamlIdp.config.secret_key
end
private :secret_key
def encoded
key = OpenSSL::PKey::RSA.new(secret_key)
Base64.encode64(key.sign(algorithm.new, raw))
end
private :encoded
def build
builder = Builder::XmlMarkup.new
builder.tag! "ds:SignedInfo", "xmlns:ds" => "http://www.w3.org/2000/09/xmldsig#" do |signed_info|
signed_info.tag!("ds:CanonicalizationMethod", Algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#") {}
signed_info.tag!("ds:SignatureMethod", Algorithm: "http://www.w3.org/2000/09/xmldsig#rsa-#{algorithm_name}") {}
signed_info.tag! "ds:Reference", URI: reference_string do |reference|
reference.tag! "ds:Transforms" do |transforms|
transforms.tag!("ds:Transform", Algorithm: "http://www.w3.org/2000/09/xmldsig#enveloped-signature") {}
transforms.tag!("ds:Transform", Algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#") {}
end
reference.tag! "ds:DigestMethod", Algorithm: "http://www.w3.org/2000/09/xmldsig##{algorithm_name}" do
end
reference.tag! "ds:DigestValue", digest_value
end
end
end
private :build
def reference_string
"#_#{reference_id}"
end
private :reference_string
def builder
@builder ||= Builder::XmlMarkup.new
end
private :builder
def algorithm_name
algorithm.to_s.split('::').last.downcase
end
private :algorithm_name
def algorithm
algorithm_check = raw_algorithm || SamlIdp.config.algorithm
return algorithm_check if algorithm_check.respond_to?(:digest)
case algorithm_check
when :sha256
OpenSSL::Digest::SHA256
when :sha384
OpenSSL::Digest::SHA384
when :sha512
OpenSSL::Digest::SHA512
else
OpenSSL::Digest::SHA1
end
end
private :algorithm
end
end
remove builder, smarter algorithm chooser method
require 'builder'
module SamlIdp
class SignedInfoBuilder
attr_accessor :reference_id
attr_accessor :digest_value
attr_accessor :raw_algorithm
def initialize(reference_id, digest_value, raw_algorithm)
self.reference_id = reference_id
self.digest_value = digest_value
self.raw_algorithm = raw_algorithm
end
def raw
build
end
def signed
encoded.gsub(/\n/, "")
end
def secret_key
SamlIdp.config.secret_key
end
private :secret_key
def encoded
key = OpenSSL::PKey::RSA.new(secret_key)
Base64.encode64(key.sign(algorithm.new, raw))
end
private :encoded
def build
builder = Builder::XmlMarkup.new
builder.tag! "ds:SignedInfo", "xmlns:ds" => "http://www.w3.org/2000/09/xmldsig#" do |signed_info|
signed_info.tag!("ds:CanonicalizationMethod", Algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#") {}
signed_info.tag!("ds:SignatureMethod", Algorithm: "http://www.w3.org/2000/09/xmldsig#rsa-#{algorithm_name}") {}
signed_info.tag! "ds:Reference", URI: reference_string do |reference|
reference.tag! "ds:Transforms" do |transforms|
transforms.tag!("ds:Transform", Algorithm: "http://www.w3.org/2000/09/xmldsig#enveloped-signature") {}
transforms.tag!("ds:Transform", Algorithm: "http://www.w3.org/2001/10/xml-exc-c14n#") {}
end
reference.tag! "ds:DigestMethod", Algorithm: "http://www.w3.org/2000/09/xmldsig##{algorithm_name}" do
end
reference.tag! "ds:DigestValue", digest_value
end
end
end
private :build
def reference_string
"#_#{reference_id}"
end
private :reference_string
def algorithm_name
algorithm.to_s.split('::').last.downcase
end
private :algorithm_name
def algorithm
algorithm_check = raw_algorithm || SamlIdp.config.algorithm
return algorithm_check if algorithm_check.respond_to?(:digest)
begin
OpenSSL::Digest.const_get(algorithm_check.to_s.upcase)
rescue NameError
OpenSSL::Digest::SHA1
end
end
private :algorithm
end
end
|
class SceneToolkit::Cache::Releases
def initialize(cache, cache_key = :releases)
@cache = cache
@cache_key = cache_key
@cache.transaction do
@cache[@cache_key] ||= {}
end
end
def modified?(release)
@cache.transaction(true) do
if @cache[@cache_key].has_key?(release.path)
@cache[@cache_key][release.path][:files].each do |filename, mtime|
file_path = File.join(release.path, filename)
unless File.exists?(file_path) and (@cache[@cache_key][release.path][:files].has_key?(filename) and File.stat(file_path).mtime.eql?(mtime))
flush(release)
return true
end
end
false
else
true
end
end
end
def errors(release, validations = SceneToolkit::Release::VALIDATIONS)
@cache.transaction(true) do
if @cache[@cache_key].has_key?(release.path)
@cache[@cache_key][release.path][:errors].reject { |validation, errors| not validations.include?(validation) }
else
raise RuntimeError.new("Release not catched")
end
end
end
def warnings(release, validations = SceneToolkit::Release::VALIDATIONS)
@cache.transaction(true) do
if @cache[@cache_key].has_key?(release.path)
@cache[@cache_key][release.path][:warnings].reject { |validation, warnings| not validations.include?(validation) }
else
raise RuntimeError.new("Release not catched")
end
end
end
def files(release)
@cache.transaction(true) do
@cache[@cache_key][release.path][:files]
end
end
def flush(release)
@cache.transaction do
@cache[@cache_key].delete(release.path) if @cache[@cache_key].has_key?(release.path)
end
end
def flush_all
@cache.transaction do
@cache[@cache_key] = {}
end
end
def store(release)
@cache.transaction do
@cache[@cache_key][release.path] = {}
@cache[@cache_key][release.path][:errors] = release.errors
@cache[@cache_key][release.path][:warnings] = release.warnings
@cache[@cache_key][release.path][:files] = Dir.glob(File.join(release.path, "*")).inject({}) do |collection, f|
collection[File.basename(f)] = File.stat(f).mtime
collection
end
end
end
end
FIX: cache is already flushed in Release#valid?
class SceneToolkit::Cache::Releases
def initialize(cache, cache_key = :releases)
@cache = cache
@cache_key = cache_key
@cache.transaction do
@cache[@cache_key] ||= {}
end
end
def modified?(release)
@cache.transaction(true) do
if @cache[@cache_key].has_key?(release.path)
@cache[@cache_key][release.path][:files].each do |filename, mtime|
file_path = File.join(release.path, filename)
unless File.exists?(file_path) and (@cache[@cache_key][release.path][:files].has_key?(filename) and File.stat(file_path).mtime.eql?(mtime))
return true
end
end
false
else
true
end
end
end
def errors(release, validations = SceneToolkit::Release::VALIDATIONS)
@cache.transaction(true) do
if @cache[@cache_key].has_key?(release.path)
@cache[@cache_key][release.path][:errors].reject { |validation, errors| not validations.include?(validation) }
else
raise RuntimeError.new("Release not catched")
end
end
end
def warnings(release, validations = SceneToolkit::Release::VALIDATIONS)
@cache.transaction(true) do
if @cache[@cache_key].has_key?(release.path)
@cache[@cache_key][release.path][:warnings].reject { |validation, warnings| not validations.include?(validation) }
else
raise RuntimeError.new("Release not catched")
end
end
end
def files(release)
@cache.transaction(true) do
@cache[@cache_key][release.path][:files]
end
end
def flush(release)
@cache.transaction do
@cache[@cache_key].delete(release.path) if @cache[@cache_key].has_key?(release.path)
end
end
def flush_all
@cache.transaction do
@cache[@cache_key] = {}
end
end
def store(release)
@cache.transaction do
@cache[@cache_key][release.path] = {}
@cache[@cache_key][release.path][:errors] = release.errors
@cache[@cache_key][release.path][:warnings] = release.warnings
@cache[@cache_key][release.path][:files] = Dir.glob(File.join(release.path, "*")).inject({}) do |collection, f|
collection[File.basename(f)] = File.stat(f).mtime
collection
end
end
end
end
|
# frozen_string_literal: true
module RubyRabbitmqJanus
module Janus
module Transactions
# @author VAILLANT Jeremy <jeremy.vaillant@dazzl.tv>
# This class work with janus and send a series of message
class Admin < Session
def initialize(session)
super(session)
@exclusive = true
end
def connect
rabbit.transaction_short do
@publisher = Rabbit::Publisher::PublisherAdmin.new(rabbit.channel)
yield
end
end
def publish_message(type, options = {})
msg = Janus::Messages::Admin.new(type, opts.merge(options))
response = read_response(publisher.publish(msg))
Janus::Responses::Admin.new(response)
end
private
# Override method for publishing an message and reading a response
def send_a_message
Janus::Responses::Admin.new(publisher.publish(yield))
end
# Read a admin pass in configuration file to this gem
def admin_secret
Tools::Config.instance.options['rabbit']['admin_pass']
end
# :reek:NilCheck
def opts
{ 'session_id' => session, 'admin_secret' => admin_secret }
end
end
end
end
end
Fix constructor
# frozen_string_literal: true
module RubyRabbitmqJanus
module Janus
module Transactions
# @author VAILLANT Jeremy <jeremy.vaillant@dazzl.tv>
# This class work with janus and send a series of message
class Admin < Session
def initialize(session)
super(true, session)
end
def connect
rabbit.transaction_short do
@publisher = Rabbit::Publisher::PublisherAdmin.new(rabbit.channel)
yield
end
end
def publish_message(type, options = {})
msg = Janus::Messages::Admin.new(type, opts.merge(options))
response = read_response(publisher.publish(msg))
Janus::Responses::Admin.new(response)
end
private
# Override method for publishing an message and reading a response
def send_a_message
Janus::Responses::Admin.new(publisher.publish(yield))
end
# Read a admin pass in configuration file to this gem
def admin_secret
Tools::Config.instance.options['rabbit']['admin_pass']
end
# :reek:NilCheck
def opts
{ 'session_id' => session, 'admin_secret' => admin_secret }
end
end
end
end
end
|
module Seleniumrc
module TestUnitDsl
class << self
def page_assert(thing)
module_eval("def assert_#{thing}(value, params={})\n" +
"page.assert_#{thing}(value, params)\n" +
"end",
__FILE__,
__LINE__ - 3
)
end
end
page_assert :title
page_assert :text_present
page_assert :text_not_present
page_assert :location_ends_with
deprecate :assert_location_ends_in, :assert_location_ends_with
# Assert and wait for the locator element to have value.
def assert_value(locator, value)
element(locator).has_value(value)
end
# Assert and wait for the locator attribute to have a value.
def assert_attribute(locator, value)
element(locator).has_attribute(value)
end
# Assert and wait for locator select element to have value option selected.
def assert_selected(locator, value)
element(locator).has_selected(value)
end
# Assert and wait for locator check box to be checked.
def assert_checked(locator)
element(locator).is_checked
end
# Assert and wait for locator check box to not be checked.
def assert_not_checked(locator)
element(locator).is_not_checked
end
# Assert and wait for locator element to have text equal to passed in text.
def assert_text(locator, text, options={})
element(locator).has_text(text, options)
end
# Assert and wait for locator element to be present.
def assert_element_present(locator, params = {})
element(locator).is_present(params)
end
# Assert and wait for locator element to not be present.
def assert_element_not_present(locator, params = {})
element(locator).is_not_present(params)
end
# Assert and wait for locator element to contain text.
def assert_element_contains(locator, text, options = {})
element(locator).contains_text(text, options)
end
# Assert and wait for locator element to not contain text.
def assert_element_does_not_contain_text(locator, text, options={})
element(locator).does_not_contain_text(text, options)
end
alias_method :assert_element_does_not_contain, :assert_element_does_not_contain_text
alias_method :wait_for_element_to_not_contain_text, :assert_element_does_not_contain_text
# Assert and wait for the element with id next sibling is the element with id expected_sibling_id.
def assert_next_sibling(locator, expected_sibling_id, options = {})
element(locator).has_next_sibling(expected_sibling_id, options)
end
# Assert and wait for locator element has text fragments in a certain order.
def assert_text_in_order(locator, *text_fragments)
element(locator).has_text_in_order(*text_fragments)
end
alias_method :wait_for_text_in_order, :assert_text_in_order
def assert_visible(locator, options = {})
element(locator).is_visible(options)
end
def assert_not_visible(locator, options = {})
element(locator).is_not_visible(options)
end
end
end
ADC/BT - refactoring
git-svn-id: c36580c8e9958a422a8d11aac42aea8d67ac7994@1057 af276e61-6b34-4dac-905b-574b5f35ef33
module Seleniumrc
module TestUnitDsl
class << self
def page_assert(thing)
module_eval(
"def assert_#{thing}(value, params={})\n" +
" page.assert_#{thing}(value, params)\n" +
"end",
__FILE__,
__LINE__ - 4
)
end
end
page_assert :title
page_assert :text_present
page_assert :text_not_present
page_assert :location_ends_with
deprecate :assert_location_ends_in, :assert_location_ends_with
# Assert and wait for the locator element to have value.
def assert_value(locator, value)
element(locator).has_value(value)
end
# Assert and wait for the locator attribute to have a value.
def assert_attribute(locator, value)
element(locator).has_attribute(value)
end
# Assert and wait for locator select element to have value option selected.
def assert_selected(locator, value)
element(locator).has_selected(value)
end
# Assert and wait for locator check box to be checked.
def assert_checked(locator)
element(locator).is_checked
end
# Assert and wait for locator check box to not be checked.
def assert_not_checked(locator)
element(locator).is_not_checked
end
# Assert and wait for locator element to have text equal to passed in text.
def assert_text(locator, text, options={})
element(locator).has_text(text, options)
end
# Assert and wait for locator element to be present.
def assert_element_present(locator, params = {})
element(locator).is_present(params)
end
# Assert and wait for locator element to not be present.
def assert_element_not_present(locator, params = {})
element(locator).is_not_present(params)
end
# Assert and wait for locator element to contain text.
def assert_element_contains(locator, text, options = {})
element(locator).contains_text(text, options)
end
# Assert and wait for locator element to not contain text.
def assert_element_does_not_contain_text(locator, text, options={})
element(locator).does_not_contain_text(text, options)
end
alias_method :assert_element_does_not_contain, :assert_element_does_not_contain_text
alias_method :wait_for_element_to_not_contain_text, :assert_element_does_not_contain_text
# Assert and wait for the element with id next sibling is the element with id expected_sibling_id.
def assert_next_sibling(locator, expected_sibling_id, options = {})
element(locator).has_next_sibling(expected_sibling_id, options)
end
# Assert and wait for locator element has text fragments in a certain order.
def assert_text_in_order(locator, *text_fragments)
element(locator).has_text_in_order(*text_fragments)
end
alias_method :wait_for_text_in_order, :assert_text_in_order
def assert_visible(locator, options = {})
element(locator).is_visible(options)
end
def assert_not_visible(locator, options = {})
element(locator).is_not_visible(options)
end
end
end |
require 'json'
# encoding: utf-8
module SensuPluginsApache
# This defines the version of the gem
module Version
MAJOR = 0
MINOR = 0
PATCH = 5
VER_STRING = [MAJOR, MINOR, PATCH].compact.join('.')
NAME = 'sensu-plugins-apache'
BANNER = "#{NAME} v%s"
module_function
def version
format(BANNER, VER_STRING)
end
def json_version
{
'version' => VER_STRING
}.to_json
end
end
end
version bump --skip-ci
require 'json'
# encoding: utf-8
module SensuPluginsApache
# This defines the version of the gem
module Version
MAJOR = 0
MINOR = 0
PATCH = 6
VER_STRING = [MAJOR, MINOR, PATCH].compact.join('.')
NAME = 'sensu-plugins-apache'
BANNER = "#{NAME} v%s"
module_function
def version
format(BANNER, VER_STRING)
end
def json_version
{
'version' => VER_STRING
}.to_json
end
end
end
|
module Shopware
module API
class Client
module Articles
def get_articles
response = self.class.get '/articles'
response['data']
end
def get_article(id)
response = self.class.get "/articles/#{id}"
response['data']
end
def find_article_by_name(name)
filter = "filter[0][property]=name&filter[0][expression]=%3D&filter[0][value]=#{name}"
response = self.class.get '/articles', { query: filter }
response['data'].empty? ? nil : response['data'].first
end
def create_article(properties)
response = self.class.post '/articles', body: properties
response['data']
end
def update_article(id, properties)
response = self.class.put "/articles/#{id}", body: properties
response['data']
end
def delete_article(id)
self.class.delete "/articles/#{id}"
end
end
end
end
end
[➠] Formatted `articles.rb`.
module Shopware
module API
class Client
module Articles
def get_articles
response = self.class.get '/articles'
response['data']
end
def get_article(id)
response = self.class.get "/articles/#{id}"
response['data']
end
def find_article_by_name(name)
filter = "filter[0][property]=name&filter[0][expression]=%3D&filter[0][value]=#{name}"
response = self.class.get '/articles', { query: filter }
response['data'].empty? ? nil : response['data'].first
end
def create_article(properties)
response = self.class.post '/articles', body: properties
response['data']
end
def update_article(id, properties)
response = self.class.put "/articles/#{id}", body: properties
response['data']
end
def delete_article(id)
self.class.delete "/articles/#{id}"
end
end
end
end
end |
module Shoulda # :nodoc:
module ActiveRecord # :nodoc:
# = Macro test helpers for your active record models
#
# These helpers will test most of the validations and associations for your ActiveRecord models.
#
# class UserTest < Test::Unit::TestCase
# should_require_attributes :name, :phone_number
# should_not_allow_values_for :phone_number, "abcd", "1234"
# should_allow_values_for :phone_number, "(123) 456-7890"
#
# should_protect_attributes :password
#
# should_have_one :profile
# should_have_many :dogs
# should_have_many :messes, :through => :dogs
# should_belong_to :lover
# end
#
# For all of these helpers, the last parameter may be a hash of options.
#
module Macros
include Helpers
include Matchers
# <b>DEPRECATED:</b> Use <tt>fixtures :all</tt> instead
#
# Loads all fixture files (<tt>test/fixtures/*.yml</tt>)
def load_all_fixtures
warn "[DEPRECATION] load_all_fixtures is deprecated. Use `fixtures :all` instead."
fixtures :all
end
# Ensures that the model cannot be saved if one of the attributes listed is not present.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.blank')</tt>
#
# Example:
# should_require_attributes :name, :phone_number
#
def should_require_attributes(*attributes)
message = get_options!(attributes, :message)
klass = model_class
attributes.each do |attribute|
matcher = require_attribute(attribute).with_message(message)
should matcher.description do
assert_accepts(matcher, get_instance_of(klass))
end
end
end
# Ensures that the model cannot be saved if one of the attributes listed is not unique.
# Requires an existing record
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.taken')</tt>
# * <tt>:scoped_to</tt> - field(s) to scope the uniqueness to.
# * <tt>:case_sensitive</tt> - whether or not uniqueness is defined by an
# exact match. Ignored by non-text attributes. Default = <tt>true</tt>
#
# Examples:
# should_require_unique_attributes :keyword, :username
# should_require_unique_attributes :name, :message => "O NOES! SOMEONE STOELED YER NAME!"
# should_require_unique_attributes :email, :scoped_to => :name
# should_require_unique_attributes :address, :scoped_to => [:first_name, :last_name]
# should_require_unique_attributes :email, :case_sensitive => false
#
def should_require_unique_attributes(*attributes)
message, scope, case_sensitive = get_options!(attributes, :message, :scoped_to, :case_sensitive)
scope = [*scope].compact
case_sensitive = true if case_sensitive.nil?
klass = model_class
attributes.each do |attribute|
matcher = require_unique_attribute(attribute).
with_message(message).scoped_to(scope)
matcher = matcher.case_insensitive unless case_sensitive
should matcher.description do
assert_accepts(matcher, get_instance_of(klass))
end
end
end
# Ensures that the attribute cannot be set on mass update.
#
# should_protect_attributes :password, :admin_flag
#
def should_protect_attributes(*attributes)
get_options!(attributes)
klass = model_class
attributes.each do |attribute|
attribute = attribute.to_sym
should "protect #{attribute} from mass updates" do
protected = klass.protected_attributes || []
accessible = klass.accessible_attributes || []
assert protected.include?(attribute.to_s) ||
(!accessible.empty? && !accessible.include?(attribute.to_s)),
(accessible.empty? ?
"#{klass} is protecting #{protected.to_a.to_sentence}, but not #{attribute}." :
"#{klass} has made #{attribute} accessible")
end
end
end
# Ensures that the attribute cannot be changed once the record has been created.
#
# should_have_readonly_attributes :password, :admin_flag
#
def should_have_readonly_attributes(*attributes)
get_options!(attributes)
klass = model_class
attributes.each do |attribute|
attribute = attribute.to_sym
should "make #{attribute} read-only" do
readonly = klass.readonly_attributes || []
assert readonly.include?(attribute.to_s),
(readonly.empty? ?
"#{klass} attribute #{attribute} is not read-only" :
"#{klass} is making #{readonly.to_a.to_sentence} read-only, but not #{attribute}.")
end
end
end
# Ensures that the attribute cannot be set to the given values
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.invalid')</tt>
#
# Example:
# should_not_allow_values_for :isbn, "bad 1", "bad 2"
#
def should_not_allow_values_for(attribute, *bad_values)
message = get_options!(bad_values, :message)
klass = model_class
bad_values.each do |value|
matcher = allow_value(value).for(attribute).with_message(message)
should "not #{matcher.description}" do
assert_rejects matcher, get_instance_of(klass)
end
end
end
# Ensures that the attribute can be set to the given values.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Example:
# should_allow_values_for :isbn, "isbn 1 2345 6789 0", "ISBN 1-2345-6789-0"
#
def should_allow_values_for(attribute, *good_values)
get_options!(good_values)
klass = model_class
klass = model_class
good_values.each do |value|
matcher = allow_value(value).for(attribute)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
end
# Ensures that the length of the attribute is in the given range
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.too_short') % range.first</tt>
# * <tt>:long_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.too_long') % range.last</tt>
#
# Example:
# should_ensure_length_in_range :password, (6..20)
#
def should_ensure_length_in_range(attribute, range, opts = {})
short_message, long_message = get_options!([opts],
:short_message,
:long_message)
klass = model_class
matcher = ensure_length_of(attribute).
is_at_least(range.first).
with_short_message(short_message).
is_at_most(range.last).
with_long_message(long_message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensures that the length of the attribute is at least a certain length
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.too_short') % min_length</tt>
#
# Example:
# should_ensure_length_at_least :name, 3
#
def should_ensure_length_at_least(attribute, min_length, opts = {})
short_message = get_options!([opts], :short_message)
klass = model_class
matcher = ensure_length_of(attribute).
is_at_least(min_length).
with_short_message(short_message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensures that the length of the attribute is exactly a certain length
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.wrong_length') % length</tt>
#
# Example:
# should_ensure_length_is :ssn, 9
#
def should_ensure_length_is(attribute, length, opts = {})
message = get_options!([opts], :message)
klass = model_class
matcher = ensure_length_of(attribute).
is_equal_to(length).
with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensure that the attribute is in the range specified
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:low_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.inclusion')</tt>
# * <tt>:high_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.inclusion')</tt>
#
# Example:
# should_ensure_value_in_range :age, (0..100)
#
def should_ensure_value_in_range(attribute, range, opts = {})
message = get_options!([opts], :message)
message ||= default_error_message(:inclusion)
klass = model_class
matcher = ensure_inclusion_of(attribute).
in_range(range).
with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensure that the attribute is numeric
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.not_a_number')</tt>
#
# Example:
# should_only_allow_numeric_values_for :age
#
def should_only_allow_numeric_values_for(*attributes)
message = get_options!(attributes, :message)
klass = model_class
attributes.each do |attribute|
matcher = only_allow_numeric_values_for(attribute).
with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
end
# Ensures that the has_many relationship exists. Will also test that the
# associated table has the required columns. Works with polymorphic
# associations.
#
# Options:
# * <tt>:through</tt> - association name for <tt>has_many :through</tt>
# * <tt>:dependent</tt> - tests that the association makes use of the dependent option.
#
# Example:
# should_have_many :friends
# should_have_many :enemies, :through => :friends
# should_have_many :enemies, :dependent => :destroy
#
def should_have_many(*associations)
through, dependent = get_options!(associations, :through, :dependent)
klass = model_class
associations.each do |association|
matcher = have_many(association).through(through).dependent(dependent)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensure that the has_one relationship exists. Will also test that the
# associated table has the required columns. Works with polymorphic
# associations.
#
# Options:
# * <tt>:dependent</tt> - tests that the association makes use of the dependent option.
#
# Example:
# should_have_one :god # unless hindu
#
def should_have_one(*associations)
dependent = get_options!(associations, :dependent)
klass = model_class
associations.each do |association|
matcher = have_one(association).dependent(dependent)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensures that the has_and_belongs_to_many relationship exists, and that the join
# table is in place.
#
# should_have_and_belong_to_many :posts, :cars
#
def should_have_and_belong_to_many(*associations)
get_options!(associations)
klass = model_class
associations.each do |association|
matcher = have_and_belong_to_many(association)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensure that the belongs_to relationship exists.
#
# should_belong_to :parent
#
def should_belong_to(*associations)
dependent = get_options!(associations, :dependent)
klass = model_class
associations.each do |association|
matcher = belong_to(association).dependent(dependent)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensure that the given class methods are defined on the model.
#
# should_have_class_methods :find, :destroy
#
def should_have_class_methods(*methods)
get_options!(methods)
klass = model_class
methods.each do |method|
should "respond to class method ##{method}" do
assert_respond_to klass, method, "#{klass.name} does not have class method #{method}"
end
end
end
# Ensure that the given instance methods are defined on the model.
#
# should_have_instance_methods :email, :name, :name=
#
def should_have_instance_methods(*methods)
get_options!(methods)
klass = model_class
methods.each do |method|
should "respond to instance method ##{method}" do
assert_respond_to klass.new, method, "#{klass.name} does not have instance method #{method}"
end
end
end
# Ensure that the given columns are defined on the models backing SQL table.
#
# should_have_db_columns :id, :email, :name, :created_at
#
def should_have_db_columns(*columns)
column_type = get_options!(columns, :type)
klass = model_class
columns.each do |name|
test_name = "have column #{name}"
test_name += " of type #{column_type}" if column_type
should test_name do
column = klass.columns.detect {|c| c.name == name.to_s }
assert column, "#{klass.name} does not have column #{name}"
end
end
end
# Ensure that the given column is defined on the models backing SQL table. The options are the same as
# the instance variables defined on the column definition: :precision, :limit, :default, :null,
# :primary, :type, :scale, and :sql_type.
#
# should_have_db_column :email, :type => "string", :default => nil, :precision => nil, :limit => 255,
# :null => true, :primary => false, :scale => nil, :sql_type => 'varchar(255)'
#
def should_have_db_column(name, opts = {})
klass = model_class
test_name = "have column named :#{name}"
test_name += " with options " + opts.inspect unless opts.empty?
should test_name do
column = klass.columns.detect {|c| c.name == name.to_s }
assert column, "#{klass.name} does not have column #{name}"
opts.each do |k, v|
assert_equal column.instance_variable_get("@#{k}").to_s, v.to_s, ":#{name} column on table for #{klass} does not match option :#{k}"
end
end
end
# Ensures that there are DB indices on the given columns or tuples of columns.
# Also aliased to should_have_index for readability
#
# Options:
# * <tt>:unique</tt> - whether or not the index has a unique
# constraint. Use <tt>true</tt> to explicitly test for a unique
# constraint. Use <tt>false</tt> to explicitly test for a non-unique
# constraint. Use <tt>nil</tt> if you don't care whether the index is
# unique or not. Default = <tt>nil</tt>
#
# Examples:
#
# should_have_indices :email, :name, [:commentable_type, :commentable_id]
# should_have_index :age
# should_have_index :ssn, :unique => true
#
def should_have_indices(*columns)
unique = get_options!(columns, :unique)
table = model_class.table_name
indices = ::ActiveRecord::Base.connection.indexes(table)
index_types = { true => "unique", false => "non-unique" }
index_type = index_types[unique] || "an"
columns.each do |column|
should "have #{index_type} index on #{table} for #{column.inspect}" do
columns = [column].flatten.map(&:to_s)
index = indices.detect {|ind| ind.columns == columns }
assert index, "#{table} does not have an index for #{column.inspect}"
if [true, false].include?(unique)
assert_equal unique, index.unique, "Expected #{index_type} index but was #{index_types[index.unique]}."
end
end
end
end
alias_method :should_have_index, :should_have_indices
# Ensures that the model cannot be saved if one of the attributes listed is not accepted.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.accepted')</tt>
#
# Example:
# should_require_acceptance_of :eula
#
def should_require_acceptance_of(*attributes)
message = get_options!(attributes, :message)
klass = model_class
attributes.each do |attribute|
matcher = require_acceptance_of(attribute).with_message(message)
should matcher.description do
assert_matches matcher, get_instance_of(klass)
end
end
end
# Ensures that the model has a method named scope_name that returns a NamedScope object with the
# proxy options set to the options you supply. scope_name can be either a symbol, or a method
# call which will be evaled against the model. The eval'd method call has access to all the same
# instance variables that a should statement would.
#
# Options: Any of the options that the named scope would pass on to find.
#
# Example:
#
# should_have_named_scope :visible, :conditions => {:visible => true}
#
# Passes for
#
# named_scope :visible, :conditions => {:visible => true}
#
# Or for
#
# def self.visible
# scoped(:conditions => {:visible => true})
# end
#
# You can test lambdas or methods that return ActiveRecord#scoped calls:
#
# should_have_named_scope 'recent(5)', :limit => 5
# should_have_named_scope 'recent(1)', :limit => 1
#
# Passes for
# named_scope :recent, lambda {|c| {:limit => c}}
#
# Or for
#
# def self.recent(c)
# scoped(:limit => c)
# end
#
def should_have_named_scope(scope_call, *args)
klass = model_class
scope_opts = args.extract_options!
scope_call = scope_call.to_s
context scope_call do
setup do
@scope = eval("#{klass}.#{scope_call}")
end
should "return a scope object" do
assert_equal ::ActiveRecord::NamedScope::Scope, @scope.class
end
unless scope_opts.empty?
should "scope itself to #{scope_opts.inspect}" do
assert_equal scope_opts, @scope.proxy_options
end
end
end
end
end
end
end
Fixed reference to assert_matches
module Shoulda # :nodoc:
module ActiveRecord # :nodoc:
# = Macro test helpers for your active record models
#
# These helpers will test most of the validations and associations for your ActiveRecord models.
#
# class UserTest < Test::Unit::TestCase
# should_require_attributes :name, :phone_number
# should_not_allow_values_for :phone_number, "abcd", "1234"
# should_allow_values_for :phone_number, "(123) 456-7890"
#
# should_protect_attributes :password
#
# should_have_one :profile
# should_have_many :dogs
# should_have_many :messes, :through => :dogs
# should_belong_to :lover
# end
#
# For all of these helpers, the last parameter may be a hash of options.
#
module Macros
include Helpers
include Matchers
# <b>DEPRECATED:</b> Use <tt>fixtures :all</tt> instead
#
# Loads all fixture files (<tt>test/fixtures/*.yml</tt>)
def load_all_fixtures
warn "[DEPRECATION] load_all_fixtures is deprecated. Use `fixtures :all` instead."
fixtures :all
end
# Ensures that the model cannot be saved if one of the attributes listed is not present.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.blank')</tt>
#
# Example:
# should_require_attributes :name, :phone_number
#
def should_require_attributes(*attributes)
message = get_options!(attributes, :message)
klass = model_class
attributes.each do |attribute|
matcher = require_attribute(attribute).with_message(message)
should matcher.description do
assert_accepts(matcher, get_instance_of(klass))
end
end
end
# Ensures that the model cannot be saved if one of the attributes listed is not unique.
# Requires an existing record
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.taken')</tt>
# * <tt>:scoped_to</tt> - field(s) to scope the uniqueness to.
# * <tt>:case_sensitive</tt> - whether or not uniqueness is defined by an
# exact match. Ignored by non-text attributes. Default = <tt>true</tt>
#
# Examples:
# should_require_unique_attributes :keyword, :username
# should_require_unique_attributes :name, :message => "O NOES! SOMEONE STOELED YER NAME!"
# should_require_unique_attributes :email, :scoped_to => :name
# should_require_unique_attributes :address, :scoped_to => [:first_name, :last_name]
# should_require_unique_attributes :email, :case_sensitive => false
#
def should_require_unique_attributes(*attributes)
message, scope, case_sensitive = get_options!(attributes, :message, :scoped_to, :case_sensitive)
scope = [*scope].compact
case_sensitive = true if case_sensitive.nil?
klass = model_class
attributes.each do |attribute|
matcher = require_unique_attribute(attribute).
with_message(message).scoped_to(scope)
matcher = matcher.case_insensitive unless case_sensitive
should matcher.description do
assert_accepts(matcher, get_instance_of(klass))
end
end
end
# Ensures that the attribute cannot be set on mass update.
#
# should_protect_attributes :password, :admin_flag
#
def should_protect_attributes(*attributes)
get_options!(attributes)
klass = model_class
attributes.each do |attribute|
attribute = attribute.to_sym
should "protect #{attribute} from mass updates" do
protected = klass.protected_attributes || []
accessible = klass.accessible_attributes || []
assert protected.include?(attribute.to_s) ||
(!accessible.empty? && !accessible.include?(attribute.to_s)),
(accessible.empty? ?
"#{klass} is protecting #{protected.to_a.to_sentence}, but not #{attribute}." :
"#{klass} has made #{attribute} accessible")
end
end
end
# Ensures that the attribute cannot be changed once the record has been created.
#
# should_have_readonly_attributes :password, :admin_flag
#
def should_have_readonly_attributes(*attributes)
get_options!(attributes)
klass = model_class
attributes.each do |attribute|
attribute = attribute.to_sym
should "make #{attribute} read-only" do
readonly = klass.readonly_attributes || []
assert readonly.include?(attribute.to_s),
(readonly.empty? ?
"#{klass} attribute #{attribute} is not read-only" :
"#{klass} is making #{readonly.to_a.to_sentence} read-only, but not #{attribute}.")
end
end
end
# Ensures that the attribute cannot be set to the given values
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.invalid')</tt>
#
# Example:
# should_not_allow_values_for :isbn, "bad 1", "bad 2"
#
def should_not_allow_values_for(attribute, *bad_values)
message = get_options!(bad_values, :message)
klass = model_class
bad_values.each do |value|
matcher = allow_value(value).for(attribute).with_message(message)
should "not #{matcher.description}" do
assert_rejects matcher, get_instance_of(klass)
end
end
end
# Ensures that the attribute can be set to the given values.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Example:
# should_allow_values_for :isbn, "isbn 1 2345 6789 0", "ISBN 1-2345-6789-0"
#
def should_allow_values_for(attribute, *good_values)
get_options!(good_values)
klass = model_class
klass = model_class
good_values.each do |value|
matcher = allow_value(value).for(attribute)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
end
# Ensures that the length of the attribute is in the given range
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.too_short') % range.first</tt>
# * <tt>:long_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.too_long') % range.last</tt>
#
# Example:
# should_ensure_length_in_range :password, (6..20)
#
def should_ensure_length_in_range(attribute, range, opts = {})
short_message, long_message = get_options!([opts],
:short_message,
:long_message)
klass = model_class
matcher = ensure_length_of(attribute).
is_at_least(range.first).
with_short_message(short_message).
is_at_most(range.last).
with_long_message(long_message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensures that the length of the attribute is at least a certain length
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:short_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.too_short') % min_length</tt>
#
# Example:
# should_ensure_length_at_least :name, 3
#
def should_ensure_length_at_least(attribute, min_length, opts = {})
short_message = get_options!([opts], :short_message)
klass = model_class
matcher = ensure_length_of(attribute).
is_at_least(min_length).
with_short_message(short_message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensures that the length of the attribute is exactly a certain length
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.wrong_length') % length</tt>
#
# Example:
# should_ensure_length_is :ssn, 9
#
def should_ensure_length_is(attribute, length, opts = {})
message = get_options!([opts], :message)
klass = model_class
matcher = ensure_length_of(attribute).
is_equal_to(length).
with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensure that the attribute is in the range specified
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:low_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.inclusion')</tt>
# * <tt>:high_message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.inclusion')</tt>
#
# Example:
# should_ensure_value_in_range :age, (0..100)
#
def should_ensure_value_in_range(attribute, range, opts = {})
message = get_options!([opts], :message)
message ||= default_error_message(:inclusion)
klass = model_class
matcher = ensure_inclusion_of(attribute).
in_range(range).
with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
# Ensure that the attribute is numeric
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.not_a_number')</tt>
#
# Example:
# should_only_allow_numeric_values_for :age
#
def should_only_allow_numeric_values_for(*attributes)
message = get_options!(attributes, :message)
klass = model_class
attributes.each do |attribute|
matcher = only_allow_numeric_values_for(attribute).
with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
end
# Ensures that the has_many relationship exists. Will also test that the
# associated table has the required columns. Works with polymorphic
# associations.
#
# Options:
# * <tt>:through</tt> - association name for <tt>has_many :through</tt>
# * <tt>:dependent</tt> - tests that the association makes use of the dependent option.
#
# Example:
# should_have_many :friends
# should_have_many :enemies, :through => :friends
# should_have_many :enemies, :dependent => :destroy
#
def should_have_many(*associations)
through, dependent = get_options!(associations, :through, :dependent)
klass = model_class
associations.each do |association|
matcher = have_many(association).through(through).dependent(dependent)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensure that the has_one relationship exists. Will also test that the
# associated table has the required columns. Works with polymorphic
# associations.
#
# Options:
# * <tt>:dependent</tt> - tests that the association makes use of the dependent option.
#
# Example:
# should_have_one :god # unless hindu
#
def should_have_one(*associations)
dependent = get_options!(associations, :dependent)
klass = model_class
associations.each do |association|
matcher = have_one(association).dependent(dependent)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensures that the has_and_belongs_to_many relationship exists, and that the join
# table is in place.
#
# should_have_and_belong_to_many :posts, :cars
#
def should_have_and_belong_to_many(*associations)
get_options!(associations)
klass = model_class
associations.each do |association|
matcher = have_and_belong_to_many(association)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensure that the belongs_to relationship exists.
#
# should_belong_to :parent
#
def should_belong_to(*associations)
dependent = get_options!(associations, :dependent)
klass = model_class
associations.each do |association|
matcher = belong_to(association).dependent(dependent)
should matcher.description do
assert_accepts(matcher, klass.new)
end
end
end
# Ensure that the given class methods are defined on the model.
#
# should_have_class_methods :find, :destroy
#
def should_have_class_methods(*methods)
get_options!(methods)
klass = model_class
methods.each do |method|
should "respond to class method ##{method}" do
assert_respond_to klass, method, "#{klass.name} does not have class method #{method}"
end
end
end
# Ensure that the given instance methods are defined on the model.
#
# should_have_instance_methods :email, :name, :name=
#
def should_have_instance_methods(*methods)
get_options!(methods)
klass = model_class
methods.each do |method|
should "respond to instance method ##{method}" do
assert_respond_to klass.new, method, "#{klass.name} does not have instance method #{method}"
end
end
end
# Ensure that the given columns are defined on the models backing SQL table.
#
# should_have_db_columns :id, :email, :name, :created_at
#
def should_have_db_columns(*columns)
column_type = get_options!(columns, :type)
klass = model_class
columns.each do |name|
test_name = "have column #{name}"
test_name += " of type #{column_type}" if column_type
should test_name do
column = klass.columns.detect {|c| c.name == name.to_s }
assert column, "#{klass.name} does not have column #{name}"
end
end
end
# Ensure that the given column is defined on the models backing SQL table. The options are the same as
# the instance variables defined on the column definition: :precision, :limit, :default, :null,
# :primary, :type, :scale, and :sql_type.
#
# should_have_db_column :email, :type => "string", :default => nil, :precision => nil, :limit => 255,
# :null => true, :primary => false, :scale => nil, :sql_type => 'varchar(255)'
#
def should_have_db_column(name, opts = {})
klass = model_class
test_name = "have column named :#{name}"
test_name += " with options " + opts.inspect unless opts.empty?
should test_name do
column = klass.columns.detect {|c| c.name == name.to_s }
assert column, "#{klass.name} does not have column #{name}"
opts.each do |k, v|
assert_equal column.instance_variable_get("@#{k}").to_s, v.to_s, ":#{name} column on table for #{klass} does not match option :#{k}"
end
end
end
# Ensures that there are DB indices on the given columns or tuples of columns.
# Also aliased to should_have_index for readability
#
# Options:
# * <tt>:unique</tt> - whether or not the index has a unique
# constraint. Use <tt>true</tt> to explicitly test for a unique
# constraint. Use <tt>false</tt> to explicitly test for a non-unique
# constraint. Use <tt>nil</tt> if you don't care whether the index is
# unique or not. Default = <tt>nil</tt>
#
# Examples:
#
# should_have_indices :email, :name, [:commentable_type, :commentable_id]
# should_have_index :age
# should_have_index :ssn, :unique => true
#
def should_have_indices(*columns)
unique = get_options!(columns, :unique)
table = model_class.table_name
indices = ::ActiveRecord::Base.connection.indexes(table)
index_types = { true => "unique", false => "non-unique" }
index_type = index_types[unique] || "an"
columns.each do |column|
should "have #{index_type} index on #{table} for #{column.inspect}" do
columns = [column].flatten.map(&:to_s)
index = indices.detect {|ind| ind.columns == columns }
assert index, "#{table} does not have an index for #{column.inspect}"
if [true, false].include?(unique)
assert_equal unique, index.unique, "Expected #{index_type} index but was #{index_types[index.unique]}."
end
end
end
end
alias_method :should_have_index, :should_have_indices
# Ensures that the model cannot be saved if one of the attributes listed is not accepted.
#
# If an instance variable has been created in the setup named after the
# model being tested, then this method will use that. Otherwise, it will
# create a new instance to test against.
#
# Options:
# * <tt>:message</tt> - value the test expects to find in <tt>errors.on(:attribute)</tt>.
# Regexp or string. Default = <tt>I18n.translate('activerecord.errors.messages.accepted')</tt>
#
# Example:
# should_require_acceptance_of :eula
#
def should_require_acceptance_of(*attributes)
message = get_options!(attributes, :message)
klass = model_class
attributes.each do |attribute|
matcher = require_acceptance_of(attribute).with_message(message)
should matcher.description do
assert_accepts matcher, get_instance_of(klass)
end
end
end
# Ensures that the model has a method named scope_name that returns a NamedScope object with the
# proxy options set to the options you supply. scope_name can be either a symbol, or a method
# call which will be evaled against the model. The eval'd method call has access to all the same
# instance variables that a should statement would.
#
# Options: Any of the options that the named scope would pass on to find.
#
# Example:
#
# should_have_named_scope :visible, :conditions => {:visible => true}
#
# Passes for
#
# named_scope :visible, :conditions => {:visible => true}
#
# Or for
#
# def self.visible
# scoped(:conditions => {:visible => true})
# end
#
# You can test lambdas or methods that return ActiveRecord#scoped calls:
#
# should_have_named_scope 'recent(5)', :limit => 5
# should_have_named_scope 'recent(1)', :limit => 1
#
# Passes for
# named_scope :recent, lambda {|c| {:limit => c}}
#
# Or for
#
# def self.recent(c)
# scoped(:limit => c)
# end
#
def should_have_named_scope(scope_call, *args)
klass = model_class
scope_opts = args.extract_options!
scope_call = scope_call.to_s
context scope_call do
setup do
@scope = eval("#{klass}.#{scope_call}")
end
should "return a scope object" do
assert_equal ::ActiveRecord::NamedScope::Scope, @scope.class
end
unless scope_opts.empty?
should "scope itself to #{scope_opts.inspect}" do
assert_equal scope_opts, @scope.proxy_options
end
end
end
end
end
end
end
|
module Rules
module Evaluators
define_evaluator :equals do
self.evaluation_method = ->(lhs, rhs) { lhs == rhs }
self.requires_rhs = true
end
define_evaluator :not_equals do
self.evaluation_method = ->(lhs, rhs) { lhs != rhs }
self.name = 'does not equal'
self.requires_rhs = true
end
define_evaluator :contains do
self.evaluation_method = ->(lhs, rhs) { lhs.include?(rhs) }
self.name = 'contains'
self.requires_rhs = true
end
define_evaluator :not_contains do
self.evaluation_method = ->(lhs, rhs) { !lhs.include?(rhs) }
self.name = 'does not contain'
end
define_evaluator :nil do
self.evaluation_method = ->(lhs) { lhs.nil? }
self.name = 'exists'
self.requires_rhs = false
end
define_evaluator :not_nil do
self.evaluation_method = ->(lhs) { !lhs.nil? }
self.name = 'does not exist'
self.requires_rhs = false
end
define_evaluator :matches do
self.evaluation_method = ->(lhs) { !!(lhs =~ rhs) }
self.name = 'matches'
self.requires_rhs = false
end
end
end
Add more evaluators
module Rules
module Evaluators
define_evaluator :equals do
self.evaluation_method = ->(lhs, rhs) { lhs == rhs }
self.requires_rhs = true
end
define_evaluator :not_equals do
self.evaluation_method = ->(lhs, rhs) { lhs != rhs }
self.name = 'does not equal'
self.requires_rhs = true
end
define_evaluator :contains do
self.evaluation_method = ->(lhs, rhs) { lhs.include?(rhs) }
self.name = 'contains'
self.requires_rhs = true
end
define_evaluator :not_contains do
self.evaluation_method = ->(lhs, rhs) { !lhs.include?(rhs) }
self.name = 'does not contain'
end
define_evaluator :nil do
self.evaluation_method = ->(lhs) { lhs.nil? }
self.name = 'exists'
self.requires_rhs = false
end
define_evaluator :not_nil do
self.evaluation_method = ->(lhs) { !lhs.nil? }
self.name = 'does not exist'
self.requires_rhs = false
end
define_evaluator :matches do
self.evaluation_method = ->(lhs) { !!(lhs =~ rhs) }
self.name = 'matches'
self.requires_rhs = false
end
define_evaluator :less_than do
self.evaluation_method = ->(lhs, rhs) { lhs < rhs }
self.name = 'less than'
end
define_evaluator :less_than_or_equal_to do
self.evaluation_method = ->(lhs, rhs) { lhs <= rhs }
self.name = 'less than or equal to'
end
define_evaluator :greater_than do
self.evaluation_method = ->(lhs, rhs) { lhs > rhs }
self.name = 'greater than'
end
define_evaluator :greater_than_or_equal_to do
self.evaluation_method = ->(lhs, rhs) { lhs >= rhs }
self.name = 'greater than or equal to'
end
end
end
|
require 'active_record/connection_adapters/abstract/query_cache'
require 'set'
module SlavePools
class ConnectionProxy
include ActiveRecord::ConnectionAdapters::QueryCache
include QueryCacheCompat
attr_accessor :master
attr_accessor :master_depth, :current, :current_pool, :slave_pools
class << self
def generate_safe_delegations
SlavePools.config.safe_methods.each do |method|
generate_safe_delegation(method) unless instance_methods.include?(method)
end
end
protected
def generate_safe_delegation(method)
class_eval %Q{
def #{method}(*args, &block)
send_to_current(:#{method}, *args, &block)
end
}, __FILE__, __LINE__
end
end
def initialize(master, slave_pools)
@master = master
@slave_pools = slave_pools
@master_depth = 0
@reconnect = false
@current_pool = default_pool
if SlavePools.config.defaults_to_master
@current = master
else
@current = current_slave
end
# this ivar is for ConnectionAdapter compatibility
# some gems (e.g. newrelic_rpm) will actually use
# instance_variable_get(:@config) to find it.
@config = current.connection_config
end
def with_pool(pool_name = 'default')
last_conn, last_pool = self.current, self.current_pool
self.current_pool = slave_pools[pool_name.to_sym] || default_pool
self.current = current_slave unless within_master_block?
yield
ensure
self.current_pool = last_pool
self.current = last_conn
end
def with_master
last_conn = self.current
self.current = master
self.master_depth += 1
yield
ensure
self.master_depth = [master_depth - 1, 0].max # ensure that master depth never gets below 0
self.current = last_conn
end
def transaction(*args, &block)
with_master { master.transaction(*args, &block) }
end
# Switches to the next slave database for read operations.
# Fails over to the master database if all slaves are unavailable.
def next_slave!
return if within_master_block? # don't if in with_master block
self.current = current_pool.next
rescue
self.current = master
end
def current_slave
current_pool.current
end
protected
def default_pool
slave_pools[:default] || slave_pools.values.first #if there is no default specified, use the first pool found
end
# Proxies any unknown methods to master.
# Safe methods have been generated during `setup!`.
# Creates a method to speed up subsequent calls.
def method_missing(method, *args, &block)
generate_unsafe_delegation(method)
send(method, *args, &block)
end
def within_master_block?
master_depth > 0
end
def generate_unsafe_delegation(method)
self.instance_eval %Q{
def #{method}(*args, &block)
send_to_master(:#{method}, *args, &block)
end
}, __FILE__, __LINE__
end
def send_to_master(method, *args, &block)
reconnect_master! if @reconnect
master.retrieve_connection.send(method, *args, &block)
rescue => e
log_errors(e, 'send_to_master', method)
raise_master_error(e)
end
def send_to_current(method, *args, &block)
reconnect_master! if @reconnect && master?
# logger.debug "[SlavePools] Using #{current.name}"
current.retrieve_connection.send(method, *args, &block)
rescue Mysql2::Error, ActiveRecord::StatementInvalid => e
log_errors(e, 'send_to_current', method)
raise_master_error(e) if master?
logger.warn "[SlavePools] Error reading from slave database"
logger.error %(#{e.message}\n#{e.backtrace.join("\n")})
if e.message.match(/Timeout waiting for a response from the last query/)
# Verify that the connection is active & re-raise
logger.error "[SlavePools] Slave Query Timeout - do not send to master"
current.retrieve_connection.verify!
raise e
else
logger.error "[SlavePools] Slave Query Error - sending to master"
send_to_master(method, *args, &block) # if cant connect, send the query to master
end
end
def reconnect_master!
master.retrieve_connection.reconnect!
@reconnect = false
end
def raise_master_error(error)
logger.fatal "[SlavePools] Error accessing master database. Scheduling reconnect"
@reconnect = true
raise error
end
def master?
current == master
end
private
def logger
SlavePools.logger
end
def log_errors(error, sp_method, db_method)
logger.error "[SlavePools] - Error: #{error}"
logger.error "[SlavePools] - SlavePool Method: #{sp_method}"
logger.error "[SlavePools] - Master Value: #{master}"
logger.error "[SlavePools] - Master Depth: #{master_depth}"
logger.error "[SlavePools] - Current Value: #{current}"
logger.error "[SlavePools] - Current Pool: #{current_pool}"
logger.error "[SlavePools] - Current Pool Slaves: #{current_pool.slaves}" if current_pool
logger.error "[SlavePools] - Current Pool Name: #{current_pool.name}" if current_pool
logger.error "[SlavePools] - Reconnect Value: #{@reconnect}"
logger.error "[SlavePools] - Default Pool: #{default_pool}"
logger.error "[SlavePools] - DB Method: #{db_method}"
end
end
end
prefer heredoc for metaprogramming
require 'active_record/connection_adapters/abstract/query_cache'
require 'set'
module SlavePools
class ConnectionProxy
include ActiveRecord::ConnectionAdapters::QueryCache
include QueryCacheCompat
attr_accessor :master
attr_accessor :master_depth, :current, :current_pool, :slave_pools
class << self
def generate_safe_delegations
SlavePools.config.safe_methods.each do |method|
generate_safe_delegation(method) unless instance_methods.include?(method)
end
end
protected
def generate_safe_delegation(method)
class_eval <<-END, __FILE__, __LINE__ + 1
def #{method}(*args, &block)
send_to_current(:#{method}, *args, &block)
end
END
end
end
def initialize(master, slave_pools)
@master = master
@slave_pools = slave_pools
@master_depth = 0
@reconnect = false
@current_pool = default_pool
if SlavePools.config.defaults_to_master
@current = master
else
@current = current_slave
end
# this ivar is for ConnectionAdapter compatibility
# some gems (e.g. newrelic_rpm) will actually use
# instance_variable_get(:@config) to find it.
@config = current.connection_config
end
def with_pool(pool_name = 'default')
last_conn, last_pool = self.current, self.current_pool
self.current_pool = slave_pools[pool_name.to_sym] || default_pool
self.current = current_slave unless within_master_block?
yield
ensure
self.current_pool = last_pool
self.current = last_conn
end
def with_master
last_conn = self.current
self.current = master
self.master_depth += 1
yield
ensure
self.master_depth = [master_depth - 1, 0].max # ensure that master depth never gets below 0
self.current = last_conn
end
def transaction(*args, &block)
with_master { master.transaction(*args, &block) }
end
# Switches to the next slave database for read operations.
# Fails over to the master database if all slaves are unavailable.
def next_slave!
return if within_master_block? # don't if in with_master block
self.current = current_pool.next
rescue
self.current = master
end
def current_slave
current_pool.current
end
protected
def default_pool
slave_pools[:default] || slave_pools.values.first #if there is no default specified, use the first pool found
end
# Proxies any unknown methods to master.
# Safe methods have been generated during `setup!`.
# Creates a method to speed up subsequent calls.
def method_missing(method, *args, &block)
generate_unsafe_delegation(method)
send(method, *args, &block)
end
def within_master_block?
master_depth > 0
end
def generate_unsafe_delegation(method)
self.class_eval <<-END, __FILE__, __LINE__ + 1
def #{method}(*args, &block)
send_to_master(:#{method}, *args, &block)
end
END
end
def send_to_master(method, *args, &block)
reconnect_master! if @reconnect
master.retrieve_connection.send(method, *args, &block)
rescue => e
log_errors(e, 'send_to_master', method)
raise_master_error(e)
end
def send_to_current(method, *args, &block)
reconnect_master! if @reconnect && master?
# logger.debug "[SlavePools] Using #{current.name}"
current.retrieve_connection.send(method, *args, &block)
rescue Mysql2::Error, ActiveRecord::StatementInvalid => e
log_errors(e, 'send_to_current', method)
raise_master_error(e) if master?
logger.warn "[SlavePools] Error reading from slave database"
logger.error %(#{e.message}\n#{e.backtrace.join("\n")})
if e.message.match(/Timeout waiting for a response from the last query/)
# Verify that the connection is active & re-raise
logger.error "[SlavePools] Slave Query Timeout - do not send to master"
current.retrieve_connection.verify!
raise e
else
logger.error "[SlavePools] Slave Query Error - sending to master"
send_to_master(method, *args, &block) # if cant connect, send the query to master
end
end
def reconnect_master!
master.retrieve_connection.reconnect!
@reconnect = false
end
def raise_master_error(error)
logger.fatal "[SlavePools] Error accessing master database. Scheduling reconnect"
@reconnect = true
raise error
end
def master?
current == master
end
private
def logger
SlavePools.logger
end
def log_errors(error, sp_method, db_method)
logger.error "[SlavePools] - Error: #{error}"
logger.error "[SlavePools] - SlavePool Method: #{sp_method}"
logger.error "[SlavePools] - Master Value: #{master}"
logger.error "[SlavePools] - Master Depth: #{master_depth}"
logger.error "[SlavePools] - Current Value: #{current}"
logger.error "[SlavePools] - Current Pool: #{current_pool}"
logger.error "[SlavePools] - Current Pool Slaves: #{current_pool.slaves}" if current_pool
logger.error "[SlavePools] - Current Pool Name: #{current_pool.name}" if current_pool
logger.error "[SlavePools] - Reconnect Value: #{@reconnect}"
logger.error "[SlavePools] - Default Pool: #{default_pool}"
logger.error "[SlavePools] - DB Method: #{db_method}"
end
end
end
|
module SchemaToScaffold
class Attribute
attr_reader :name, :type
def initialize(type, name)
@name, @type = name, type
end
def to_script
"#{name}:#{type}"
end
def self.parse(attribute)
Attribute.new(*attribute.match(/t\.(\w+)\s+"(\w+)"/).captures)
end
end
end
excluding "created_at" and "updated_at" fields from string
module SchemaToScaffold
class Attribute
attr_reader :name, :type
def initialize(type, name)
@name, @type = name, type
end
def to_script
"#{name}:#{type}" unless ["created_at","updated_at"].include? name
end
def self.parse(attribute)
Attribute.new(*attribute.match(/t\.(\w+)\s+"(\w+)"/).captures)
end
end
end
|
module SocialStream
module Models
# {Subject Subjects} are subtypes of {Actor Actors}. {SocialStream Social Stream} provides two
# {Subject Subjects}, {User} and {Group}
#
# Each {Subject} must defined in +config/initializers/social_stream.rb+ in order to be
# included in the application.
#
# = Scopes
# There are several scopes available for subjects
#
# alphabetic:: sort subjects by name
# name_search:: simple search by name
# distinct_initials:: get only the first letter of the name
# followed:: sort by most following incoming {Tie ties}
# liked:: sort by most likes
#
module Subject
extend ActiveSupport::Concern
included do
subtype_of :actor,
:build => { :subject_type => to_s }
has_one :activity_object, :through => :actor
has_one :profile, :through => :actor
validates_presence_of :name
accepts_nested_attributes_for :profile
scope :alphabetic, joins(:actor).merge(Actor.alphabetic)
scope :letter, lambda{ |param|
joins(:actor).merge(Actor.letter(param))
}
scope :name_search, lambda{ |param|
joins(:actor).merge(Actor.name_search(param))
}
scope :tagged_with, lambda { |param|
if param.present?
joins(:actor => :activity_object).merge(ActivityObject.tagged_with(param))
end
}
scope :distinct_initials, joins(:actor).merge(Actor.distinct_initials)
scope :followed, lambda {
joins(:actor).
merge(Actor.followed)
}
scope :liked, lambda {
joins(:actor => :activity_object).
order('activity_objects.like_count DESC')
}
scope :most, lambda { |m|
types = %w( followed liked )
if types.include?(m)
__send__ m
end
}
scope :recent, -> {
order('groups.updated_at DESC')
}
define_index do
indexes actor.name, :sortable => true
indexes actor.email
indexes actor.slug
has created_at
has activity_object.popularity, :as => :popularity, :sortable => true
has activity_object.qscore, :as => :qscore, :sortable => true
has activity_object.ranking, :as => :ranking, :sortable => true
has activity_object.activity_object_audiences(:relation_id), :as => :relation_ids
has activity_object.scope, :as => :scope, :type => :integer
has activity_object.title_length, :as => :title_length, :type => :integer, :sortable => true
has activity_object.desc_length, :as => :desc_length, :type => :integer, :sortable => true
has activity_object.tags_length, :as => :tags_length, :type => :integer, :sortable => true
end
end
module ClassMethods
def find_by_slug(perm)
includes(:actor).where('actors.slug' => perm).first
end
def find_by_slug!(perm)
find_by_slug(perm) ||
raise(ActiveRecord::RecordNotFound)
end
# The types of actors that appear in the contacts/index
#
# You can customize this in each class
def contact_index_models
SocialStream.contact_index_models
end
end
def to_param
slug
end
end
end
end
Bug fixed. Index updated_at for subjects.
module SocialStream
module Models
# {Subject Subjects} are subtypes of {Actor Actors}. {SocialStream Social Stream} provides two
# {Subject Subjects}, {User} and {Group}
#
# Each {Subject} must defined in +config/initializers/social_stream.rb+ in order to be
# included in the application.
#
# = Scopes
# There are several scopes available for subjects
#
# alphabetic:: sort subjects by name
# name_search:: simple search by name
# distinct_initials:: get only the first letter of the name
# followed:: sort by most following incoming {Tie ties}
# liked:: sort by most likes
#
module Subject
extend ActiveSupport::Concern
included do
subtype_of :actor,
:build => { :subject_type => to_s }
has_one :activity_object, :through => :actor
has_one :profile, :through => :actor
validates_presence_of :name
accepts_nested_attributes_for :profile
scope :alphabetic, joins(:actor).merge(Actor.alphabetic)
scope :letter, lambda{ |param|
joins(:actor).merge(Actor.letter(param))
}
scope :name_search, lambda{ |param|
joins(:actor).merge(Actor.name_search(param))
}
scope :tagged_with, lambda { |param|
if param.present?
joins(:actor => :activity_object).merge(ActivityObject.tagged_with(param))
end
}
scope :distinct_initials, joins(:actor).merge(Actor.distinct_initials)
scope :followed, lambda {
joins(:actor).
merge(Actor.followed)
}
scope :liked, lambda {
joins(:actor => :activity_object).
order('activity_objects.like_count DESC')
}
scope :most, lambda { |m|
types = %w( followed liked )
if types.include?(m)
__send__ m
end
}
scope :recent, -> {
order('groups.updated_at DESC')
}
define_index do
indexes actor.name, :sortable => true
indexes actor.email
indexes actor.slug
has created_at
has updated_at
has activity_object.popularity, :as => :popularity, :sortable => true
has activity_object.qscore, :as => :qscore, :sortable => true
has activity_object.ranking, :as => :ranking, :sortable => true
has activity_object.activity_object_audiences(:relation_id), :as => :relation_ids
has activity_object.scope, :as => :scope, :type => :integer
has activity_object.title_length, :as => :title_length, :type => :integer, :sortable => true
has activity_object.desc_length, :as => :desc_length, :type => :integer, :sortable => true
has activity_object.tags_length, :as => :tags_length, :type => :integer, :sortable => true
end
end
module ClassMethods
def find_by_slug(perm)
includes(:actor).where('actors.slug' => perm).first
end
def find_by_slug!(perm)
find_by_slug(perm) ||
raise(ActiveRecord::RecordNotFound)
end
# The types of actors that appear in the contacts/index
#
# You can customize this in each class
def contact_index_models
SocialStream.contact_index_models
end
end
def to_param
slug
end
end
end
end
|
module Sequel
Dataset::NON_SQL_OPTIONS << :disable_insert_output
module MSSQL
module DatabaseMethods
AUTO_INCREMENT = 'IDENTITY(1,1)'.freeze
SERVER_VERSION_RE = /^(\d+)\.(\d+)\.(\d+)/.freeze
SERVER_VERSION_SQL = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS varchar)".freeze
SQL_BEGIN = "BEGIN TRANSACTION".freeze
SQL_COMMIT = "COMMIT TRANSACTION".freeze
SQL_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION".freeze
SQL_ROLLBACK_TO_SAVEPOINT = 'IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION autopoint_%d'.freeze
SQL_SAVEPOINT = 'SAVE TRANSACTION autopoint_%d'.freeze
# The types to check for 0 scale to transform :decimal types
# to :integer.
DECIMAL_TYPE_RE = /number|numeric|decimal/io
# Microsoft SQL Server uses the :mssql type.
def database_type
:mssql
end
# The version of the MSSQL server, as an integer (e.g. 10001600 for
# SQL Server 2008 Express).
def server_version(server=nil)
return @server_version if @server_version
@server_version = synchronize(server) do |conn|
(conn.server_version rescue nil) if conn.respond_to?(:server_version)
end
unless @server_version
m = SERVER_VERSION_RE.match(fetch(SERVER_VERSION_SQL).single_value.to_s)
@server_version = (m[1].to_i * 1000000) + (m[2].to_i * 10000) + m[3].to_i
end
@server_version
end
# MSSQL supports savepoints, though it doesn't support committing/releasing them savepoint
def supports_savepoints?
true
end
# MSSQL supports transaction isolation levels
def supports_transaction_isolation_levels?
true
end
# Microsoft SQL Server supports using the INFORMATION_SCHEMA to get
# information on tables.
def tables(opts={})
m = output_identifier_meth
metadata_dataset.from(:information_schema__tables___t).
select(:table_name).
filter(:table_type=>'BASE TABLE', :table_schema=>(opts[:schema]||default_schema||'dbo').to_s).
map{|x| m.call(x[:table_name])}
end
private
# MSSQL uses the IDENTITY(1,1) column for autoincrementing columns.
def auto_increment_sql
AUTO_INCREMENT
end
# MSSQL specific syntax for altering tables.
def alter_table_sql(table, op)
case op[:op]
when :add_column
"ALTER TABLE #{quote_schema_table(table)} ADD #{column_definition_sql(op)}"
when :rename_column
"sp_rename #{literal("#{quote_schema_table(table)}.#{quote_identifier(op[:name])}")}, #{literal(op[:new_name].to_s)}, 'COLUMN'"
when :set_column_type
"ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(op[:name])} #{type_literal(op)}"
when :set_column_null
sch = schema(table).find{|k,v| k.to_s == op[:name].to_s}.last
type = sch[:db_type]
if [:string, :decimal].include?(sch[:type]) and size = (sch[:max_chars] || sch[:column_size])
type += "(#{size}#{", #{sch[:scale]}" if sch[:scale] && sch[:scale].to_i > 0})"
end
"ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(op[:name])} #{type_literal(:type=>type)} #{'NOT ' unless op[:null]}NULL"
when :set_column_default
"ALTER TABLE #{quote_schema_table(table)} ADD CONSTRAINT #{quote_identifier("sequel_#{table}_#{op[:name]}_def")} DEFAULT #{literal(op[:default])} FOR #{quote_identifier(op[:name])}"
else
super(table, op)
end
end
# SQL to start a new savepoint
def begin_savepoint_sql(depth)
SQL_SAVEPOINT % depth
end
# SQL to BEGIN a transaction.
def begin_transaction_sql
SQL_BEGIN
end
# Commit the active transaction on the connection, does not commit/release
# savepoints.
def commit_transaction(conn, opts={})
log_connection_execute(conn, commit_transaction_sql) unless Thread.current[:sequel_transaction_depth] > 1
end
# SQL to COMMIT a transaction.
def commit_transaction_sql
SQL_COMMIT
end
# MSSQL uses the name of the table to decide the difference between
# a regular and temporary table, with temporary table names starting with
# a #.
def create_table_sql(name, generator, options)
"CREATE TABLE #{quote_schema_table(options[:temp] ? "##{name}" : name)} (#{column_list_sql(generator)})"
end
# The SQL to drop an index for the table.
def drop_index_sql(table, op)
"DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))} ON #{quote_schema_table(table)}"
end
# Always quote identifiers in the metadata_dataset, so schema parsing works.
def metadata_dataset
ds = super
ds.quote_identifiers = true
ds
end
# Use sp_rename to rename the table
def rename_table_sql(name, new_name)
"sp_rename #{literal(quote_schema_table(name))}, #{quote_identifier(schema_and_table(new_name).pop)}"
end
# SQL to rollback to a savepoint
def rollback_savepoint_sql(depth)
SQL_ROLLBACK_TO_SAVEPOINT % depth
end
# SQL to ROLLBACK a transaction.
def rollback_transaction_sql
SQL_ROLLBACK
end
# MSSQL uses the INFORMATION_SCHEMA to hold column information. This method does
# not support the parsing of primary key information.
def schema_parse_table(table_name, opts)
m = output_identifier_meth
m2 = input_identifier_meth
ds = metadata_dataset.from(:information_schema__tables___t).
join(:information_schema__columns___c, :table_catalog=>:table_catalog,
:table_schema => :table_schema, :table_name => :table_name).
select(:column_name___column, :data_type___db_type, :character_maximum_length___max_chars, :column_default___default, :is_nullable___allow_null, :numeric_precision___column_size, :numeric_scale___scale).
filter(:c__table_name=>m2.call(table_name.to_s))
if schema = opts[:schema] || default_schema
ds.filter!(:c__table_schema=>schema)
end
ds.map do |row|
row[:allow_null] = row[:allow_null] == 'YES' ? true : false
row[:default] = nil if blank_object?(row[:default])
row[:type] = if row[:db_type] =~ DECIMAL_TYPE_RE && row[:scale] == 0
:integer
else
schema_column_type(row[:db_type])
end
[m.call(row.delete(:column)), row]
end
end
# MSSQL has both datetime and timestamp classes, most people are going
# to want datetime
def type_literal_generic_datetime(column)
:datetime
end
# MSSQL has both datetime and timestamp classes, most people are going
# to want datetime
def type_literal_generic_time(column)
column[:only_time] ? :time : :datetime
end
# MSSQL doesn't have a true boolean class, so it uses bit
def type_literal_generic_trueclass(column)
:bit
end
# MSSQL uses image type for blobs
def type_literal_generic_file(column)
:image
end
# support for clustered index type
def index_definition_sql(table_name, index)
index_name = index[:name] || default_index_name(table_name, index[:columns])
clustered = index[:type] == :clustered
if index[:where]
raise Error, "Partial indexes are not supported for this database"
else
"CREATE #{'UNIQUE ' if index[:unique]}#{'CLUSTERED ' if clustered}INDEX #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}"
end
end
end
module DatasetMethods
BOOL_TRUE = '1'.freeze
BOOL_FALSE = '0'.freeze
COMMA_SEPARATOR = ', '.freeze
DELETE_CLAUSE_METHODS = Dataset.clause_methods(:delete, %w'with from output from2 where')
INSERT_CLAUSE_METHODS = Dataset.clause_methods(:insert, %w'with into columns output values')
SELECT_CLAUSE_METHODS = Dataset.clause_methods(:select, %w'with distinct limit columns into from lock join where group having order compounds')
UPDATE_CLAUSE_METHODS = Dataset.clause_methods(:update, %w'with table set output from where')
NOLOCK = ' WITH (NOLOCK)'.freeze
UPDLOCK = ' WITH (UPDLOCK)'.freeze
WILDCARD = LiteralString.new('*').freeze
CONSTANT_MAP = {:CURRENT_DATE=>'CAST(CURRENT_TIMESTAMP AS DATE)'.freeze, :CURRENT_TIME=>'CAST(CURRENT_TIMESTAMP AS TIME)'.freeze}
# MSSQL uses + for string concatenation, and LIKE is case insensitive by default.
def complex_expression_sql(op, args)
case op
when :'||'
super(:+, args)
when :ILIKE
super(:LIKE, args)
when :"NOT ILIKE"
super(:"NOT LIKE", args)
when :<<
"(#{literal(args[0])} * POWER(2, #{literal(args[1])}))"
when :>>
"(#{literal(args[0])} / POWER(2, #{literal(args[1])}))"
else
super(op, args)
end
end
# MSSQL doesn't support the SQL standard CURRENT_DATE or CURRENT_TIME
def constant_sql(constant)
CONSTANT_MAP[constant] || super
end
# Disable the use of INSERT OUTPUT
def disable_insert_output
clone(:disable_insert_output=>true)
end
# Disable the use of INSERT OUTPUT, modifying the receiver
def disable_insert_output!
mutation_method(:disable_insert_output)
end
# When returning all rows, if an offset is used, delete the row_number column
# before yielding the row.
def fetch_rows(sql, &block)
@opts[:offset] ? super(sql){|r| r.delete(row_number_column); yield r} : super(sql, &block)
end
# MSSQL uses the CONTAINS keyword for full text search
def full_text_search(cols, terms, opts = {})
filter("CONTAINS (#{literal(cols)}, #{literal(terms)})")
end
# Use the OUTPUT clause to get the value of all columns for the newly inserted record.
def insert_select(*values)
return unless supports_output_clause?
naked.clone(default_server_opts(:sql=>output(nil, [:inserted.*]).insert_sql(*values))).single_record unless opts[:disable_insert_output]
end
# Specify a table for a SELECT ... INTO query.
def into(table)
clone(:into => table)
end
# MSSQL uses a UNION ALL statement to insert multiple values at once.
def multi_insert_sql(columns, values)
[insert_sql(columns, LiteralString.new(values.map {|r| "SELECT #{expression_list(r)}" }.join(" UNION ALL ")))]
end
# Allows you to do a dirty read of uncommitted data using WITH (NOLOCK).
def nolock
lock_style(:dirty)
end
# Include an OUTPUT clause in the eventual INSERT, UPDATE, or DELETE query.
#
# The first argument is the table to output into, and the second argument
# is either an Array of column values to select, or a Hash which maps output
# column names to selected values, in the style of #insert or #update.
#
# Output into a returned result set is not currently supported.
#
# Examples:
#
# dataset.output(:output_table, [:deleted__id, :deleted__name])
# dataset.output(:output_table, :id => :inserted__id, :name => :inserted__name)
def output(into, values)
raise(Error, "SQL Server versions 2000 and earlier do not support the OUTPUT clause") unless supports_output_clause?
output = {}
case values
when Hash
output[:column_list], output[:select_list] = values.keys, values.values
when Array
output[:select_list] = values
end
output[:into] = into
clone({:output => output})
end
# An output method that modifies the receiver.
def output!(into, values)
mutation_method(:output, into, values)
end
# MSSQL uses [] to quote identifiers
def quoted_identifier(name)
"[#{name}]"
end
# MSSQL Requires the use of the ROW_NUMBER window function to emulate
# an offset. This implementation requires MSSQL 2005 or greater (offset
# can't be emulated well in MSSQL 2000).
#
# The implementation is ugly, cloning the current dataset and modifying
# the clone to add a ROW_NUMBER window function (and some other things),
# then using the modified clone in a subselect which is selected from.
#
# If offset is used, an order must be provided, because the use of ROW_NUMBER
# requires an order.
def select_sql
return super unless o = @opts[:offset]
raise(Error, 'MSSQL requires an order be provided if using an offset') unless order = @opts[:order]
dsa1 = dataset_alias(1)
rn = row_number_column
subselect_sql(unlimited.
unordered.
select_append{ROW_NUMBER(:over, :order=>order){}.as(rn)}.
from_self(:alias=>dsa1).
limit(@opts[:limit]).
where(SQL::Identifier.new(rn) > o))
end
# The version of the database server.
def server_version
db.server_version(@opts[:server])
end
# MSSQL 2005+ supports INTERSECT and EXCEPT
def supports_intersect_except?
server_version >= 9000000
end
# MSSQL does not support IS TRUE
def supports_is_true?
false
end
# MSSQL doesn't support JOIN USING
def supports_join_using?
false
end
# MSSQL 2005+ supports modifying joined datasets
def supports_modifying_joins?
true
end
# MSSQL does not support multiple columns for the IN/NOT IN operators
def supports_multiple_column_in?
false
end
# Only 2005+ supports the output clause.
def supports_output_clause?
server_version >= 9000000
end
# MSSQL 2005+ supports window functions
def supports_window_functions?
true
end
protected
# MSSQL does not allow ordering in sub-clauses unless 'top' (limit) is specified
def aggregate_dataset
(options_overlap(Sequel::Dataset::COUNT_FROM_SELF_OPTS) && !options_overlap([:limit])) ? unordered.from_self : super
end
private
# MSSQL supports the OUTPUT clause for DELETE statements.
# It also allows prepending a WITH clause.
def delete_clause_methods
DELETE_CLAUSE_METHODS
end
# Only include the primary table in the main delete clause
def delete_from_sql(sql)
sql << " FROM #{source_list(@opts[:from][0..0])}"
end
# MSSQL supports FROM clauses in DELETE and UPDATE statements.
def delete_from2_sql(sql)
if joined_dataset?
select_from_sql(sql)
select_join_sql(sql)
end
end
alias update_from_sql delete_from2_sql
# Handle the with clause for delete, insert, and update statements
# to be the same as the insert statement.
def delete_with_sql(sql)
select_with_sql(sql)
end
alias insert_with_sql delete_with_sql
alias update_with_sql delete_with_sql
# MSSQL raises an error if you try to provide more than 3 decimal places
# for a fractional timestamp. This probably doesn't work for smalldatetime
# fields.
def format_timestamp_usec(usec)
sprintf(".%03d", usec/1000)
end
# MSSQL supports the OUTPUT clause for INSERT statements.
# It also allows prepending a WITH clause.
def insert_clause_methods
INSERT_CLAUSE_METHODS
end
# MSSQL uses a literal hexidecimal number for blob strings
def literal_blob(v)
blob = '0x'
v.each_byte{|x| blob << sprintf('%02x', x)}
blob
end
# Use unicode string syntax for all strings. Don't double backslashes.
def literal_string(v)
"N'#{v.gsub(/'/, "''")}'"
end
# Use 0 for false on MSSQL
def literal_false
BOOL_FALSE
end
# Use 1 for true on MSSQL
def literal_true
BOOL_TRUE
end
# The alias to use for the row_number column when emulating OFFSET
def row_number_column
:x_sequel_row_number_x
end
# MSSQL adds the limit before the columns
def select_clause_methods
SELECT_CLAUSE_METHODS
end
def select_into_sql(sql)
sql << " INTO #{table_ref(@opts[:into])}" if @opts[:into]
end
# MSSQL uses TOP N for limit. For MSSQL 2005+ TOP (N) is used
# to allow the limit to be a bound variable.
def select_limit_sql(sql)
if l = @opts[:limit]
l = literal(l)
l = "(#{l})" if server_version >= 9000000
sql << " TOP #{l}"
end
end
# Support different types of locking styles
def select_lock_sql(sql)
case @opts[:lock]
when :update
sql << UPDLOCK
when :dirty
sql << NOLOCK
else
super
end
end
# SQL fragment for MSSQL's OUTPUT clause.
def output_sql(sql)
return unless supports_output_clause?
return unless output = @opts[:output]
sql << " OUTPUT #{column_list(output[:select_list])}"
if into = output[:into]
sql << " INTO #{table_ref(into)}"
if column_list = output[:column_list]
cl = []
column_list.each { |k, v| cl << literal(String === k ? k.to_sym : k) }
sql << " (#{cl.join(COMMA_SEPARATOR)})"
end
end
end
alias delete_output_sql output_sql
alias update_output_sql output_sql
alias insert_output_sql output_sql
# MSSQL supports the OUTPUT clause for UPDATE statements.
# It also allows prepending a WITH clause.
def update_clause_methods
UPDATE_CLAUSE_METHODS
end
# Only include the primary table in the main update clause
def update_table_sql(sql)
sql << " #{source_list(@opts[:from][0..0])}"
end
end
end
end
Consistency, refactoring.
module Sequel
Dataset::NON_SQL_OPTIONS << :disable_insert_output
module MSSQL
module DatabaseMethods
AUTO_INCREMENT = 'IDENTITY(1,1)'.freeze
SERVER_VERSION_RE = /^(\d+)\.(\d+)\.(\d+)/.freeze
SERVER_VERSION_SQL = "SELECT CAST(SERVERPROPERTY('ProductVersion') AS varchar)".freeze
SQL_BEGIN = "BEGIN TRANSACTION".freeze
SQL_COMMIT = "COMMIT TRANSACTION".freeze
SQL_ROLLBACK = "IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION".freeze
SQL_ROLLBACK_TO_SAVEPOINT = 'IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION autopoint_%d'.freeze
SQL_SAVEPOINT = 'SAVE TRANSACTION autopoint_%d'.freeze
# The types to check for 0 scale to transform :decimal types
# to :integer.
DECIMAL_TYPE_RE = /number|numeric|decimal/io
# Microsoft SQL Server uses the :mssql type.
def database_type
:mssql
end
# The version of the MSSQL server, as an integer (e.g. 10001600 for
# SQL Server 2008 Express).
def server_version(server=nil)
return @server_version if @server_version
@server_version = synchronize(server) do |conn|
(conn.server_version rescue nil) if conn.respond_to?(:server_version)
end
unless @server_version
m = SERVER_VERSION_RE.match(fetch(SERVER_VERSION_SQL).single_value.to_s)
@server_version = (m[1].to_i * 1000000) + (m[2].to_i * 10000) + m[3].to_i
end
@server_version
end
# MSSQL supports savepoints, though it doesn't support committing/releasing them savepoint
def supports_savepoints?
true
end
# MSSQL supports transaction isolation levels
def supports_transaction_isolation_levels?
true
end
# Microsoft SQL Server supports using the INFORMATION_SCHEMA to get
# information on tables.
def tables(opts={})
m = output_identifier_meth
metadata_dataset.from(:information_schema__tables___t).
select(:table_name).
filter(:table_type=>'BASE TABLE', :table_schema=>(opts[:schema]||default_schema||'dbo').to_s).
map{|x| m.call(x[:table_name])}
end
private
# MSSQL uses the IDENTITY(1,1) column for autoincrementing columns.
def auto_increment_sql
AUTO_INCREMENT
end
# MSSQL specific syntax for altering tables.
def alter_table_sql(table, op)
case op[:op]
when :add_column
"ALTER TABLE #{quote_schema_table(table)} ADD #{column_definition_sql(op)}"
when :rename_column
"sp_rename #{literal("#{quote_schema_table(table)}.#{quote_identifier(op[:name])}")}, #{literal(op[:new_name].to_s)}, 'COLUMN'"
when :set_column_type
"ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(op[:name])} #{type_literal(op)}"
when :set_column_null
sch = schema(table).find{|k,v| k.to_s == op[:name].to_s}.last
type = sch[:db_type]
if [:string, :decimal].include?(sch[:type]) and size = (sch[:max_chars] || sch[:column_size])
type += "(#{size}#{", #{sch[:scale]}" if sch[:scale] && sch[:scale].to_i > 0})"
end
"ALTER TABLE #{quote_schema_table(table)} ALTER COLUMN #{quote_identifier(op[:name])} #{type_literal(:type=>type)} #{'NOT ' unless op[:null]}NULL"
when :set_column_default
"ALTER TABLE #{quote_schema_table(table)} ADD CONSTRAINT #{quote_identifier("sequel_#{table}_#{op[:name]}_def")} DEFAULT #{literal(op[:default])} FOR #{quote_identifier(op[:name])}"
else
super(table, op)
end
end
# SQL to start a new savepoint
def begin_savepoint_sql(depth)
SQL_SAVEPOINT % depth
end
# SQL to BEGIN a transaction.
def begin_transaction_sql
SQL_BEGIN
end
# Commit the active transaction on the connection, does not commit/release
# savepoints.
def commit_transaction(conn, opts={})
log_connection_execute(conn, commit_transaction_sql) unless Thread.current[:sequel_transaction_depth] > 1
end
# SQL to COMMIT a transaction.
def commit_transaction_sql
SQL_COMMIT
end
# MSSQL uses the name of the table to decide the difference between
# a regular and temporary table, with temporary table names starting with
# a #.
def create_table_sql(name, generator, options)
"CREATE TABLE #{quote_schema_table(options[:temp] ? "##{name}" : name)} (#{column_list_sql(generator)})"
end
# The SQL to drop an index for the table.
def drop_index_sql(table, op)
"DROP INDEX #{quote_identifier(op[:name] || default_index_name(table, op[:columns]))} ON #{quote_schema_table(table)}"
end
# Always quote identifiers in the metadata_dataset, so schema parsing works.
def metadata_dataset
ds = super
ds.quote_identifiers = true
ds
end
# Use sp_rename to rename the table
def rename_table_sql(name, new_name)
"sp_rename #{literal(quote_schema_table(name))}, #{quote_identifier(schema_and_table(new_name).pop)}"
end
# SQL to rollback to a savepoint
def rollback_savepoint_sql(depth)
SQL_ROLLBACK_TO_SAVEPOINT % depth
end
# SQL to ROLLBACK a transaction.
def rollback_transaction_sql
SQL_ROLLBACK
end
# MSSQL uses the INFORMATION_SCHEMA to hold column information. This method does
# not support the parsing of primary key information.
def schema_parse_table(table_name, opts)
m = output_identifier_meth
m2 = input_identifier_meth
ds = metadata_dataset.from(:information_schema__tables___t).
join(:information_schema__columns___c, :table_catalog=>:table_catalog,
:table_schema => :table_schema, :table_name => :table_name).
select(:column_name___column, :data_type___db_type, :character_maximum_length___max_chars, :column_default___default, :is_nullable___allow_null, :numeric_precision___column_size, :numeric_scale___scale).
filter(:c__table_name=>m2.call(table_name.to_s))
if schema = opts[:schema] || default_schema
ds.filter!(:c__table_schema=>schema)
end
ds.map do |row|
row[:allow_null] = row[:allow_null] == 'YES' ? true : false
row[:default] = nil if blank_object?(row[:default])
row[:type] = if row[:db_type] =~ DECIMAL_TYPE_RE && row[:scale] == 0
:integer
else
schema_column_type(row[:db_type])
end
[m.call(row.delete(:column)), row]
end
end
# MSSQL has both datetime and timestamp classes, most people are going
# to want datetime
def type_literal_generic_datetime(column)
:datetime
end
# MSSQL has both datetime and timestamp classes, most people are going
# to want datetime
def type_literal_generic_time(column)
column[:only_time] ? :time : :datetime
end
# MSSQL doesn't have a true boolean class, so it uses bit
def type_literal_generic_trueclass(column)
:bit
end
# MSSQL uses image type for blobs
def type_literal_generic_file(column)
:image
end
# support for clustered index type
def index_definition_sql(table_name, index)
index_name = index[:name] || default_index_name(table_name, index[:columns])
clustered = index[:type] == :clustered
if index[:where]
raise Error, "Partial indexes are not supported for this database"
else
"CREATE #{'UNIQUE ' if index[:unique]}#{'CLUSTERED ' if clustered}INDEX #{quote_identifier(index_name)} ON #{quote_schema_table(table_name)} #{literal(index[:columns])}"
end
end
end
module DatasetMethods
BOOL_TRUE = '1'.freeze
BOOL_FALSE = '0'.freeze
COMMA_SEPARATOR = ', '.freeze
DELETE_CLAUSE_METHODS = Dataset.clause_methods(:delete, %w'with from output from2 where')
INSERT_CLAUSE_METHODS = Dataset.clause_methods(:insert, %w'with into columns output values')
SELECT_CLAUSE_METHODS = Dataset.clause_methods(:select, %w'with distinct limit columns into from lock join where group having order compounds')
UPDATE_CLAUSE_METHODS = Dataset.clause_methods(:update, %w'with table set output from where')
NOLOCK = ' WITH (NOLOCK)'.freeze
UPDLOCK = ' WITH (UPDLOCK)'.freeze
WILDCARD = LiteralString.new('*').freeze
CONSTANT_MAP = {:CURRENT_DATE=>'CAST(CURRENT_TIMESTAMP AS DATE)'.freeze, :CURRENT_TIME=>'CAST(CURRENT_TIMESTAMP AS TIME)'.freeze}
# MSSQL uses + for string concatenation, and LIKE is case insensitive by default.
def complex_expression_sql(op, args)
case op
when :'||'
super(:+, args)
when :ILIKE
super(:LIKE, args)
when :"NOT ILIKE"
super(:"NOT LIKE", args)
when :<<
"(#{literal(args[0])} * POWER(2, #{literal(args[1])}))"
when :>>
"(#{literal(args[0])} / POWER(2, #{literal(args[1])}))"
else
super(op, args)
end
end
# MSSQL doesn't support the SQL standard CURRENT_DATE or CURRENT_TIME
def constant_sql(constant)
CONSTANT_MAP[constant] || super
end
# Disable the use of INSERT OUTPUT
def disable_insert_output
clone(:disable_insert_output=>true)
end
# Disable the use of INSERT OUTPUT, modifying the receiver
def disable_insert_output!
mutation_method(:disable_insert_output)
end
# When returning all rows, if an offset is used, delete the row_number column
# before yielding the row.
def fetch_rows(sql, &block)
@opts[:offset] ? super(sql){|r| r.delete(row_number_column); yield r} : super(sql, &block)
end
# MSSQL uses the CONTAINS keyword for full text search
def full_text_search(cols, terms, opts = {})
filter("CONTAINS (#{literal(cols)}, #{literal(terms)})")
end
# Use the OUTPUT clause to get the value of all columns for the newly inserted record.
def insert_select(*values)
return unless supports_output_clause?
naked.clone(default_server_opts(:sql=>output(nil, [:inserted.*]).insert_sql(*values))).single_record unless opts[:disable_insert_output]
end
# Specify a table for a SELECT ... INTO query.
def into(table)
clone(:into => table)
end
# MSSQL uses a UNION ALL statement to insert multiple values at once.
def multi_insert_sql(columns, values)
[insert_sql(columns, LiteralString.new(values.map {|r| "SELECT #{expression_list(r)}" }.join(" UNION ALL ")))]
end
# Allows you to do a dirty read of uncommitted data using WITH (NOLOCK).
def nolock
lock_style(:dirty)
end
# Include an OUTPUT clause in the eventual INSERT, UPDATE, or DELETE query.
#
# The first argument is the table to output into, and the second argument
# is either an Array of column values to select, or a Hash which maps output
# column names to selected values, in the style of #insert or #update.
#
# Output into a returned result set is not currently supported.
#
# Examples:
#
# dataset.output(:output_table, [:deleted__id, :deleted__name])
# dataset.output(:output_table, :id => :inserted__id, :name => :inserted__name)
def output(into, values)
raise(Error, "SQL Server versions 2000 and earlier do not support the OUTPUT clause") unless supports_output_clause?
output = {}
case values
when Hash
output[:column_list], output[:select_list] = values.keys, values.values
when Array
output[:select_list] = values
end
output[:into] = into
clone({:output => output})
end
# An output method that modifies the receiver.
def output!(into, values)
mutation_method(:output, into, values)
end
# MSSQL uses [] to quote identifiers
def quoted_identifier(name)
"[#{name}]"
end
# MSSQL Requires the use of the ROW_NUMBER window function to emulate
# an offset. This implementation requires MSSQL 2005 or greater (offset
# can't be emulated well in MSSQL 2000).
#
# The implementation is ugly, cloning the current dataset and modifying
# the clone to add a ROW_NUMBER window function (and some other things),
# then using the modified clone in a subselect which is selected from.
#
# If offset is used, an order must be provided, because the use of ROW_NUMBER
# requires an order.
def select_sql
return super unless o = @opts[:offset]
raise(Error, 'MSSQL requires an order be provided if using an offset') unless order = @opts[:order]
dsa1 = dataset_alias(1)
rn = row_number_column
subselect_sql(unlimited.
unordered.
select_append{ROW_NUMBER(:over, :order=>order){}.as(rn)}.
from_self(:alias=>dsa1).
limit(@opts[:limit]).
where(SQL::Identifier.new(rn) > o))
end
# The version of the database server.
def server_version
db.server_version(@opts[:server])
end
# MSSQL 2005+ supports INTERSECT and EXCEPT
def supports_intersect_except?
is_2005_or_later?
end
# MSSQL does not support IS TRUE
def supports_is_true?
false
end
# MSSQL doesn't support JOIN USING
def supports_join_using?
false
end
# MSSQL 2005+ supports modifying joined datasets
def supports_modifying_joins?
is_2005_or_later?
end
# MSSQL does not support multiple columns for the IN/NOT IN operators
def supports_multiple_column_in?
false
end
# MSSQL 2005+ supports the output clause.
def supports_output_clause?
is_2005_or_later?
end
# MSSQL 2005+ supports window functions
def supports_window_functions?
true
end
protected
# MSSQL does not allow ordering in sub-clauses unless 'top' (limit) is specified
def aggregate_dataset
(options_overlap(Sequel::Dataset::COUNT_FROM_SELF_OPTS) && !options_overlap([:limit])) ? unordered.from_self : super
end
private
def is_2005_or_later?
server_version >= 9000000
end
# MSSQL supports the OUTPUT clause for DELETE statements.
# It also allows prepending a WITH clause.
def delete_clause_methods
DELETE_CLAUSE_METHODS
end
# Only include the primary table in the main delete clause
def delete_from_sql(sql)
sql << " FROM #{source_list(@opts[:from][0..0])}"
end
# MSSQL supports FROM clauses in DELETE and UPDATE statements.
def delete_from2_sql(sql)
if joined_dataset?
select_from_sql(sql)
select_join_sql(sql)
end
end
alias update_from_sql delete_from2_sql
# Handle the with clause for delete, insert, and update statements
# to be the same as the insert statement.
def delete_with_sql(sql)
select_with_sql(sql)
end
alias insert_with_sql delete_with_sql
alias update_with_sql delete_with_sql
# MSSQL raises an error if you try to provide more than 3 decimal places
# for a fractional timestamp. This probably doesn't work for smalldatetime
# fields.
def format_timestamp_usec(usec)
sprintf(".%03d", usec/1000)
end
# MSSQL supports the OUTPUT clause for INSERT statements.
# It also allows prepending a WITH clause.
def insert_clause_methods
INSERT_CLAUSE_METHODS
end
# MSSQL uses a literal hexidecimal number for blob strings
def literal_blob(v)
blob = '0x'
v.each_byte{|x| blob << sprintf('%02x', x)}
blob
end
# Use unicode string syntax for all strings. Don't double backslashes.
def literal_string(v)
"N'#{v.gsub(/'/, "''")}'"
end
# Use 0 for false on MSSQL
def literal_false
BOOL_FALSE
end
# Use 1 for true on MSSQL
def literal_true
BOOL_TRUE
end
# The alias to use for the row_number column when emulating OFFSET
def row_number_column
:x_sequel_row_number_x
end
# MSSQL adds the limit before the columns
def select_clause_methods
SELECT_CLAUSE_METHODS
end
def select_into_sql(sql)
sql << " INTO #{table_ref(@opts[:into])}" if @opts[:into]
end
# MSSQL uses TOP N for limit. For MSSQL 2005+ TOP (N) is used
# to allow the limit to be a bound variable.
def select_limit_sql(sql)
if l = @opts[:limit]
l = literal(l)
l = "(#{l})" if server_version >= 9000000
sql << " TOP #{l}"
end
end
# Support different types of locking styles
def select_lock_sql(sql)
case @opts[:lock]
when :update
sql << UPDLOCK
when :dirty
sql << NOLOCK
else
super
end
end
# SQL fragment for MSSQL's OUTPUT clause.
def output_sql(sql)
return unless supports_output_clause?
return unless output = @opts[:output]
sql << " OUTPUT #{column_list(output[:select_list])}"
if into = output[:into]
sql << " INTO #{table_ref(into)}"
if column_list = output[:column_list]
cl = []
column_list.each { |k, v| cl << literal(String === k ? k.to_sym : k) }
sql << " (#{cl.join(COMMA_SEPARATOR)})"
end
end
end
alias delete_output_sql output_sql
alias update_output_sql output_sql
alias insert_output_sql output_sql
# MSSQL supports the OUTPUT clause for UPDATE statements.
# It also allows prepending a WITH clause.
def update_clause_methods
UPDATE_CLAUSE_METHODS
end
# Only include the primary table in the main update clause
def update_table_sql(sql)
sql << " #{source_list(@opts[:from][0..0])}"
end
end
end
end
|
require 'active_support/concern'
module SocialStream
module Models
# {Subject Subjects} are subtypes of {Actor}. {SocialStream} provides two
# {Subject Subjects}, {User} and {Group}
#
# Each {Subject} is defined in +config/initializers/social_stream.rb+
#
# This module provides additional features for models that are subjects,
# extending them. Including the module in each {Subject} model is not required!
# After declared in +config/initializers/social_stream.rb+, {SocialStream} is
# responsible for adding subject features to each model.
#
# = Scopes
# There are several scopes available for subjects
#
# alphabetic:: sort subjects by name
# search:: simple search by name
# distinct_initials:: get only the first letter of the name
# popular:: sort by most incoming {Tie ties}
#
module Subject
extend ActiveSupport::Concern
included do
belongs_to :actor,
:validate => true,
:autosave => true
has_one :profile, :through => :actor
accepts_nested_attributes_for :profile
validates_presence_of :name
scope :alphabetic, joins(:actor).merge(Actor.alphabetic)
scope :letter, lambda{ |param|
joins(:actor).merge(Actor.letter(param))
}
scope :search, lambda{ |param|
joins(:actor).merge(Actor.search(param))
}
scope :with_sent_ties, joins(:actor => :sent_ties)
scope :with_received_ties, joins(:actor => :received_ties)
scope :distinct_initials, joins(:actor).select('DISTINCT SUBSTR(actors.name,1,1) as initial').order("initial ASC")
scope :popular, lambda {
joins(:actor => :received_ties).
select("DISTINCT #{ table_name }.*, COUNT(#{ table_name}.id) AS popularity").
group("#{ table_name }.id").
order("popularity DESC")
}
end
module InstanceMethods
def actor!
actor || build_actor(:subject_type => self.class.to_s)
end
def to_param
slug
end
# Delegate missing methods to {Actor}, if they are defined there
def method_missing(method, *args, &block)
super
rescue NameError => subject_error
begin
actor!.__send__ method, *args, &block
rescue NameError
raise subject_error
end
end
# {Actor} handles some methods
def respond_to? *args
super || actor!.respond_to?(*args)
end
end
module ClassMethods
def find_by_slug(perm)
includes(:actor).where('actors.slug' => perm).first
end
def find_by_slug!(perm)
find_by_slug(perm) ||
raise(ActiveRecord::RecordNotFound)
end
end
end
end
end
Don't masquerade Actor errors raised from Subject
require 'active_support/concern'
module SocialStream
module Models
# {Subject Subjects} are subtypes of {Actor}. {SocialStream} provides two
# {Subject Subjects}, {User} and {Group}
#
# Each {Subject} is defined in +config/initializers/social_stream.rb+
#
# This module provides additional features for models that are subjects,
# extending them. Including the module in each {Subject} model is not required!
# After declared in +config/initializers/social_stream.rb+, {SocialStream} is
# responsible for adding subject features to each model.
#
# = Scopes
# There are several scopes available for subjects
#
# alphabetic:: sort subjects by name
# search:: simple search by name
# distinct_initials:: get only the first letter of the name
# popular:: sort by most incoming {Tie ties}
#
module Subject
extend ActiveSupport::Concern
included do
belongs_to :actor,
:validate => true,
:autosave => true
has_one :profile, :through => :actor
accepts_nested_attributes_for :profile
validates_presence_of :name
scope :alphabetic, joins(:actor).merge(Actor.alphabetic)
scope :letter, lambda{ |param|
joins(:actor).merge(Actor.letter(param))
}
scope :search, lambda{ |param|
joins(:actor).merge(Actor.search(param))
}
scope :with_sent_ties, joins(:actor => :sent_ties)
scope :with_received_ties, joins(:actor => :received_ties)
scope :distinct_initials, joins(:actor).select('DISTINCT SUBSTR(actors.name,1,1) as initial').order("initial ASC")
scope :popular, lambda {
joins(:actor => :received_ties).
select("DISTINCT #{ table_name }.*, COUNT(#{ table_name}.id) AS popularity").
group("#{ table_name }.id").
order("popularity DESC")
}
end
module InstanceMethods
def actor!
actor || build_actor(:subject_type => self.class.to_s)
end
def to_param
slug
end
# Delegate missing methods to {Actor}, if they are defined there
def method_missing(method, *args, &block)
super
rescue NameError => subject_error
actor!.__send__ method, *args, &block
end
# {Actor} handles some methods
def respond_to? *args
super || actor!.respond_to?(*args)
end
end
module ClassMethods
def find_by_slug(perm)
includes(:actor).where('actors.slug' => perm).first
end
def find_by_slug!(perm)
find_by_slug(perm) ||
raise(ActiveRecord::RecordNotFound)
end
end
end
end
end
|
module ServiceMonitor
class BaseService
attr_accessor :cmd
def initialize(cmd:)
self.cmd = cmd
end
def call
`#{cmd}`
end
end
end
catch exceptions for executing bad command
module ServiceMonitor
class BaseService
attr_accessor :cmd
def initialize(cmd:)
self.cmd = cmd
end
def call
begin
output = `#{cmd}`
rescue Exception => e
output = e.message
puts "[+] There was a problem running the #{cmd} command!\n[+] Please fix it!\n#{output}"
exit
end
output
end
end
end
|
module SourceRoute
class GenerateResult
Config = Struct.new(:format, :show_additional_attrs,
:include_local_var, :include_instance_var, :include_tp_self,
:filename, :import_return_to_call) do
def initialize(f="silence", s=[], ilr=false, iiv=false)
super(f, s, ilr, iiv)
end
end
# see event description in TracePoint API Doc
DEFAULT_ATTRS = {
call: [:defined_class, :method_id],
return: [:defined_class, :method_id, :return_value],
c_call: [:defined_class, :method_id],
line: [:path, :lineno],
# following are not tested yet
class: [:defined_class],
end: [:defined_class],
c_return: [:defined_class, :method_id, :return_value],
raise: [:raised_exception],
b_call: [:binding, :defined_class, :method_id],
b_return: [:binding, :defined_class, :method_id, :return_value],
thread_begin: [:defined_class, :method_id],
thread_end: [:defined_class, :method_id]
}
def initialize(wrapper)
@wrapper = wrapper
@config = @wrapper.condition.result_config
@tp_events = @wrapper.condition.events
end
def output_attributes(event)
attrs = DEFAULT_ATTRS[event] + Array(@config.show_additional_attrs)
attrs.push(:event) if @tp_events.size > 1
attrs.uniq
end
def build(trace_point_instance)
@tp = trace_point_instance
collect_tp_data
collect_tp_self if @config[:include_tp_self]
collect_local_var_data if @config[:include_local_var]
collect_instance_var_data if @config[:include_instance_var]
@collect_data
end
def output(tp_ins)
format = @config.format
format = format.to_sym if format.respond_to? :to_sym
case format
when :none
# do nothing
when :console # need @collect_data
console_put
when :html
# I cant solve the problem: to generate html at the end,
# I have to know when the application is end
when :test, :silence
# do nothing at now
when :stack_overflow
console_stack_overflow
when Proc
format.call(tp_ins)
else
klass = "SourceRoute::Formats::#{format.to_s.capitalize}"
::SourceRoute.const_get(klass).render(self, tp_ins)
end
end
private
# include? will evaluate @tp.self, if @tp.self is AR::Relation, it could cause problems
# So that's why I use object_id as replace
def collect_tp_self
unless @wrapper.tp_self_caches.map(&:object_id).include? @tp.self.object_id
@wrapper.tp_self_caches.push @tp.self
end
@collect_data[:tp_self] = @wrapper.tp_self_caches.map(&:object_id).index(@tp.self.object_id)
end
def collect_tp_data
@collect_data = output_attributes(@tp.event).inject({}) do |memo, key|
memo[key.to_sym] = @tp.send(key) if @tp.respond_to?(key)
memo
end
end
def collect_local_var_data
local_var_hash = {}
# Warn: @tp.binding.eval('local_variables') =! @tp.binding.send('local_variables')
@tp.binding.eval('local_variables').each do |v|
local_var_hash[v] = @tp.binding.local_variable_get v
end
if local_var_hash != {}
@collect_data.merge!(local_var: local_var_hash)
end
end
def collect_instance_var_data
instance_var_hash = {}
@tp.self.instance_variables.each do |key|
instance_var_hash[key] = @tp.self.instance_variable_get(key)
end
if instance_var_hash != {}
@collect_data.merge!(instance_var: instance_var_hash)
end
end
def console_put
ret = []
ret << "#{@collect_data[:defined_class].inspect}##{@collect_data[:method_id]}"
left_values = @collect_data.reject { |k, v| %w[defined_class method_id].include? k.to_s }
unless left_values == {}
ret << left_values
end
ap ret
end
def console_stack_overflow
ap "#{@collect_data[:defined_class].inspect}##{@collect_data[:method_id]}"
end
end # END GenerateResult
end
fix bug if tp_self is thin object which does not has object_id method(but has method_messiong metho)
module SourceRoute
class GenerateResult
Config = Struct.new(:format, :show_additional_attrs,
:include_local_var, :include_instance_var, :include_tp_self,
:filename, :import_return_to_call) do
def initialize(f="silence", s=[], ilr=false, iiv=false)
super(f, s, ilr, iiv)
end
end
# see event description in TracePoint API Doc
DEFAULT_ATTRS = {
call: [:defined_class, :method_id],
return: [:defined_class, :method_id, :return_value],
c_call: [:defined_class, :method_id],
line: [:path, :lineno],
# following are not tested yet
class: [:defined_class],
end: [:defined_class],
c_return: [:defined_class, :method_id, :return_value],
raise: [:raised_exception],
b_call: [:binding, :defined_class, :method_id],
b_return: [:binding, :defined_class, :method_id, :return_value],
thread_begin: [:defined_class, :method_id],
thread_end: [:defined_class, :method_id]
}
def initialize(wrapper)
@wrapper = wrapper
@config = @wrapper.condition.result_config
@tp_events = @wrapper.condition.events
end
def output_attributes(event)
attrs = DEFAULT_ATTRS[event] + Array(@config.show_additional_attrs)
attrs.push(:event) if @tp_events.size > 1
attrs.uniq
end
def build(trace_point_instance)
@tp = trace_point_instance
collect_tp_data
collect_tp_self if @config[:include_tp_self]
collect_local_var_data if @config[:include_local_var]
collect_instance_var_data if @config[:include_instance_var]
@collect_data
end
def output(tp_ins)
format = @config.format
format = format.to_sym if format.respond_to? :to_sym
case format
when :none
# do nothing
when :console # need @collect_data
console_put
when :html
# I cant solve the problem: to generate html at the end,
# I have to know when the application is end
when :test, :silence
# do nothing at now
when :stack_overflow
console_stack_overflow
when Proc
format.call(tp_ins)
else
klass = "SourceRoute::Formats::#{format.to_s.capitalize}"
::SourceRoute.const_get(klass).render(self, tp_ins)
end
end
private
# include? will evaluate @tp.self, if @tp.self is AR::Relation, it could cause problems
# So that's why I use object_id as replace
def collect_tp_self
unless @wrapper.tp_self_caches.find { |tp_cache| tp_cache.equal? @tp.self }
@wrapper.tp_self_caches.push @tp.self
end
@collect_data[:tp_self] = @wrapper.tp_self_caches.map(&:__id__).index(@tp.self.__id__)
end
def collect_tp_data
@collect_data = output_attributes(@tp.event).inject({}) do |memo, key|
memo[key.to_sym] = @tp.send(key) if @tp.respond_to?(key)
memo
end
end
def collect_local_var_data
local_var_hash = {}
# Warn: @tp.binding.eval('local_variables') =! @tp.binding.send('local_variables')
@tp.binding.eval('local_variables').each do |v|
local_var_hash[v] = @tp.binding.local_variable_get v
end
if local_var_hash != {}
@collect_data.merge!(local_var: local_var_hash)
end
end
def collect_instance_var_data
instance_var_hash = {}
@tp.self.instance_variables.each do |key|
instance_var_hash[key] = @tp.self.instance_variable_get(key)
end
if instance_var_hash != {}
@collect_data.merge!(instance_var: instance_var_hash)
end
end
def console_put
ret = []
ret << "#{@collect_data[:defined_class].inspect}##{@collect_data[:method_id]}"
left_values = @collect_data.reject { |k, v| %w[defined_class method_id].include? k.to_s }
unless left_values == {}
ret << left_values
end
ap ret
end
def console_stack_overflow
ap "#{@collect_data[:defined_class].inspect}##{@collect_data[:method_id]}"
end
end # END GenerateResult
end
|
module SimpleForm
module Wrappers
# Provides the builder syntax for components. The builder provides
# only one method (called `use`) and it allows the following invocations:
#
# config.wrappers do |b|
# # Use a single component
# b.use :placeholder
#
# # Use a component with specific wrapper options
# b.use :error, :tag => "span", :class => "error"
#
# # Use a set of components by wrapping them in a tag+class.
# b.use :tag => "div", :class => "another" do |ba|
# ba.use :label
# ba.use :input
# end
#
# # Use a set of components by wrapping them in a tag+class.
# # This wrapper is identified by :label_input, which means it can
# # be turned off on demand with `f.input :name, :label_input => false`
# b.use :label_input, :tag => "div", :class => "another" do |ba|
# ba.use :label
# ba.use :input
# end
# end
#
# The builder also accepts default options at the root level. This is usually
# used if you want a component to be disabled by default:
#
# config.wrappers :hint => false do |b|
# b.use :hint
# b.use :label_input
# end
#
# In the example above, hint defaults to false, which means it won't automatically
# do the lookup anymore. It will only be triggered when :hint is explicitly set.
class Builder
def initialize(options)
@options = options
@components = []
end
def use(name, options=nil, &block)
add(name, options, &block)
end
def optional(name, options=nil, &block)
@options[name] = false
add(name, options, &block)
end
def to_a
@components
end
private
def add(name, options)
if block_given?
name, options = nil, name if name.is_a?(Hash)
builder = self.class.new(@options)
options ||= {}
options[:tag] = :div if options[:tag].nil?
yield builder
@components << Many.new(name, builder.to_a, options)
elsif options
@components << Single.new(name, options)
else
@components << name
end
end
end
end
end
Cleaner builder API.
module SimpleForm
module Wrappers
# Provides the builder syntax for components. The builder provides
# only one method (called `use`) and it allows the following invocations:
#
# config.wrappers do |b|
# # Use a single component
# b.use :placeholder
#
# # Use a component with specific wrapper options
# b.use :error, :tag => "span", :class => "error"
#
# # Use a set of components by wrapping them in a tag+class.
# b.use :tag => "div", :class => "another" do |ba|
# ba.use :label
# ba.use :input
# end
#
# # Use a set of components by wrapping them in a tag+class.
# # This wrapper is identified by :label_input, which means it can
# # be turned off on demand with `f.input :name, :label_input => false`
# b.use :label_input, :tag => "div", :class => "another" do |ba|
# ba.use :label
# ba.use :input
# end
# end
#
# The builder also accepts default options at the root level. This is usually
# used if you want a component to be disabled by default:
#
# config.wrappers :hint => false do |b|
# b.use :hint
# b.use :label_input
# end
#
# In the example above, hint defaults to false, which means it won't automatically
# do the lookup anymore. It will only be triggered when :hint is explicitly set.
class Builder
def initialize(options)
@options = options
@components = []
end
def use(name, options=nil, &block)
if block_given?
ActiveSupport::Deprecation.warn "Passing a block to use is deprecated. " \
"Please use wrapper instead of use."
return wrapper(name, options, &block)
end
if options && options.keys != [:wrap_with]
ActiveSupport::Deprecation.warn "Passing :tag, :class and others to use is deprecated. " \
"Please invoke b.use #{name.inspect}, :wrap_with => #{options.inspect} instead."
options = { :wrap_with => options }
end
if options && wrapper = options[:wrap_with]
@components << Single.new(name, wrapper)
else
@components << name
end
end
def optional(name, options=nil, &block)
if block_given?
ActiveSupport::Deprecation.warn "Passing a block to optional is deprecated. " \
"Please use wrapper instead of optional."
return wrapper(name, options, &block)
end
if options && options.keys != [:wrap_with]
ActiveSupport::Deprecation.warn "Passing :tag, :class and others to optional is deprecated. " \
"Please invoke b.optional #{name.inspect}, :wrap_with => #{options.inspect} instead."
options = { :wrap_with => options }
end
@options[name] = false
use(name, options, &block)
end
def wrapper(name, options=nil)
if block_given?
name, options = nil, name if name.is_a?(Hash)
builder = self.class.new(@options)
options ||= {}
options[:tag] = :div if options[:tag].nil?
yield builder
@components << Many.new(name, builder.to_a, options)
else
raise ArgumentError, "A block is required as argument to wrapper"
end
end
def to_a
@components
end
end
end
end |
class Fastmerge < Formula
desc 'Script to quickly pull and push github pull requests to keep commit history cleaner, merging directly to master and closing the previous pull request'
homepage 'https://github.com/vitorgalvao/tiny-scripts'
url 'https://github.com/vitorgalvao/tiny-scripts.git'
version '0.7.1'
def install
bin.install 'fastmerge'
end
end
fastmerge.rb: add dependency on ghi
class Fastmerge < Formula
depends_on 'ghi'
desc 'Script to quickly pull and push github pull requests to keep commit history cleaner, merging directly to master and closing the previous pull request'
homepage 'https://github.com/vitorgalvao/tiny-scripts'
url 'https://github.com/vitorgalvao/tiny-scripts.git'
version '0.7.1'
def install
bin.install 'fastmerge'
end
end
|
require 'socket'
begin
require 'fastthread'
rescue LoadError
# puts 'fastthread not installed, using thread instead'
require 'thread'
end
# String
class Skynet
class UniqueDBNumGenerator
class Config
attr_accessor :lockfile, :pidfile, :server_num, :pid_id, :use_incremental_ids
end
@@config ||= Config.new
def self.configure
yield @@config
end
def self.server_num(hostname=nil)
@@config.server_num ||= Socket.gethostname.sum / 20000
# hostname = Socket.gethostname unless hostname
# matched = hostname.match(/^\w+-([\d].*?)\./)
# if matched
# matched[1].to_i
# else
# 1
# end
# end
end
def self.pid_id
$$
# pid = 0
# Lockfile.new(@@config.lockfile) do
# if not File.file? @@config.pidfile
# FileUtils.touch(@@config.pidfile)
# end
#
# pid = open(@@config.pidfile, 'r'){|f| f.read.to_i}
# if pid == 99
# pid = 0
# else
# pid += 1
# end
# open(@@config.pidfile, 'w'){|f| f << pid}
# end
# pid
end
def self.use_incremental_ids
@@config.use_incremental_ids
end
end
module GuidGenerator
@@pid_ctr = 0
@@model_ctrs ||= {}
def get_unique_id(nodb=nil)
if defined?(Skynet::CONFIG) and Skynet::CONFIG[:GUID_GENERATOR]
Skynet::CONFIG[:GUID_GENERATOR].call
else
@@pid_id ||= Skynet::UniqueDBNumGenerator.pid_id
if not Skynet::UniqueDBNumGenerator.server_num or not @@pid_id
raise 'SERVER_NUM or PIDID not defined, please check environment.rb for the proper code.'
end
mutex = Mutex.new
mutex.synchronize do
timeprt = Time.now.to_f - 1151107200
timeprt = timeprt * 10000
@@pid_ctr += 1
@@pid_ctr = 0 if @@pid_ctr > 99
sprintf("%12d%03d%02d%02d", timeprt, Skynet::UniqueDBNumGenerator.server_num, @@pid_id, @@pid_ctr)
end
end
end
end
end
#3249 - Rewrite the skynet_guid_generator (thanks justin)
require 'socket'
begin
require 'fastthread'
rescue LoadError
require 'thread'
end
class Skynet
class UniqueDBNumGenerator
class Config
attr_accessor :lockfile, :pidfile, :server_num, :pid_id, :use_incremental_ids
end
@@config ||= Config.new
def self.configure
yield @@config
end
def self.server_num(hostname=nil)
@@config.server_num ||= Socket.gethostname.sum
end
def self.pid_id
$$
end
def self.use_incremental_ids
@@config.use_incremental_ids
end
end
module GuidGenerator
@@pid_ctr = 0
def get_unique_id(nodb=nil)
if defined?(Skynet::CONFIG) and Skynet::CONFIG[:GUID_GENERATOR]
Skynet::CONFIG[:GUID_GENERATOR].call
else
@@pid_id ||= Skynet::UniqueDBNumGenerator.pid_id
if not Skynet::UniqueDBNumGenerator.server_num or not @@pid_id
raise 'SERVER_NUM or PIDID not defined, please check environment.rb for the proper code.'
end
Mutex.new.synchronize do
timeprt = Time.now.to_f - 870678000 # figure it out
timeprt = timeprt * 1000
@@pid_ctr += 1
guid_parts = [[timeprt,26],[Skynet::UniqueDBNumGenerator.server_num,12],[@@pid_id,19],[@@pid_ctr,6]]
guid = 0
guid_parts.each do |part, bitlength|
guid = guid << bitlength
guid += part.to_i % (2 ** bitlength)
guid
end
end
end
end
end
end |
# encoding: utf-8
require "forwardable"
require_relative "./rack"
module SockJS
module Thin
class Request < Rack::Request
end
# This is just to make Rack happy.
DUMMY_RESPONSE ||= [-1, Hash.new, Array.new]
class AsyncResponse < Response
extend Forwardable
# env["async.callback"]
def initialize(async_callback, status = nil, headers = Hash.new, &block)
@async_callback = async_callback
@status, @headers = status, headers
@body = DelayedResponseBody.new
block.call(self) if block
end
def write_head(status = nil, headers = nil)
super(status, headers) do
@async_callback.call(@status, @headers, @body)
end
end
def_delegator :body, :write
def_delegator :body, :finish
end
class DelayedResponseBody
include EventMachine::Deferrable
def call(body)
body.each do |chunk|
self.write(chunk)
end
end
def write(chunk)
@body_callback.call(chunk)
end
def each(&block)
@body_callback = block
end
alias_method :finish, :succeed
end
end
end
Thin::Response class.
# encoding: utf-8
require "forwardable"
require_relative "./rack"
module SockJS
module Thin
class Request < Rack::Request
end
# This is just to make Rack happy.
DUMMY_RESPONSE ||= [-1, Hash.new, Array.new]
class Response < Response
def async?
@body.is_a?(DelayedResponseBody)
end
end
class AsyncResponse < Response
extend Forwardable
# env["async.callback"]
def initialize(async_callback, status = nil, headers = Hash.new, &block)
@async_callback = async_callback
@status, @headers = status, headers
@body = DelayedResponseBody.new
block.call(self) if block
end
def write_head(status = nil, headers = nil)
super(status, headers) do
@async_callback.call(@status, @headers, @body)
end
end
def_delegator :body, :write
def_delegator :body, :finish
end
class DelayedResponseBody
include EventMachine::Deferrable
def call(body)
body.each do |chunk|
self.write(chunk)
end
end
def write(chunk)
@body_callback.call(chunk)
end
def each(&block)
@body_callback = block
end
alias_method :finish, :succeed
end
end
end
|
require 'cucumber'
require 'cucumber/rake/task'
require 'rake'
module Squcumber
module Postgres
module Rake
class Task
include ::Rake::DSL if defined? ::Rake::DSL
def install_tasks
namespace :test do
# Auto-generate Rake tasks for each feature and each of their parent directories
@features_dir = File.join(FileUtils.pwd, 'features')
features = Dir.glob("#{@features_dir}/**/*.feature")
parent_directories = features.map { |f| f.split('/')[0..-2].join('/') }.uniq
features.each do |feature|
feature_name = feature.gsub(@features_dir + '/', '').gsub('.feature', '')
task_name = feature_name.gsub('/', ':')
desc "Run SQL tests for feature #{feature_name}"
task "sql:#{task_name}".to_sym, [:scenario_line_number] do |_, args|
cucumber_task_name = "cucumber_#{task_name}".to_sym
::Cucumber::Rake::Task.new(cucumber_task_name) do |t|
line_number = args[:scenario_line_number].nil? ? '' : ":#{args[:scenario_line_number]}"
output_dir = ENV['CUSTOM_OUTPUT_DIR'] ? ENV['CUSTOM_OUTPUT_DIR'] : '/tmp'
output_file = output_dir + '/' + feature_name.gsub('/', '_')
output_opts = "--format html --out #{output_file}.html --format json --out #{output_file}.json"
t.cucumber_opts = "#{feature}#{line_number} --format pretty #{output_opts} --require #{File.dirname(__FILE__)}/../support --require #{File.dirname(__FILE__)}/../step_definitions #{ENV['CUSTOM_STEPS_DIR'] ? '--require ' + ENV['CUSTOM_STEPS_DIR'] : ''}"
end
::Rake::Task[cucumber_task_name].execute
end
end
parent_directories.each do |feature|
feature_name = feature.gsub(@features_dir + '/', '')
task_name = feature_name.gsub('/', ':')
if feature_name.eql?(@features_dir)
feature_name = 'features'
task_name = 'all'
end
desc "Run SQL tests for all features in /#{feature_name}"
task "sql:#{task_name}".to_sym do
cucumber_task_name = "cucumber_#{task_name}".to_sym
::Cucumber::Rake::Task.new(cucumber_task_name) do |t|
t.cucumber_opts = "#{feature} --format pretty #{output_opts} --require #{File.dirname(__FILE__)}/../support --require #{File.dirname(__FILE__)}/../step_definitions #{ENV['CUSTOM_STEPS_DIR'] ? '--require ' + ENV['CUSTOM_STEPS_DIR'] : ''}"
end
::Rake::Task[cucumber_task_name].execute
end
end
end
end
end
end
end
end
Squcumber::Postgres::Rake::Task.new.install_tasks
Add environment variable for output file name
require 'cucumber'
require 'cucumber/rake/task'
require 'rake'
module Squcumber
module Postgres
module Rake
class Task
include ::Rake::DSL if defined? ::Rake::DSL
def install_tasks
namespace :test do
# Auto-generate Rake tasks for each feature and each of their parent directories
@features_dir = File.join(FileUtils.pwd, 'features')
features = Dir.glob("#{@features_dir}/**/*.feature")
parent_directories = features.map { |f| f.split('/')[0..-2].join('/') }.uniq
features.each do |feature|
feature_name = feature.gsub(@features_dir + '/', '').gsub('.feature', '')
task_name = feature_name.gsub('/', ':')
desc "Run SQL tests for feature #{feature_name}"
task "sql:#{task_name}".to_sym, [:scenario_line_number] do |_, args|
cucumber_task_name = "cucumber_#{task_name}".to_sym
::Cucumber::Rake::Task.new(cucumber_task_name) do |t|
line_number = args[:scenario_line_number].nil? ? '' : ":#{args[:scenario_line_number]}"
output_dir = ENV['CUSTOM_OUTPUT_DIR'] ? ENV['CUSTOM_OUTPUT_DIR'] : '/tmp'
output_file = ENV['CUSTOM_OUTPUT_NAME'] ? ENV['CUSTOM_OUTPUT_NAME'] : feature_name.gsub('/', '_')
output_path = output_dir + '/' + output_file
output_opts = "--format html --out #{output_path}.html --format json --out #{output_path}.json"
t.cucumber_opts = "#{feature}#{line_number} --format pretty #{output_opts} --require #{File.dirname(__FILE__)}/../support --require #{File.dirname(__FILE__)}/../step_definitions #{ENV['CUSTOM_STEPS_DIR'] ? '--require ' + ENV['CUSTOM_STEPS_DIR'] : ''}"
end
::Rake::Task[cucumber_task_name].execute
end
end
parent_directories.each do |feature|
feature_name = feature.gsub(@features_dir + '/', '')
task_name = feature_name.gsub('/', ':')
if feature_name.eql?(@features_dir)
feature_name = 'features'
task_name = 'all'
end
desc "Run SQL tests for all features in /#{feature_name}"
task "sql:#{task_name}".to_sym do
cucumber_task_name = "cucumber_#{task_name}".to_sym
::Cucumber::Rake::Task.new(cucumber_task_name) do |t|
output_dir = ENV['CUSTOM_OUTPUT_DIR'] ? ENV['CUSTOM_OUTPUT_DIR'] : '/tmp'
output_file = ENV['CUSTOM_OUTPUT_NAME'] ? ENV['CUSTOM_OUTPUT_NAME'] : feature_name.gsub('/', '_')
output_path = output_dir + '/' + output_file
output_opts = "--format html --out #{output_path}.html --format json --out #{output_path}.json"
t.cucumber_opts = "#{feature} --format pretty #{output_opts} --require #{File.dirname(__FILE__)}/../support --require #{File.dirname(__FILE__)}/../step_definitions #{ENV['CUSTOM_STEPS_DIR'] ? '--require ' + ENV['CUSTOM_STEPS_DIR'] : ''}"
end
::Rake::Task[cucumber_task_name].execute
end
end
end
end
end
end
end
end
Squcumber::Postgres::Rake::Task.new.install_tasks
|
module Spec
module Example
module ExampleMethods
extend Spec::Example::ModuleReopeningFix
include Spec::Example::Subject::ExampleMethods
def violated(message="")
raise Spec::Expectations::ExpectationNotMetError.new(message)
end
# Declared description for this example:
#
# describe Account do
# it "should start with a balance of 0" do
# ...
#
# description
# => "should start with a balance of 0"
def description
@_defined_description || ::Spec::Matchers.generated_description || "NO NAME"
end
def options # :nodoc:
@_options
end
def execute(options, instance_variables) # :nodoc:
# FIXME - there is no reason to have example_started pass a name
# - in fact, it would introduce bugs in cases where no docstring
# is passed to it()
options.reporter.example_started("")
set_instance_variables_from_hash(instance_variables)
execution_error = nil
Timeout.timeout(options.timeout) do
begin
before_each_example
instance_eval(&@_implementation)
rescue Exception => e
execution_error ||= e
end
begin
after_each_example
rescue Exception => e
execution_error ||= e
end
end
options.reporter.example_finished(updated_desc = ExampleDescription.new(description), execution_error)
success = execution_error.nil? || ExamplePendingError === execution_error
end
def eval_each_fail_fast(blocks) # :nodoc:
blocks.each do |block|
instance_eval(&block)
end
end
def eval_each_fail_slow(blocks) # :nodoc:
first_exception = nil
blocks.each do |block|
begin
instance_eval(&block)
rescue Exception => e
first_exception ||= e
end
end
raise first_exception if first_exception
end
def instance_variable_hash # :nodoc:
instance_variables.inject({}) do |variable_hash, variable_name|
variable_hash[variable_name] = instance_variable_get(variable_name)
variable_hash
end
end
def set_instance_variables_from_hash(ivars) # :nodoc:
ivars.each do |variable_name, value|
# Ruby 1.9 requires variable.to_s on the next line
unless ['@_implementation', '@_defined_description', '@_matcher_description', '@method_name'].include?(variable_name.to_s)
instance_variable_set variable_name, value
end
end
end
# Provides the backtrace up to where this example was declared.
def backtrace
@_backtrace
end
# Deprecated - use +backtrace()+
def implementation_backtrace
Kernel.warn <<-WARNING
ExampleMethods#implementation_backtrace is deprecated and will be removed
from a future version. Please use ExampleMethods#backtrace instead.
WARNING
backtrace
end
# Run all the before(:each) blocks for this example
def run_before_each
example_group_hierarchy.run_before_each(self)
end
# Run all the after(:each) blocks for this example
def run_after_each
example_group_hierarchy.run_after_each(self)
end
private
include Matchers
include Pending
def before_each_example # :nodoc:
setup_mocks_for_rspec
run_before_each
end
def after_each_example # :nodoc:
run_after_each
verify_mocks_for_rspec
ensure
teardown_mocks_for_rspec
end
def described_class # :nodoc:
self.class.described_class
end
private
def example_group_hierarchy
self.class.example_group_hierarchy
end
end
end
end
one-liner
module Spec
module Example
module ExampleMethods
extend Spec::Example::ModuleReopeningFix
include Spec::Example::Subject::ExampleMethods
def violated(message="")
raise Spec::Expectations::ExpectationNotMetError.new(message)
end
# Declared description for this example:
#
# describe Account do
# it "should start with a balance of 0" do
# ...
#
# description
# => "should start with a balance of 0"
def description
@_defined_description || ::Spec::Matchers.generated_description || "NO NAME"
end
def options # :nodoc:
@_options
end
def execute(options, instance_variables) # :nodoc:
# FIXME - there is no reason to have example_started pass a name
# - in fact, it would introduce bugs in cases where no docstring
# is passed to it()
options.reporter.example_started("")
set_instance_variables_from_hash(instance_variables)
execution_error = nil
Timeout.timeout(options.timeout) do
begin
before_each_example
instance_eval(&@_implementation)
rescue Exception => e
execution_error ||= e
end
begin
after_each_example
rescue Exception => e
execution_error ||= e
end
end
options.reporter.example_finished(updated_desc = ExampleDescription.new(description), execution_error)
success = execution_error.nil? || ExamplePendingError === execution_error
end
def eval_each_fail_fast(blocks) # :nodoc:
blocks.each {|block| instance_eval(&block)}
end
def eval_each_fail_slow(blocks) # :nodoc:
first_exception = nil
blocks.each do |block|
begin
instance_eval(&block)
rescue Exception => e
first_exception ||= e
end
end
raise first_exception if first_exception
end
def instance_variable_hash # :nodoc:
instance_variables.inject({}) do |variable_hash, variable_name|
variable_hash[variable_name] = instance_variable_get(variable_name)
variable_hash
end
end
def set_instance_variables_from_hash(ivars) # :nodoc:
ivars.each do |variable_name, value|
# Ruby 1.9 requires variable.to_s on the next line
unless ['@_implementation', '@_defined_description', '@_matcher_description', '@method_name'].include?(variable_name.to_s)
instance_variable_set variable_name, value
end
end
end
# Provides the backtrace up to where this example was declared.
def backtrace
@_backtrace
end
# Deprecated - use +backtrace()+
def implementation_backtrace
Kernel.warn <<-WARNING
ExampleMethods#implementation_backtrace is deprecated and will be removed
from a future version. Please use ExampleMethods#backtrace instead.
WARNING
backtrace
end
# Run all the before(:each) blocks for this example
def run_before_each
example_group_hierarchy.run_before_each(self)
end
# Run all the after(:each) blocks for this example
def run_after_each
example_group_hierarchy.run_after_each(self)
end
private
include Matchers
include Pending
def before_each_example # :nodoc:
setup_mocks_for_rspec
run_before_each
end
def after_each_example # :nodoc:
run_after_each
verify_mocks_for_rspec
ensure
teardown_mocks_for_rspec
end
def described_class # :nodoc:
self.class.described_class
end
private
def example_group_hierarchy
self.class.example_group_hierarchy
end
end
end
end
|
require 'contracts'
require 'moneta'
require 'securerandom'
require_relative 'amazon'
require_relative 'config'
require_relative 'hdp/bootstrap_properties'
require_relative 'ssh'
module StackatoLKG
class BootstrapAgent
include ::Contracts::Core
include ::Contracts::Builtin
Contract None => String
def create_vpc
cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id|
ec2.assign_name(bootstrap_tag, vpc_id)
end
end
Contract None => Maybe[String]
def find_vpc
ENV.fetch('BOOTSTRAP_VPC_ID') do
cache.fetch(:vpc_id) do
cache.store :vpc_id, ec2
.tagged(type: 'vpc', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def internet_gateway
find_internet_gateway || create_internet_gateway
end
Contract None => String
def create_internet_gateway
cache.store(:internet_gateway_id,
ec2.create_internet_gateway.internet_gateway_id
).tap { |internet_gateway_id| ec2.assign_name bootstrap_tag, internet_gateway_id }
end
Contract None => Maybe[String]
def find_internet_gateway
ENV.fetch('BOOTSTRAP_INTERNET_GATEWAY_ID') do
cache.fetch(:internet_gateway_id) do
find_tagged_internet_gateway || find_internet_gateway_for_vpc
end
end
end
Contract None => Maybe[String]
def find_tagged_internet_gateway
ec2
.tagged(type: 'internet-gateway', value: bootstrap_tag)
.map { |resource| resource.resource.id }
.first
end
Contract None => Maybe[String]
def find_internet_gateway_for_vpc
ec2
.internet_gateways
.select { |gateway| gateway.attachments.any? { |attachment| attachment.vpc_id == vpc } }
.map { |gateway| gateway.internet_gateway_id }
.first
end
Contract None => String
def create_jumpbox_security_group
cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg|
ec2.assign_name(bootstrap_tag, sg)
end
end
Contract None => Maybe[String]
def find_jumpbox_security_group
@jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do
cache.fetch(:jumpbox_security_group) do
cache.store :jumpbox_security_group, ec2
.tagged(type: 'security-group', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => Bool
def allow_ssh
ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group
end
Contract None => String
def jumpbox_security_group
find_jumpbox_security_group || create_jumpbox_security_group
end
Contract None => String
def private_subnet
@private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do
cache.fetch(:private_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.private_cidr_block }
cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def public_subnet
@public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do
cache.fetch(:public_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.public_cidr_block }
cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def route_table
@route_table ||= ENV.fetch('BOOTSTRAP_ROUTE_TABLE_ID') do
cache.fetch(:route_table_id) do
cache.store(:route_table_id, ec2
.route_tables
.select { |route_table| route_table.vpc_id == vpc }
.map { |route_table| route_table.route_table_id }
.first).tap do |route_table_id|
ec2.assign_name bootstrap_tag, route_table_id
end
end
end
end
Contract None => Bool
def attach_gateway
ec2.attach_internet_gateway internet_gateway, vpc # TODO: Cache this
end
Contract None => Bool
def default_route
ec2.create_route('0.0.0.0/0', internet_gateway, route_table) # TODO: Cache this
end
Contract None => ArrayOf[String]
def subnets
[public_subnet, private_subnet]
end
Contract None => Bool
def enable_public_ips
ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true)
end
Contract None => String
def vpc
find_vpc || create_vpc
end
Contract None => String
def create_jumpbox
upload_ssh_key
cache.store(:jumpbox_id, ec2.create_instance(
image_id: ami,
instance_type: config.instance_type,
key_name: bootstrap_tag,
client_token: Digest::SHA256.hexdigest(bootstrap_tag),
network_interfaces: [{
device_index: 0,
subnet_id: public_subnet,
associate_public_ip_address: true,
groups: [jumpbox_security_group]
}]
).instance_id).tap do |instance_id|
ec2.assign_name bootstrap_tag, instance_id
end
end
Contract None => Maybe[String]
def find_jumpbox
ENV.fetch('BOOTSTRAP_JUMPBOX_ID') do
cache.fetch(:jumpbox_id) do
ec2
.tagged(type: 'instance', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def jumpbox
find_jumpbox || create_jumpbox
end
Contract None => String
def ami
@ami ||= ENV.fetch('BOOTSTRAP_AMI') do
cache.fetch(:ami_id) do
cache.store :ami_id, ec2.latest_ubuntu(config.ubuntu_release).image_id
end
end
end
Contract None => String
def upload_ssh_key
ec2.import_key_pair bootstrap_tag, ssh_key.to_s # TODO: Cache this.
end
Contract None => SSH::Key
def ssh_key
@ssh_key ||= SSH::Key.new bootstrap_tag
end
Contract None => String
def bootstrap_tag
@bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do
"lkg@#{username}/#{uuid}"
end
end
Contract None => String
def username
@username ||= ENV.fetch('BOOTSTRAP_USERNAME') do
cache.fetch(:username) do
cache.store(:username, iam.user.user_name)
end
end
end
Contract None => String
def uuid
@uuid ||= ENV.fetch('BOOTSTRAP_UUID') do
cache.fetch(:uuid) do
cache.store(:uuid, SecureRandom.uuid)
end
end
end
Contract None => String
def availability_zone
@availability_zone ||= ENV.fetch('BOOTSTRAP_AVAILABILITY_ZONE') do
cache.fetch(:availability_zone) do
cache.store(:availability_zone, ec2
.subnets
.select { |subnet| subnet.subnet_id == public_subnet }
.map { |subnet| subnet.availability_zone }
.first)
end
end
end
Contract None => String
def jumpbox_ip
@jumpbox_ip ||= ENV.fetch('BOOTSTRAP_JUMPBOX_IP') do
cache.fetch(:jumpbox_ip) do
cache.store(:jumpbox_ip, ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.flat_map(&:network_interfaces)
.map(&:association)
.map(&:public_ip)
.first)
end
end
end
Contract None => Bool
def configure_hdp
bootstrap_properties
.update('AWS.Region', config.region)
.update('AWS.AvailabilityZones', availability_zone)
.update('AWS.Keypair', bootstrap_tag)
.update('AWS.KeypairFile', 'bootstrap.pem')
.update('AWS.JumpboxCIDR', '0.0.0.0/0')
.update('AWS.VPCID', vpc)
.update('AWS.LinuxAMI', ami)
.save!
end
Contract None => Bool
def jumpbox_running?
ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.map { |instance| instance.state.name }
.first == 'running'
end
Contract None => Any
def configure_jumpbox
private_key = ssh_key.private_file
properties = bootstrap_properties.file
ssh.to(jumpbox_ip) do
'/home/ubuntu/.ssh/id_rsa'.tap do |target|
execute :chmod, '+w', target
upload! private_key, target
execute :chmod, '-w', target
end
upload! properties, '/home/ubuntu/bootstrap.properties'
as :root do
execute :apt, *%w(install --assume-yes genisoimage)
end
end
end
private
Contract None => SSH::Client
def ssh
@ssh ||= SSH::Client.new(ssh_key.private_file)
end
Contract None => HDP::BootstrapProperties
def bootstrap_properties
@hdp ||= HDP::BootstrapProperties.new
end
Contract None => Amazon::EC2
def ec2
@ec2 ||= Amazon::EC2.new
end
Contract None => Amazon::IAM
def iam
@iam ||= Amazon::IAM.new
end
Contract None => Config
def config
@config ||= Config.new
end
Contract None => Moneta::Proxy
def cache
@cache ||= Moneta.new :File, dir: config.cache_path
end
end
end
Update keypairfile in bootstrap properties.
require 'contracts'
require 'moneta'
require 'securerandom'
require_relative 'amazon'
require_relative 'config'
require_relative 'hdp/bootstrap_properties'
require_relative 'ssh'
module StackatoLKG
class BootstrapAgent
include ::Contracts::Core
include ::Contracts::Builtin
Contract None => String
def create_vpc
cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id|
ec2.assign_name(bootstrap_tag, vpc_id)
end
end
Contract None => Maybe[String]
def find_vpc
ENV.fetch('BOOTSTRAP_VPC_ID') do
cache.fetch(:vpc_id) do
cache.store :vpc_id, ec2
.tagged(type: 'vpc', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def internet_gateway
find_internet_gateway || create_internet_gateway
end
Contract None => String
def create_internet_gateway
cache.store(:internet_gateway_id,
ec2.create_internet_gateway.internet_gateway_id
).tap { |internet_gateway_id| ec2.assign_name bootstrap_tag, internet_gateway_id }
end
Contract None => Maybe[String]
def find_internet_gateway
ENV.fetch('BOOTSTRAP_INTERNET_GATEWAY_ID') do
cache.fetch(:internet_gateway_id) do
find_tagged_internet_gateway || find_internet_gateway_for_vpc
end
end
end
Contract None => Maybe[String]
def find_tagged_internet_gateway
ec2
.tagged(type: 'internet-gateway', value: bootstrap_tag)
.map { |resource| resource.resource.id }
.first
end
Contract None => Maybe[String]
def find_internet_gateway_for_vpc
ec2
.internet_gateways
.select { |gateway| gateway.attachments.any? { |attachment| attachment.vpc_id == vpc } }
.map { |gateway| gateway.internet_gateway_id }
.first
end
Contract None => String
def create_jumpbox_security_group
cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg|
ec2.assign_name(bootstrap_tag, sg)
end
end
Contract None => Maybe[String]
def find_jumpbox_security_group
@jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do
cache.fetch(:jumpbox_security_group) do
cache.store :jumpbox_security_group, ec2
.tagged(type: 'security-group', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => Bool
def allow_ssh
ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group
end
Contract None => String
def jumpbox_security_group
find_jumpbox_security_group || create_jumpbox_security_group
end
Contract None => String
def private_subnet
@private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do
cache.fetch(:private_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.private_cidr_block }
cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def public_subnet
@public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do
cache.fetch(:public_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.public_cidr_block }
cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def route_table
@route_table ||= ENV.fetch('BOOTSTRAP_ROUTE_TABLE_ID') do
cache.fetch(:route_table_id) do
cache.store(:route_table_id, ec2
.route_tables
.select { |route_table| route_table.vpc_id == vpc }
.map { |route_table| route_table.route_table_id }
.first).tap do |route_table_id|
ec2.assign_name bootstrap_tag, route_table_id
end
end
end
end
Contract None => Bool
def attach_gateway
ec2.attach_internet_gateway internet_gateway, vpc # TODO: Cache this
end
Contract None => Bool
def default_route
ec2.create_route('0.0.0.0/0', internet_gateway, route_table) # TODO: Cache this
end
Contract None => ArrayOf[String]
def subnets
[public_subnet, private_subnet]
end
Contract None => Bool
def enable_public_ips
ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true)
end
Contract None => String
def vpc
find_vpc || create_vpc
end
Contract None => String
def create_jumpbox
upload_ssh_key
cache.store(:jumpbox_id, ec2.create_instance(
image_id: ami,
instance_type: config.instance_type,
key_name: bootstrap_tag,
client_token: Digest::SHA256.hexdigest(bootstrap_tag),
network_interfaces: [{
device_index: 0,
subnet_id: public_subnet,
associate_public_ip_address: true,
groups: [jumpbox_security_group]
}]
).instance_id).tap do |instance_id|
ec2.assign_name bootstrap_tag, instance_id
end
end
Contract None => Maybe[String]
def find_jumpbox
ENV.fetch('BOOTSTRAP_JUMPBOX_ID') do
cache.fetch(:jumpbox_id) do
ec2
.tagged(type: 'instance', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def jumpbox
find_jumpbox || create_jumpbox
end
Contract None => String
def ami
@ami ||= ENV.fetch('BOOTSTRAP_AMI') do
cache.fetch(:ami_id) do
cache.store :ami_id, ec2.latest_ubuntu(config.ubuntu_release).image_id
end
end
end
Contract None => String
def upload_ssh_key
ec2.import_key_pair bootstrap_tag, ssh_key.to_s # TODO: Cache this.
end
Contract None => SSH::Key
def ssh_key
@ssh_key ||= SSH::Key.new bootstrap_tag
end
Contract None => String
def bootstrap_tag
@bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do
"lkg@#{username}/#{uuid}"
end
end
Contract None => String
def username
@username ||= ENV.fetch('BOOTSTRAP_USERNAME') do
cache.fetch(:username) do
cache.store(:username, iam.user.user_name)
end
end
end
Contract None => String
def uuid
@uuid ||= ENV.fetch('BOOTSTRAP_UUID') do
cache.fetch(:uuid) do
cache.store(:uuid, SecureRandom.uuid)
end
end
end
Contract None => String
def availability_zone
@availability_zone ||= ENV.fetch('BOOTSTRAP_AVAILABILITY_ZONE') do
cache.fetch(:availability_zone) do
cache.store(:availability_zone, ec2
.subnets
.select { |subnet| subnet.subnet_id == public_subnet }
.map { |subnet| subnet.availability_zone }
.first)
end
end
end
Contract None => String
def jumpbox_ip
@jumpbox_ip ||= ENV.fetch('BOOTSTRAP_JUMPBOX_IP') do
cache.fetch(:jumpbox_ip) do
cache.store(:jumpbox_ip, ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.flat_map(&:network_interfaces)
.map(&:association)
.map(&:public_ip)
.first)
end
end
end
Contract None => Bool
def configure_hdp
bootstrap_properties
.update('AWS.Region', config.region)
.update('AWS.AvailabilityZones', availability_zone)
.update('AWS.Keypair', bootstrap_tag)
.update('AWS.KeypairFile', '/home/ubuntu/.ssh/id_rsa')
.update('AWS.JumpboxCIDR', '0.0.0.0/0')
.update('AWS.VPCID', vpc)
.update('AWS.LinuxAMI', ami)
.save!
end
Contract None => Bool
def jumpbox_running?
ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.map { |instance| instance.state.name }
.first == 'running'
end
Contract None => Any
def configure_jumpbox
private_key = ssh_key.private_file
properties = bootstrap_properties.file
ssh.to(jumpbox_ip) do
'/home/ubuntu/.ssh/id_rsa'.tap do |target|
execute :chmod, '+w', target
upload! private_key, target
execute :chmod, '-w', target
end
upload! properties, '/home/ubuntu/bootstrap.properties'
as :root do
execute :apt, *%w(install --assume-yes genisoimage)
end
end
end
private
Contract None => SSH::Client
def ssh
@ssh ||= SSH::Client.new(ssh_key.private_file)
end
Contract None => HDP::BootstrapProperties
def bootstrap_properties
@hdp ||= HDP::BootstrapProperties.new
end
Contract None => Amazon::EC2
def ec2
@ec2 ||= Amazon::EC2.new
end
Contract None => Amazon::IAM
def iam
@iam ||= Amazon::IAM.new
end
Contract None => Config
def config
@config ||= Config.new
end
Contract None => Moneta::Proxy
def cache
@cache ||= Moneta.new :File, dir: config.cache_path
end
end
end
|
require 'stackbuilder/allocator/namespace'
require 'stackbuilder/allocator/host'
class StackBuilder::Allocator::Hosts
attr_reader :hosts
def initialize(args)
@hosts = args[:hosts]
@logger = args[:logger]
fail 'Cannot initialise Host Allocator with no hosts to allocate!' if hosts.empty?
hosts.each do |host|
host.preference_functions = args[:preference_functions]
end
end
public
def do_allocation(specs)
allocated_machines = Hash[hosts.map do |host|
host.allocated_machines.map do |machine|
[machine, host.fqdn]
end
end.flatten(1)]
already_allocated = allocated_machines.reject do |machine, _host|
!specs.include?(machine)
end
{
:already_allocated => already_allocated,
:newly_allocated => allocate(specs)
}
end
private
def find_suitable_host_for(machine)
allocation_denials = []
fail "Unable to allocate #{machine[:hostname]} as there are no hosts available" if hosts.empty?
candidate_hosts = hosts.reject do |host|
allocation_check_result = host.can_allocate(machine)
unless allocation_check_result[:allocatable]
reasons = allocation_check_result[:reasons]
reason_message = if reasons.empty?
'unsuitable for an unknown reason'
else
allocation_check_result[:reasons].join("; ")
end
unless @logger.nil?
@logger.debug("Allocating #{machine[:hostname]} -- skipping #{host.fqdn} - #{reasons.size} " \
"reasons:\n * #{reason_message}")
end
allocation_denials << "unable to allocate to #{host.fqdn} because it is [#{reason_message}]"
end
!allocation_check_result[:allocatable]
end
if candidate_hosts.empty?
fail "Unable to allocate #{machine[:hostname]} due to policy violation:\n #{allocation_denials.join("\n ")}"
end
candidate_hosts.sort_by(&:preference)[0]
end
private
def unallocated_machines(machines)
allocated_machines = []
hosts.each do |host|
host.allocated_machines.each do |machine|
allocated_machines << machine
end
end
machines - allocated_machines
end
public
def allocate(machines)
unallocated_machines = unallocated_machines(machines)
allocated_machines = Hash[unallocated_machines.map do |machine|
host = find_suitable_host_for(machine)
host.provisionally_allocate(machine)
[machine, host.fqdn]
end]
return_map = {}
allocated_machines.each do |machine, host|
return_map[host] = [] unless return_map[host]
return_map[host] << machine
end
return_map
end
end
add debug info explaining why a particular kvm host was picked
require 'stackbuilder/allocator/namespace'
require 'stackbuilder/allocator/host'
class StackBuilder::Allocator::Hosts
attr_reader :hosts
def initialize(args)
@hosts = args[:hosts]
@logger = args[:logger]
fail 'Cannot initialise Host Allocator with no hosts to allocate!' if hosts.empty?
hosts.each do |host|
host.preference_functions = args[:preference_functions]
end
end
public
def do_allocation(specs)
allocated_machines = Hash[hosts.map do |host|
host.allocated_machines.map do |machine|
[machine, host.fqdn]
end
end.flatten(1)]
already_allocated = allocated_machines.reject do |machine, _host|
!specs.include?(machine)
end
{
:already_allocated => already_allocated,
:newly_allocated => allocate(specs)
}
end
private
def find_suitable_host_for(machine)
allocation_denials = []
fail "Unable to allocate #{machine[:hostname]} as there are no hosts available" if hosts.empty?
candidate_hosts = hosts.reject do |host|
allocation_check_result = host.can_allocate(machine)
unless allocation_check_result[:allocatable]
reasons = allocation_check_result[:reasons]
reason_message = if reasons.empty?
'unsuitable for an unknown reason'
else
allocation_check_result[:reasons].join("; ")
end
unless @logger.nil?
@logger.debug("Allocating #{machine[:hostname]} -- skipping #{host.fqdn} - #{reasons.size} " \
"reasons:\n * #{reason_message}")
end
allocation_denials << "unable to allocate to #{host.fqdn} because it is [#{reason_message}]"
end
!allocation_check_result[:allocatable]
end
if candidate_hosts.empty?
fail "Unable to allocate #{machine[:hostname]} due to policy violation:\n #{allocation_denials.join("\n ")}"
end
candidate_hosts = candidate_hosts.sort_by(&:preference)
@logger.debug("kvm host preference list:")
candidate_hosts.each { |p| @logger.debug(" #{p.preference}") }
candidate_hosts[0]
end
private
def unallocated_machines(machines)
allocated_machines = []
hosts.each do |host|
host.allocated_machines.each do |machine|
allocated_machines << machine
end
end
machines - allocated_machines
end
public
def allocate(machines)
unallocated_machines = unallocated_machines(machines)
allocated_machines = Hash[unallocated_machines.map do |machine|
host = find_suitable_host_for(machine)
host.provisionally_allocate(machine)
[machine, host.fqdn]
end]
return_map = {}
allocated_machines.each do |machine, host|
return_map[host] = [] unless return_map[host]
return_map[host] << machine
end
return_map
end
end
|
require 'contracts'
require 'moneta'
require 'securerandom'
require_relative 'amazon'
require_relative 'config'
module StackatoLKG
class BootstrapAgent
include ::Contracts::Core
include ::Contracts::Builtin
Contract None => String
def create_vpc
cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id|
ec2.assign_name(bootstrap_tag, vpc_id)
end
end
Contract None => Maybe[String]
def find_vpc
ENV.fetch('BOOTSTRAP_VPC_ID') do
cache.fetch(:vpc_id) do
cache.store :vpc_id, ec2
.tagged(type: 'vpc', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def create_jumpbox_security_group
cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg|
ec2.assign_name(bootstrap_tag, sg)
end
end
Contract None => Maybe[String]
def find_jumpbox_security_group
@jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do
cache.fetch(:jumpbox_security_group) do
cache.store :jumpbox_security_group, ec2
.tagged(type: 'security-group', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => Bool
def allow_ssh
ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group
end
Contract None => String
def jumpbox_security_group
find_jumpbox_security_group || create_jumpbox_security_group
end
Contract None => String
def private_subnet
@private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do
cache.fetch(:private_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.private_cidr_block }
cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def public_subnet
@public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do
cache.fetch(:public_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.public_cidr_block }
cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => ArrayOf[String]
def subnets
[public_subnet, private_subnet]
end
Contract None => Bool
def vpc
find_vpc || create_vpc
end
Contract None => String
def bootstrap_tag
@bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do
"lkg@#{username}/#{uuid}"
end
end
Contract None => String
def username
@username ||= ENV.fetch('BOOTSTRAP_USERNAME') do
cache.fetch(:username) do
cache.store(:username, iam.user.user_name)
end
end
end
Contract None => String
def uuid
@uuid ||= ENV.fetch('BOOTSTRAP_UUID') do
cache.fetch(:uuid) do
cache.store(:uuid, SecureRandom.uuid)
end
end
end
private
Contract None => Amazon::EC2
def ec2
@ec2 ||= Amazon::EC2.new
end
Contract None => Amazon::IAM
def iam
@iam ||= Amazon::IAM.new
end
Contract None => Config
def config
@config ||= Config.new
end
Contract None => Moneta::Proxy
def cache
@cache ||= Moneta.new :File, dir: config.cache_path
end
end
end
Add feature to assign public IPS
require 'contracts'
require 'moneta'
require 'securerandom'
require_relative 'amazon'
require_relative 'config'
module StackatoLKG
class BootstrapAgent
include ::Contracts::Core
include ::Contracts::Builtin
Contract None => String
def create_vpc
cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id|
ec2.assign_name(bootstrap_tag, vpc_id)
end
end
Contract None => Maybe[String]
def find_vpc
ENV.fetch('BOOTSTRAP_VPC_ID') do
cache.fetch(:vpc_id) do
cache.store :vpc_id, ec2
.tagged(type: 'vpc', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def create_jumpbox_security_group
cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg|
ec2.assign_name(bootstrap_tag, sg)
end
end
Contract None => Maybe[String]
def find_jumpbox_security_group
@jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do
cache.fetch(:jumpbox_security_group) do
cache.store :jumpbox_security_group, ec2
.tagged(type: 'security-group', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => Bool
def allow_ssh
ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group
end
Contract None => String
def jumpbox_security_group
find_jumpbox_security_group || create_jumpbox_security_group
end
Contract None => String
def private_subnet
@private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do
cache.fetch(:private_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.private_cidr_block }
cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def public_subnet
@public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do
cache.fetch(:public_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.public_cidr_block }
cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => ArrayOf[String]
def subnets
[public_subnet, private_subnet]
end
Contract None => Bool
def enable_public_ips
ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true)
end
Contract None => String
def vpc
find_vpc || create_vpc
end
Contract None => String
def bootstrap_tag
@bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do
"lkg@#{username}/#{uuid}"
end
end
Contract None => String
def username
@username ||= ENV.fetch('BOOTSTRAP_USERNAME') do
cache.fetch(:username) do
cache.store(:username, iam.user.user_name)
end
end
end
Contract None => String
def uuid
@uuid ||= ENV.fetch('BOOTSTRAP_UUID') do
cache.fetch(:uuid) do
cache.store(:uuid, SecureRandom.uuid)
end
end
end
private
Contract None => Amazon::EC2
def ec2
@ec2 ||= Amazon::EC2.new
end
Contract None => Amazon::IAM
def iam
@iam ||= Amazon::IAM.new
end
Contract None => Config
def config
@config ||= Config.new
end
Contract None => Moneta::Proxy
def cache
@cache ||= Moneta.new :File, dir: config.cache_path
end
end
end
|
require 'contracts'
require 'moneta'
require 'securerandom'
require_relative 'amazon'
require_relative 'config'
require_relative 'hdp/bootstrap_properties'
require_relative 'ssh'
module StackatoLKG
class BootstrapAgent
include ::Contracts::Core
include ::Contracts::Builtin
Contract None => String
def create_vpc
cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id|
ec2.assign_name(bootstrap_tag, vpc_id)
end
end
Contract None => Maybe[String]
def find_vpc
ENV.fetch('BOOTSTRAP_VPC_ID') do
cache.fetch(:vpc_id) do
cache.store :vpc_id, ec2
.tagged(type: 'vpc', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def internet_gateway
find_internet_gateway || create_internet_gateway
end
Contract None => String
def create_internet_gateway
cache.store(:internet_gateway_id,
ec2.create_internet_gateway.internet_gateway_id
).tap { |internet_gateway_id| ec2.assign_name bootstrap_tag, internet_gateway_id }
end
Contract None => String
def nat_gateway_ip_allocation
ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ALLOCATION_ID') do
cache.fetch(:nat_gateway_allocation_id) do # TODO: Simplify this.
id = ec2
.nat_gateways
.select { |nat_gateway| nat_gateway.vpc_id == vpc }
.flat_map { |nat_gateway| nat_gateway.nat_gateway_addresses.map { |address| address.allocation_id } }
.first || ec2.unassociated_address || ec2.create_address
cache.store(:nat_gateway_allocation_id, id)
end
end
end
Contract None => Maybe[String]
def find_nat_gateway
ec2
.nat_gateways
.select { |nat_gateway| nat_gateway.vpc_id == vpc }
.map { |nat_gateway| nat_gateway.nat_gateway_id }
.first
end
Contract None => String
def create_nat_gateway
ec2.create_nat_gateway(private_subnet, nat_gateway_ip_allocation).nat_gateway_id
end
Contract None => String
def nat_gateway
ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ID') do
cache.fetch(:nat_gateway_id) do
cache.store(:nat_gateway_id, (find_nat_gateway || create_nat_gateway))
end
end
end
Contract None => Maybe[String]
def find_internet_gateway
ENV.fetch('BOOTSTRAP_INTERNET_GATEWAY_ID') do
cache.fetch(:internet_gateway_id) do
find_tagged_internet_gateway || find_internet_gateway_for_vpc
end
end
end
Contract None => Maybe[String]
def find_tagged_internet_gateway
ec2
.tagged(type: 'internet-gateway', value: bootstrap_tag)
.map { |resource| resource.resource.id }
.first
end
Contract None => Maybe[String]
def find_internet_gateway_for_vpc
ec2
.internet_gateways
.select { |gateway| gateway.attachments.any? { |attachment| attachment.vpc_id == vpc } }
.map { |gateway| gateway.internet_gateway_id }
.first
end
Contract None => String
def create_jumpbox_security_group
cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg|
ec2.assign_name(bootstrap_tag, sg)
end
end
Contract None => Maybe[String]
def find_jumpbox_security_group
@jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do
cache.fetch(:jumpbox_security_group) do
cache.store :jumpbox_security_group, ec2
.tagged(type: 'security-group', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => Bool
def allow_ssh
ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group
end
Contract None => String
def jumpbox_security_group
find_jumpbox_security_group || create_jumpbox_security_group
end
Contract None => String
def private_subnet
@private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do
cache.fetch(:private_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.private_cidr_block }
cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def public_subnet
@public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do
cache.fetch(:public_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.public_cidr_block }
cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def route_table
@route_table ||= ENV.fetch('BOOTSTRAP_ROUTE_TABLE_ID') do
cache.fetch(:route_table_id) do
cache.store(:route_table_id, ec2
.route_tables
.select { |route_table| route_table.vpc_id == vpc }
.map { |route_table| route_table.route_table_id }
.first).tap do |route_table_id|
ec2.assign_name bootstrap_tag, route_table_id
end
end
end
end
Contract None => Bool
def attach_gateway
ec2.attach_internet_gateway internet_gateway, vpc # TODO: Cache this
end
Contract None => Bool
def default_route
ec2.create_route('0.0.0.0/0', internet_gateway, route_table) # TODO: Cache this
end
Contract None => ArrayOf[String]
def subnets
[public_subnet, private_subnet]
end
Contract None => Bool
def enable_public_ips
ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true)
end
Contract None => String
def vpc
find_vpc || create_vpc
end
Contract None => String
def create_jumpbox
upload_ssh_key
cache.store(:jumpbox_id, ec2.create_instance(
image_id: ami,
instance_type: config.instance_type,
key_name: bootstrap_tag,
client_token: Digest::SHA256.hexdigest(bootstrap_tag),
network_interfaces: [{
device_index: 0,
subnet_id: public_subnet,
associate_public_ip_address: true,
groups: [jumpbox_security_group]
}]
).instance_id).tap do |instance_id|
ec2.assign_name bootstrap_tag, instance_id
end
end
Contract None => Maybe[String]
def find_jumpbox
ENV.fetch('BOOTSTRAP_JUMPBOX_ID') do
cache.fetch(:jumpbox_id) do
ec2
.tagged(type: 'instance', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def jumpbox
find_jumpbox || create_jumpbox
end
Contract None => String
def ami
@ami ||= ENV.fetch('BOOTSTRAP_AMI') do
cache.fetch(:ami_id) do
cache.store :ami_id, ec2.latest_ubuntu(config.ubuntu_release).image_id
end
end
end
Contract None => String
def upload_ssh_key
ec2.import_key_pair bootstrap_tag, ssh_key.to_s # TODO: Cache this.
end
Contract None => SSH::Key
def ssh_key
@ssh_key ||= SSH::Key.new bootstrap_tag
end
Contract None => String
def bootstrap_tag
@bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do
"lkg@#{username}/#{uuid}"
end
end
Contract None => String
def username
@username ||= ENV.fetch('BOOTSTRAP_USERNAME') do
cache.fetch(:username) do
cache.store(:username, iam.user.user_name)
end
end
end
Contract None => String
def uuid
@uuid ||= ENV.fetch('BOOTSTRAP_UUID') do
cache.fetch(:uuid) do
cache.store(:uuid, SecureRandom.uuid)
end
end
end
Contract None => String
def public_availability_zone
@public_availability_zone ||= ENV.fetch('BOOTSTRAP_PUBLIC_AVAILABILITY_ZONE') do
cache.fetch(:public_availability_zone) do
cache.store(:public_availability_zone, ec2
.subnets
.select { |subnet| subnet.subnet_id == public_subnet }
.map { |subnet| subnet.availability_zone }
.first)
end
end
end
Contract None => String
def private_availability_zone
@private_availability_zone ||= ENV.fetch('BOOTSTRAP_PRIVATE_AVAILABILITY_ZONE') do
cache.fetch(:private_availability_zone) do
cache.store(:private_availability_zone, ec2
.subnets
.select { |subnet| subnet.subnet_id == private_subnet }
.map { |subnet| subnet.availability_zone }
.first)
end
end
end
Contract None => String
def jumpbox_ip
@jumpbox_ip ||= ENV.fetch('BOOTSTRAP_JUMPBOX_IP') do
cache.fetch(:jumpbox_ip) do
cache.store(:jumpbox_ip, ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.flat_map(&:network_interfaces)
.map(&:association)
.map(&:public_ip)
.first)
end
end
end
Contract None => Bool
def configure_hdp
bootstrap_properties
.update('Provider', 'AWS')
.update('AWS.Region', config.region)
.update('AWS.AvailabilityZones', public_availability_zone)
.update('AWS.PublicSubnetIDsAndAZ', [public_subnet, public_availability_zone].join(':'))
.update('AWS.PrivateSubnetIDsAndAZ', [private_subnet, private_availability_zone].join(':'))
.update('AWS.Keypair', bootstrap_tag)
.update('AWS.KeypairFile', '/home/ubuntu/.ssh/id_rsa')
.update('AWS.JumpboxCIDR', '0.0.0.0/0')
.update('AWS.VPCID', vpc)
.update('AWS.LinuxAMI', ami)
.save!
end
Contract None => Bool
def jumpbox_running?
ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.map { |instance| instance.state.name }
.first == 'running'
end
Contract None => Any
def configure_jumpbox
private_key = ssh_key.private_file
properties = bootstrap_properties.file
package = config.hdp_package_url
ssh.to(jumpbox_ip) do
'/home/ubuntu/.ssh/id_rsa'.tap do |target|
execute :rm, '-f', target
upload! private_key, target
execute :chmod, '-w', target
end
upload! properties, '/home/ubuntu/bootstrap.properties'
as :root do
execute :apt, *%w(install --assume-yes genisoimage aria2)
execute :aria2c, '--continue=true', '--dir=/opt', '--out=bootstrap.deb', package
execute :dpkg, *%w(--install /opt/bootstrap.deb)
end
end
end
Contract None => Bool
def requires_human_oversight?
['false', 'nil', nil].include? ENV['BOOTSTRAP_WITHOUT_HUMAN_OVERSIGHT']
end
Contract None => Any
def launch
return false if requires_human_oversight?
access_key_id = ec2.api.config.credentials.credentials.access_key_id
secret_access_key = ec2.api.config.credentials.credentials.secret_access_key
ssh.to(jumpbox_ip) do
with(aws_access_key_id: access_key_id, aws_secret_access_key: secret_access_key) do
execute :bootstrap, *%w(install bootstrap.properties 2>&1 | tee bootstrap.log)
end
end
end
private
Contract None => SSH::Client
def ssh
@ssh ||= SSH::Client.new(ssh_key.private_file)
end
Contract None => HDP::BootstrapProperties
def bootstrap_properties
@hdp ||= HDP::BootstrapProperties.new
end
Contract None => Amazon::EC2
def ec2
@ec2 ||= Amazon::EC2.new
end
Contract None => Amazon::IAM
def iam
@iam ||= Amazon::IAM.new
end
Contract None => Config
def config
@config ||= Config.new
end
Contract None => Moneta::Proxy
def cache
@cache ||= Moneta.new :File, dir: config.cache_path
end
end
end
Update route_table to return main route table
require 'contracts'
require 'moneta'
require 'securerandom'
require_relative 'amazon'
require_relative 'config'
require_relative 'hdp/bootstrap_properties'
require_relative 'ssh'
module StackatoLKG
class BootstrapAgent
include ::Contracts::Core
include ::Contracts::Builtin
Contract None => String
def create_vpc
cache.store(:vpc_id, ec2.create_vpc.vpc_id).tap do |vpc_id|
ec2.assign_name(bootstrap_tag, vpc_id)
end
end
Contract None => Maybe[String]
def find_vpc
ENV.fetch('BOOTSTRAP_VPC_ID') do
cache.fetch(:vpc_id) do
cache.store :vpc_id, ec2
.tagged(type: 'vpc', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def internet_gateway
find_internet_gateway || create_internet_gateway
end
Contract None => String
def create_internet_gateway
cache.store(:internet_gateway_id,
ec2.create_internet_gateway.internet_gateway_id
).tap { |internet_gateway_id| ec2.assign_name bootstrap_tag, internet_gateway_id }
end
Contract None => String
def nat_gateway_ip_allocation
ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ALLOCATION_ID') do
cache.fetch(:nat_gateway_allocation_id) do # TODO: Simplify this.
id = ec2
.nat_gateways
.select { |nat_gateway| nat_gateway.vpc_id == vpc }
.flat_map { |nat_gateway| nat_gateway.nat_gateway_addresses.map { |address| address.allocation_id } }
.first || ec2.unassociated_address || ec2.create_address
cache.store(:nat_gateway_allocation_id, id)
end
end
end
Contract None => Maybe[String]
def find_nat_gateway
ec2
.nat_gateways
.select { |nat_gateway| nat_gateway.vpc_id == vpc }
.map { |nat_gateway| nat_gateway.nat_gateway_id }
.first
end
Contract None => String
def create_nat_gateway
ec2.create_nat_gateway(private_subnet, nat_gateway_ip_allocation).nat_gateway_id
end
Contract None => String
def nat_gateway
ENV.fetch('BOOTSTRAP_NAT_GATEWAY_ID') do
cache.fetch(:nat_gateway_id) do
cache.store(:nat_gateway_id, (find_nat_gateway || create_nat_gateway))
end
end
end
Contract None => Maybe[String]
def find_internet_gateway
ENV.fetch('BOOTSTRAP_INTERNET_GATEWAY_ID') do
cache.fetch(:internet_gateway_id) do
find_tagged_internet_gateway || find_internet_gateway_for_vpc
end
end
end
Contract None => Maybe[String]
def find_tagged_internet_gateway
ec2
.tagged(type: 'internet-gateway', value: bootstrap_tag)
.map { |resource| resource.resource.id }
.first
end
Contract None => Maybe[String]
def find_internet_gateway_for_vpc
ec2
.internet_gateways
.select { |gateway| gateway.attachments.any? { |attachment| attachment.vpc_id == vpc } }
.map { |gateway| gateway.internet_gateway_id }
.first
end
Contract None => String
def create_jumpbox_security_group
cache.store(:jumpbox_security_group, ec2.create_security_group(:jumpbox, vpc)).tap do |sg|
ec2.assign_name(bootstrap_tag, sg)
end
end
Contract None => Maybe[String]
def find_jumpbox_security_group
@jumpbox_security_group ||= ENV.fetch('BOOTSTRAP_JUMPBOX_SECURITY_GROUP') do
cache.fetch(:jumpbox_security_group) do
cache.store :jumpbox_security_group, ec2
.tagged(type: 'security-group', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => Bool
def allow_ssh
ec2.authorize_security_group_ingress :tcp, 22, '0.0.0.0/0', jumpbox_security_group
end
Contract None => String
def jumpbox_security_group
find_jumpbox_security_group || create_jumpbox_security_group
end
Contract None => String
def private_subnet
@private_subnet ||= ENV.fetch('BOOTSTRAP_PRIVATE_SUBNET_ID') do
cache.fetch(:private_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.private_cidr_block }
cache.store(:private_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def public_subnet
@public_subnet ||= ENV.fetch('BOOTSTRAP_PUBLIC_SUBNET_ID') do
cache.fetch(:public_subnet_id) do
properties = { vpc_id: vpc, cidr_block: config.public_cidr_block }
cache.store(:public_subnet_id, (ec2.subnet(properties) || ec2.create_subnet(properties)).tap do |subnet|
ec2.assign_name bootstrap_tag, subnet.subnet_id unless subnet.tags.any? do |tag|
tag.key == 'Name' && tag.value = bootstrap_tag
end
end.subnet_id)
end
end
end
Contract None => String
def route_table
@route_table ||= ENV.fetch('BOOTSTRAP_ROUTE_TABLE_ID') do
cache.fetch(:route_table_id) do
cache.store(:route_table_id, ec2
.route_tables
.select { |route_table| route_table.vpc_id == vpc }
.select { |route_table| route_table.associations.any? { |association| association.main } }
.map { |route_table| route_table.route_table_id }
.first).tap do |route_table_id|
ec2.assign_name bootstrap_tag, route_table_id
end
end
end
end
Contract None => Bool
def attach_gateway
ec2.attach_internet_gateway internet_gateway, vpc # TODO: Cache this
end
Contract None => Bool
def default_route
ec2.create_route('0.0.0.0/0', internet_gateway, route_table) # TODO: Cache this
end
Contract None => ArrayOf[String]
def subnets
[public_subnet, private_subnet]
end
Contract None => Bool
def enable_public_ips
ec2.map_public_ip_on_launch?(public_subnet) || ec2.map_public_ip_on_launch(public_subnet, true)
end
Contract None => String
def vpc
find_vpc || create_vpc
end
Contract None => String
def create_jumpbox
upload_ssh_key
cache.store(:jumpbox_id, ec2.create_instance(
image_id: ami,
instance_type: config.instance_type,
key_name: bootstrap_tag,
client_token: Digest::SHA256.hexdigest(bootstrap_tag),
network_interfaces: [{
device_index: 0,
subnet_id: public_subnet,
associate_public_ip_address: true,
groups: [jumpbox_security_group]
}]
).instance_id).tap do |instance_id|
ec2.assign_name bootstrap_tag, instance_id
end
end
Contract None => Maybe[String]
def find_jumpbox
ENV.fetch('BOOTSTRAP_JUMPBOX_ID') do
cache.fetch(:jumpbox_id) do
ec2
.tagged(type: 'instance', value: bootstrap_tag)
.map(&:resource_id)
.first
end
end
end
Contract None => String
def jumpbox
find_jumpbox || create_jumpbox
end
Contract None => String
def ami
@ami ||= ENV.fetch('BOOTSTRAP_AMI') do
cache.fetch(:ami_id) do
cache.store :ami_id, ec2.latest_ubuntu(config.ubuntu_release).image_id
end
end
end
Contract None => String
def upload_ssh_key
ec2.import_key_pair bootstrap_tag, ssh_key.to_s # TODO: Cache this.
end
Contract None => SSH::Key
def ssh_key
@ssh_key ||= SSH::Key.new bootstrap_tag
end
Contract None => String
def bootstrap_tag
@bootstrap_tag ||= ENV.fetch('BOOTSTRAP_TAG') do
"lkg@#{username}/#{uuid}"
end
end
Contract None => String
def username
@username ||= ENV.fetch('BOOTSTRAP_USERNAME') do
cache.fetch(:username) do
cache.store(:username, iam.user.user_name)
end
end
end
Contract None => String
def uuid
@uuid ||= ENV.fetch('BOOTSTRAP_UUID') do
cache.fetch(:uuid) do
cache.store(:uuid, SecureRandom.uuid)
end
end
end
Contract None => String
def public_availability_zone
@public_availability_zone ||= ENV.fetch('BOOTSTRAP_PUBLIC_AVAILABILITY_ZONE') do
cache.fetch(:public_availability_zone) do
cache.store(:public_availability_zone, ec2
.subnets
.select { |subnet| subnet.subnet_id == public_subnet }
.map { |subnet| subnet.availability_zone }
.first)
end
end
end
Contract None => String
def private_availability_zone
@private_availability_zone ||= ENV.fetch('BOOTSTRAP_PRIVATE_AVAILABILITY_ZONE') do
cache.fetch(:private_availability_zone) do
cache.store(:private_availability_zone, ec2
.subnets
.select { |subnet| subnet.subnet_id == private_subnet }
.map { |subnet| subnet.availability_zone }
.first)
end
end
end
Contract None => String
def jumpbox_ip
@jumpbox_ip ||= ENV.fetch('BOOTSTRAP_JUMPBOX_IP') do
cache.fetch(:jumpbox_ip) do
cache.store(:jumpbox_ip, ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.flat_map(&:network_interfaces)
.map(&:association)
.map(&:public_ip)
.first)
end
end
end
Contract None => Bool
def configure_hdp
bootstrap_properties
.update('Provider', 'AWS')
.update('AWS.Region', config.region)
.update('AWS.AvailabilityZones', public_availability_zone)
.update('AWS.PublicSubnetIDsAndAZ', [public_subnet, public_availability_zone].join(':'))
.update('AWS.PrivateSubnetIDsAndAZ', [private_subnet, private_availability_zone].join(':'))
.update('AWS.Keypair', bootstrap_tag)
.update('AWS.KeypairFile', '/home/ubuntu/.ssh/id_rsa')
.update('AWS.JumpboxCIDR', '0.0.0.0/0')
.update('AWS.VPCID', vpc)
.update('AWS.LinuxAMI', ami)
.save!
end
Contract None => Bool
def jumpbox_running?
ec2
.instances
.select { |instance| instance.instance_id == jumpbox }
.map { |instance| instance.state.name }
.first == 'running'
end
Contract None => Any
def configure_jumpbox
private_key = ssh_key.private_file
properties = bootstrap_properties.file
package = config.hdp_package_url
ssh.to(jumpbox_ip) do
'/home/ubuntu/.ssh/id_rsa'.tap do |target|
execute :rm, '-f', target
upload! private_key, target
execute :chmod, '-w', target
end
upload! properties, '/home/ubuntu/bootstrap.properties'
as :root do
execute :apt, *%w(install --assume-yes genisoimage aria2)
execute :aria2c, '--continue=true', '--dir=/opt', '--out=bootstrap.deb', package
execute :dpkg, *%w(--install /opt/bootstrap.deb)
end
end
end
Contract None => Bool
def requires_human_oversight?
['false', 'nil', nil].include? ENV['BOOTSTRAP_WITHOUT_HUMAN_OVERSIGHT']
end
Contract None => Any
def launch
return false if requires_human_oversight?
access_key_id = ec2.api.config.credentials.credentials.access_key_id
secret_access_key = ec2.api.config.credentials.credentials.secret_access_key
ssh.to(jumpbox_ip) do
with(aws_access_key_id: access_key_id, aws_secret_access_key: secret_access_key) do
execute :bootstrap, *%w(install bootstrap.properties 2>&1 | tee bootstrap.log)
end
end
end
private
Contract None => SSH::Client
def ssh
@ssh ||= SSH::Client.new(ssh_key.private_file)
end
Contract None => HDP::BootstrapProperties
def bootstrap_properties
@hdp ||= HDP::BootstrapProperties.new
end
Contract None => Amazon::EC2
def ec2
@ec2 ||= Amazon::EC2.new
end
Contract None => Amazon::IAM
def iam
@iam ||= Amazon::IAM.new
end
Contract None => Config
def config
@config ||= Config.new
end
Contract None => Moneta::Proxy
def cache
@cache ||= Moneta.new :File, dir: config.cache_path
end
end
end
|
# NOTE: only doing this in development as some production environments (Heroku)
# NOTE: are sensitive to local FS writes, and besides -- it's just not proper
# NOTE: to have a dev-mode tool do its thing in production.
if Rails.env.development?
task :set_annotation_options do
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults(
'routes' => 'false',
'position_in_routes' => 'before',
'position_in_class' => 'before',
'position_in_test' => 'before',
'position_in_fixture' => 'before',
'position_in_factory' => 'before',
'position_in_serializer' => 'before',
'show_foreign_keys' => 'true',
'show_indexes' => 'true',
'simple_indexes' => 'false',
'model_dir' => 'app/models',
'root_dir' => '',
'include_version' => 'false',
'require' => '',
'exclude_tests' => 'false',
'exclude_fixtures' => 'false',
'exclude_factories' => 'false',
'exclude_serializers' => 'false',
'exclude_scaffolds' => 'true',
'exclude_controllers' => 'true',
'exclude_helpers' => 'false',
'ignore_model_sub_dir' => 'false',
'ignore_columns' => nil,
'ignore_unknown_models' => 'false',
'hide_limit_column_types' => 'integer,boolean',
'skip_on_db_migrate' => 'false',
'format_bare' => 'true',
'format_rdoc' => 'false',
'format_markdown' => 'false',
'sort' => 'false',
'force' => 'false',
'trace' => 'false',
'wrapper_open' => nil,
'wrapper_close' => nil,
)
end
Annotate.load_tasks
end
don't annotate helpers.
# NOTE: only doing this in development as some production environments (Heroku)
# NOTE: are sensitive to local FS writes, and besides -- it's just not proper
# NOTE: to have a dev-mode tool do its thing in production.
if Rails.env.development?
task :set_annotation_options do
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults(
'routes' => 'false',
'position_in_routes' => 'before',
'position_in_class' => 'before',
'position_in_test' => 'before',
'position_in_fixture' => 'before',
'position_in_factory' => 'before',
'position_in_serializer' => 'before',
'show_foreign_keys' => 'true',
'show_indexes' => 'true',
'simple_indexes' => 'false',
'model_dir' => 'app/models',
'root_dir' => '',
'include_version' => 'false',
'require' => '',
'exclude_tests' => 'false',
'exclude_fixtures' => 'false',
'exclude_factories' => 'false',
'exclude_serializers' => 'false',
'exclude_scaffolds' => 'true',
'exclude_controllers' => 'true',
'exclude_helpers' => 'true',
'ignore_model_sub_dir' => 'false',
'ignore_columns' => nil,
'ignore_unknown_models' => 'false',
'hide_limit_column_types' => 'integer,boolean',
'skip_on_db_migrate' => 'false',
'format_bare' => 'true',
'format_rdoc' => 'false',
'format_markdown' => 'false',
'sort' => 'false',
'force' => 'false',
'trace' => 'false',
'wrapper_open' => nil,
'wrapper_close' => nil,
)
end
Annotate.load_tasks
end
|
require "csv"
desc "Load MSF's Interim spreadsheet into the DB"
task :load_msf_spreadsheet, [:csv_file] => [:environment] do |_t, args|
rows = CSV.read(args[:csv_file], headers: true,
header_converters: :symbol,
converters: :all)
default_topic = StudyTopic.find_by_name!("Other")
default_concept_paper_date = Time.zone.today
default_stage = StudyStage.find_by_name!("Concept")
default_setting = StudySetting.find_by_name!("Stable")
rows.each do |row|
next if row[:study_title].blank? || row[:study_reference_].blank?
# We need to map some of the spreadsheet values to the new data structure
stage = row[:study_status]
stage = "Delivery" if stage == "Active"
stage = "Protocol & ERB" if stage == "Protocol review"
stage = "Concept" if stage == "Concept paper"
stage = "Completion" if stage == "Completed"
stage = "Withdrawn or Postponed" if stage == "Postponed / withdrawn"
unless row[:study_type].blank?
type = row[:study_type].gsub(/\s\(.*\)/, "")
end
type = StudyType.find_by_name(type) || StudyType.find_by_name("Other")
if type == StudyType.other_study_type
other_study_type = "Was empty in spreadsheet"
else
other_study_type = nil
end
if row[:concept_paper_date].blank?
date = default_concept_paper_date
else
date = Date.strptime(row[:concept_paper_date], "%d/%m/%Y")
end
Study.create!(
reference_number: row[:study_reference_],
title: row[:study_title],
study_type: type,
other_study_type: other_study_type,
study_stage: StudyStage.find_by_name(stage) || default_stage,
concept_paper_date: date,
study_topic: StudyTopic.find_by_name(row[:disease]) || default_topic,
# This isn't specified in the CSV at all, so just assume a value
protocol_needed: true,
# This isn't specified either
study_setting: default_setting
)
end
end
Import countries when importing MSF's spreadsheet
require "csv"
desc "Load MSF's Interim spreadsheet into the DB"
task :load_msf_spreadsheet, [:csv_file] => [:environment] do |_t, args|
rows = CSV.read(args[:csv_file], headers: true,
header_converters: :symbol,
converters: :all)
default_topic = StudyTopic.find_by_name!("Other")
default_concept_paper_date = Time.zone.today
default_stage = StudyStage.find_by_name!("Concept")
default_setting = StudySetting.find_by_name!("Stable")
rows.each do |row|
next if row[:study_title].blank? || row[:study_reference_].blank?
# We need to map some of the spreadsheet values to the new data structure
stage = row[:study_status]
stage = "Delivery" if stage == "Active"
stage = "Protocol & ERB" if stage == "Protocol review"
stage = "Concept" if stage == "Concept paper"
stage = "Completion" if stage == "Completed"
stage = "Withdrawn or Postponed" if stage == "Postponed / withdrawn"
unless row[:study_type].blank?
type = row[:study_type].gsub(/\s\(.*\)/, "")
end
type = StudyType.find_by_name(type) || StudyType.find_by_name("Other")
if type == StudyType.other_study_type
other_study_type = "Was empty in spreadsheet"
else
other_study_type = nil
end
if row[:concept_paper_date].blank?
date = default_concept_paper_date
else
date = Date.strptime(row[:concept_paper_date], "%d/%m/%Y")
end
country_code = nil
unless row[:study_location].blank?
study_location = row[:study_location]
# The countries gem is very particular about some names
if study_location == "Democratic Republic of the Congo"
study_location = "Congo, The Democratic Republic Of The"
elsif study_location == "Burma"
study_location = "Myanmar"
end
country = ISO3166::Country.find_country_by_name(study_location)
country_code = country.alpha2 unless country.nil?
end
Study.create!(
reference_number: row[:study_reference_],
title: row[:study_title],
study_type: type,
other_study_type: other_study_type,
study_stage: StudyStage.find_by_name(stage) || default_stage,
concept_paper_date: date,
study_topic: StudyTopic.find_by_name(row[:disease]) || default_topic,
# This isn't specified in the CSV at all, so just assume a value
protocol_needed: true,
# This isn't specified either
study_setting: default_setting,
country_code: country_code
)
end
end
|
# desc "Explaining what the task does"
namespace :query_reviewer do
desc "Create a default config/query_reviewer.yml"
task :setup do
FileUtils.copy(File.join(File.dirname(__FILE__), "..", "query_reviewer_defaults.yml"), File.join(RAILS_ROOT, "config", "query_reviewer.yml"))
end
end
Fix bug in rake task
# desc "Explaining what the task does"
namespace :query_reviewer do
desc "Create a default config/query_reviewer.yml"
task :setup do
FileUtils.copy(File.join(File.dirname(__FILE__), "../..", "query_reviewer_defaults.yml"), File.join(RAILS_ROOT, "config", "query_reviewer.yml"))
end
end
|
# desc "Explaining what the task does"
# task :transam_transit do
# # Task goes here
# end
namespace :transam_transit_data do
task add_early_disposition_requests_bulk_update: :environment do
unless FileContentType.find_by(builder_name: "TransitEarlyDispositionRequestUpdatesTemplateBuilder").present?
FileContentType.create!({:active => 1, :name => 'Early Disposition Requests', :class_name => 'EarlyDispositionRequestUpdatesFileHandler', :builder_name => "TransitEarlyDispositionRequestUpdatesTemplateBuilder", :description => 'Worksheet requests early disposition for existing inventory.'})
end
end
desc 'add roles list for org types'
task add_roles_organization_types: :environment do
OrganizationType.find_by(class_name: 'Grantor').update!(roles: 'guest,manager')
OrganizationType.find_by(class_name: 'TransitOperator').update!(roles: 'guest,user,transit_manager')
OrganizationType.find_by(class_name: 'PlanningPartner').update!(roles: 'guest')
end
desc 'add facility rollup asset type/subtype'
task add_facility_asset_subtypes: :environment do
parent_policy_id = Policy.where('parent_id IS NULL').pluck(:id).first
new_types = [
{name: 'Substructure', description: 'Substructure', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Shell', description: 'Shell', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Interior', description: 'Interiors', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Conveyance', description: 'Conveyance', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Plumbing', description: 'Plumbing', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'HVAC', description: 'HVAC', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Fire Protection', description: 'Fire Protection', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Electrical', description: 'Electrical', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Site', description: 'Site', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true}
].each do |type|
if AssetType.find_by(name: type[:name]).nil?
a = AssetType.create!(type)
PolicyAssetTypeRule.create(policy_id: parent_policy_id, asset_type_id: a.id, service_life_calculation_type_id: ServiceLifeCalculationType.find_by(name: 'Condition Only').id, replacement_cost_calculation_type_id: CostCalculationType.find_by(name: 'Purchase Price + Interest').id, condition_rollup_calculation_type_id: 1, annual_inflation_rate: 1.1, pcnt_residual_value: 0, condition_rollup_weight: 0 )
end
end
[
{asset_type: 'Substructure', name: 'All Substructure', description: 'All Substructures', active: true},
{asset_type: 'Substructure', name: 'Foundation', description: 'Foundations', active: true},
{asset_type: 'Substructure', name: 'Basement', description: 'Basement', active: true},
{asset_type: 'Substructure', name: 'Foundation - Wall', description: 'Foundation - Wall', active: true},
{asset_type: 'Substructure', name: 'Foundation - Column', description: 'Foundation - Column', active: true},
{asset_type: 'Substructure', name: 'Foundation - Piling', description: 'Foundation - Piling', active: true},
{asset_type: 'Substructure', name: 'Basement - Materials', description: 'Basement - Materials', active: true},
{asset_type: 'Substructure', name: 'Basement - Insulation', description: 'Basement - Insulation', active: true},
{asset_type: 'Substructure', name: 'Basement - Slab', description: 'Basement - Slab', active: true},
{asset_type: 'Substructure', name: 'Basement - Floor Underpinning', description: 'Basement - Floor Underpinning', active: true},
{asset_type: 'Shell', name: 'All Shell Structure', description: 'All Structures', active: true},
{asset_type: 'Shell', name: 'Superstructure', description: 'Superstructure', active: true},
{asset_type: 'Shell', name: 'Roof', description: 'Roof', active: true},
{asset_type: 'Shell', name: 'Exterior', description: 'Exterior', active: true},
{asset_type: 'Shell', name: 'Shell Appurtenance', description: 'Shell Appurtenances', active: true},
{asset_type: 'Shell', name: 'Superstructure - Column', description: 'Superstructure - Column', active: true},
{asset_type: 'Shell', name: 'Superstructure - Pillar', description: 'Superstructure - Pillar', active: true},
{asset_type: 'Shell', name: 'Superstructure - Wall', description: 'Superstructure - Wall', active: true},
{asset_type: 'Interior', name: 'All Interior', description: 'All Interior', active: true},
{asset_type: 'Interior', name: 'Partition', description: 'Partition', active: true},
{asset_type: 'Interior', name: 'Stairs', description: 'Stairs', active: true},
{asset_type: 'Interior', name: 'Finishes', description: 'Finishes', active: true},
{asset_type: 'Interior', name: 'Partition - Wall', description: 'Partition - Wall', active: true},
{asset_type: 'Interior', name: 'Partition - Door', description: 'Partition - Door', active: true},
{asset_type: 'Interior', name: 'Partition - Fittings', description: 'Partition - Fittings', active: true},
{asset_type: 'Interior', name: 'Stairs - Landing', description: 'Stairs - Landing', active: true},
{asset_type: 'Interior', name: 'Finishes - Wall Materials', description: 'Finishes - Wall Materials', active: true},
{asset_type: 'Interior', name: 'Finishes - Floor Materials', description: 'Finishes - Floor Materials', active: true},
{asset_type: 'Interior', name: 'Finishes - Ceiling Materials', description: 'Finishes - Ceiling Materials', active: true},
{asset_type: 'Conveyance', name: 'All Conveyance', description: 'All Conveyance', active: true},
{asset_type: 'Conveyance', name: 'Elevator', description: 'Elevator', active: true},
{asset_type: 'Conveyance', name: 'Escalator', description: 'Escalator', active: true},
{asset_type: 'Conveyance', name: 'Lift', description: 'Lift', active: true},
{asset_type: 'Plumbing', name: 'All Plumbing', description: 'All Plumbing', active: true},
{asset_type: 'Plumbing', name: 'Fixture', description: 'Fixture', active: true},
{asset_type: 'Plumbing', name: 'Water Distribution', description: 'Water Distribution', active: true},
{asset_type: 'Plumbing', name: 'Sanitary Waste', description: 'Sanitary Waste', active: true},
{asset_type: 'Plumbing', name: 'Rain Water Drainage', description: 'Rain Water Drainage', active: true},
{asset_type: 'HVAC', name: 'HVAC System', description: 'HVAC System', active: true},
{asset_type: 'HVAC', name: 'Energy Supply', description: 'Energy Supply', active: true},
{asset_type: 'HVAC', name: 'Heat Generation and Distribution System', description: 'Heat Generation and Distribution System', active: true},
{asset_type: 'HVAC', name: 'Cooling Generation and Distribution System', description: 'Cooling Generation and Distribution System', active: true},
{asset_type: 'HVAC', name: 'Instrumentation', description: 'Testing, Balancing, Controls and Instrumentation', active: true},
{asset_type: 'Fire Protection', name: 'All Fire Protection', description: 'All Fire Protection', active: true},
{asset_type: 'Fire Protection', name: 'Sprinkler', description: 'Sprinkler', active: true},
{asset_type: 'Fire Protection', name: 'Standpipes', description: 'Standpipes', active: true},
{asset_type: 'Fire Protection', name: 'Hydrant', description: 'Hydrant', active: true},
{asset_type: 'Fire Protection', name: 'Other Fire Protection', description: 'Other Fire Protection', active: true},
{asset_type: 'Electrical', name: 'All Electrical', description: 'All Electrical', active: true},
{asset_type: 'Electrical', name: 'Service & Distribution', description: 'Service & Distribution', active: true},
{asset_type: 'Electrical', name: 'Lighting & Branch Wiring', description: 'Lighting & Branch Wiring', active: true},
{asset_type: 'Electrical', name: 'Communications & Security', description: 'Communications & Security', active: true},
{asset_type: 'Electrical', name: 'Other Electrical', description: 'Other Electrical', active: true},
{asset_type: 'Electrical', name: 'Lighting & Branch Wiring - Interior', description: 'Lighting & Branch Wiring - Interior', active: true},
{asset_type: 'Electrical', name: 'Lighting & Branch Wiring - Exterior', description: 'Lighting & Branch Wiring - Exterior', active: true},
{asset_type: 'Electrical', name: 'Lighting Protection', description: 'Lighting Protection', active: true},
{asset_type: 'Electrical', name: 'Generator', description: 'Generator', active: true},
{asset_type: 'Electrical', name: 'Emergency Lighting', description: ' Emergency Lighting', active: true},
{asset_type: 'Site', name: 'All Site', description: 'All Site', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways', description: 'Roadways/Driveways', active: true},
{asset_type: 'Site', name: 'Parking', description: 'Parking', active: true},
{asset_type: 'Site', name: 'Pedestrian Area', description: 'Pedestrian Area', active: true},
{asset_type: 'Site', name: 'Site Development', description: 'Site Development', active: true},
{asset_type: 'Site', name: 'Landscaping and Irrigation', description: 'Landscaping and Irrigation', active: true},
{asset_type: 'Site', name: 'Utilities', description: 'Utilities', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways - Signage', description: 'Roadways/Driveways - Signage', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways - Markings', description: 'Roadways/Driveways - Markings', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways - Equipment', description: 'Roadways/Driveways - Equipment', active: true},
{asset_type: 'Site', name: 'Parking - Signage', description: 'Parking - Signage', active: true},
{asset_type: 'Site', name: 'Parking - Markings', description: 'Parking - Markings', active: true},
{asset_type: 'Site', name: 'Parking - Equipment', description: 'Parking - Equipment', active: true},
{asset_type: 'Site', name: 'Pedestrian Area - Signage', description: 'Pedestrian Area - Signage', active: true},
{asset_type: 'Site', name: 'Pedestrian Area - Markings', description: 'Pedestrian Area - Markings', active: true},
{asset_type: 'Site', name: 'Pedestrian Area - Equipment', description: 'Pedestrian Area - Equipment', active: true},
{asset_type: 'Site', name: 'Site Development - Fence', description: 'Site Development - Fence', active: true},
{asset_type: 'Site', name: 'Site Development - Wall', description: 'Site Development - Wall', active: true},
].each do |subtype|
if AssetSubtype.find_by(name: subtype[:name]).nil?
a = AssetSubtype.new (subtype.except(:asset_type))
a.asset_type = AssetType.find_by(name: subtype[:asset_type])
a.save!
PolicyAssetSubtypeRule.create!(policy_id: parent_policy_id, asset_subtype_id: a.id, min_service_life_months: 120, min_used_purchase_service_life_months: 48, replace_with_new: true, replace_with_leased: false, purchase_replacement_code: 'XX.XX.XX', rehabilitation_code: 'XX.XX.XX')
end
end
end
end
component asset type/subtypes - add to list
# desc "Explaining what the task does"
# task :transam_transit do
# # Task goes here
# end
namespace :transam_transit_data do
task add_early_disposition_requests_bulk_update: :environment do
unless FileContentType.find_by(builder_name: "TransitEarlyDispositionRequestUpdatesTemplateBuilder").present?
FileContentType.create!({:active => 1, :name => 'Early Disposition Requests', :class_name => 'EarlyDispositionRequestUpdatesFileHandler', :builder_name => "TransitEarlyDispositionRequestUpdatesTemplateBuilder", :description => 'Worksheet requests early disposition for existing inventory.'})
end
end
desc 'add roles list for org types'
task add_roles_organization_types: :environment do
OrganizationType.find_by(class_name: 'Grantor').update!(roles: 'guest,manager')
OrganizationType.find_by(class_name: 'TransitOperator').update!(roles: 'guest,user,transit_manager')
OrganizationType.find_by(class_name: 'PlanningPartner').update!(roles: 'guest')
end
desc 'add facility rollup asset type/subtype'
task add_facility_asset_subtypes: :environment do
parent_policy_id = Policy.where('parent_id IS NULL').pluck(:id).first
new_types = [
{name: 'Substructure', description: 'Substructure', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Shell', description: 'Shell', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Interior', description: 'Interiors', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Conveyance', description: 'Conveyance', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Plumbing', description: 'Plumbing', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'HVAC', description: 'HVAC', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Fire Protection', description: 'Fire Protection', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Electrical', description: 'Electrical', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true},
{name: 'Site', description: 'Site', class_name: 'Component', display_icon_name: 'fa fa-cogs', map_icon_name: 'blueIcon', active: true}
].each do |type|
if AssetType.find_by(name: type[:name]).nil?
a = AssetType.create!(type)
PolicyAssetTypeRule.create(policy_id: parent_policy_id, asset_type_id: a.id, service_life_calculation_type_id: ServiceLifeCalculationType.find_by(name: 'Condition Only').id, replacement_cost_calculation_type_id: CostCalculationType.find_by(name: 'Purchase Price + Interest').id, condition_rollup_calculation_type_id: 1, annual_inflation_rate: 1.1, pcnt_residual_value: 0, condition_rollup_weight: 0 )
end
end
[
{asset_type: 'Substructure', name: 'All Substructure', description: 'All Substructures', active: true},
{asset_type: 'Substructure', name: 'Foundation', description: 'Foundations', active: true},
{asset_type: 'Substructure', name: 'Basement', description: 'Basement', active: true},
{asset_type: 'Substructure', name: 'Foundation - Wall', description: 'Foundation - Wall', active: true},
{asset_type: 'Substructure', name: 'Foundation - Column', description: 'Foundation - Column', active: true},
{asset_type: 'Substructure', name: 'Foundation - Piling', description: 'Foundation - Piling', active: true},
{asset_type: 'Substructure', name: 'Basement - Materials', description: 'Basement - Materials', active: true},
{asset_type: 'Substructure', name: 'Basement - Insulation', description: 'Basement - Insulation', active: true},
{asset_type: 'Substructure', name: 'Basement - Slab', description: 'Basement - Slab', active: true},
{asset_type: 'Substructure', name: 'Basement - Floor Underpinning', description: 'Basement - Floor Underpinning', active: true},
{asset_type: 'Shell', name: 'All Shell Structure', description: 'All Structures', active: true},
{asset_type: 'Shell', name: 'Superstructure', description: 'Superstructure', active: true},
{asset_type: 'Shell', name: 'Roof', description: 'Roof', active: true},
{asset_type: 'Shell', name: 'Exterior', description: 'Exterior', active: true},
{asset_type: 'Shell', name: 'Shell Appurtenance', description: 'Shell Appurtenances', active: true},
{asset_type: 'Shell', name: 'Superstructure - Column', description: 'Superstructure - Column', active: true},
{asset_type: 'Shell', name: 'Superstructure - Pillar', description: 'Superstructure - Pillar', active: true},
{asset_type: 'Shell', name: 'Superstructure - Wall', description: 'Superstructure - Wall', active: true},
{asset_type: 'Shell', name: 'Roof - Surface', description: 'Roof - Surface', active: true},
{asset_type: 'Shell', name: 'Roof - Gutters', description: 'Roof - Gutters', active: true},
{asset_type: 'Shell', name: 'Roof - Eaves', description: 'Roof - Eaves', active: true},
{asset_type: 'Shell', name: 'Roof - Skylight', description: 'Roof - Skylight', active: true},
{asset_type: 'Shell', name: 'Roof - Chimney Surroundings', description: 'Roof - Chimney Surroundings', active: true},
{asset_type: 'Shell', name: 'Exterior - Window', description: 'Exterior - Window', active: true},
{asset_type: 'Shell', name: 'Exterior - Door', description: 'Exterior - Door', active: true},
{asset_type: 'Shell', name: 'Exterior - Finishes', description: 'Exterior - Finishes', active: true},
{asset_type: 'Shell', name: 'Shell Appurtenance - Balcony', description: 'Shell Appurtenance - Balcony', active: true},
{asset_type: 'Shell', name: 'Shell Appurtenance - Fire Escape', description: 'Shell Appurtenance - Fire Escape', active: true},
{asset_type: 'Shell', name: 'Shell Appurtenance - Gutter', description: 'Shell Appurtenance - Gutter', active: true},
{asset_type: 'Shell', name: 'Shell Appurtenance - Downspout', description: 'Shell Appurtenance - Downspout', active: true},
{asset_type: 'Interior', name: 'All Interior', description: 'All Interior', active: true},
{asset_type: 'Interior', name: 'Partition', description: 'Partition', active: true},
{asset_type: 'Interior', name: 'Stairs', description: 'Stairs', active: true},
{asset_type: 'Interior', name: 'Finishes', description: 'Finishes', active: true},
{asset_type: 'Interior', name: 'Partition - Wall', description: 'Partition - Wall', active: true},
{asset_type: 'Interior', name: 'Partition - Door', description: 'Partition - Door', active: true},
{asset_type: 'Interior', name: 'Partition - Fittings', description: 'Partition - Fittings', active: true},
{asset_type: 'Interior', name: 'Stairs - Landing', description: 'Stairs - Landing', active: true},
{asset_type: 'Interior', name: 'Finishes - Wall Materials', description: 'Finishes - Wall Materials', active: true},
{asset_type: 'Interior', name: 'Finishes - Floor Materials', description: 'Finishes - Floor Materials', active: true},
{asset_type: 'Interior', name: 'Finishes - Ceiling Materials', description: 'Finishes - Ceiling Materials', active: true},
{asset_type: 'Conveyance', name: 'All Conveyance', description: 'All Conveyance', active: true},
{asset_type: 'Conveyance', name: 'Elevator', description: 'Elevator', active: true},
{asset_type: 'Conveyance', name: 'Escalator', description: 'Escalator', active: true},
{asset_type: 'Conveyance', name: 'Lift', description: 'Lift', active: true},
{asset_type: 'Plumbing', name: 'All Plumbing', description: 'All Plumbing', active: true},
{asset_type: 'Plumbing', name: 'Fixture', description: 'Fixture', active: true},
{asset_type: 'Plumbing', name: 'Water Distribution', description: 'Water Distribution', active: true},
{asset_type: 'Plumbing', name: 'Sanitary Waste', description: 'Sanitary Waste', active: true},
{asset_type: 'Plumbing', name: 'Rain Water Drainage', description: 'Rain Water Drainage', active: true},
{asset_type: 'HVAC', name: 'HVAC System', description: 'HVAC System', active: true},
{asset_type: 'HVAC', name: 'Energy Supply', description: 'Energy Supply', active: true},
{asset_type: 'HVAC', name: 'Heat Generation and Distribution System', description: 'Heat Generation and Distribution System', active: true},
{asset_type: 'HVAC', name: 'Cooling Generation and Distribution System', description: 'Cooling Generation and Distribution System', active: true},
{asset_type: 'HVAC', name: 'Instrumentation', description: 'Testing, Balancing, Controls and Instrumentation', active: true},
{asset_type: 'Fire Protection', name: 'All Fire Protection', description: 'All Fire Protection', active: true},
{asset_type: 'Fire Protection', name: 'Sprinkler', description: 'Sprinkler', active: true},
{asset_type: 'Fire Protection', name: 'Standpipes', description: 'Standpipes', active: true},
{asset_type: 'Fire Protection', name: 'Hydrant', description: 'Hydrant', active: true},
{asset_type: 'Fire Protection', name: 'Other Fire Protection', description: 'Other Fire Protection', active: true},
{asset_type: 'Electrical', name: 'All Electrical', description: 'All Electrical', active: true},
{asset_type: 'Electrical', name: 'Service & Distribution', description: 'Service & Distribution', active: true},
{asset_type: 'Electrical', name: 'Lighting & Branch Wiring', description: 'Lighting & Branch Wiring', active: true},
{asset_type: 'Electrical', name: 'Communications & Security', description: 'Communications & Security', active: true},
{asset_type: 'Electrical', name: 'Other Electrical', description: 'Other Electrical', active: true},
{asset_type: 'Electrical', name: 'Lighting & Branch Wiring - Interior', description: 'Lighting & Branch Wiring - Interior', active: true},
{asset_type: 'Electrical', name: 'Lighting & Branch Wiring - Exterior', description: 'Lighting & Branch Wiring - Exterior', active: true},
{asset_type: 'Electrical', name: 'Lighting Protection', description: 'Lighting Protection', active: true},
{asset_type: 'Electrical', name: 'Generator', description: 'Generator', active: true},
{asset_type: 'Electrical', name: 'Emergency Lighting', description: ' Emergency Lighting', active: true},
{asset_type: 'Site', name: 'All Site', description: 'All Site', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways', description: 'Roadways/Driveways', active: true},
{asset_type: 'Site', name: 'Parking', description: 'Parking', active: true},
{asset_type: 'Site', name: 'Pedestrian Area', description: 'Pedestrian Area', active: true},
{asset_type: 'Site', name: 'Site Development', description: 'Site Development', active: true},
{asset_type: 'Site', name: 'Landscaping and Irrigation', description: 'Landscaping and Irrigation', active: true},
{asset_type: 'Site', name: 'Utilities', description: 'Utilities', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways - Signage', description: 'Roadways/Driveways - Signage', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways - Markings', description: 'Roadways/Driveways - Markings', active: true},
{asset_type: 'Site', name: 'Roadways/Driveways - Equipment', description: 'Roadways/Driveways - Equipment', active: true},
{asset_type: 'Site', name: 'Parking - Signage', description: 'Parking - Signage', active: true},
{asset_type: 'Site', name: 'Parking - Markings', description: 'Parking - Markings', active: true},
{asset_type: 'Site', name: 'Parking - Equipment', description: 'Parking - Equipment', active: true},
{asset_type: 'Site', name: 'Pedestrian Area - Signage', description: 'Pedestrian Area - Signage', active: true},
{asset_type: 'Site', name: 'Pedestrian Area - Markings', description: 'Pedestrian Area - Markings', active: true},
{asset_type: 'Site', name: 'Pedestrian Area - Equipment', description: 'Pedestrian Area - Equipment', active: true},
{asset_type: 'Site', name: 'Site Development - Fence', description: 'Site Development - Fence', active: true},
{asset_type: 'Site', name: 'Site Development - Wall', description: 'Site Development - Wall', active: true},
].each do |subtype|
if AssetSubtype.find_by(name: subtype[:name]).nil?
a = AssetSubtype.new (subtype.except(:asset_type))
a.asset_type = AssetType.find_by(name: subtype[:asset_type])
a.save!
PolicyAssetSubtypeRule.create!(policy_id: parent_policy_id, asset_subtype_id: a.id, min_service_life_months: 120, min_used_purchase_service_life_months: 48, replace_with_new: true, replace_with_leased: false, purchase_replacement_code: 'XX.XX.XX', rehabilitation_code: 'XX.XX.XX')
end
end
end
end |
module TChart
class ChartBuilder
def self.build(layout, items) # => Chart
ChartBuilder.new(layout, items).build
end
attr_reader :layout # Dimensions of the label areas, the plot area, etc.
attr_reader :items # The items being plotted.
attr_reader :elements # Generated grid lines, labels, and bars that make up the chart.
def initialize(layout, items)
@items = items
@layout = layout
@elements = []
end
def build # => Chart
build_frame
build_x_items
build_y_items
Chart.new(elements)
end
private
def build_frame
elements.push new_frame_top
elements.push new_frame_bottom
end
def new_frame_top # => GridLine
GridLine.new(xy(0, layout.y_axis_length), xy(layout.x_axis_length, layout.y_axis_length))
end
def new_frame_bottom # => GridLine
GridLine.new(xy(0, 0), xy(layout.x_axis_length, 0))
end
def build_x_items
layout.x_axis_tick_dates.zip(layout.x_axis_tick_x_coordinates).each do |date, x|
@elements.push new_x_label(date.year, x)
@elements.push new_x_gridline(x)
end
end
def new_x_label(year, x) # => Label
Label.build_xlabel(xy(x, layout.x_axis_label_y_coordinate), layout.x_axis_label_width, year.to_s)
end
def new_x_gridline(x) # => GridLine
GridLine.new(xy(x, 0), xy(x, layout.y_axis_length))
end
def build_y_items
items.zip(layout.y_axis_tick_y_coordinates).each do |item, y|
@elements.concat item.build(@layout, y)
end
end
end
end
Add '# private' comment.
Attributes, #initialize, and #build in ChartBuilder should ideally
be private.
module TChart
class ChartBuilder
def self.build(layout, items) # => Chart
ChartBuilder.new(layout, items).build
end
# private
attr_reader :layout # Dimensions of the label areas, the plot area, etc.
attr_reader :items # The items being plotted.
attr_reader :elements # Generated grid lines, labels, and bars that make up the chart.
def initialize(layout, items)
@items = items
@layout = layout
@elements = []
end
def build # => Chart
build_frame
build_x_items
build_y_items
Chart.new(elements)
end
private
def build_frame
elements.push new_frame_top
elements.push new_frame_bottom
end
def new_frame_top # => GridLine
GridLine.new(xy(0, layout.y_axis_length), xy(layout.x_axis_length, layout.y_axis_length))
end
def new_frame_bottom # => GridLine
GridLine.new(xy(0, 0), xy(layout.x_axis_length, 0))
end
def build_x_items
layout.x_axis_tick_dates.zip(layout.x_axis_tick_x_coordinates).each do |date, x|
@elements.push new_x_label(date.year, x)
@elements.push new_x_gridline(x)
end
end
def new_x_label(year, x) # => Label
Label.build_xlabel(xy(x, layout.x_axis_label_y_coordinate), layout.x_axis_label_width, year.to_s)
end
def new_x_gridline(x) # => GridLine
GridLine.new(xy(x, 0), xy(x, layout.y_axis_length))
end
def build_y_items
items.zip(layout.y_axis_tick_y_coordinates).each do |item, y|
@elements.concat item.build(@layout, y)
end
end
end
end
|
module Synthesis
class ExpectationRecord
class << self
include Logging
def add_expectation(receiver, method, track, args = [])
unless ignore?(receiver)
expectation = Expectation.new(receiver, method, track, args)
expectations << expectation
expectation
end
end
def ignore(*args)
ignored.merge(args)
end
def expectations
# Using an Array instead of a Set because the +Expectation+ instance
# is not complete when first added. A Set would result to possible duplicates.
# obj.expects(:method).with(:args)
# the +Expectation+ will be added when obj.expects(:method) is called
# the +Expectation+ arguments will be added when .with(:args) is called
@expectations ||= []
end
def ignored
@ignored ||= Set.new
end
def [](matcher)
# Using a hash for faster look up of expectations
# when recording invocations
expectations_hash[matcher] || Expectation::NilExpectation.new
end
def record_invocations
expectations.map! { |e| e.explode }
expectations.flatten!
expectations.uniq!
expectations.each { |e| e.record_invocations }
end
def tested_expectations
expectations.select { |e| e.invoked? }
end
def untested_expectations
expectations.select { |e| !e.invoked? }
end
# def print_tested_expectations
# log; log "Tested Expectations: "
# tested_expectations.each { |e| log e }
# end
#
# def print_untested_expectations
# log; log "Untested Expectations: "
# untested_expectations.each { |e| log e }
# end
#
# def print_ignored
# log; log "Ignoring: #{ignored.to_a * ', '}"
# end
private
def expectations_hash
@expectations_hash ||= expectations.inject({}) do |hash, expectation|
hash[expectation] = expectation
hash
end
end
def ignore?(obj)
ignored.include?(obj.class) ||
(obj.is_a?(Class) && ignored.include?(obj)) ||
obj.is_a?(MOCK_OBJECT)
end
def reset!
@expectations_hash, @expectations, @ignored = nil
end
end
end
end
removed unused formatting methods from expectation_record
module Synthesis
class ExpectationRecord
class << self
include Logging
def add_expectation(receiver, method, track, args = [])
unless ignore?(receiver)
expectation = Expectation.new(receiver, method, track, args)
expectations << expectation
expectation
end
end
def ignore(*args)
ignored.merge(args)
end
def expectations
# Using an Array instead of a Set because the +Expectation+ instance
# is not complete when first added. A Set would result to possible duplicates.
# obj.expects(:method).with(:args)
# the +Expectation+ will be added when obj.expects(:method) is called
# the +Expectation+ arguments will be added when .with(:args) is called
@expectations ||= []
end
def ignored
@ignored ||= Set.new
end
def [](matcher)
# Using a hash for faster look up of expectations
# when recording invocations
expectations_hash[matcher] || Expectation::NilExpectation.new
end
def record_invocations
expectations.map! { |e| e.explode }
expectations.flatten!
expectations.uniq!
expectations.each { |e| e.record_invocations }
end
def tested_expectations
expectations.select { |e| e.invoked? }
end
def untested_expectations
expectations.select { |e| !e.invoked? }
end
private
def expectations_hash
@expectations_hash ||= expectations.inject({}) do |hash, expectation|
hash[expectation] = expectation
hash
end
end
def ignore?(obj)
ignored.include?(obj.class) ||
(obj.is_a?(Class) && ignored.include?(obj)) ||
obj.is_a?(MOCK_OBJECT)
end
def reset!
@expectations_hash, @expectations, @ignored = nil
end
end
end
end
|
# NOTE: only doing this in development as some production environments (Heroku)
# NOTE: are sensitive to local FS writes, and besides -- it's just not proper
# NOTE: to have a dev-mode tool do its thing in production.
if Rails.env.development?
task :set_annotation_options do
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults(
routes: false,
position_in_routes: "before",
position_in_class: "before",
position_in_test: "before",
position_in_fixture: "before",
position_in_factory: "before",
position_in_serializer: "before",
show_foreign_keys: true,
show_indexes: true,
simple_indexes: false,
model_dir: "app/models",
root_dir: "",
include_version: false,
require: "",
exclude_tests: true,
exclude_fixtures: true,
exclude_factories: true,
exclude_serializers: true,
exclude_scaffolds: true,
exclude_controllers: true,
exclude_helpers: true,
ignore_model_sub_dir: false,
ignore_columns: nil,
ignore_unknown_models: false,
hide_limit_column_types: "integer,boolean",
skip_on_db_migrate: false,
format_bare: true,
format_rdoc: false,
format_markdown: false,
sort: false,
force: false,
trace: false,
wrapper_open: nil,
wrapper_close: nil
)
end
Annotate.load_tasks
end
update auto_annotate task
# NOTE: only doing this in development as some production environments (Heroku)
# NOTE: are sensitive to local FS writes, and besides -- it's just not proper
# NOTE: to have a dev-mode tool do its thing in production.
if Rails.env.development?
task :set_annotation_options do
# You can override any of these by setting an environment variable of the
# same name.
Annotate.set_defaults(
routes: false,
position_in_routes: "before",
position_in_class: "before",
position_in_test: "before",
position_in_fixture: "before",
position_in_factory: "before",
position_in_serializer: "before",
show_foreign_keys: true,
show_indexes: true,
simple_indexes: false,
model_dir: "app/models",
root_dir: "",
include_version: false,
require: "",
exclude_tests: true,
exclude_fixtures: true,
exclude_factories: true,
exclude_serializers: true,
exclude_scaffolds: true,
exclude_controllers: true,
exclude_helpers: true,
ignore_model_sub_dir: false,
ignore_columns: nil,
ignore_routes: nil,
ignore_unknown_models: false,
hide_limit_column_types: "integer,boolean",
skip_on_db_migrate: false,
format_bare: true,
format_rdoc: false,
format_markdown: false,
sort: false,
force: false,
trace: false,
wrapper_open: nil,
wrapper_close: nil
)
end
Annotate.load_tasks
end
|
module Texas
module Build
module Task
class PublishPDF < Base
def master_file
build.master_file
end
def build_path
build.__path__
end
def dest_file
build.dest_file
end
def run
run_pdflatex
copy_pdf_file_to_dest_dir
end
def copy_pdf_file_to_dest_dir
tmp_file = File.join(build_path, "#{File.basename(master_file, '.tex')}.pdf")
FileUtils.mkdir_p File.dirname(dest_file)
FileUtils.copy tmp_file, dest_file
verbose {
file = File.join(build_path, "master.log")
output = `grep "Output written on" #{file}`
numbers = output.scan(/\((\d+?) pages\, (\d+?) bytes\)\./).flatten
@page_count = numbers.first.to_i
"Written PDF in #{dest_file.gsub(build.root, '')} (#{@page_count} pages)".green
}
end
def run_pdflatex
verbose { "Running pdflatex in #{build_path} ..." }
Dir.chdir build_path
`pdflatex #{File.basename(master_file)}`
`pdflatex #{File.basename(master_file)}`
end
end
end
end
end
Fix Task::PublishPDF interpreted "1 page" from logfile as "0 pages".
module Texas
module Build
module Task
class PublishPDF < Base
def master_file
build.master_file
end
def build_path
build.__path__
end
def dest_file
build.dest_file
end
def run
run_pdflatex
copy_pdf_file_to_dest_dir
end
def copy_pdf_file_to_dest_dir
tmp_file = File.join(build_path, "#{File.basename(master_file, '.tex')}.pdf")
FileUtils.mkdir_p File.dirname(dest_file)
FileUtils.copy tmp_file, dest_file
verbose {
file = File.join(build_path, "master.log")
output = `grep "Output written on" #{file}`
numbers = output.scan(/\((\d+?) pages?\, (\d+?) bytes\)\./).flatten
@page_count = numbers.first.to_i
"Written PDF in #{dest_file.gsub(build.root, '')} (#{@page_count} pages)".green
}
end
def run_pdflatex
verbose { "Running pdflatex in #{build_path} ..." }
Dir.chdir build_path
`pdflatex #{File.basename(master_file)}`
`pdflatex #{File.basename(master_file)}`
end
end
end
end
end
|
module NewSectionMigration
def self.delete_all_section_tags
deleted_count = Tag.where(tag_type: 'section').delete_all
end
def self.wipe_sections_from_artefacts
Artefact.all.each do |artefact|
artefact.sections = []
artefact.save!
end
end
def self.import_new_sections(csv_path)
ensure_file_exists!(csv_path)
csv_obj = CSV.new(File.read(csv_path), {headers: :first_row, return_headers: false})
# eg: [title, slug, desc, parent_slug]
csv_obj.each do |row|
row = row.map { |k,v| v && v.strip }
parent = nil
if !row[3].blank?
parent = Tag.where(tag_type: 'section', tag_id: clean_slug(row[3])).first
if parent.nil?
raise "Stop! Parent section #{clean_slug(row[3])} could not be found."
end
end
full_slug = construct_full_slug(row[3], row[1])
if row[1] != full_slug.split("/").last # hack to get the cleaned up child slug
puts "Warning: Had to modify slug from '#{row[1]}' to '#{full_slug.split("/").last}'"
end
t = Tag.create!(tag_type: 'section', title: row[0], tag_id: full_slug,
description: row[2], parent_id: parent ? parent.tag_id : nil)
# NOTE CuratedList currently validates it's slug as a slug.
# That means it can't include a slash, but subsection urls have slashes...
#
# If the tag has a parent, that makes it a subsection.
# If it's a subsection we want it to have a CuratedList.
# if t.has_parent?
# CuratedList.create!(slug: full_slug, sections: [t.tag_id])
# end
end
end
def self.export_artefacts(csv_save_path)
query = Artefact.where(:state.nin => ["archived"]).order([:name, :asc])
a_file = File.open(csv_save_path, 'w+')
# Don't trust the Artefact state flag
really_live_artefacts = query.reject do |artefact|
(artefact.owning_app == "publisher") &&
(Edition.where(panopticon_id: artefact.id, :state.nin => ["archived"]).count == 0)
end
puts "Exporting #{really_live_artefacts.size} artefacts that are live or in progress"
really_live_artefacts.each do |a|
a_file.write([a.name, a.slug].to_csv)
end
a_file.close
end
def self.tag_content_with_new_sections(content_csv)
ensure_file_exists!(content_csv)
csv_obj = CSV.new(File.read(content_csv), {headers: :first_row, return_headers: false})
# eg: [title,slug_of_content,section_slug,section_slug,section_slug...]
csv_obj.each do |csv_row|
row = csv_row.fields
next if row[1].blank?
clean_slug = clean_slug(row[1])
a = Artefact.where(slug: clean_slug).first
if a.nil?
puts "Had to ignore Artefact '#{clean_slug}' - could not be found. It's probably been renamed."
next
end
row.shift # remove the artefact title
row.shift # remove the artefact slug
sections = []
clean_section_slugs = row.compact.map { |slug_with_slashes| slug_with_slashes.strip.gsub(%r{^/}, "") }
clean_section_slugs.each do |clean_section_slug|
if clean_section_slug
tag = Tag.where(tag_type: 'section', tag_id: clean_section_slug).first
if tag.nil?
raise "Stop! New section '#{clean_section_slug}' for Artefact: #{a.slug} was not found."
end
sections << tag.tag_id
end
end
a.sections = sections
a.save!
end
end
private
def self.ensure_file_exists!(filepath)
raise "FATAL: File must be specified" if filepath.blank?
raise "FATAL: File not found #{filepath}" if !File.exist?(filepath)
end
def self.clean_slug(raw_slug)
raw_slug.nil? ? nil : raw_slug.parameterize
end
def self.construct_full_slug(parent_slug, child_slug)
[parent_slug, child_slug]
.reject(&:blank?)
.map(&:parameterize)
.join("/")
end
end
namespace :migrate do
desc "Remove old sections, insert new ones, setup curated list"
task :delete_all_section_tags => :environment do
deleted_count = NewSectionMigration.delete_all_section_tags
puts "Deleted #{deleted_count} section tags"
puts "Clearing sections on all #{Artefact.count} artefacts..."
NewSectionMigration.wipe_sections_from_artefacts
end
task :import_new_sections, [:section_csv] => :environment do |t, args|
NewSectionMigration.import_new_sections(args[:section_csv])
end
task :export_all_artefacts, [:artefact_csv] => :environment do |t, args|
NewSectionMigration.export_artefacts(args[:artefact_csv])
end
task :tag_content_with_new_sections, [:content_csv] => :environment do |t, args|
NewSectionMigration.tag_content_with_new_sections(args[:content_csv])
end
end
Handle errors from rummager/router callbacks
On first attempt in preview, one of the Artefacts 404d, most likely
from the router. These changes mean that we will continue the import.
The artefact will have been saved anyway.
module NewSectionMigration
def self.delete_all_section_tags
deleted_count = Tag.where(tag_type: 'section').delete_all
end
def self.wipe_sections_from_artefacts
Artefact.all.each do |artefact|
artefact.sections = []
begin
artefact.save!
rescue StandardError => e
puts "Encountered error when saving artefact: #{artefact.slug}: #{e.to_s}. Sections stored in the database are now: #{artefact.reload.sections}"
end
end
end
def self.import_new_sections(csv_path)
ensure_file_exists!(csv_path)
csv_obj = CSV.new(File.read(csv_path), {headers: :first_row, return_headers: false})
# eg: [title, slug, desc, parent_slug]
csv_obj.each do |row|
row = row.map { |k,v| v && v.strip }
parent = nil
if !row[3].blank?
parent = Tag.where(tag_type: 'section', tag_id: clean_slug(row[3])).first
if parent.nil?
raise "Stop! Parent section #{clean_slug(row[3])} could not be found."
end
end
full_slug = construct_full_slug(row[3], row[1])
if row[1] != full_slug.split("/").last # hack to get the cleaned up child slug
puts "Warning: Had to modify slug from '#{row[1]}' to '#{full_slug.split("/").last}'"
end
t = Tag.create!(tag_type: 'section', title: row[0], tag_id: full_slug,
description: row[2], parent_id: parent ? parent.tag_id : nil)
# NOTE CuratedList currently validates it's slug as a slug.
# That means it can't include a slash, but subsection urls have slashes...
#
# If the tag has a parent, that makes it a subsection.
# If it's a subsection we want it to have a CuratedList.
# if t.has_parent?
# CuratedList.create!(slug: full_slug, sections: [t.tag_id])
# end
end
end
def self.export_artefacts(csv_save_path)
query = Artefact.where(:state.nin => ["archived"]).order([:name, :asc])
a_file = File.open(csv_save_path, 'w+')
# Don't trust the Artefact state flag
really_live_artefacts = query.reject do |artefact|
(artefact.owning_app == "publisher") &&
(Edition.where(panopticon_id: artefact.id, :state.nin => ["archived"]).count == 0)
end
puts "Exporting #{really_live_artefacts.size} artefacts that are live or in progress"
really_live_artefacts.each do |a|
a_file.write([a.name, a.slug].to_csv)
end
a_file.close
end
def self.tag_content_with_new_sections(content_csv)
ensure_file_exists!(content_csv)
csv_obj = CSV.new(File.read(content_csv), {headers: :first_row, return_headers: false})
# eg: [title,slug_of_content,section_slug,section_slug,section_slug...]
csv_obj.each do |csv_row|
row = csv_row.fields
next if row[1].blank?
clean_slug = clean_slug(row[1])
a = Artefact.where(slug: clean_slug).first
if a.nil?
puts "Had to ignore Artefact '#{clean_slug}' - could not be found. It's probably been renamed."
next
end
row.shift # remove the artefact title
row.shift # remove the artefact slug
sections = []
clean_section_slugs = row.compact.map { |slug_with_slashes| slug_with_slashes.strip.gsub(%r{^/}, "") }
clean_section_slugs.each do |clean_section_slug|
if clean_section_slug
tag = Tag.where(tag_type: 'section', tag_id: clean_section_slug).first
if tag.nil?
raise "Stop! New section '#{clean_section_slug}' for Artefact: #{a.slug} was not found."
end
sections << tag.tag_id
end
end
a.sections = sections
begin
a.save!
rescue StandardError => e
puts "Encountered error when saving artefact: #{artefact.slug}: #{e.to_s}. Sections stored in the database are now: #{artefact.reload.sections}"
end
end
end
private
def self.ensure_file_exists!(filepath)
raise "FATAL: File must be specified" if filepath.blank?
raise "FATAL: File not found #{filepath}" if !File.exist?(filepath)
end
def self.clean_slug(raw_slug)
raw_slug.nil? ? nil : raw_slug.parameterize
end
def self.construct_full_slug(parent_slug, child_slug)
[parent_slug, child_slug]
.reject(&:blank?)
.map(&:parameterize)
.join("/")
end
end
namespace :migrate do
desc "Remove old sections, insert new ones, setup curated list"
task :delete_all_section_tags => :environment do
deleted_count = NewSectionMigration.delete_all_section_tags
puts "Deleted #{deleted_count} section tags"
puts "Clearing sections on all #{Artefact.count} artefacts..."
NewSectionMigration.wipe_sections_from_artefacts
end
task :import_new_sections, [:section_csv] => :environment do |t, args|
NewSectionMigration.import_new_sections(args[:section_csv])
end
task :export_all_artefacts, [:artefact_csv] => :environment do |t, args|
NewSectionMigration.export_artefacts(args[:artefact_csv])
end
task :tag_content_with_new_sections, [:content_csv] => :environment do |t, args|
NewSectionMigration.tag_content_with_new_sections(args[:content_csv])
end
end
|
def apply_to paths, extension, method, klazz
RailsDbViews::Factory.clear!
paths.each do |path|
RailsDbViews::Factory.register_files klazz,
Dir[File.join(path, extension)].map{|x| File.expand_path(x)}.sort
end
RailsDbViews::Factory.send(method, klazz)
end
namespace :db do
desc "Create all the database views of the current project. Views are usually located in db/views"
task :create_views => :environment do
config = Rails.configuration.rails_db_views
apply_to config.views_paths, config.views_extension, :create, RailsDbViews::View
end
desc "Drop all the database views of the current project"
task :drop_views => :environment do
config = Rails.configuration.rails_db_views
apply_to config.views_paths, config.views_extension, :drop, RailsDbViews::View
end
desc "Create or replace all the functions"
task :create_functions => :environment do
adapter_type = ActiveRecord::Base.connection.adapter_name.downcase.to_sym
config = Rails.configuration.rails_db_views
if adapter_type != :sqlite
apply_to config.functions_paths, config.functions_extension, :create, RailsDbViews::Function
else
if config.functions_paths.length>=1 || File.is_directory?(config.functions_paths.try(:first))
puts "Notice: db:create_functions will not trigger for sqlite."
end
end
end
desc "Remove all the functions (to use manually only)"
task :drop_functions => :environment do
config = Rails.configuration.rails_db_views
apply_to config.functions_paths, config.functions_extension, :drop, RailsDbViews::Function
end
end
require 'rake/hooks'
Rails.configuration.rails_db_views.migration_tasks.each do |task|
before(task){ Rake::Task['db:drop_views'].invoke }
before(task){ Rake::Task['db:create_functions'].invoke }
after(task){ Rake::Task['db:create_views'].invoke }
end
expand the file locations using a seperate function, reverse the order when dropping.
def apply_to files, method, klazz
RailsDbViews::Factory.clear!
RailsDbViews::Factory.register_files klazz, files
RailsDbViews::Factory.send(method, klazz)
end
def expand_files paths, extension
files = []
paths.each do |path|
files = files + Dir[File.join(path, extension)].map{|x| File.expand_path(x)}.sort
end
return files
end
namespace :db do
desc "Create all the database views of the current project. Views are usually located in db/views"
task :create_views => :environment do
config = Rails.configuration.rails_db_views
files = expand_files config.views_paths, config.views_extension
apply_to files, :create, RailsDbViews::View
end
desc "Drop all the database views of the current project"
task :drop_views => :environment do
config = Rails.configuration.rails_db_views
files = expand_files config.views_paths, config.views_extension
apply_to files.reverse, :drop, RailsDbViews::View
end
desc "Create or replace all the functions"
task :create_functions => :environment do
adapter_type = ActiveRecord::Base.connection.adapter_name.downcase.to_sym
config = Rails.configuration.rails_db_views
if adapter_type != :sqlite
files = expand_files config.functions_paths, config.functions_extension
apply_to files, :create, RailsDbViews::Function
else
if config.functions_paths.length>=1 || File.is_directory?(config.functions_paths.try(:first))
puts "Notice: db:create_functions will not trigger for sqlite."
end
end
end
desc "Remove all the functions (to use manually only)"
task :drop_functions => :environment do
config = Rails.configuration.rails_db_views
files = expand_files config.functions_paths, config.functions_extension
apply_to files.reverse, :drop, RailsDbViews::Function
end
end
require 'rake/hooks'
Rails.configuration.rails_db_views.migration_tasks.each do |task|
before(task){ Rake::Task['db:drop_views'].invoke }
before(task){ Rake::Task['db:create_functions'].invoke }
after(task){ Rake::Task['db:create_views'].invoke }
end
|
require 'open-uri'
require 'rubygems/package'
require 'zlib'
##################################################################
# Synchronizes staging or dev environment with production database
#
# 1) Download and import a target production database backup
# 2) Drops, recreates, and imports new considerit database
# 3) Imports file attachments into local environment
# 4) Appends .ghost to all non-super admin user email addresses
# to prevent emails being sent to real users in a testing context
# 5) Migrates the database so it is in sync with current environment
# dumps are located in ~/Dropbox/Apps/considerit_backup/xenogear
# This script assumes a tarball created via the Backup gem.
DATABASE_BACKUP_URL = "https://www.dropbox.com/s/97j6j3qdaig9yd4/xenogear.tar?dl=1"
# Where production assets are served from
PRODUCTION_ASSET_HOST = "http://d2rtgkroh5y135.cloudfront.net"
task :sync_with_production, [:sql_url] => :environment do |t, args|
sql_url = args[:sql_url] ? args[:sql_url] : DATABASE_BACKUP_URL
puts "Preparing local database based on production database #{sql_url}..."
success = prepare_production_database sql_url
if success
puts "Downloading file attachments from production..."
download_files_from_production
else
puts "Failed"
end
end
def prepare_production_database(sql_url)
# Download and extract target production database backup
open('tmp/production_db.tar', 'wb') do |file|
file << open(URI.parse(sql_url)).read
end
# Backup's tarball is a directory xenogear/databases/MySQL.sql.gz
tar_extract = Gem::Package::TarReader.new(open('tmp/production_db.tar'))
tar_extract.rewind # The extract has to be rewinded after every iteration
tar_extract.each do |entry|
if entry.full_name.end_with?('.sql.gz')
open('tmp/production_db.sql', 'wb') do |gz|
gz << Zlib::GzipReader.new(entry).read
end
end
end
tar_extract.close
puts "...downloaded and extracted production database backup from #{DATABASE_BACKUP_URL}"
# Drop existing database
filename = "test/data/test.sql"
Rake::Task["db:drop"].invoke
Rake::Task["db:create"].invoke
puts "...dropped and recreated database #{Rails.configuration.database_configuration[Rails.env]["database"]}"
# Import production database backup
puts "...now we're importing data. Might take a few minutes."
db = Rails.configuration.database_configuration[Rails.env]
system "mysql -u#{db['username']} -p#{db['password']} #{db['database']} < #{Rails.root}/tmp/production_db.sql"
puts "...imported production db into #{Rails.configuration.database_configuration[Rails.env]["database"]}"
# Append .ghost to all non-super admin user email addresses
# to prevent emails being sent to real users in a testing context
ActiveRecord::Base.connection.execute("UPDATE users SET email=CONCAT(email,'.ghost') WHERE email IS NOT NULL AND super_admin=false")
puts "...modified non superadmin email addresses to prevent email notifications"
# Migrates the database so it is in sync with current environment
system "bundle exec rake db:migrate > /dev/null 2>&1"
puts "...migrated the database"
cleanup = ['tmp/production_db.tar', 'tmp/production_db.sql']
cleanup.each do |f|
File.delete f if File.exist?(f)
end
puts "...cleaned up tmp files"
return true
end
# Serving assets from AWS via Cloudfront and S3
# helps speed up page loads by distributing the
# requests across multiple servers that are on average
# more geographic proximate to clients.
#
# However, AWS creates some problems when we want to pull in
# the production database to use in a test or staging
# environment. Specifically, all the files, such as avatars,
# that have been uploaded by users via Paperclip continue to
# live at the production AWS S3 bucket.
# - In staging, we use a different S3 bucket, so the
# staging environment can't serve the files
# - In development, our local machines aren't
# configured to use AWS, so we can't see the files
#
# This rake task will download all file uploads for the
# currently loaded database to the local environment.
# You need to configure the source asset host from which
# the database originated. It will default to the asset host
# for consider.it.
task :download_files_from_production => :environment do
download_files_from_production
end
def download_files_from_production
# The attachments to synchronize.
attachments = [
{name: 'avatars', model: User},
{name: 'logos', model: Subdomain},
{name: 'mastheads', model: Subdomain},
{name: 'icons', model: Assessable::Verdict}
]
# find out where we store out assets...
has_aws = Rails.env.production? && APP_CONFIG.has_key?(:aws) && APP_CONFIG[:aws].has_key?(:access_key_id) && !APP_CONFIG[:aws][:access_key_id].nil?
if has_aws
local_asset_host = "http://#{APP_CONFIG[:aws][:cloudfront]}.cloudfront.net"
path_template = Paperclip::Attachment.default_options[:path]
else
# default_options[:url] will look like "/system/:attachment/:id/:style/:filename"
path_template = Paperclip::Attachment.default_options[:url]
end
attachments.each do |attachment|
# for each object of model that has an attachment of this type
field = "#{attachment[:name].singularize}_file_name"
attachment[:model].where("#{field} IS NOT NULL").each do |obj|
url = path_template
.gsub(":attachment", attachment[:name])
.gsub(":id", obj.id.to_s)
.gsub(":style", "original")
.gsub(":filename", obj[field])
# check if the file is already downloaded
if has_aws
already_downloaded = url_exist?("#{local_asset_host}/#{url}")
url = "#{PRODUCTION_ASSET_HOST}/#{url}"
else
path = "#{Rails.root.to_s}/public#{url}"
already_downloaded = File.exist?(path)
url = "#{PRODUCTION_ASSET_HOST}#{url}"
end
if !already_downloaded
# if not, download it
io = URI.parse(url)
begin
open(io) #trigger an error if url doesn't exist
rescue
pp "FAILED DOWNLOADING: #{url}"
else
# now save the attachment
begin
# for some reason, the following doesn't trigger
# the correct paperclip saving mechanim...
#
# obj.send(attachment[:name].singularize, io)
#
# ...so we'll just do it manually
case attachment[:name].singularize
when 'avatar'
data = Base64.encode64(open(io).read)
obj.b64_thumbnail = "data:image/jpeg;base64,#{data.gsub(/\n/,' ')}"
obj.avatar = io
when 'icon'
obj.icon = io
when 'masthead'
obj.masthead = io
when 'logo'
obj.logo = io
end
obj.save
rescue => e
pp "FAILED SAVING: #{url} because of #{e.to_s}"
else
pp "Saved locally: #{url}"
end
end
end
end
end
# Avatar attachments are processed as background tasks
Delayed::Worker.new.work_off(Delayed::Job.count)
end
# from http://stackoverflow.com/questions/5908017/check-if-url-exists-in-ruby
require "net/http"
def url_exist?(url_string)
url = URI.parse(url_string)
req = Net::HTTP.new(url.host, url.port)
path = url.path if url.path.present?
res = req.request_head(path || '/')
!["404", "403"].include? res.code
rescue Errno::ENOENT
false # false if can't find the server
end
recover from sql failures due to large avatars
Former-commit-id: 21f7c51347de94eb5663ca0d1f8d27bc167e328b [formerly 41757e208c380094cc456225051668e31e3ba268] [formerly d6428673187c87365956ddbd43a0a0c2ff2a866c [formerly d68cd0be06332422c45a3dd6834468bd554598c7]] [formerly 655e080cd50173b744b6dcbbba2d0b07332c6f6a [formerly dc9b0a5bc43fa68663f62731ab9e2fe062e36714] [formerly 798e700a48b32937f7641c9f8c2911568f9e7c5d [formerly 798e700a48b32937f7641c9f8c2911568f9e7c5d [formerly 3772062c68f01940eb42d111a6cb61bee2ca6437]]]]
Former-commit-id: a6559280da3db01c5f8673af1aa9cb538fc30be7 [formerly 21b7be45cdb3833238e9cadfa123ab12759f3790] [formerly c3505ad30f0fa237bbfccb2da952e7146dda029b [formerly a11968a0b1ae98f6c6f67c32f1adba216d599ef9]]
Former-commit-id: 6c8ee58270a87213ce1a8833779b20b82d07604f [formerly 8c1d69febf238f13486c34697cac300f89bc4865]
Former-commit-id: b1a769583fffe9df28dbac9db969359df68d070f
Former-commit-id: cecbb32c5935b686d63e7c07c4bec4671ab05d04
require 'open-uri'
require 'rubygems/package'
require 'zlib'
##################################################################
# Synchronizes staging or dev environment with production database
#
# 1) Download and import a target production database backup
# 2) Drops, recreates, and imports new considerit database
# 3) Imports file attachments into local environment
# 4) Appends .ghost to all non-super admin user email addresses
# to prevent emails being sent to real users in a testing context
# 5) Migrates the database so it is in sync with current environment
# dumps are located in ~/Dropbox/Apps/considerit_backup/xenogear
# This script assumes a tarball created via the Backup gem.
DATABASE_BACKUP_URL = "https://www.dropbox.com/s/97j6j3qdaig9yd4/xenogear.tar?dl=1"
# Where production assets are served from
PRODUCTION_ASSET_HOST = "http://d2rtgkroh5y135.cloudfront.net"
task :sync_with_production, [:sql_url] => :environment do |t, args|
sql_url = args[:sql_url] ? args[:sql_url] : DATABASE_BACKUP_URL
puts "Preparing local database based on production database #{sql_url}..."
success = prepare_production_database sql_url
if success
puts "Downloading file attachments from production..."
download_files_from_production
else
puts "Failed"
end
end
def prepare_production_database(sql_url)
# Download and extract target production database backup
open('tmp/production_db.tar', 'wb') do |file|
file << open(URI.parse(sql_url)).read
end
# Backup's tarball is a directory xenogear/databases/MySQL.sql.gz
tar_extract = Gem::Package::TarReader.new(open('tmp/production_db.tar'))
tar_extract.rewind # The extract has to be rewinded after every iteration
tar_extract.each do |entry|
if entry.full_name.end_with?('.sql.gz')
open('tmp/production_db.sql', 'wb') do |gz|
gz << Zlib::GzipReader.new(entry).read
end
end
end
tar_extract.close
puts "...downloaded and extracted production database backup from #{DATABASE_BACKUP_URL}"
# Drop existing database
filename = "test/data/test.sql"
Rake::Task["db:drop"].invoke
Rake::Task["db:create"].invoke
puts "...dropped and recreated database #{Rails.configuration.database_configuration[Rails.env]["database"]}"
# Import production database backup
puts "...now we're importing data. Might take a few minutes."
db = Rails.configuration.database_configuration[Rails.env]
system "mysql -u#{db['username']} -p#{db['password']} #{db['database']} < #{Rails.root}/tmp/production_db.sql"
puts "...imported production db into #{Rails.configuration.database_configuration[Rails.env]["database"]}"
# Append .ghost to all non-super admin user email addresses
# to prevent emails being sent to real users in a testing context
ActiveRecord::Base.connection.execute("UPDATE users SET email=CONCAT(email,'.ghost') WHERE email IS NOT NULL AND super_admin=false")
puts "...modified non superadmin email addresses to prevent email notifications"
# Migrates the database so it is in sync with current environment
system "bundle exec rake db:migrate > /dev/null 2>&1"
puts "...migrated the database"
cleanup = ['tmp/production_db.tar', 'tmp/production_db.sql']
cleanup.each do |f|
File.delete f if File.exist?(f)
end
puts "...cleaned up tmp files"
return true
end
# Serving assets from AWS via Cloudfront and S3
# helps speed up page loads by distributing the
# requests across multiple servers that are on average
# more geographic proximate to clients.
#
# However, AWS creates some problems when we want to pull in
# the production database to use in a test or staging
# environment. Specifically, all the files, such as avatars,
# that have been uploaded by users via Paperclip continue to
# live at the production AWS S3 bucket.
# - In staging, we use a different S3 bucket, so the
# staging environment can't serve the files
# - In development, our local machines aren't
# configured to use AWS, so we can't see the files
#
# This rake task will download all file uploads for the
# currently loaded database to the local environment.
# You need to configure the source asset host from which
# the database originated. It will default to the asset host
# for consider.it.
task :download_files_from_production => :environment do
download_files_from_production
end
def download_files_from_production
# The attachments to synchronize.
attachments = [
{name: 'avatars', model: User},
{name: 'logos', model: Subdomain},
{name: 'mastheads', model: Subdomain},
{name: 'icons', model: Assessable::Verdict}
]
# find out where we store out assets...
has_aws = Rails.env.production? && APP_CONFIG.has_key?(:aws) && APP_CONFIG[:aws].has_key?(:access_key_id) && !APP_CONFIG[:aws][:access_key_id].nil?
if has_aws
local_asset_host = "http://#{APP_CONFIG[:aws][:cloudfront]}.cloudfront.net"
path_template = Paperclip::Attachment.default_options[:path]
else
# default_options[:url] will look like "/system/:attachment/:id/:style/:filename"
path_template = Paperclip::Attachment.default_options[:url]
end
attachments.each do |attachment|
# for each object of model that has an attachment of this type
field = "#{attachment[:name].singularize}_file_name"
attachment[:model].where("#{field} IS NOT NULL").each do |obj|
url = path_template
.gsub(":attachment", attachment[:name])
.gsub(":id", obj.id.to_s)
.gsub(":style", "original")
.gsub(":filename", obj[field])
# check if the file is already downloaded
if has_aws
already_downloaded = url_exist?("#{local_asset_host}/#{url}")
url = "#{PRODUCTION_ASSET_HOST}/#{url}"
else
path = "#{Rails.root.to_s}/public#{url}"
already_downloaded = File.exist?(path)
url = "#{PRODUCTION_ASSET_HOST}#{url}"
end
if !already_downloaded
# if not, download it
io = URI.parse(url)
begin
open(io) #trigger an error if url doesn't exist
rescue
pp "FAILED DOWNLOADING: #{url}"
else
# now save the attachment
begin
# for some reason, the following doesn't trigger
# the correct paperclip saving mechanim...
#
# obj.send(attachment[:name].singularize, io)
#
# ...so we'll just do it manually
case attachment[:name].singularize
when 'avatar'
data = Base64.encode64(open(io).read)
obj.b64_thumbnail = "data:image/jpeg;base64,#{data.gsub(/\n/,' ')}"
obj.avatar = io
when 'icon'
obj.icon = io
when 'masthead'
obj.masthead = io
when 'logo'
obj.logo = io
end
obj.save
rescue => e
pp "FAILED SAVING: #{url} because of #{e.to_s}"
ActiveRecord::Base.connection.reconnect!
else
pp "Saved locally: #{url}"
end
end
end
end
end
# Avatar attachments are processed as background tasks
Delayed::Worker.new.work_off(Delayed::Job.count)
end
# from http://stackoverflow.com/questions/5908017/check-if-url-exists-in-ruby
require "net/http"
def url_exist?(url_string)
url = URI.parse(url_string)
req = Net::HTTP.new(url.host, url.port)
path = url.path if url.path.present?
res = req.request_head(path || '/')
!["404", "403"].include? res.code
rescue Errno::ENOENT
false # false if can't find the server
end
|
require 'octokit'
require 'pry'
require 'excon'
require 'colored'
require 'json'
module Fastlane
class Bot
SLUG = "fastlane/fastlane"
ISSUE_WARNING = 2
ISSUE_CLOSED = 0.3 # plus the x months from ISSUE_WARNING
AWAITING_REPLY = "waiting-for-reply"
AUTO_CLOSED = "auto-closed"
def client
@client ||= Octokit::Client.new(access_token: ENV["GITHUB_API_TOKEN"])
end
def start
client.auto_paginate = true
puts "Fetching issues from '#{SLUG}'..."
counter = 0
client.issues(SLUG, per_page: 30, state: "open", direction: 'asc').each do |issue|
next unless issue.pull_request.nil? # no PRs for now
next if issue.labels.collect { |a| a.name }.include?("feature") # we ignore all feature requests for now
puts "Investigating issue ##{issue.number}..."
process(issue)
counter += 1
end
puts "[SUCCESS] I worked through #{counter} issues / PRs, much faster than human beings, bots will take over"
end
def process(issue)
process_inactive(issue)
process_code_signing(issue)
end
def myself
client.user.login
end
# Responsible for commenting to inactive issues
def process_inactive(issue)
return if issue.comments == 0 # we haven't replied yet :(
diff_in_months = (Time.now - issue.updated_at) / 60.0 / 60.0 / 24.0 / 30.0
warning_sent = !!issue.labels.find { |a| a.name == AWAITING_REPLY }
if warning_sent && diff_in_months > ISSUE_CLOSED
# We sent off a warning, but we have to check if the user replied
if client.issue_comments(SLUG, issue.number).last.user.login == myself
# No reply from the user, let's close the issue
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) is #{diff_in_months.round(1)} months old, closing now"
body = []
body << "This issue will be auto-closed because there hasn't been any activity for a few months. Feel free to [open a new one](https://github.com/fastlane/fastlane/issues/new) if you still experience this problem 👍"
client.add_comment(SLUG, issue.number, body.join("\n\n"))
client.close_issue(SLUG, issue.number)
client.add_labels_to_an_issue(SLUG, issue.number, AUTO_CLOSED)
else
# User replied, let's remove the label
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) was replied to by a different user"
client.remove_label(SLUG, issue.number, AWAITING_REPLY)
end
smart_sleep
elsif diff_in_months > ISSUE_WARNING
return if issue.labels.find { |a| a.name == AWAITING_REPLY }
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) is #{diff_in_months.round(1)} months old, pinging now"
body = []
body << "There hasn't been any activity on this issue recently. Due to the high number of incoming GitHub notifications, we have to clean some of the old issues, as many of them have already been resolved with the latest updates."
body << "Please make sure to update to the latest `fastlane` version and check if that solves the issue. Let us know if that works for you by adding a comment :+1:"
client.add_comment(SLUG, issue.number, body.join("\n\n"))
client.add_labels_to_an_issue(SLUG, issue.number, [AWAITING_REPLY])
smart_sleep
end
end
def process_code_signing(issue)
return if issue.comments > 0 # we might have already replied, no bot necessary
signing_words = ["signing", "provisioning"]
body = issue.body + issue.title
signing_related = signing_words.find_all do |keyword|
body.downcase.include?(keyword)
end
return if signing_related.count == 0
url = "https://github.com/fastlane/fastlane/tree/codesigning-guide/fastlane/docs/Codesigning" # TODO: Update URL once the PR is merged
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) might have something to do with code signing"
body = []
body << "It seems like this issue might be related to code signing :no_entry_sign:"
body << "Check out the [Code Signing Troubleshooting Guide](#{url}) for more information on how to fix common code signing issues :+1:"
client.add_comment(SLUG, issue.number, body.join("\n\n"))
end
def smart_sleep
sleep 5
end
end
end
Updated codesigning URL
require 'octokit'
require 'pry'
require 'excon'
require 'colored'
require 'json'
module Fastlane
class Bot
SLUG = "fastlane/fastlane"
ISSUE_WARNING = 2
ISSUE_CLOSED = 0.3 # plus the x months from ISSUE_WARNING
AWAITING_REPLY = "waiting-for-reply"
AUTO_CLOSED = "auto-closed"
def client
@client ||= Octokit::Client.new(access_token: ENV["GITHUB_API_TOKEN"])
end
def start
client.auto_paginate = true
puts "Fetching issues from '#{SLUG}'..."
counter = 0
client.issues(SLUG, per_page: 30, state: "open", direction: 'asc').each do |issue|
next unless issue.pull_request.nil? # no PRs for now
next if issue.labels.collect { |a| a.name }.include?("feature") # we ignore all feature requests for now
puts "Investigating issue ##{issue.number}..."
process(issue)
counter += 1
end
puts "[SUCCESS] I worked through #{counter} issues / PRs, much faster than human beings, bots will take over"
end
def process(issue)
process_inactive(issue)
process_code_signing(issue)
end
def myself
client.user.login
end
# Responsible for commenting to inactive issues
def process_inactive(issue)
return if issue.comments == 0 # we haven't replied yet :(
diff_in_months = (Time.now - issue.updated_at) / 60.0 / 60.0 / 24.0 / 30.0
warning_sent = !!issue.labels.find { |a| a.name == AWAITING_REPLY }
if warning_sent && diff_in_months > ISSUE_CLOSED
# We sent off a warning, but we have to check if the user replied
if client.issue_comments(SLUG, issue.number).last.user.login == myself
# No reply from the user, let's close the issue
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) is #{diff_in_months.round(1)} months old, closing now"
body = []
body << "This issue will be auto-closed because there hasn't been any activity for a few months. Feel free to [open a new one](https://github.com/fastlane/fastlane/issues/new) if you still experience this problem 👍"
client.add_comment(SLUG, issue.number, body.join("\n\n"))
client.close_issue(SLUG, issue.number)
client.add_labels_to_an_issue(SLUG, issue.number, AUTO_CLOSED)
else
# User replied, let's remove the label
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) was replied to by a different user"
client.remove_label(SLUG, issue.number, AWAITING_REPLY)
end
smart_sleep
elsif diff_in_months > ISSUE_WARNING
return if issue.labels.find { |a| a.name == AWAITING_REPLY }
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) is #{diff_in_months.round(1)} months old, pinging now"
body = []
body << "There hasn't been any activity on this issue recently. Due to the high number of incoming GitHub notifications, we have to clean some of the old issues, as many of them have already been resolved with the latest updates."
body << "Please make sure to update to the latest `fastlane` version and check if that solves the issue. Let us know if that works for you by adding a comment :+1:"
client.add_comment(SLUG, issue.number, body.join("\n\n"))
client.add_labels_to_an_issue(SLUG, issue.number, [AWAITING_REPLY])
smart_sleep
end
end
def process_code_signing(issue)
return if issue.comments > 0 # we might have already replied, no bot necessary
signing_words = ["signing", "provisioning"]
body = issue.body + issue.title
signing_related = signing_words.find_all do |keyword|
body.downcase.include?(keyword)
end
return if signing_related.count == 0
url = "https://github.com/fastlane/fastlane/tree/master/fastlane/docs/Codesigning"
puts "https://github.com/#{SLUG}/issues/#{issue.number} (#{issue.title}) might have something to do with code signing"
body = []
body << "It seems like this issue might be related to code signing :no_entry_sign:"
body << "Check out the [Code Signing Troubleshooting Guide](#{url}) for more information on how to fix common code signing issues :+1:"
client.add_comment(SLUG, issue.number, body.join("\n\n"))
end
def smart_sleep
sleep 5
end
end
end
|
# Mixin for SolrDocument to allow deserializing item information
# to a userful structure
module TrlnArgon
module ItemDeserializer
include ActionView::Helpers::TextHelper
def deserialize
(self[TrlnArgon::Fields::ITEMS] || ['{}']).map { |d| JSON.parse(d) }
.group_by { |rec| rec['library'] }
end
def read_items
@read_items ||= deserialize
end
def deserialize_holdings
items = (self[TrlnArgon::Fields::ITEMS] || {}).map { |x| JSON.parse(x) }
holdings = (self[TrlnArgon::Fields::HOLDINGS] || {}).map { |x| JSON.parse(x) }
# { LIBRARY => { LOCATION => [ items ] } }
items_intermediate = Hash[items.group_by { |i| i['library'] }.map do |lib, locations|
[lib, locations.group_by { |i| i['shelving_location'] }]
end]
h_final = Hash[items_intermediate.map do |lib, loc_map|
[lib, Hash[loc_map.map do |loc, loc_items|
h = holdings.find { |i| i['library'] == lib && i['location'] == loc } ||
{ 'summary' => '', 'call_number' => '', 'notes' => [] }
h['items'] = loc_items.collect do |i|
i.reject { |k, _v| %w[library shelving_location].include?(k) }
end
h['call_number'] = cn_prefix(h['items'])
if h['summary'].empty?
items = h['items'] || []
avail = items.count { |i| 'available' == i['status'].downcase rescue false }
sum = "(#{pluralize(items.count, 'copy')}"
if avail != items.count
sum << ", #{avail} available"
end
sum << ")"
h['summary'] = sum
end
[loc, h]
end]]
end]
# finally, create holdings where we have summaries but no
# items ... potentially controversial
holdings.each do |h|
lib = h['library']
loc = h['location']
loc_map = h_final[lib] ||= {}
loc_map[loc] ||= h.update('items' => [])
end
h_final
end
def holdings
@holdings || deserialize_holdings
end
def cn_prefix(items)
cns = items.reject(&:nil?).collect { |i| i['call_number'].gsub(/\d{4}$/, '') }
cns[0]
end
end
end
Hide nil libraries from holdings output
# Mixin for SolrDocument to allow deserializing item information
# to a userful structure
module TrlnArgon
module ItemDeserializer
include ActionView::Helpers::TextHelper
def deserialize
(self[TrlnArgon::Fields::ITEMS] || ['{}']).map { |d| JSON.parse(d) }
.group_by { |rec| rec['library'] }
end
def read_items
@read_items ||= deserialize
end
def deserialize_holdings
items = (self[TrlnArgon::Fields::ITEMS] || {}).map { |x| JSON.parse(x) }
holdings = (self[TrlnArgon::Fields::HOLDINGS] || {}).map { |x| JSON.parse(x) }
# { LIBRARY => { LOCATION => [ items ] } }
items_intermediate = Hash[items.group_by { |i| i['library'] }.map do |lib, locations|
[lib, locations.group_by { |i| i['shelving_location'] }]
end]
h_final = Hash[items_intermediate.map do |lib, loc_map|
[lib, Hash[loc_map.map do |loc, loc_items|
h = holdings.find { |i| i['library'] == lib && i['location'] == loc } ||
{ 'summary' => '', 'call_number' => '', 'notes' => [] }
h['items'] = loc_items.collect do |i|
i.reject { |k, _v| %w[library shelving_location].include?(k) }
end
h['call_number'] = cn_prefix(h['items'])
if h['summary'].empty?
items = h['items'] || []
avail = items.count { |i| 'available' == i['status'].downcase rescue false }
sum = "(#{pluralize(items.count, 'copy')}"
if avail != items.count
sum << ", #{avail} available"
end
sum << ")"
h['summary'] = sum
end
[loc, h]
end]]
end]
# finally, create holdings where we have summaries but no
# items ... potentially controversial
holdings.each do |h|
lib = h['library']
loc = h['location']
loc_map = h_final[lib] ||= {}
loc_map[loc] ||= h.update('items' => [])
end
h_final.reject { |k, v| k.nil? }
end
def holdings
@holdings || deserialize_holdings
end
def cn_prefix(items)
cns = items.reject(&:nil?).collect { |i| i['call_number'].gsub(/\d{4}$/, '') }
cns[0]
end
end
end
|
require 'sequel'
require 'jdbc/postgres'
require "delegate"
require "active_support/core_ext/string/filters"
module Travis
module Logs
module Helpers
# The Database helper talks to the Postgres database.
#
# No database-specific logic (such as table names and SQL queries) should
# be outside of this class.
class Database
# This method should only be called for "maintenance" tasks (such as
# creating the tables or debugging).
def self.create_sequel
config = Travis::Logs.config.logs_database
Sequel.connect(jdbc_uri_from_config(config), max_connections: config[:pool]).tap do |db|
db.timezone = :utc
end
end
def self.jdbc_uri_from_config(config)
host = config[:host] || 'localhost'
port = config[:port] || 5432
database = config[:database]
username = config[:username] || ENV["USER"]
params = {
user: username,
password: config[:password],
}
unless ENV['PG_DISABLE_SSL']
params.merge!(
ssl: true,
sslfactory: 'org.postgresql.ssl.NonValidatingFactory'
)
end
"jdbc:postgresql://#{host}:#{port}/#{database}?#{URI.encode_www_form(params)}"
end
def self.connect
new.tap(&:connect)
end
def initialize
@db = self.class.create_sequel
end
def connect
@db.test_connection
@db << "SET application_name = 'logs'"
@db << "SET TIME ZONE 'UTC'"
prepare_statements
end
def log_for_id(log_id)
@db.call(:find_log, log_id: log_id).first
end
def log_for_job_id(job_id)
@db.call(:find_log_id, job_id: job_id).first
end
def log_content_length_for_id(log_id)
@db[:logs].select{[id, job_id, octet_length(content).as(content_length)]}.where(id: log_id).first
end
def update_archiving_status(log_id, archiving)
@db[:logs].where(id: log_id).update(archiving: archiving)
end
def mark_archive_verified(log_id)
@db[:logs].where(id: log_id).update(archived_at: Time.now.utc, archive_verified: true)
end
def mark_not_archived(log_id)
@db[:logs].where(id: log_id).update(archived_at: nil, archive_verified: false)
end
def purge(log_id)
@db[:logs].where(id: log_id).update(purged_at: Time.now.utc, content: nil)
end
def create_log(job_id)
@db.call(:create_log, {
job_id: job_id,
created_at: Time.now.utc,
updated_at: Time.now.utc
})
end
def create_log_part(params)
@db.call(:create_log_part, params.merge(created_at: Time.now.utc))
end
def delete_log_parts(log_id)
@db.call(:delete_log_parts, log_id: log_id)
end
def set_log_content(log_id, content)
delete_log_parts(log_id)
@db[:logs].where(id: log_id).update(content: content, aggregated_at: Time.now.utc, archived_at: nil, archive_verified: nil, updated_at: Time.now.utc)
end
AGGREGATEABLE_SELECT_SQL = <<-SQL.squish
SELECT DISTINCT log_id
FROM log_parts
WHERE (created_at <= NOW() - interval '? seconds' AND final = ?)
OR created_at <= NOW() - interval '? seconds'
SQL
def aggregatable_log_parts(regular_interval, force_interval)
@db[AGGREGATEABLE_SELECT_SQL, regular_interval, true, force_interval].map(:log_id)
end
AGGREGATE_PARTS_SELECT_SQL = <<-SQL.squish
SELECT array_to_string(array_agg(log_parts.content ORDER BY number, id), '')
FROM log_parts
WHERE log_id = ?
SQL
AGGREGATE_UPDATE_SQL = <<-SQL.squish
UPDATE logs
SET aggregated_at = ?,
content = (COALESCE(content, '') || (#{AGGREGATE_PARTS_SELECT_SQL}))
WHERE logs.id = ?
SQL
def aggregate(log_id)
@db[AGGREGATE_UPDATE_SQL, Time.now.utc, log_id, log_id].update
end
def transaction(&block)
@db.transaction(&block)
end
private
def prepare_statements
@db[:logs].where(id: :$log_id).prepare(:select, :find_log)
@db[:logs].select(:id).where(job_id: :$job_id).prepare(:select, :find_log_id)
@db[:logs].prepare(:insert, :create_log, {
job_id: :$job_id,
created_at: :$created_at,
updated_at: :$updated_at,
})
@db[:log_parts].prepare(:insert, :create_log_part, {
log_id: :$log_id,
content: :$content,
number: :$number,
final: :$final,
created_at: :$created_at,
})
@db[:log_parts].where(log_id: :$log_id).prepare(:delete, :delete_log_parts)
end
end
end
end
end
Touch up the SSL-specific database param setting
require 'sequel'
require 'jdbc/postgres'
require "delegate"
require "active_support/core_ext/string/filters"
module Travis
module Logs
module Helpers
# The Database helper talks to the Postgres database.
#
# No database-specific logic (such as table names and SQL queries) should
# be outside of this class.
class Database
# This method should only be called for "maintenance" tasks (such as
# creating the tables or debugging).
def self.create_sequel
config = Travis::Logs.config.logs_database
Sequel.connect(jdbc_uri_from_config(config), max_connections: config[:pool]).tap do |db|
db.timezone = :utc
end
end
def self.jdbc_uri_from_config(config)
host = config[:host] || 'localhost'
port = config[:port] || 5432
database = config[:database]
username = config[:username] || ENV["USER"]
params = {
user: username,
password: config[:password],
}
params.merge!(
ssl: true,
sslfactory: 'org.postgresql.ssl.NonValidatingFactory'
) unless %w(1 yes on).include?(ENV['PG_DISABLE_SSL'].to_s.downcase)
"jdbc:postgresql://#{host}:#{port}/#{database}?#{URI.encode_www_form(params)}"
end
def self.connect
new.tap(&:connect)
end
def initialize
@db = self.class.create_sequel
end
def connect
@db.test_connection
@db << "SET application_name = 'logs'"
@db << "SET TIME ZONE 'UTC'"
prepare_statements
end
def log_for_id(log_id)
@db.call(:find_log, log_id: log_id).first
end
def log_for_job_id(job_id)
@db.call(:find_log_id, job_id: job_id).first
end
def log_content_length_for_id(log_id)
@db[:logs].select{[id, job_id, octet_length(content).as(content_length)]}.where(id: log_id).first
end
def update_archiving_status(log_id, archiving)
@db[:logs].where(id: log_id).update(archiving: archiving)
end
def mark_archive_verified(log_id)
@db[:logs].where(id: log_id).update(archived_at: Time.now.utc, archive_verified: true)
end
def mark_not_archived(log_id)
@db[:logs].where(id: log_id).update(archived_at: nil, archive_verified: false)
end
def purge(log_id)
@db[:logs].where(id: log_id).update(purged_at: Time.now.utc, content: nil)
end
def create_log(job_id)
@db.call(:create_log, {
job_id: job_id,
created_at: Time.now.utc,
updated_at: Time.now.utc
})
end
def create_log_part(params)
@db.call(:create_log_part, params.merge(created_at: Time.now.utc))
end
def delete_log_parts(log_id)
@db.call(:delete_log_parts, log_id: log_id)
end
def set_log_content(log_id, content)
delete_log_parts(log_id)
@db[:logs].where(id: log_id).update(content: content, aggregated_at: Time.now.utc, archived_at: nil, archive_verified: nil, updated_at: Time.now.utc)
end
AGGREGATEABLE_SELECT_SQL = <<-SQL.squish
SELECT DISTINCT log_id
FROM log_parts
WHERE (created_at <= NOW() - interval '? seconds' AND final = ?)
OR created_at <= NOW() - interval '? seconds'
SQL
def aggregatable_log_parts(regular_interval, force_interval)
@db[AGGREGATEABLE_SELECT_SQL, regular_interval, true, force_interval].map(:log_id)
end
AGGREGATE_PARTS_SELECT_SQL = <<-SQL.squish
SELECT array_to_string(array_agg(log_parts.content ORDER BY number, id), '')
FROM log_parts
WHERE log_id = ?
SQL
AGGREGATE_UPDATE_SQL = <<-SQL.squish
UPDATE logs
SET aggregated_at = ?,
content = (COALESCE(content, '') || (#{AGGREGATE_PARTS_SELECT_SQL}))
WHERE logs.id = ?
SQL
def aggregate(log_id)
@db[AGGREGATE_UPDATE_SQL, Time.now.utc, log_id, log_id].update
end
def transaction(&block)
@db.transaction(&block)
end
private
def prepare_statements
@db[:logs].where(id: :$log_id).prepare(:select, :find_log)
@db[:logs].select(:id).where(job_id: :$job_id).prepare(:select, :find_log_id)
@db[:logs].prepare(:insert, :create_log, {
job_id: :$job_id,
created_at: :$created_at,
updated_at: :$updated_at,
})
@db[:log_parts].prepare(:insert, :create_log_part, {
log_id: :$log_id,
content: :$content,
number: :$number,
final: :$final,
created_at: :$created_at,
})
@db[:log_parts].where(log_id: :$log_id).prepare(:delete, :delete_log_parts)
end
end
end
end
end
|
module VagrantPlugins
module Babushka
# The main implementation class for the Babushka provisioner
class Provisioner < Vagrant.plugin("2", :provisioner)
def initialize(machine, config)
super
end
def configure(root_config)
@username = root_config.ssh.username || root_config.ssh.default.username
@hostname = root_config.vm.hostname
if @config.local_deps_path
local_path = @config.local_deps_path
remote_path = "/home/#{@username}/babushka-deps"
opts = {id: 'babushka_deps', nfs: false}
root_config.vm.synced_folder local_path, remote_path, opts
end
end
# This is the method called when the actual provisioning should
# be done. The communicator is guaranteed to be ready at this
# point, and any shared folders or networds are already set up.
def provision
render_messages!
bootstrap_babushka! unless @machine.communicate.test('babushka --version')
@config.deps.map do |dep|
run_remote "babushka --update --defaults --color #{dep.command}"
end
end
private
# Renders the messages to the log output
#
# The config object maintains a list of "messages" to be shown
# when provisioning occurs, since there's no way to show messages
# at the time of configuration actually occurring. This displays
# the messages that were saved.
def render_messages!
@config.messages.each do |(level, info, caller)|
info = "vagrant-babushka: #{info}"
info += "\nIn #{caller.first}" unless caller.nil?
@machine.env.ui.send level.to_sym, info.to_s, :scope => @machine.name
end
end
# Installs Babushka on the guest using the bootstrap script
def bootstrap_babushka!
require 'net/http'
@machine.env.ui.info("Installing babushka on #{@hostname}.")
local_tmpfile = remote_tmpfile = "/tmp/babushka_me_up"
File.open(local_tmpfile, 'w') {|f| f.write `curl #{babushka_uri}` }
@machine.communicate.upload(local_tmpfile, remote_tmpfile)
run_remote "#{proxy_env} sh #{remote_tmpfile}"
end
# Extracts the HTTPS proxy from the host environment variables
def proxy_env
vars = ''
vars_from_env = ENV.select { |k, _| /https_proxy/i.match(k) }
vars = vars_from_env.to_a.map{ |pair| pair.join('=') }.join(' ') unless vars_from_env.empty?
vars
end
# Retrieves the URL to use to bootstrap Babushka on the guest
def babushka_uri
uri = 'https://babushka.me/up'
uri = "#{uri}/#{@config.bootstrap_branch}" unless @config.bootstrap_branch.nil?
uri
end
# Executes a command on the guest and handles logging the output
#
# * command: The command to execute (as a string)
def run_remote(command)
@machine.communicate.sudo(command) do |type, data|
color = type == :stdout ? :green : :red
@machine.env.ui.info(data.chomp, :color => color, :prefix => false)
end
end
end
end
end
Add missing internal documentation
module VagrantPlugins
module Babushka
# The main implementation class for the Babushka provisioner
class Provisioner < Vagrant.plugin("2", :provisioner)
def initialize(machine, config)
super
end
# Called with the root configuration of the machine so the
# provisioner can add some configuration on top of the machine.
#
# During this step, and this step only, the provisioner should
# modify the root machine configuration to add any additional
# features it may need. Examples include sharing folders,
# networking, and so on. This step is guaranteed to be called
# before any of those steps are done so the provisioner may do
# that.
def configure(root_config)
@username = root_config.ssh.username || root_config.ssh.default.username
@hostname = root_config.vm.hostname
if @config.local_deps_path
local_path = @config.local_deps_path
remote_path = "/home/#{@username}/babushka-deps"
opts = {id: 'babushka_deps', nfs: false}
root_config.vm.synced_folder local_path, remote_path, opts
end
end
# This is the method called when the actual provisioning should
# be done. The communicator is guaranteed to be ready at this
# point, and any shared folders or networds are already set up.
def provision
render_messages!
bootstrap_babushka! unless @machine.communicate.test('babushka --version')
@config.deps.map do |dep|
run_remote "babushka --update --defaults --color #{dep.command}"
end
end
private
# Renders the messages to the log output
#
# The config object maintains a list of "messages" to be shown
# when provisioning occurs, since there's no way to show messages
# at the time of configuration actually occurring. This displays
# the messages that were saved.
def render_messages!
@config.messages.each do |(level, info, caller)|
info = "vagrant-babushka: #{info}"
info += "\nIn #{caller.first}" unless caller.nil?
@machine.env.ui.send level.to_sym, info.to_s, :scope => @machine.name
end
end
# Installs Babushka on the guest using the bootstrap script
def bootstrap_babushka!
require 'net/http'
@machine.env.ui.info("Installing babushka on #{@hostname}.")
local_tmpfile = remote_tmpfile = "/tmp/babushka_me_up"
File.open(local_tmpfile, 'w') {|f| f.write `curl #{babushka_uri}` }
@machine.communicate.upload(local_tmpfile, remote_tmpfile)
run_remote "#{proxy_env} sh #{remote_tmpfile}"
end
# Extracts the HTTPS proxy from the host environment variables
def proxy_env
vars = ''
vars_from_env = ENV.select { |k, _| /https_proxy/i.match(k) }
vars = vars_from_env.to_a.map{ |pair| pair.join('=') }.join(' ') unless vars_from_env.empty?
vars
end
# Retrieves the URL to use to bootstrap Babushka on the guest
def babushka_uri
uri = 'https://babushka.me/up'
uri = "#{uri}/#{@config.bootstrap_branch}" unless @config.bootstrap_branch.nil?
uri
end
# Executes a command on the guest and handles logging the output
#
# * command: The command to execute (as a string)
def run_remote(command)
@machine.communicate.sudo(command) do |type, data|
color = type == :stdout ? :green : :red
@machine.env.ui.info(data.chomp, :color => color, :prefix => false)
end
end
end
end
end
|
require 'sequel'
require 'jdbc/postgres'
module Travis
module Logs
module Helpers
class Database
# This method should only be called for "maintenance" tasks (such as
# creating the tables or debugging).
def self.create_sequel
config = { username: ENV["USER"] }.merge(Travis::Logs.config.database)
Sequel.connect(jdbc_uri_from_config(config), max_connections: config[:pool]).tap do |db|
db.logger = Travis.logger unless Travis::Logs.config.env == 'production'
db.timezone = :utc
end
end
def self.jdbc_uri_from_config(config)
"jdbc:postgresql://#{config[:host]}:#{config[:port]}/#{config[:database]}?user=#{config[:username]}&password=#{config[:password]}"
end
def self.connect
new.tap(&:connect)
end
def initialize
@db = self.class.create_sequel
end
def connect
@db.test_connection
@db << "SET application_name = 'logs'"
prepare_statements
end
def log_for_id(log_id)
@db.call(:find_log, log_id: log_id).first
@db[:logs].where(id: log_id).first
end
def log_for_job_id(job_id)
@db.call(:find_log_id, job_id: job_id).first
end
def update_archiving_status(log_id, archiving)
@db[:logs].where(id: log_id).update(archiving: archiving)
end
def mark_archive_verified(log_id)
@db[:logs].where(id: log_id).update(archived_at: Time.now.utc, archive_verified: true)
end
def create_log(job_id)
@db.call(:create_log, job_id: job_id, created_at: Time.now, updated_at: Time.now.utc)
end
def create_log_part(params)
@db.call(:create_log_part, params.merge(created_at: Time.now.utc))
end
# For compatibility API
# TODO: Remove these when all Sequel calls are handled in this class
def [](table)
@db[table]
end
def call(*args)
@db.call(*args)
end
private
def prepare_statements
@db[:logs].where(id: :$log_id).prepare(:select, :find_log)
@db[:logs].select(:id).where(job_id: :$job_id).prepare(:select, :find_log_id)
@db[:logs].prepare(:insert, :create_log, {
job_id: :$job_id,
created_at: :$created_at,
updated_at: :$updated_at,
})
@db[:log_parts].prepare(:insert, :create_log_part, {
log_id: :$log_id,
content: :$content,
number: :$number,
final: :$final,
created_at: :$created_at,
})
end
end
end
end
end
Fix delegate method
The [] method on a Sequel object can take more than one argument, which
the aggregate_logs service depends on.
require 'sequel'
require 'jdbc/postgres'
require "delegate"
module Travis
module Logs
module Helpers
class Database
# This method should only be called for "maintenance" tasks (such as
# creating the tables or debugging).
def self.create_sequel
config = { username: ENV["USER"] }.merge(Travis::Logs.config.database)
Sequel.connect(jdbc_uri_from_config(config), max_connections: config[:pool]).tap do |db|
db.logger = Travis.logger unless Travis::Logs.config.env == 'production'
db.timezone = :utc
end
end
def self.jdbc_uri_from_config(config)
"jdbc:postgresql://#{config[:host]}:#{config[:port]}/#{config[:database]}?user=#{config[:username]}&password=#{config[:password]}"
end
def self.connect
new.tap(&:connect)
end
def initialize
@db = self.class.create_sequel
end
def connect
@db.test_connection
@db << "SET application_name = 'logs'"
prepare_statements
end
def log_for_id(log_id)
@db.call(:find_log, log_id: log_id).first
@db[:logs].where(id: log_id).first
end
def log_for_job_id(job_id)
@db.call(:find_log_id, job_id: job_id).first
end
def update_archiving_status(log_id, archiving)
@db[:logs].where(id: log_id).update(archiving: archiving)
end
def mark_archive_verified(log_id)
@db[:logs].where(id: log_id).update(archived_at: Time.now.utc, archive_verified: true)
end
def create_log(job_id)
@db.call(:create_log, job_id: job_id, created_at: Time.now, updated_at: Time.now.utc)
end
def create_log_part(params)
@db.call(:create_log_part, params.merge(created_at: Time.now.utc))
end
# For compatibility API
# TODO: Remove these when all Sequel calls are handled in this class
def [](*args)
@db[*args]
end
def call(*args)
@db.call(*args)
end
private
def prepare_statements
@db[:logs].where(id: :$log_id).prepare(:select, :find_log)
@db[:logs].select(:id).where(job_id: :$job_id).prepare(:select, :find_log_id)
@db[:logs].prepare(:insert, :create_log, {
job_id: :$job_id,
created_at: :$created_at,
updated_at: :$updated_at,
})
@db[:log_parts].prepare(:insert, :create_log_part, {
log_id: :$log_id,
content: :$content,
number: :$number,
final: :$final,
created_at: :$created_at,
})
end
end
end
end
end
|
module VagrantPlugins
module ProviderKvm
module Action
class CheckBox
def initialize(app, env)
@app = app
end
def call(env)
box_name = env[:machine].config.vm.box
raise Vagrant::Errors::BoxNotSpecified if !box_name
if !env[:box_collection].find(box_name, :kvm)
box_url = env[:machine].config.vm.box_url
raise Vagrant::Errors::BoxSpecifiedDoesntExist, :name => box_name if !box_url
# Add the box then reload the box collection so that it becomes
# aware of it.
env[:ui].info I18n.t("vagrant.actions.vm.check_box.not_found", :name => box_name)
env[:action_runner].run(Vagrant::Action.action_box_add, {
:box_name => box_name,
:box_provider => env[:machine].provider_name,
:box_url => box_url
})
# Reload the environment and set the VM to be the new loaded VM.
env[:machine] = env[:machine].env.machine(
env[:machine].name, env[:machine].provider_name, true)
end
@app.call(env)
end
end
end
end
end
Added missing argument :provider
module VagrantPlugins
module ProviderKvm
module Action
class CheckBox
def initialize(app, env)
@app = app
end
def call(env)
box_name = env[:machine].config.vm.box
raise Vagrant::Errors::BoxNotSpecified if !box_name
if !env[:box_collection].find(box_name, :kvm)
box_url = env[:machine].config.vm.box_url
raise Vagrant::Errors::BoxSpecifiedDoesntExist, :name => box_name if !box_url
# Add the box then reload the box collection so that it becomes
# aware of it.
env[:ui].info I18n.t("vagrant.actions.vm.check_box.not_found", :name => box_name, :provider => env[:machine].provider_name)
env[:action_runner].run(Vagrant::Action.action_box_add, {
:box_name => box_name,
:box_provider => env[:machine].provider_name,
:box_url => box_url
})
# Reload the environment and set the VM to be the new loaded VM.
env[:machine] = env[:machine].env.machine(
env[:machine].name, env[:machine].provider_name, true)
end
@app.call(env)
end
end
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.